jeudi 4 août 2016

Urgent: ParseError: bad input [on hold]

Help:( whats wrong with this bit

remainder = sum1 % 10

if remainder == 0 :

PyQt - QScrollBar

Dear Stacktoverflow, can you show me an example of how to use a QScrollBar? Thanks.

window.location.reload() used in my js page I am getting logout I am using spring security

I need to reload my page using window.location.reload() but I am facing logout. I am using spring security jquery

How to parse parse large .csv file in java? [on hold]

I want to parse different format large csv file and generate pdf based upon the csv file values. how to do this?

How to set the build description via Jenkins REST API or Python?

Is there any way (like Jenkins REST API or Python module) to set the existing jenkins build's build description ?

Many thanks :)

How to interface Python with Qlikview for data visualization?

I am using Scikit-Learn and Pandas libraries of Python for Data Analysis. How to interface Python with data visualization tools such as Qlikview?

Python 2 change the way to start a new process

Can I change the way Python 2 creates a new process, like what set_start_method does in Python 3 on UNIX based OSes?

How to make QPushButton editable text when one click on it?

Using Python 2.7 and PyQt4. So I need a way to make a text of the QPushButton editable when click on it, like on QTextEdit.

Django retrieve all rows from a table but the last three

I have the last three rows by using Book.objects.order_by('-id')[:3], is there a way to get all the rows excluding those three elements?

which site provide python packages?

i need some packages for data mining programming.Can you tell me which packages are good and also need trusted sites which contain the packages?

How I can make a python program search for updates?

I have a python script that I want it can search for updates and if there is an update, it downloads it and installs it.

Level_date into Singe cell

I am having One method that Methon return two date Object (eg : (datetime.date(2016, 6, 20), datetime.date(2016, 6, 26))). How to store this into single cell in a table?

Writing plot increments in Latex font?

Is there a way to type the increments on the x and y axes in Latex font, instead of just Arial?

Likewise, the legend?

how to install python for cygwin? Mine python's sys.platform == "win32"

My python in cygwin environment is: sys.platform == "win32"

But I want to use pexpect.spawn(...) method which is not available on win32 platform.

What features would a *perfect* Python debugger have?

Please tell me which features you wish your current Python debugger had. I'm creating a new Python IDE/debugger and am looking forward to challenging requests!

How to get mouses scrollX value from a point of event's call in jQuery?

I need to know mouse scrollX value not by left window's border, but by element that has triggered an event. Thank you, i rely on you guys!

Do something only once Python

I have this sequence of numbers 12345 do something 12345 12345 12346 do something 12346 12346 12346 12347 do something 12347 12347 12347 The numbers are repeated unknown number of times I just need to do something on the first change

how to listen docker events and run command when new event emit?

I know docker events command can listen docker events, but how to watch docker events 's output and run command when have new output?

Installing pip on Mac OS X

I spent most of the day yesterday searching for a clear answer for installing pip. I can't find a good solution.

Can somebody help me install it?

How can convert YYYY-MM-DD hh mm ss into MonthName, date, year | Hour:Minuts (am/pm) in JavaScript or jQuery

I have date string (2013-03-10 19:43:55) and want to convert it in this format (Mar 10, 2013 | 7:43 pm) using JavaScript or jQuery. How can I do this ??

Onchange open URL via select - jQuery

What would be the best way to attach an event so on change of a select option a URL. Store the href in an attr and grab it on change?

How to increase the perfomance of R in machine learning?

I am using both R and python(Anaconda).When it comes to modelling,R is taking more time for the same operation.Is there any method for parallel operations or multi threading in R?

find google spreadsheet by title via api in python

I would like to retrieve data of spreadsheet by searching for the spreadsheet by name. I wonder how it works?

result = service.spreadsheets().values().get(title=spreadsheetTitle, range=rangeName).execute()

mercredi 3 août 2016

Writing multi-line strings into cells using openpyxl

I'm trying to write data into a cell, which has multiple line breaks (I believe n), the resulting .xlsx has line breaks removed. Is there a way to keep these line breaks?

How to compare two psv files through Robot framework; is it possible?

I have two psv (pipe-separated) files, I need to compare the data columnwise.

How can I compare those two files, is it possible to compare two psv files through Robot??

Python: How do you unit test a nested function?

How would you unit test the nested function f1() in the following example?

def f():
    def f1():
       return 1
    return 2

Or should functions that need testing not be nested?

Get Big Query Metadata

How can I get table meta data (Last Modified Time) in Big Query using Python?

I will use the BigQuery table only if its last modified datetime is greater than some datetime.

ImportError when importing scitools

I am using python 3.4, and every time I use scitools, I get this error:

  File "<stdin>", line 1, in <module>
ImportError: No module named 'scitools'

Checking network connection

I want to see if I can access an online API, but for that I need to have Internet access.

How can I see if there's a connection available and active using Python?

Use os.system in Python 3 script [on hold]

I would like to install matplotlib to Python 2.7 with a script that I wrote in Python 3:

os.system('c:\Python27\python.exe c:\Debug2.py') 

But nothing happens.

I am looking for a scroll bar jquery for my photo gallery [on hold]

enter image description here

Can anyone help me to find such gallery??

how can i adjust the delay timing of bootstrap slider changing

am trying to adjust the delay time of bootstrap slider. How can i adjust that please check the link http://bootsnipp.com/snippets/featured/responsive-bs-carousel-with-hero-headers

How to achieve this in python? [on hold]

I have something like this

उत्तराखंड |2

स्टेट |3

इंफ्रास्ट्रेक्चर |1

डेवलपमेंट |1

कॉर्पोरेशन |2

लि. |3

I want to achieve this:

1->इंफ्रास्ट्रेक्चर,डेवलपमेंट

2->उत्तराखंड,कॉर्पोरेशन

3->कॉर्पोरेशन,लि.

Get error when importing FuncAnimation from matplotlib.animation

I can't import FuncAnimation from matplotlib.animation. When I try to do it I get the error :

ValueError: insecure string pickle

I use matplotlib 1.5.1, Python 2.7, Mac OSX 10.11.3 , in Jupyter Notebook.

django.db.migrations.exceptions.NodeNotFoundError

When i run makemigrations command, i got this error:

Traceback (most recent call last):
 ...
django.db.migrations.exceptions.NodeNotFoundError: Migration products.0002_auto_20160618_1143 dependencies reference nonexistent parent node (u'products', u'0001_initial')

jQuery UI Datepicker - Multiple Date Selections

Is there a way to use the jQuery UI Datepicker widget to select multiple dates?

All help is appreciated! If its not posable to use the jquery UI datepicker then is there something similar that does?

Get by condition column values

I have following dataframe:

   A      B
0  1      5
1  2      3
2  3      2
3  4      0
4  5      1

How I can get by condition values of column A ?

For example all values that great then 3 and less then 6.

Difference between exit(0) and exit(1) in Python

What's the difference between exit(0) and exit(1) in Python?

I tried looking around but didn't find a specific question on these lines. If it's already been answered, a link would be sufficient.

Remove pre heades from csv before using DictReader - Python

Hi I have csv file like this here is some text some more text summary id score 1 33 2 22 3 11 detail id try score 1 1 22 1 2 11 2 1 10 2 2 12 3 1 11 I want to parse the data id, try, score which comes after detail to DictReader How can I do that?

Jquery Datatable Pagination : Listbox combine with Full numbers

I want to display listbox along with full numbers pagination ? anyone have idea how to combine both of them

Attached Image - for pagination

Starting jupyter notebook programmatically from another notebook

Is it possible to start another notebook from the current notebook? I know how to create and save the current notebook but I cannot launch another notebook from the current one. %run does not work while starting another notebook

Make footer menu collapse to dropdowns

Hostgator has a great way of making the footer collapse and only show the headers with accordion type dropdown for the links below it, when it's in mobile mode. How can I achieve the same?

Thanks Anton

When running a python script in IDLE, is there a way to pass in command line arguments (args)?

I'm testing some python code that parses command line input. Is there a way to pass this input in through IDLE? Currently I'm saving in the IDLE editor and running from a command prompt.

I'm running Windows.

What are the parameters sent to .fail in jQuery?

I can’t find the documentation on what the names of the three parameters are when $.ajax fails.

Right now, I’m just using:

.fail(function(A, B, C) {

How to turn a string into a dict in Python

I have a string

"{a:'b', c:'d',e:''}"

What would be the most convenient way to make it to a dictionary

{'a':'b', 'c':'d', 'e':''}

jQuery equivalent of MooTools' Scroll().toElementCenter()

I am adapting someone else's script to my site. The use MooTools; I use jQuery. Their code has the following line:

new FX.Scroll(window).toElementCenter('obj');

How would I do this in jQuery?

Python skip block of code if it take more then 2 second

I am new to python and I would like to ask if there is a way to skip a line of code in a python script if that line take more then a given time (like for 2 second) ? Thank you very much !

mardi 2 août 2016

How I can check whether a page is loaded completely or not in web driver?

I am writing some Java Webdriver code to automate my application. How can I correctly check whether the page has been loaded or not? The application has some Ajax calls, too.

I have declared an implicit wait for WebDriver.

python: IOError: [Errno 36] File name too long:

I want to create a file within tmpfs (under CentOS 6.5) like this: fpath = '/tmpfs_mounted/with/long/file/name' with open(fpath, 'w') as fd: write(somedata) ... But I got the IOError: [Errno 36] File name too long: ... error, How to fix it?

Given a python whl package, is it possible to retrieve it's development status information?

So I have a python .whl package, and I want to get the development status (dev, beta, release etc.) of it, is it possible to do that without scanning and parsing the setup.py file and only with the given package?

Get user input until Enter key is pressed twice

I want to get user input multiple times and store the input data together in a string until the user presses Enter twice. I think a for loop can work, but I don't know how to do it.

Specifying vertex position via coordinates in python graph-tool

Is it possible to plot a vertex at a particular position on the xy-axis by specifying coordinates? I want to have a square lattice of vertices without the edges between them (and then add edges later as I see fit).

Thanks

Micro:bit import songs? [Python]

Would it be possible to import songs from my desktop and play them on my micro:bit? I have configured my speakers for it and they work - but could it play actual songs? If so, how would I go about doing it?

How to find particular column unique values count in python pandas?

I have following dataframe.,

company,sector,marks
a,b1,21
b,b2,27
c,b2,20
a,b3,70

I have to display no of company,sector and sum of marks how do we take unique column value length in pandas

How to add image as watermark in microsoft document using Java?

Image Link

I have added watermark image in this document manually. Is there any way to add image as watermark in Microsoft document using Java or JavaScript(jquery) programming language ?

How do I show a constantly changing variable in python?

New to python. I have a variable called 'score' which changes constantly throughout the running of the program. Is there a way to show the variable at all times in a window/place so that the user can see their score changing? Thanks!

Host a Python based Websocket server

I am looking to host a basic Websocket server.

The code I want to see running is : FastFlicker

Do you know how and where I can host this application online?

How is list += implemented in Python?

What is its time and space complexity?

I haven't been able to find an authoritative answer elsewhere on the web.

Also, not sure why, but StackOverflow won't let me post this question until I write more text in this box.

How can one load an AppEngine cloud storage backup to a local development server?

I'm experimenting with the Google cloud storage backup feature for an application.

After downloading the backup files using gsutil, how can they be loaded into a local development server?

Is there a parser available for these formats (eg, protocol buffers)?

How to On webcam on page load in jquery webcam

I am using Jquery-Webcam-Plugin to capture Images. But every time when I load the page I have to click on "Allow" button of Flash file to start the webcam. I want to on camera on page load without clicking any button. How can I do it ?

how to get equation for nonlinear mutivariate regression in which one variable is dependent on other two independent variables in python

I have set of 5000 data points of like_so_ (x,y,z) for eg (0,1,50) where x=1,y=2,z=120.with help of these 5000 enteries,i have to get an equation in
which given x and y ,equation should be able to get value of z

How do I draw a grid onto a plot in Python?

I just finished writing code to make a plot using pylab in Python and now I would like to superimpose a grid of 10x10 onto the scatter plot. How do I do that?

How to resize image using Cropit js

Hi I am using cropit js library for image manipulation. I have new zoomed height and width of the image so i want to resize the image using cropit js to new height and width. enter image description here Could anybody help on how to do this?

The ouput of the code is 3. Can someone explain how?

def my_fun(x):     
    z = 0     
    for item in x:         
       m = x.count(item)         
       if m > z:             
           z = m     
       return z  

y = ["cat", 4, "dog" , "cat" , 2, "cat", 2] 
print (my_fun(y))

The ouput of the code is 3. Can someone explain how?

Adding a meta tag via jquery?

I need to add this meta-tag in the head section of the page as i need the page to force IE7.

<meta http-equiv="X-UA-Compatible" content="IE=EmulateIE7" />

I am using DNN 5.6

How can i do this?

Removing specific matching substring from a string python

I want to remove a matching substring from a string in python .

Here is what I have tried so far:

abc= "20160622125255102D87Z2"

if "Z2" in abc:
    abc.rstrip("Z2")
    print(abc)

But this doesn't work. Kindly help

Nagios alert over phone call

Does anyone has idea how can get Nagios alert over phone call using Python or any other method? Please share with me.

But except Pager-Duty which we are already using so am planning to create an alternate of PD.

Thanks in advance

Add space after first character of a string

I want to add a space to the first character of a string using jquery.

For example, I have a number "92030" and I want to replace it with "9 2030"

Is there a simple way to do it with jquery ?

Why is Spyder so slow in OS X? Is there a way to make it faster?

I have Spyder installed as part of the Anaconda Python analytics package and I'm finding the editor to be very slow. There's always a half-second lag time between key presses and the letter showing up on screen. I'm using Spyder on a fairly new i7 MacBook.

Why is this regex matching taking forever?

I'm trying to query html using the request python module and this is taking forever:

ad = re.findall(r'([^>]+)><a class=" td-n"([^>]+)>', str(soup_url))

Why is that so and how can I optimize this?

Why do I keep getting this invalid syntax error? [on hold]

def both_positive(x, y):
"""
Returns True if both x and y are positive.
>>> both_positive(-1, 1)
False
>>> both_positive(1, 1)
True
"""
If x > 0 and y > 0:
    Return True
Else:
     Return False 

What am I doing wrong?

lundi 1 août 2016

from Nondeterministic finite automaton-lambda to Deterministic finite automaton

How do I code a program that receives a NFA-l and throws the equivalent DFA in a .txt. I need to make this in Python, and I have no idea what to do. I can't implement the algorythm, because I have no clue how. Pls send help

Movement between Images in Gallery with Next & Prev Buttons

i have how many images in gallery.i would like to implement a previous and next button that i can movement between images. i have found this simple but it doesn't work(accepted answer). please you try. ٍsimple link

Open source alternative to MATLAB's InterX function?

Is there an open-source alternative to MATLAB's InterX function for intersection of curves? I'm rewriting a MATLAB program to use Python and this is the only function I haven't found an equivalent to. I know the function " Python curves intersection with fsolve() ". Is it similar to InterX in MATLAB

Retrieve data from jQuery Object

I am having problems with my jQuery object which I recieve from Ajax function.

console.log(data) ==> dumps {"isUnique":true}

and

console.log(data.isUnique) ==> dumps undefined

How should I get these "isUnique" data?

python beautifulsoup : lxml html.parser

I must use beautifulsoup, but i don't know which parser I have to take. I hesitate between lxml and html.parser, or why not both. How to know if a web page is lxml compliant ? How to know if a web page is html parser compliant ? Many thanks

How to debug a python function in ipython?

I have a python function, for example:

def fun():    
    a = 1.0
    b = a*2+1
    return b

But I want to debug it in ipython, so I want to watch all the variable a and b, like a global variable, how can I do this?

I don't know how to use vivus.js [on hold]

I am very new to web design.

I wanted to use vivus.js plugin animation for my svg, but i can't seem to make it work. i have added the vivus script in my svg code as well. can anybody help me with the code? thank you

Fetch entire set of twitter user IDs from accounts created at given date?

Cant find method from REST and streaming API docs for fetching entire set of user IDs from accounts created at a given date. Similar question asked here at twittercommunity in 2014 but still unanswered...

Sorry for bad english.

How to redirect urls using django on a raspberry pi hotspot network?

I have a raspberry pi hotspot running with internet shared through ethernet. I also have django installed and running with a basic application. I want to use django to redirect any http request to a different url based on the previous url. How can I go about doing this?

Anything slider Delay Appearance

I am trying to use the AnythingSlider to play two songs. I want the arrows to be disabled for 30 seconds so that you have to listen for 30 seconds before you can go to the next song. Does anyone know how to put a delay on the Anything Slider options?

Is there an "exists" function for jQuery?

How can I check the existence of an element in jQuery?

The current code that I have is this:

if ($(selector).length>0) {
    // Do something
}

Is there is a more elegant way to approach this? Perhaps a plugin or a function?

I am getting a syntax error when trying to lock a label in ClearCase in a python script

I am new to python and I am trying to execute a cleartool lock command.

Here is my code:

 def lock_label(lname):
        os.system('cleartool lock lbtype:' + lname'@vob:/cm_data/jupsw')

lname is my variable name

plotting from a data frame in pandas

Please I'm new to pandas and want to obtain a multiple time series plot with the dataframe below using TIMESTAMP as index.

TIMESTAMP shf_1 shf_2 shf_3 2016-06-18 09:20:00 24.98201 40.98293 18.75554 2016-06-18 09:25:00 24.59746 37.85617 18.11409 2016-06-18 09:30:00 24.93322 40.07658 20.18585 2016-06-18 09:35:00 25.79265 40.91981 21.60389 2016-06-18 09:40:00 26.49355 45.02221 23.86291 2016-06-18 09:45:00 25.65839 42.93957 23.56091 2016-06-18 09:50:00 28.22184 47.68266 25.76584 2016-06-18 09:55:00 28.68465 49.86813 26.68878 2016-06-18 10:00:00 25.28899 48.88993 26.958 2016-06-18 10:05:00 22.24257 43.74584 24.88566 2016-06-18 10:10:00 21.02077 39.90298 23.48933

How to stem a list of 1000 documents in python using PorterStemmer?

I am recently doing project in nlp using python. Where I need to preprocess a excel file which contains text with many row and column. I could became able to stem only simple sentence only. And couldn't able to stem whole excel file at once. How can I do that?

How to find the sum of an array of numbers

Given an array [1, 2, 3, 4], how can I find the sum of its elements? (In this case, the sum would be 10.)

I thought $.each might be useful, but I'm not sure how to implement it.

Problems with pip (python 2.7)

I am trying to install pandas library and have a problem with pip (the picture below). I`ve changed the name of computer (login, main directory) but nothing have changed.

UnicodeDecodeError: "ascii" codec can`t decode byte 0Xd2 in position 0: ordinal not in range <128> 

How to find number of vowels in each word of string using python

s=input("Enter a sentence: ")

emp = "" vow=0 for i in s: if i.isspace() == False: emp = emp+i else: for j in emp: if j in 'aeiouAEIOU': vow=vow+1 print("The number of vowels in",emp,"are",vow) emp = "" it only gives vowels for first word.

Python: How to read data from webpage and then write back from database?

I am a beginner. I want to read two inputs (probably from a slide down menu) from a web page and use them as variables to execute python program, then return the result to a database and also display it on the webpage. I`m using mySQL for database management.

jQuery popup min and max width/height

If I set the popup minWidth to 440 px (example), will the width automatically grow with the content? Do I have to write extra code to make it dynamically growing?

dialogDiv.dialog({
        title: "Confirm Delete",
        autoOpen: false,
        modal: true,
        draggable: false,
        resizable: false,
        closeOnEscape: false,
        minWidth: 440,
        minHeight:220,

I have written two separate files, one containing classes and the other calling them but calling one makes object of all. Why?

separate.py

    class foo():
       print 'a bunch of time consuming work'

    class tryme():
       print 'try me'*

main.py

from separate import *

foo()

It however printed both:

a bunch of time consuming work
try me

How can i write to a specific memory address using python?

I'm working in python in ubuntu. I have an object named packet which I don't have access to its fields. I want to somehow get its address in memory and write to an offset of that address. something like (in c): address=&packet address+=offset *address=0

any suggestions?

How to append variables to a string inside for loop in python?

I am trying to append variable inside for loop (cname[0].decode('utf-8')). In php we could do like this :

TotalData .= ",".$cname[0];

How we could achieve same thing using python ?(ouput be 1,2,3,,4)

for cname in match:
         TotalData .= ","+cname[0].decode('utf-8');

print TotalData

is it possible to use .stopPropagation() on .trigger() function?

How can I use the .trigger()-event together with .stopPropagation() ? I need to simulate a submit event without triggering the submit event.

$('.form .submit').trigger('click', function (e) {
    e.stopPropagation();
});

does not work. Is there any way to achieve this?

how to open chrome in incognito mode from Python

This works, in powershell:

Start-Process chrome.exe -ArgumentList @( '-incognito', 'www.foo.com' )

How can this be achieved from Python?

EDIT: Like this!

import subprocess
subprocess.Popen(["C:Program Files (x86)GoogleChromeApplicationchrome.exe", "-incognito", "www.google.com"])

dimanche 31 juillet 2016

How to send automatic email notification by checking with date in odoo

I have a calendar module there I have fields like start date and end date. I want to sent an email if the current date is more that end date of calendar to attendees of calendar module i.e calendar.event. Any ideas how this can be done?

Python: Given a link, how to save locally if the link is an image and do not save if it is not an image?

I am currently using

import urllib

urllib.urlretrieve("http://www.digimouth.com/news/media/2011/09/google-logo.jpg", "local-filename.jpg")

Is there a way to see if the link contains a pic or not, if not then no need to download, if so, then download.

Thanks!

How to Python prettyprint a JSON file

I have a JSON file that is a mess that I want to prettyprint-- what's the easiest way to do this in python? I know PrettyPrint takes an "object", which I think can be a file, but I don't know how to pass a file in-- just using the filename doesn't work.

Find the maximum sum of list values in dictionary

I need help trying to find the student who has the highest total scores.

s1= {'A': [100, 95, 100], 'B': [100, 100, 100], 'C': [95, 95, 80], 'D': [100, 100, 80]}
def wrtd2():
  for k, v in s1.iteritems():
     total = 0
     for i in v:
      total = total + i
     print total

wrtd2()

But it is printing the total for all students.

How to compare one employee to all employees salary in django model?

emp = Employee.objects.filter(id=1)

Persons =  Employee.objects.extra(select={'difference':(emp.values_list("Salary",flat=True)[0]-float('Salary'))})

But it give Error :

Exception Type: ValueError

Exception Value:could not convert string to float: 'Salary'.

How can i solve this Error.

How can I tell whether my Django application is running on development server or not?

How can I be certain that my application is running on development server or not? I suppose I could check value of settings.DEBUG and assume if DEBUG is True then it's running on development server, but I'd prefer to know for sure than relying on convention.

Find numpy array values bounding an input value

I have a value, say 2016 and a numpy array: [2005, 2010, 2015, 2020, 2025, 2030]. What is the pythonic way to find the 2 values in the array that bound 2016. In this case, the answer will be an array [2015, 2020].

Not sure how to do it other than loop, but hoping for a more numpy based solution

How to read a binary file of type complex64 values in Python

I have a binary file that contains several complex numbers of type complex64? (i.e. four bytes of type float for the real part and another four bytes for the imaginary part). The real and imaginary parts are multiplexed so that the real part is stored first and followed by the imaginary part.

Jquery Append or Insert Text After Specific Words

How to append word "THIRD" after these two words "FIRST SECOND" but before word "FOURTH".

This appends after "FOURTH": https://jsfiddle.net/bagn96ee/

<p id="para">FIRST SECOND FOURTH</p>
$('#para').append('THIRD');

how to avoid simple quote in MySQLdb python

How to avoid simple quotes when I pass two variables into the query

import sys

first_arg = sys.argv[1]
second_arg = sys.argv[2]



with con:
        def alter (var1=first_arg, var2=second_arg):
                cur = con.cursor()
                cur.execute("alter table joinit ALTER s SET DEFAULT 'TEST', ALGORITHM = %s, LOCK = %s", (var1,var2))

E-mail my g-mail contacts with python

Is it possible to have a python script which uses my already logged in gmail(via chrome) to send an email to all of my contacts? And also is it be possible to attach a file to the email?

I wouldn't be surprised if this isn't possible but I thought I would ask anyway.

How to organize a relatively large Flask application?

I'm building my first Flask app and I can't figure out a good, clean Pythonic way of organizing my application. I don't want to have everything in a single .py file as in their example. I would like to have each part of my app in a separate module. What would be a good way to organize things?

How can I get a parent window's height from within iFrame using jQuery?

Within an iFrame, we need to get the parent's window/document height.

Is there a way to get this using jQuery?

I know we can use $(document).height() to get a page's height. I just can't figure out how to get the parent's value from within the iFrame.

Please help!

Are there default icons in PyQt/PySide?

I'm reading a tutorial on PySide and I was thinking , do I need to find my own icons for every thing or is there some way to use some built in icons . That way I wouldn't need to find an entire new set of icons if I want my little gui to run on another desktop environment .

how can i make click enabled at owl-carousel slider?

enter image description here

I customize jQuery owl-carousel and make this slider.Now i want to add another options. The option is when I clicked any images then it have to go center.

Get value from jquery object

I want to get value of description from jQuery object. my object something like this. enter image description here

I am using JSON.parse but with this, I am getting undefined.

what's the typeof(jQuery)

i just tried this code console.log(typeof(jQuery)) <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.1/jquery.min.js"></script> It alerts function, which means the typeof jQuery is function. My question is, what's the exact type of jQuery? If it's function, how come it has properties like jQuery.browser and jQuery.ajax?

Fixed seed random number between 0 and 1

I want to generate list of fixed random numbers by giving a seed between 0 and 1 in python. For example, l = [0.1, 0.5, 0.6, 0.9, 0.75]. I can get this by using random.random(). But every time it gives a new random number list. I want to fix it by giving some some seed.

How can I do that. Thanks in advance!

matplotlib 2D slice of 3D data

I haven't been able to find anything on this, maybe because I don't have the right nomenclature (i.e. I don't know exactly how to ask for it), but anyway, I have a 3D numpy array "a". I would like to identify and plot the 2D surface where a=0. Does matplotlib have a ready-made routine for doing this?

TD/IDF in scikit-learn

Is there a complete Python 2.7 example about how to use TfidfTransformer (http://scikit-learn.org/stable/modules/feature_extraction.html) to generate TF/IDF for n-grams for a corpus? Look around scikit-learn pages and it only have code snippet (not complete samples).

regards, Lin

Disable Esc close for colorbox

I'm using the colorbox plugin for jQuery.

I know I don't have to have a close button, and overlayClose: false will prevent the window from being closed by clicking the overlay.

Is there a way to remove the Esc key-listener event?

Trying to assign values to keys in dictionary gives type error

dict["north-west"]=(south+width_NS,west) TypeError: 'type' object does not support item assignment class Building: def __init__(self, south, west, width_WE, width_NS, height=10): keys=("north-west","north-east","south-west","south-east") dict.fromkeys(keys) dict['north-west']=(south+width_NS,west) dict["north-east"]=(south+width_NS,west+width_WE) dict["south-west"]=(south,west) dict["south-east"]=(south,west+width_WE) self.corners=dict

JQuery and JavaScript methods

In majority of JavaScript method(iterator) callback first argument is element and second is index. But in case of jQuery always second argument is element and first one is index. Why they formatted differently? Is that for avoiding confusion between them, since both contains methods like map, filter, etc. Is there any special meaning behind that? I'm just curious to know.

In getorgchart jquery plugin how to remove the getorgchart hyperlink present at the bottom of the screen

I am trying to use getorgchart jquery plugin. And I want to remove the 'GetOrgChart' hyprlink which is showing in the bottom of the screen. I have tried removing it from getorgchart.js file but it is still showing up. Is it part of the theme? How Can I stop showig it on my webpage???

Please help..

samedi 30 juillet 2016

What is the difference between "window.location.href" and "window.location.hash"?

I learned "window.location.hash" new and tried in my jquery code instead of "window.location.href" and both of them gave same results.

Code is here :

window.location.href = ($(e.currentTarget).attr("href"));
window.location.hash = ($(e.currentTarget).attr("href"));

What is the difference between them?

Form a big 2d array from multiple smaller 2d arrays

The question is the inverse of this question. I'm looking for a generic method to from the original big array from small arrays:

array([[[ 0,  1,  2],
        [ 6,  7,  8]],    
       [[ 3,  4,  5],
        [ 9, 10, 11]], 
       [[12, 13, 14],
        [18, 19, 20]],    
       [[15, 16, 17],
        [21, 22, 23]]])

->

array([[ 0,  1,  2,  3,  4,  5],
       [ 6,  7,  8,  9, 10, 11],
       [12, 13, 14, 15, 16, 17],
       [18, 19, 20, 21, 22, 23]])

I am currently developing a solution, will post it when it's done, would however like to see other (better) ways.

unpack tuple containing datetime

I have a function f(date, level), I want to unpack arguments from a numpy.record or a tuple

print(tuple(row))
(datetime.datetime(2016, 6, 17, 18, 57, 00), 123)

but

print(*tuple(row))
2016-06-17 18:57:00 123

which is 3 arguments to my function, so error.
how to keep first tuple element as datetime object ?

Can jQuery nextUntil perform my function

I can do this

        $("#id")
            .closest("div")
            .nextUntil("div.stop-class")
            .addClass("new-class");

What I want to do is this

        $("#id")
            .closest("div")
            .nextUntil("div.stop-class")
            .myFunction(someParameter);

I can extend jQuery, but is there another way?

Unsupported operands for range and float, what am I doing wrong?

I'm trying to pass a range of numbers to a function and have that function then give me an array of numbers back. This is my code and the error I've received. I'm brand new to python, so this might be a silly question. This is my snippet of code

How to create multiple mysql tables with MySQLdb in python?

This is what i am trying to do:

cursor.execute("CREATE DATABASE testing")
cursor.execute("USE testing")
cursor.execute("CREATE TABLE Contract(mEnd varchar(7))")    
cursor.execute("CREATE TABLE User(uName varchar(15)")

When I run the python script using MySQLdb it only creates the first table and it ignores all the other lines of code.

can't get rid of 1e-5 while formatting in python 3 programming

I am creating a length calculator and need to format it so it doesn't show 1e-5 from going to mm to km. i have tried '{:.6}'.format() but doesn't seem to work as still outputs it as 1e-5.

Any help on what to do to get rid of this?

Key bindings for interrupt execution in Python Sublime REPL

I'm using REPL extension for Sublime text 3 for my python projects. Currently when I want to interrupt a running script I have to close to close the REPL window to stop execution and all computations are so far are lost. I was wondering if anybody knows how to interrupt an execution and have a short cut or key bindings for that

how to save a scikit-learn pipline with keras regressor inside to disk?

I have a scikit-learn pipline with kerasRegressor in it: estimators = [ ('standardize', StandardScaler()), ('mlp', KerasRegressor(build_fn=baseline_model, nb_epoch=5, batch_size=1000, verbose=1)) ] pipeline = Pipeline(estimators) After, training the pipline, I am trying to save to disk using joblib... joblib.dump(pipeline, filename , compress=9) But I am getting an error: RuntimeError: maximum recursion depth exceeded How would you save the pipeline to disk?

How to increment a numeric string by +1 with Javascript/jQuery

I have the following variable: pageID = 7 I'd like to increment this number on a link: $('#arrowRight').attr('href', 'page.html?='+pageID); So this outputs 7, I'd like to append the link to say 8. But if I add +1: $('#arrowRight').attr('href', 'page.html?='+pageID+1); I get the following output: 1.html?=71 instead of 8. How can I increment this number to be pageID+1?

New to flask and Flask-Login - ImportError: No module named login

It appears that installation of flask-login has issues. Despite a successful install using the below

 pip install flask-login

My app.py file:

 from flaskext.login import LoginManager
 lm = LoginManager()

I get this error :

ImportError: No module named login

So how do I resolve

Indexing one array by another in numpy

Suppose I have a matrix A with some arbitrary values:

array([[ 2, 4, 5, 3],
       [ 1, 6, 8, 9],
       [ 8, 7, 0, 2]])

And a matrix B which contains indices of elements in A:

array([[0, 0, 1, 2],
       [0, 3, 2, 1],
       [3, 2, 1, 0]])

How do I select values from A pointed by B, i.e.:

A[B] = [[2, 2, 4, 5],
        [1, 9, 8, 6],
        [2, 0, 7, 8]]

How do I create sub arrays from a JSON object

I have a JSON object as show here:

[
{
    "ID": "1",
    "Country": "India",
    "Value1": "100",
    "Value2": "200"
},
{
    "ID": "2",
    "Country": "China",
    "Value1": "230",
    "Value2": "800"
}
]

This is the result that I am looking for:

[
        ['India', 100],
        ['China', 230],
    ]

I tried using Jquery $.map function but was unable to get what exactly I wanted. Any pointers would be appreciated.

Prevent ipython from storing outputs in Out variable

I'm currently working with pandas and ipython. Since pandas dataframes are copied when you perform operations with it, my memory usage increases by 500 mb with every cell. I believe it's because the data gets stored in the Out variable, since this doesn't happen with the default python interpreter.

How do I disable the Out variable?

replace semicolon by newline in python code

I would like to parse Python codes that contain semicolons ; for separating commands and produce code that replaces those by newlines n. E.g., from

def main():
    a = "a;b"; return a

I'd like to produce

def main():
    a = "a;b"
    return a

Any hints?

Close popup with key Esc

I try to close popup when I press Esc but it only works while video isn't on play.

$(document).bind('keydown', function (e) {
    if(e.which === 27){
        $('#youmax-video-lightbox').attr('src', '');
        $('#youmax-lightbox').hide();
    }
});

U can see in: http://www.vigerm.com/videos

How to create a navigation bar which on hover, slidedown the entire length size of navigation bar and has other options? As shown in the pictures

Click here to see the image that shows what a want to accomplish

As shown in the pictures.

Click here to see the image that shows what a want to accomplish

Bootstrap data-toggle="toggle" checked,unchecked by jquery

I'm using bootstrap checkbox with data-toggle="toggle" attribute. I want to set it checked and unchecked with jquery. I tried many ways but it didn't work. Here is my code. <input type="checkbox" data-toggle="toggle" data-size="small" id="checkbox1"> for button click: $("#checkbox").attr('checked',true); But it's working when I remove data-toggle="toggle" attribute. Any help is greatly appreciated! Thanks.

Disable focus outside the page

I'm making a web-page based application which would have keyboard (a joystick) only navigation. I use tabindex, but I also need to disable focus on the address bar, search bar or anything else outside the page.

This app would be run only on one specific device, so it's okay (actually needed) to disable some functionality.

Is it possible?

How to translate entire .txt file using Google Translate API in Python?

I am trying to translate an entire .txt file using Google Translate API in Python.

The default code is:

print(service.translations().list(source='zh',
                                  target='en',
                                  q=['上海熙缘节能环保科技服务有限公司',
                                     '广东宏德科技物业有限公司']).execute())

if __name__ == '__main__':
    main()

How can I modify this code so it can translate a .txt file?

Pass info from plot to function

I want to write interactive simulation using graph-tool. What I would like to do is first to visualize the graph, then pick nodes as an input for later actual simulation. How do I pass information from plot to function?

What I did so far - I looked through documentation and examples which do not provide such info.

Thanks!

convert sql from multiple tables with subquery IN to django orm.

How can I convert this sql to django orm? Effectively.

select * from friend where party_id IN(select party_id from party where venue=venue123)


class Friend(models.Model):
    party = models.ForeignKey(Party, related_name='partyid')


class Party(models.Model):
    venue = models.ForeignKey(Venue, related_name='venueid')


class Venue(models.Model):
    venue_name = models.CharField(max_length=33, default='')

add variable to PATH when activateing conda virtual env

assume you want to add/remove a variable to your PATH variable whenever you (de)activate a virtual environment in conda.

I'm working with PyQt5 and by default it doesn't recognize pyuic5 as a command. So I would want to add the location of this command to the PATH env. variable, but only for the time the virtual env. is activated.

Change text (html) with .animate

I am trying to animate the html part of a tag ( <font id="test" size="7">This Text!</font> ) using jQuery's Animate function, like so:

$("#test").delay(1500).animate({text:'The text has now changed!'},500);

However nothing happens, it does not change the text.

How can I do this? Thanks!

vendredi 29 juillet 2016

Python palindrome code not working

I just write a program for checking palindrome in python. I don't know why it is not working. Any help will be greatly appreciated.

def palindrome(word):
    rev_palindrome = []
    for i in word[::-1]:
        rev_palindrome.append(i)
        " ".join(rev_palindrome)
    if word == rev_palindrome:
        print "It is a palindrome"
    else:
        print "It is not a palindrome"
palindrome(mom)

How to make all AJAX calls sequential?

I use jQuery. And I don't want parallel AJAX calls on my application, each call must wait the previous before starting. How to implement it? There is any helper?

UPDATE If there is any synchronous version of the XMLHttpRequest or jQuery.post I would like to know. But sequential != synchronous, and I would like an asynchronous and sequential solution.

gender input loop keeps repeating even if I enter "m" or "f"

If it's not m or f, repeat prompt until it's either or. I typed m or f, but the loop keeps repeating. Why?

gender = input('m/f? ')

while gender != 'm' or gender != 'f': 
    print("Type 'm' or 'f'") 
    gender = input('m/f? ') 
if gender == 'm': 
    gender = 'him' 
elif gender == 'f': 
    gender = 'her' 

print("It read {}".format(gender))

Set border using Python xlwings

Is there a way to set border lines for an Excel file from Python using xlwings? I was looking at the documentation but cannot figure out.

I want to create a file like this using xlwings enter image description here

Data undefined in a library initialisation Javascript

I use dropzone library, when I load the page the item-id attribute is null, but after a click get a new value but in the initialisation remains null. How can I update the value in dropzone initialisation?

    $("div#client_documents").dropzone({
        url: '/clients/' + $('#rootwizard').attr('item-id') + '/documentsUpload', // $('#rootwizard').attr('item-id') is null 
        maxFilesize: 20,
        paramName: 'file',

     ...................

Parsing html for specific script type

In the html code, Vine has <script type="application/ld+json"> with links to all the videos on the page, how would I got about accessing this JSON?

import requests
from bs4 import BeautifulSoup

url = 'https://vine.co/tags/funny'
source_code = requests.get(url)
plain_text = source_code.text
soup = BeautifulSoup(plain_text, 'html.parser')

Python Saving long string in text file

I have a long string that I want to save in a text file with the code:

taxtfile.write(a)

but because the string is to long its save it like it print it as:

"something something ..... something something"   

how do I make sure it will save the entire string without truncating it ?

Add a prefix to all Flask routes

I have a prefix that I want to add to every route. Right now I add a constant to the route at every definition. Is there a way to do this automatically?

PREFIX = "/abc/123"

@app.route(PREFIX + "/")
def index_page():
  return "This is a website about burritos"

@app.route(PREFIX + "/about")
def about_page():
  return "This is a website about burritos"

List of pairs, find those who are not

I read a list of pairs in the filesystem (Linux)... UniqueDocument.xml UniqueDocument.pdf

I need to find the entries that does not have a xml file, then I need to fetch it.

Been trying with os.list and regex but havent found a sutible solution and Dir() in Ruby. But I cant get to the end... my mind blocks me.

What does PuLP LpStatus=Undefined actually mean?

When I add a particular constraint to my problem, the LpStatus of the problem after solving changes to "Undefined" (without this constraint, it was "Optimal"). At the top of this page, the possibilities of the return status are shown, but it doesn't seem to explain what they mean. Can anyone explain what an "undefined" status means? It it something like a syntax error in specifying the constraint?

saving list values when terminating

I am doing some test, running time functions and appending values to a list.

I am not really sure what to receive. I am thinking to cancel shell over some time, however I would like to see what values were appended to a list. Is there any pythonic way to do this? Or is it really best to save data to some txt file?

Jquery css transform scale centered

Hello guys i've got this code:

(jQuery)

$("#chart1").css({transform:'scale(1,10)'})

with this css code

#chart1{
    position:absolute; 
    bottom:0px;

    width:166px;
    height:10px;

    background-color:purple;
}

It works actually very good, but it scales the hight from the middle. And i want it to scale from the bottom to the top.

Jquery Bootstrap version conflict

Previously I have used bootstrap for opening a pop up and it was working fine but now I am trying to implement Grid.Mvc and for this I need to install Bootstrap version 3.x.x When I did this I got following exception on page inspector on my pop up page

Bootstrap's JavaScript requires jQuery version 1.9.1 or higher, but lower than version 3

Parse XML file python

I have an XML file (made with ONIXEDIT) with doctype :

<!DOCTYPE ONIXMessage SYSTEM "http://www.editeur.org/onix/2.1/reference/onix-international.dtd>

the file contains XHTML entities, when i try to parse using xml.etree.ElementTree, it gives this error :

xml.etree.ElementTree.ParseError: undefined entity &nbsp;

How can i solve this ?

On Icon Hover Draw Icon

I'm trying to create this Icon Animate effect for my personal work. As they are using images to draw icon on hover. Any other trick to use this one. Please advise

Live Working Link

http://puu.sh/pAksc/8c81c44718.png

Python2.7 Read a file and use it for if in

So what I'm trying to do is use the below code to read a .txt file, and then use that in a if in statement. window is event.WindowName from pyHook.

try:
    with open("log.txt") as f:
        data = f.read().split()
except:
    print "Failed.1"
try:
    if data in window:
        #do stuff

It prints the data as ['foo', 'bar']... Any ideas?

what is d braceopening 4 braceclosing in python?

I am learning python and views in Django. What represents this d in the following code url(r'^articles/(?Pd{4})/(?Pd{2})/$','list_articles'), # views for year and months

I think it 's d4 for 2016 for example and d2 for 06 , but what is the d with those braces. Thanks.

ps : sorry for the title, it was not accepting the { and } characters

jQuery bvalidator Phone Number Validation

I'm using bValidator for form validation. Form fields are generated dynamically from a json file and loaded into an angularJS view on the fly. I'm trying to validate a phone number input field using regex, I don't want user's to enter 9999999999 as phone number.Below is the regex expression data-bvalidator="number,required,regex[!(9999999999)]" I also tried data-bvalidator="number,required,regex[^(9999999999)]" and many others. But not getting the desired result

How can I show json data after select dropdown?

How can I show json data after select dropdown? I Get this json data.

{
"london": {
    "shop1": {
        "address": "address1",
        "phone": "0123456"
    },
    "shop2": {
        "address": "address2",
        "phone": "2223456"
    }
},
"liverpool": {
    "shop1": {
        "address": "address3",
        "phone": "3123456"
    },
    "shop2": {
        "address": "address4",
        "phone": "4223456"
    }
},
"manchester": {
    "shop1": {
        "address": "address5",
        "phone": "5123456"
    }}

I want to do like this

enter image description here

pandas DataFrame - find max between offset columns

Suppose I have a pandas dataframe given by import pandas as pd import numpy as np df = pd.DataFrame(np.random.randn(5,2)) df 0 1 0 0.264053 -1.225456 1 0.805492 -1.072943 2 0.142433 -0.469905 3 0.758322 0.804881 4 -0.281493 0.602433 I want to return a Series object with 4 rows, containing max(df[0,0], df[1,1]), max(df[1,0], df[2,1]), max(df[2,0], df[3,1]), max(df[3,0], df[4,1]). More generally, what is the best way to compare the max of column 0 and column 1 offset by n rows? Thanks.

Convert Arabic Characters (Eastern Arabic Numerals) to Arabic Numerals in Python

Some of our clients submit timestamps like ٢٠١٥-١٠-٠٣ ١٩:٠١:٤٣ which Google translates to "03/10/2015 19:01:43". Link here.

How can I achieve the same in Python?

Python intersection with custom equality

I want to build the intersection of two python sets, but i need to have a custom equality to do this. Is there a way to specify "equaliy" directly when doing the intersection? For example due to a lambda-expressions?

I know there is way by overriding eq, but i have to do several intersections on the same classes with different "equalities".

Thanks!

How do we know customer is logged or not

I am new to Volusion, I am planning to create menu like options sign in, create account etc. So here If customer logged in to website I need to change sign in as Log out and disable the Create Account option. if Logged out I need to revert sign in and create account in menu.

I don't know how to do this. If any answers Appreciate.

How to check/uncheck radio button on click?

I want to be able to uncheck a radio button by clicking on it.

So, if a radio button is unchecked, I want to check it, if it is checked, I want to uncheck it.

This does not work:

$('input[type=radio]:checked').click(function(){
    $(this).attr('checked', false);
});

I am not able to check a radio button now.

jeudi 28 juillet 2016

Restarting Interval not working after clearing

I am getting num1 and num2 value from service call. I am trying reset interval after clearing it but it does not work this way. I have also tried other ways mentioned in stackoverflow. Nothing works.

function func(){    
     if (num1 > num2 ) {
          console.log(" gt greater than lt");
          clearInterval(interval);
          flag = true;
          setInterval(func,1800000);
          $('.class').trigger('point');
          return;

        }
//do something
}

var interval = setInterval(func,10);

plotting a sequence results in: "ValueError: x and y must have same first dimension"

I'm a beginner here and I'm experiencing a problem when I'm trying to plot a sequence:

My code gives me this error message: "ValueError: x and y must have same first dimension"

hold(True)
x=[0.5]
for r in arange(2,4,0.1):
    for i in range(170):
        xn= x[-1]
        xnp1 = r*xn*(1-xn)
        x.append(xnp1)
        xa=array(x)   
        rplot=0*xa+r
plot (rplot, xn,".")
show()

How to make string interpreted as bytes?

Python 2 str compatable with bytes, but on Python 3 str is unicode.

I working on porting some project to Python3, but with support Python2.7. This prodject has tests with many string constants. Also there is few '...'.join(...) and '...'.format(...).

How to make Python3 to b'123' == '123' ?

Application shows error context out of request in flask in ibmqradar

I want to know the best practices used by the QRadar developers community to run the process in background. Like QRadar provides the SDK for building the apps which is in Python and used Flask Web application framework now I want to create an app that poll the data from the server and update the QRadar Reference sets. I come to know there are 3 options. Threads(which throws error ) flask-celery Crontab

framework7 load external jquery script

I am trying to load an external jquery script to my Framework7 app. I am using the following code which loads the javascript successfully, however it is currently just adding that JS code into my Div as HTML. How do I load the JS and also have it compile as JS?

myApp.onPageInit('about', function (page) {
  $$.get('js/sc-player.js', {}, function (data) {
    $$('#sc-js').html(data);
  });
});

How can i get a image related to a given Text

I am working on a project in Artificial Intelligence, Where I need to get Image Media related to a given Phrase. For example, if I give "Tiger Woods", it should give me Image of Tiger Woods golfer, and if I give "Tiger in Woods", it should give me an Image of a tiger in woods.

Any Script in python, or any link to a website would help me.

How to link element to slider move?

I downloaded one of the free sliders (http://flexslider.woothemes.com)

How can I slide an element outside the actual slider? is there any command to act as a short in slider but targeting the something outside the slider?

Please take look at attached image

Pygame inflate not working

So I'm making a game using python and I'm looking to make a rectangle grow.

I saw on the pygame website that you use the inflate method and saw a demo of it and tried it but it does not work.

Here is my code:

# defining statement
player = Rect(300, 100, 50, 50)
grow = player.inflate(100, 100)

# calling statement
if player.colliderect(food):
    foods.remove(food)
    grow

Fill the outside of contours OpenCV

I am trying to color in black the outside region of a contours using openCV and python language. Here is my code :

contours, hierarchy = cv2.findContours(copy.deepcopy(img_copy),cv2.RETR_TREE,cv2.CHAIN_APPROX_SIMPLE)
areas = [cv2.contourArea(c) for c in contours]
max_index = np.argmax(areas)
cnt=contours[max_index]
# how to fill of black the outside of the contours cnt please? `

Converting a log file into a csv file using Python

I have the following problem at work - I need to take a log file with items arranged as follows:

A1
B1
C1
A2
B2
C2
.
.
.
An
Bn
Cn

I need a complete csv file like so:

A1,B1,C1
A2,B2,C2
A3,B3,C3
...
An,Bn,Cn

How can I do this using a python script?

Making animations like those on apple web site

I want to make animations like those on apple web site:

http://www.apple.com/iphone/

or if above link is not working http://www.youtube.com/watch?v=05WEIWZvw2Q

Is there some productive framework (eg jquery plugin) dedicated to this kind of job?

How to set request.body in django Request factory post request?

trying to set request.body in python unit test as

        self.factory = RequestFactory()
        self.request = self.factory.get(reverse('get_associations'))
        self.request.user = self.auth_user
        self.request.body = json.dumps(self.post_data)

but it gives error:

self.request.body = json.dumps(self.post_data)
AttributeError: can't set attribute

can anybody help me to fix this?

can't understand python set operation

I can't understand a simply python code. Below, 'blobs' is a list of ndarray and 'end' is explained to be 'optional name of layer'.

   if end is not None:
        end_ind = list(self._layer_names).index(end)
        outputs = set([end] + blobs)     # <== this line.
    else:
        end_ind = len(self.layers) - 1
        outputs = set(self.outputs + blobs)

What does the statement 'set([end] + blobs) mean?

Jquery event not working

I've made this Jquery event and want to apply opacity on my button but it's not working.Please help!

<button type="button" id="btn-opacity" class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal">
  Sign-Up
</button>
button#btn-opacity {
    background-color: aqua;
    border: hidden;
}
$(document).ready(function() {
    $('#btn-opacity').mouseenter(function(event) {
        /* Act on the event */
        $(this).fadeTo('slow', 0.3);
    });
}); 

how to add content-type with $.post method in ajax call

Hi i want to add contentType:"application/json" to $.post method I don't want to use $.ajax as

$.ajax({
  url:url,
  type:"POST",
  data:data,
  contentType:"application/json",
  dataType:"json",
  success: function(){
    //success code
}

but I want to use $.post method

$.post(url,data,function(result){
    //success code
});

Please any one help me to specify contentType with $.post method

setState in $.get

Uncaught TypeError: undefined is not a function is throw when this.setState is use within the $.get scope, it works fine when I place the code outside the scope. How do you deal with it?

$.get(APIURL, function (data) {
   this.setState({resdata: "This is a new state"});
});

I'm not sure what is the best practice to replace JQuery AJAX to other small AJAX libraries. Please advice.

PIL - apply the same operation to every pixel

I create an image and fill the pixels:

img = Image.new( 'RGB', (2000,2000), "black") # create a new black image
pixels = img.load() # create the pixel map

for i in range(img.size[0]):    # for every pixel:
    for j in range(img.size[1]):
      #do some stuff that requires i and j as parameter

Can this be done more elegant (and may be faster, since theoretically the loops are parallelizable)?

Create a mapping from a file in awk or shell script or python

I have a file which contains airport code like below

ATQ 
HYD 
BLR
GOI 
AMD
CCJ
TRV

from the same file i have to create source destination mapping like below in gawk.

 src dest
 ATQ HYD
 ATQ BLR
 ATQ GOI
 ATQ AMD
 ATQ CCJ
 ATQ TRV
 HYD ATQ
 HYD BLR
 HYD AMD
 ....
 ...

can anyone help me here,thanks in advance

Bootstrap(2.3.2) modal popup visibility check

I need to insert a class name to body tag when the bootstrap pop up is opened. I have tried adding using jquery but unfortunately it is not working. Any help would be appreciated.

Here is my code

if(!$('.modal-backdrop').is(':visible'))
{
$(body).addClass("test");
}

Demo

Why do identical strings return false with ==?

This is the simplified version of my problem.

QA = open('Qestions and answers.txt')
Q = []
A = []

for line in QA:
  (first,second) = line.split(';')
   Q.append(first)
   A.append(second)

QA.close()

print(A[0], A[1])
print(A[0] == '1981')
print(A[1] == 'Feb')
print(str(A[0]) == '1981') # I even tried str
print(str(A[1]) == "Feb")

Output:

1981
 Feb

False
False
False
False

Rename Files in Python

I'm trying to rename some files in a directory using Python.

Say I have a file called CHEESE_CHEESE_TYPE.*** and want to remove CHEESE_ so my resulting filename would be CHEESE_TYPE

I'm trying to use the os.path.split but it's not working properly. I have also considered using string manipulations, but have not been successful with that either.

TensorFlow Setup Issue

I just setup TensorFlow on my MacBook Pro (El Capitan) and ran the installation test suggested on the website. This is what shows up:

hello = tf.constant('Hello, TensorFlow!')

sess = tf.Session()

print(sess.run(hello))

b'Hello, TensorFlow!'

Are the "b" and quotations around Hello, TensorFlow a result of something wrong done during installation?

Thanks!

How to change the background color of a coloumn in a jQuery DataTable?

Im new to jQuery and JavaScript, I want to change the background color of a specific column if the if statement is true.

$('#myTable').DataTable({
    "ajax": {
        "url": "/project/loadClientData",
        "type": "GET",
        "datatype": "json"
    },
    "columns" : 
    [
        { "data": "name", "autoWidth": true, "bSortable": true},
        {
            "data": "active", "autoWidth": true, "bSortable": true, "mRender": function (data, type, full, meta)
            {
                if (full.active == true) {
                    // i wanna make this cell background green.
                    return 'Ja';
                }   
                else {
                    return 'Nej';
                }
            }
        }
    ]
});

'Time to go offline' what is the best technologies to start? [on hold]

If I am familiar with 'angularjs','jQuery' and chrome features like push notifications and service worker.Is it necessary to use a framework or we can use native HTML5 and CSS3. The best way to get is with service worker a chrome features . Here are some questions that might help you to answer my question: What makes offline applications different from online application? What technologies are used for this approach? Does using framework increases efficiency?

mercredi 27 juillet 2016

html change text based on input field

I have an <h3> that I want the value of to change based on what is typed in the input field. Here is the code I currently have:

<input id="Medication" name="Medication" size="50" type="text" value="">
<script>
$(document).ready(function () {
  $('#Medication').change(function () {
    $('#myAnchor').text($(this).val());
  });
});
</script>
<h3 id="myAnchor"></h3>

Saving a key from a dictionary without value

I am representing a weighted graph as a dictionary where the key represents a vertex and the following lists, the links that are connecting the vertex (first number weight and second number linked vertex): wGraph = { 1 : [[2, 2],[3, 4],[3, 3]], 3 : [[3, 2],[5, 4],[7, 5]], 2 : [[2, 1],[4, 4],[3, 6]], 4 : [[3, 1],[4, 2],[1, 6],[5, 3]], 6 : [[3, 2],[1, 4],[8, 5]], 5 : [[7, 3],[8, 6],[9, 7]], 7 : [9, 5]} I would like to save a random key without its value from the dictionary to a list called visited. random_num = random.randrange(len(wGraph)) visited = [] How can I get the key from the dictionary according to the random number?

How to change the order of DataFrame columns?

I have the following DataFrame (df):

import numpy as np
import pandas as pd

df = pd.DataFrame(np.random.rand(10, 5))

I add more column(s) by assignment:

df['mean'] = df.mean(1)

How can I move the column mean to the front, i.e. set it as first column leaving the order of the other columns untouched?

set c# label visible by JQUERY

Is there any way to set asp label visible by Jquery?

I have a label like this:

<asp:Label runat="server" ID="lblCheckboxesError" Text="test" visible="false"></asp:Label>

and in *.js file a have this:

$("[id*=lblCheckboxesError]").show();

but nothing happened :( I have tried some next solutions, but nothings works for me :( any idea? thanks :)

Python pass more than one arguments to tcl proc using Tkinter tcl.eval

how to pass more than one arguments to tcl proc using Tkinter. i want to pass 3 args to tcl proc tableParser from python proc validate_op which has 3 args...

from Tkinter import Tcl
import os

tcl = Tcl()

def validate_op(fetch, header, value):
    tcl.eval('source tcl_proc.tcl') 
    tcl.eval('set op [tableParser $fetch $header $value]') <<<<< not working



proc tableParser { result_col args} {

  ..
..
..

}

Send ipynb to server and open it

I monitor a bunch of Python scripts each of them representing a trading strategy. In a database I store for each script the entire source code + results. I can convert my scripts into valid ipynb json documents (on the fly). Ideally I would like to send those documents to an existing Jupyter server (without going through saving them on disc). So is there a chance to post json documents to an Jupyter server? Thomas

Global variable in python function doesn't work for my code

This works.

a = [2,5,3,7,9,12]
def mean_list(x):
      b = 0
      for i in x:
            b=b+i
            c = b/len(x)
      return c
print(mean_list(a))

but this doesn't work, even though I have declared my list as global. Why?

def mean_list(x):
      global a
      a = [2,5,3,7,9,12]
      b = 0
      for i in x:
            b=b+i
            c = b/len(x)
      return c
print(mean_list(a))

Execute onclick of ESC Key

Briefly, my problem is that I would like to execute the effect of Esc button by a line of javascript, for example execute an effect onclick of the Esc button. How can I do It ?

[ What I have is an upload in a jQuery box, so I would like that when the upload will finish, the escape function will be executed automatically to close the box]

Why does "import ctask as task" fail in pyinvoke?

When I try to use ctask as defined in the getting started guide, it fails with the following error:

>>> from invoke import ctask as task
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ImportError: cannot import name task

What happened to the ctask module?

Lexicographic comparison of two numpy ndarrays

I couldn't find a straightforward way to compare two (multidimensional in my case) arrays the in a lexicographic way.

Ie.

a = [1,2,3,4]
b = [4,0,1,6]

For a < b I want to get true where I get [true, false, false, true]
For a > b I want to get false where I get [false, true, true, false]

Pandas - count if multiple conditions

Having a dataframe in python:

CASE    TYPE
1          A
1          A
1          A
2          A
2          B
3          B
3          B
3          B

how can I create a result dataframe which would yield all cases and either an "A" if the case had only "A's" assigned, "B" if it was only "B's" or "MIXED" if the case had both A and B?

Result would be then:

Case     Type
1        A
2        MIXED
3        B

check username exists using ajax

I use this code to check username exists in database before or not. code works good and shows available or taken username. now i want to submit button should be disable when user select username that was taken befor and enable when username available . please guide me how.

$(document).ready(function() {
    $('#username').keyup(function() {
        $.post('adm/chk_uname_avail.php', { 
            uname : changeuser.username.value 
        }, function(result){
            $('#available').html(result);
        })
    })
})

Call a python function from one class in another

I am new to Python and I have difficulties in the basics of functions

a.py

import b
from ConfigParser import SafeConfigParser

class A:
  def method1():
    config = SafeConfigParser()
    b = B()
    b.method2(config)

b.py

class B:
  def method2(config)
    config.
    # The editor does not show the inbuilt methods of config here

I am using IntelliJ IDE

Get unique values from a list in python

I want to get the unique values from the following list:

[u'nowplaying', u'PBS', u'PBS', u'nowplaying', u'job', u'debate', u'thenandnow']

The output which I require is:

[u'nowplaying', u'PBS', u'job', u'debate', u'thenandnow']

I tried the following code:

for x in trends:
    if x not in output:
        output.append(x)
        print output

but it didn't work. Any help would be appreciated.

Trying to identify the errors and provide the python code that accomplishes the task

if n is an integer, write the expression that will determine if n is odd and between 200 and 2000, exclusive?

I have no idea what odd/even and exclusive/inclusive means in an expression like this, can someone give me a briefing of it. Below is what I have got so far

n >= 200 and n <= 2000

Please help me understand exclusive/inclusive and even/odd. Thank You.

how to used objloader in three.js to load an object or image from blob link?

Hello I need Help on this.

This is my code for showing an object

but the object that I need to show is not display.

   var loader = new THREE.OBJLoader( manager );
    loader.load('https://twportal.blob.core.windows.net/ecardbackground/scenes1.obj', function ( object ) {

        object.traverse( function ( child ) {

            if ( child instanceof THREE.Mesh ) {

                child.material.map = texture;

            }

        } );

please let me know what is my error.

matplotlib: AttributeError: 'AxesSubplot' object has no attribute 'add_axes'

Not sure exactly sure how to fix the following attribute error:

AttributeError: 'AxesSubplot' object has no attribute 'add_axes'

The offending problem seems to be linked to the way I have set up my plot:

gridspec_layout = gridspec.GridSpec(3,3)
pyplot_2 = fig.add_subplot(gridspec_layout[2])

ax = WCSAxes(fig, [0.1, 0.1, 0.8, 0.8], wcs=wcs)
pyplot_2.add_axes(ax)

Does anybody know how to solve this? Many thanks.

How to get similarity from LSA

I am working on latent semantic analysis, i am trying to get similarity from 2 documents. I run my code of latent semantic analysis on Python and when i run it i get :

Here are the singular values
[ 0.7376057   0.4596623   0.25422212]
Here are the first 3 columns of the U matrix
[[ 0.98465137 -0.172792   -0.02458864]
[ 0.15675976  0.81362269  0.55986114]
[ 0.07673365  0.55512255 -0.82822153]]
Here are the first 3 rows of the Vt matrix
[[ 0.08861949  0.02992777  0.36751379  0.9253024 ]
[ 0.78716383  0.34742637  0.43792207 -0.26056147]
[ 0.29462756 -0.93722956  0.17407106 -0.06704194]]

How i will find similarity from this numbers ?

How to get the index of the element by class that is clicked

I have this code:

<button class="remove" value="1" />
<button class="remove" value="2" />
<button class="remove" value="3" />
$(document).on('click', ".remove", function(e) {
    alert($(this).index());
});

It is always alerting 0. If the user clicked the button that has a value of 2, it must alert 1 but in my code it alerts 0.

Convert Pandas DataFrame to dictionary

I have a DataFrame with four columns. I want to convert this DataFrame to a python dictionary. I want the elements of first column be keys and the elements of other columns in same row be values.

Dataframe:

    ID   A   B   C
0   p    1   3   2
1   q    4   3   2
2   r    4   0   9  

Output should be like this:

Dictionary:

{'p': [1,3,2],'q': [4,3,2],'r': [4,0,9]}

Animating HTML Text Change jQuery

I am attempting to change the text of a HTML element using javascript and jquery. This is my code so far, and I can't seem to get it to work. I have googled it and can't seem to find anything on it.

$("div#title").hover(
    function() {
        $(this).stop().animate({
            $("div#title").html("Hello")
        }, "fast");
    },
    function(){
        $(this).stop.animate({
            $("div#title").html("Good Bye")
        }, "fast");
    }
);

Any help would be greatly apreciated.

Replace text of element that start with specific text

I have html like bottom code

<table>
    <tr>
        <td>
            {name length='100'}
        </td>
        <td>
            {otherText length='100'}
        </td>
        <td>
            {otherText2 length='100'}
        </td>
    </tr>
</table>

I want to change tds text that start with {name.

How can i do this?

Add form with scripts in WP

I am trying to add code to my WPpost page, but I don't know how to add it.

I tried to add to the child theme, but it didn't work:

global $allowedposttags;
$allowedposttags['script'] = array(
 'type' => array(),
 'src' => array()
);

I have to add this source code to a classic WordPress page. How do I do that?

updating prior rows of dataframe conditionally upon current

I have a dataframe (ev), and I would like to read it and whenever the value of the 'trig' column is 64, I need to update the value of the critical column that is 4 rows above, and change it to 999. I tried the code below but it does not change anything, though seems it should work.

for i in range(0,len(ev)):  
    if ev['trig'][i] == 64:
        ev['critical'][i-4] == 999

mardi 26 juillet 2016

lutorpy for shared memory between python and torch

I am trying to install lutorpy to load a network trained in torch and use it in python code. I get the following error:

lutorpy/_lupa.c:299:17: fatal error: lua.h: no such file or directory

I do have lua.h in torch/install/include folder.

I'm following the instructions here and get this error: https://github.com/imodpasteur/lutorpy

Spark Matrix multiplication with python

I am trying to do matrix multiplication using Apache Spark and Python.

Here is my data

from pyspark.mllib.linalg.distributed import RowMatrix

My RDD of vectors

rows_1 = sc.parallelize([[1, 2], [4, 5], [7, 8]])
rows_2 = sc.parallelize([[1, 2], [4, 5]])

My maxtrix

mat1 = RowMatrix(rows_1)
mat2 = RowMatrix(rows_2)

I would like to do something like this:

mat = mat1 * mat2

POS tagging in German

I am using NLTK to extract nouns from a text-string starting with the following command:

tagged_text = nltk.pos_tag(nltk.Text(nltk.word_tokenize(some_string)))

It works fine in English. Is there an easy way to make it work for German as well?

(I have no experience with natural language programming, but I managed to use the python nltk library which is great so far.)

Python - How to Compare a column value of one row with value in next row

I want to compare the S.No. of different rows, if it is same then I want to calculate the datetime difference and print details.(If datetime difference is not possible then only date difference would also be fine.)

Input

S.No.   Datetime    Details

1    2010/6/7 19:01 asd 

1    2010/6/8 4:00  dfg 

2    2010/6/9 0:00  dfg 

2   2010/6/10 0:00  gfd 

2   2010/6/11 0:00  gfd 

3   2010/6/12 0:00  gfd 

3   2010/6/13 0:00  abc 

4   2010/6/14 0:00  abc 

4   2010/6/15 0:00  def 

Expected output

1   0.3 asd dfg

2   1   dfg gfd

2   1   gfd gfd

3   1   gfd abc

4   1   abc def

Search Multiple Strings (from File) in a file and print the line

Again apologies for been noob here ; trying below code for searching multiple strings read from keywords and search in f and printing the line. it works if i have only one keyword but not if i have more then one

keywords = input ("Please Enter keywords path as c:/example/ n :")
 keys = open((keywords) , "r").readline()        
        with open("c:/saad/saad.txt") as f:
                         for line in f:
                                if (keys) in line:
                                        print (line)

Bitshifting with and without leading zero [duplicate]

This question already has an answer here:

I wonder why adding one or multiple leading zeros to an integer in Python leads to different results when using the bitshift-operators:

In:  10<<1
Out: 20

Adding a "0" in front of the integer:

In:  010<<1
Out: 16

Series of instructive pop-up on page, how to handle the mark up with Jquery?

I'm bulding an intranet which required pop-ups when users first use the site. What really concern me though, is how to generate the mark up into html when there are so much content to be loaded. Should i do it manually or generate the content automically ? is there good approach (pattern, method...) for either of them ? For the record, i'm a front-end developer who know a little about back-end stuff such as PHP and MySQL, hope that helps.

Create a questionnaire? Where to start? [on hold]

I'm looking for guidance on how to create a questionnaire using python?

Essentially this is what I would be looking to do:

  1. Enter subejct information (name + number)
  2. Instruction page
  3. Question 1: Pick form 1-5
  4. Upon click, goes to next frame (question 2)... ect

and the values would be output to a CVS file.

Any advice on where to start would be helpful. Thank you!

How to get the text/html value from event.target using jQuery

I'm using Clipboard.js and am trying to get the text in a <td> node using the following:

$('.clipboard').click(function(evt) {
    clipboard.copy(evt.target.val()).then(
      function(){console.log("success");},
      function(err){console.log("failure", err);}
    );
});

Obviously .val() is not a valid method on evt.target. What's the correct way of getting the nodes text value using evt here?

Adding values associated with the same key in two different dictionaries

I've looked through a few of the questions here and none of them seem to be exactly my problem. Say I have 2 dictionaries, and they are dict1

{'A': 25 , 'B': 41, 'C': 32}

and dict2

{'D':21, 'A': 12, 'B':62}

I'm writing a program where I need to add the values associated with the same key. So like this:

{'A': [25 + 12], 'B': [41 + 62], 'C': [32], 'D': [21]}

Pandas Series: Log Normalize

I have a Pandas Series, that needs to be log-transformed to be normal distributed. But I can´t log transform yet, because there are 1 < values < 1. Therefore I want to normalize the Series first. I heard of StandardScaler(scikit-learn), Z-score standardization and Min-Max scaling(normalization). I want to cluster the data later, which would be the best method? StandardScaler and Z-score standardization use mean, variance etc. Can I use them on "not yet normal distibuted" data?

Stop channel.basic_consume if the connection is idle/Not consuming from long time

I am having a use case in which i want get the last idle time(last message processed time) of a pika consumer(pika.BlockingConnection).
Usecase:
If the last processed time is greater than Threshold time(ex: 1 hr). I want the consumer to get exited or have a callback method to decide on what i need to do? Like sending a notification to a user.

Is there any way to do this?

Unable to detect the JAVA_HOME path in mac El Capitan

import os
import sys

print os.environ.get('JAVA_HOME') #Output:: printing None

Unable to detect the JAVA_HOME path in mac El Capitan for python. But when I print the environment variables it is showing in the list.

enter image description here

How to fix this issue?

Find specific values inside array

I'm trying to insert conditioned values in an array into an empty array in exact position.

empty_array = np.zeros([40,100])
for x in range (1,24):
    array[x,:,:] #which is also sized 40x100
    if the_values_in_the_array < 0.25:
         the_values_in_the_array = 0
    empty_array = empty_array + array [x,:,:]

Which syntax should I use for this logic? And how should I scan the_values_in_the_array to find the conditioned values?

How create animated emoticons for Hybrid App

I am developing a chat app (Hybrid app) for android and IOS. I intend to use some animated emoticons to add spice to chat.

I have 2 questions here:

  1. How to create custom animated emoticons that I could integrate into my chat app and user could use to chat.

  2. Will animated emoticons impact the app performance, especially if I attach sound to them?

Thanks alot!

How to show data stored (sql server database) in a 'select option' with json or/and javascript?

I'm new in the mvc world, so, I don't understand a couple of things. I'm working with c#, javascript and sql server to do a webservice. The point is that I need to show data from a table by populating a 'select option' (created with javascript) and I would like to do this with javascript, json or jquery, without php. Please, I need you to be specific for me to understand. Thank you for your attention and help!

Ways to implement hooks in Python

I recently learnt the concept hooks. I understand the concept that hooks are a way for third party developers to modify an api. I wanted to know the different ways of implementing hooks in Python(Currently I can think none other than plain inheritance). Are there specific design patterns for implementing hooks. Examples would be nice or can some one point to projects where they have been implemented. I want to know different ways to implement hooks. Thanks in advance.

Python, copy only directories

I have a program that has a list of some files. I have to copy only the directories and the subdirectories from the list to a specified directories and don't need to copy the files. I tried this, but it doesn't work. def copiarDirs(): items = list.curselection() desti = tkFileDialog.askdirectory() for dirs in os.walk(items, topdown=False): for name in dirs: #for i in items : aux=root+"/"+list.get(i) tryhard=("cp "+str(aux)+" "+str(desti)) os.system(tryhard)

How to calculate a TCP packet checksum using Python?

I'm using Scapy (the below code) to capture the IP/TCP packets on network:

sniff(iface='ens33', prn=call_back, filter="ip and dst host 10.0.0.12", store=0)

def call_back(packet):
    ip_packet = packet['IP']
    tcp_packet = ip_packet['TCP']

When I got 'ip_packet', I need to change its source address to another one, and send it out.

How can I re-calculate its checksum in IP header and TCP header?

Browser side CSS abstract syntax tree generator. (Javascript but Not node)

I'm looking for a client-side standalone javascript library (if it runs on node then i can't use it) that consumes a string of text (that has valid CSS) and produces a css Abstract Syntax Tree. Something like JavaScript AST visualizer: http://jointjs.com/demos/javascript-ast but for css.

It has to be client side standlone javascript, not NODE.

Thanks in advance for all your answers!!

typehead.js JSON AJAX BASIC SETUP

I cant get anything to load or error from typehead.js

This is the script. I check the console and it wont error or get anything I want to load in api data from json format.

$(document).ready(function() {      
        $('input.typeahead').typeahead({        
          source: function (typeahead,query) {
            $.ajax({
              url: '/api/location',
              type: 'POST',
              dataType: 'JSON',
              data: 'sstr=' + query,
              async: true,
              success: function(data) {         
                console.log(data);
                alert("I am an alert box!");

              }
            });
          }
        });
      });

How to read dictionaries in python?

I have a file of name "input.txt". In this text file a lot of dictionaries are stored. I have to iterate through these dictionaries. How do read the file? Whenever I read the file using open(), file.read() it coverts the whole text into a string type. How to read this file as collection of dictionaries?

Contents of input.txt:

{"label":18,"words":["realclearpolitics","-","election","2016","-","2016","republican","presidential","nomination","polls","year","state"]}

Video.js Show play button only when paused

I am currently using video.js on my website.

I have made controls false, which also hides the play button.

I am looking to have the play button display only when the video is paused, and not display whilst the video is playing.

I tried the following , but it doesn't work.

videojs("myPlayer").ready(function(){
  var myPlayer = this;
  myPlayer.on("paused", function(){
    myPlayer.bigPlayButton.show();
  });
});

Thank you!

What is the best jquery/js plugin to build a drag & drop form builder?

i am building a system like http://www.youtube.com/watch?feature=player_embedded&v=cIjADcI37oE#! http://wufoo.com/

which provide a function of building a input form and building the workflow model using drag & drop interface.

hope someone can suggest the plugins that is most suitable.

lundi 25 juillet 2016

How can I convert a tensor into a numpy array in TensorFlow?

I know how to convert an numpy array into a tensor object with the function tf.convert_to_tensor(img.eval()).

My problem is that after I apply some preprocessing to this tensors in terms of brightness, contrast, etc, I would like to view the resulting transformations to evaluate and tweak my parameters.

How can I convert a tensor into a numpy array so I can show it as an image with PIL?

Jquery combine click and change

Is it possible listen click and change for one code?

$(document).on("click", "button.options_buy",function(event) {

//   same code
}


$(document).on("change", "select.options_buy",function(event) {

//   same code
}

I try this

$(document).on("click change", "button.options_buy,select.options_buy",function(event) { }

It works but I want 'click' only for 'button.options_buy' and 'change' for 'select.options_buy'

is it possible?

print one time uniqe variable in if or while statement python

Is there a way to see / print looping variables which have unique values?

for an example:

while random.randint(0,15) != 7:

If I do:

while random.randint(0,15) != 7:
     print (random.randint(0,15))

I won't get the same result as it was produced in while loop It can happen while statement generates seven, but print statement would produce different number. So how to see through what variables were you really looping?

'import module' or 'from module import'

I've tried to find a comprehensive guide on whether it is best to use import module or from module import. I've just started with Python, with the intention for developing web applications with Django and I'm trying to start off with best practices in mind.

Basically, I was hoping if anyone could share their experiences, what preferences other developers have and whats the best way to avoid any gotchas down the road.

How to change the order of python unit test cases in 'tests' directory

I have flask project. I want to run unit test cases which are in tests directory using test suite. As we know that python modules in the tests directory get executed alphabetically. Can I change that order of execution?

Suppose I have a directory structure like:

/tests
     test_add.py
     test_delete.py
     test_get.py
     test_put.py

But I want to run add, get, delete then put. Is that possible?

jQuery: Find word and change every few seconds

How can I change a word every 2-3 seconds using jQuery?

For example:

I have this:

<div>
    <span>This is so</span>
    <span>awesome</span>
</div>

... and I want the awesome to change into cool,fantastic,incredible and keep cycling with loop using fadeOut/fadeIn effect maybe?

Is it possible?

Thanks alot

NetworkError: 404 Not Found IIS Windows 2008 R2

I have dedicated windows 2008 R2 server where I have IIS website in html website. Every thing is working fine but on some of the pages when I go to firebug I can see that some css and jQuery files are showing NetworkError: 404 not found

But when I go to the directory on the server physically files are there then why it is showing not found !!!

can somebody tell me what can be the issue!!

'ManyToManyDescriptor' object has no attribute 'add', why?

So I refer to another model :

 subscriptions = models.ManyToManyField(Season)

So I use :

@api_view(['POST'])
def buy_season(request):
    _id = 1
    season = Season.objects.get(id = _id)

    a = ExtUser.subscriptions.add(season)

    a.save()

    return Response({'status': 'success'}, status=status.HTTP_200_OK)

I get an error object 'ManyToManyDescriptor' does not attribute the "Add" Do many to many directly , and not through the " throw " , why there is this error ?

Showing dynamic rates for all dates using jquery ui calendar

In a Car Rental Website Reservation System, i am using jquery ui calendar as a date range picker for "From Date" and "To Date" selection.

I want to show dynamic rates for different dates as shown in figure. Please let me know how i can do that ?

dynamic rates for different dates

Python sqlite3 delete not doing anything

I am a noob about sqlite (but somewhat experienced as Pythonista), but I am deeply confused why this (Python 2.7, DBPATH is the path to the database)...

import sqlite3

connection = sqlite3.connect(DBPATH)
conn = connection.cursor()
query = "SELECT * from jobs"
conn.execute(query)
print(conn.fectchall)
query = "DELETE from jobs"
conn.execute(query)

...Outputs the contents of the table (thus the name of the table is right) without altering it. Could someone point out the obvious?

Python and Matplotlib: Plot multiple graphs on the same figure fast

Is there a faster way of plotting multiple curves over the same x range than the following?

import numpy as np
import matplotlib.pyplot as plt

N = 100
x = np.linspace(0, 2*np.pi, 1e5)
y = [np.sin(x)**i for i in range(N)]

color = iter(plt.cm.rainbow(np.linspace(0, 1, N)))
[plt.plot(x, y[i], c=next(color)) for i in range(N)]
plt.show())

This code takes considerable time when plotting many trajectories :(

alternate button text automatically without click

I would like alternate between 2 pieces of text on a button in 2 sec intervals. This is NOT a click event. I just want the button to rotate between 'click here' and 'download'. This is what Im trying with no luck:

<div class="assetClass customButton1_1Div" id="download_btn1">
<input type="button" class="customButton1_1" name="button1_1" value="click here" title="download_btn1" />
</div>

setInterval(toggle, 2000);
function toggle() {
document.getElementByName("button1_1").value = "download";
}

Installing SciPy with pip

It is possible to install NumPy with pip using pip install numpy.

Is there a similar possibility with SciPy? (Doing pip install scipy does not work.)


Update

The package SciPy is now available to be installed with pip!

How to pass hidden field value as parameter to action method

How do I pass a hidden field value as parameter to action method from kendo grid action method?

.Selectable(s => s.Mode(GridSelectionMode.Single))
 .Events(e => e.Change("UtilitySelected"))
  //.ClientDetailTemplateId("utility-detail")
   .DataSource(dataSource => dataSource
   .Ajax()
   .ServerOperation(false)
   .Group(groups => groups.Add(p => p.ISO))
   .Read(operationBuilder => operationBuilder
   .Action("SearchResultJson", "Flash", new { historyType=$("#HistoryName")})

Need to pass $("#HistoryName") value to the controller

Any way to do that?

Python sum 2D list column coincident

I'm looking for the most efficient method to do the following calculation:

I have three matrix, like this:

[[Brand1, operationCost], [Brand2, operationCost],...]

[[Brand1, maintenanceCost],[Brand2, maintenanceCost]...]

[[Brand1, replacementCost],[Brand2, replacementCost]...]

and I need to calculate the total cost, operation+maintenance+replacement, of each of the brands. It is posible that same of the marks are not in all the matrix. And obtain another matrix like this:

[[Brand1, totalCost],[Brand2, totalCost]...]    

How can I track number of downloads for images in website

I have a <img download> tag in my page. Every time a user clicks on it, file will download.

I can track number of clicks on this <img> tag and store in db for track number of downloads.

But what if user cancel the download file prompt (Select location for downloading file),

How can I track whether user is actually downloading file or not?

Generating random value for given cdf

Depending on sample of values of random variable I create cumulative density function using kernel density estimation.

cdf = gaussian_kde(sample)

What I need is to generate sample values of random variable whose density function is equal to constructed cdf. I know about the way of inversing the probability distribution function, but since I can not do it analitically it requires pretty complicated preparations. Is there integrated solution or maybe another way to accomplish the task?

Auto it click exception: access violation reading 0x00000083

My code should open a window from taskbar and then click a control from it. The problem is that after it opens the window I get the error : "exception: access violation reading 0x00000083".I am new to Python (and in programing) and I have no ideea what that means or how to solve it.My code looks like this : import autoit, time autoit.win_activate("KOPLAYER 1.3.1040") time.sleep(2) autoit.mouse_click(131, 507) It opens (activates) the window but after that I get that exception error.

Jquery checking if user scrolled to bottom works reversed

I have got this code in three different js files var sd=0;

$(window).scroll(function() {
               if($(window).scrollTop() + $(window).height() == $(document).height()) {
                sd++;
                          $.ajax({
                            url: '../connect.php',
                            type: 'GET',
                            cache: false,
                            contentType: false,
                            processData: false,
                            data:"SMu=true&&sd="+sd,                         
                            success: function(d)
                            {    
                                $(".upfile").append(d);
                                $(".ShowMoreUpl").remove();
                            }   
                        });
               }
            });

In one file it works quintessentially while in other it works when i scroll to the apex.What may be the reason that causes this problem?

Proper initialization of flot.time with timezone-js (Angular & require.js)

Could someone tell me what is correct configuration of require.js to draw timezone-specific graps with flot.time.js on Angular app? My current rconfig.js looks like this:

paths: {
     ...
    'angular':                      '../bower_components' + '/angular/angular.min',
     ...
    'jQuery':                       '../bower_components' + '/jquery/dist/jquery',
     ...
    'timezone-js':                  '../bower_components' + '/timezone-js/src/date'
},
shim: {
     ...
    'flot': { deps: ['jQuery','timezone-js']},
    'flot-pie': { deps: ['flot']},
    'flot-time': { deps: ['flot']},
 ...
},

But with this config timezoneJS is undefined when flot.time is loading

[JavaScript][jQuery Datatables] Hiding rows with class "hidden" after change the checkbox

I'm using jQuery datatables. I'd like to hide all rows with class="hidden".

This code:

var table = $('#table1').DataTable();
table.rows('.hidden').hide();

It's not working (rows are not hidden), and I see this text in console:

table.rows(...).hide is not a function

How can I use class="hidden" to hide all rows?

python, tcpServer tcpClient, [WinError 10061]

when I try to run tcpServer and tcpClient on the same local network, it works, but I can't run them on the external network. The OS refuses the connection.

''Main builtins.ConnectionRefusedError: [WinError 10061] No connection could be made because the target machine actively refused it''

  • I checked whether tcpServer is running or not using netstat, and it is in the listening state.

What am I supposed to do?

Thanks

Save the state of the menu in the Simple Sidebar

In this example: http://startbootstrap.com/template-overviews/simple-sidebar/

What is needed so that the menu does not return to be visible when the page is refreshed?

Because what happens is that when:

(1) menu visible / refresh page / menu visible
(2) menu hidden / refresh page / menu visible

1, is ok, but 2 it's wrong. The correct would be:

(2) menu hidden / refresh page / menu hidden

I have file where at start of line tabs are for tree level, how to count tabs in start of lines

I want to count tabs in the start
of lines and create tree levels

$(".importTree").on("change", function(e) {

    var file = this.files[0];
    var reader = new FileReader();
    reader.onload = function(progressEvent){
           var tree = this.result.split('n');
           var tabLvl = [] ;
           for (line in tree) {
                tabLvl.push(tree[line].split(/[^t]/)[0].length)
                console.log(tabLvl);
           };
          //after I split file into lines tabs are disappeared
      };
      reader.readAsText(file);
   };
});

after I split file into lines tabs are disappeared

dimanche 24 juillet 2016

jQuery auto background color transition

I tried many ways I found it very simple for me but one thing I can't figure it out. Changing background automatically is working well but it happens very quickly. I wonder is there a solution to make it slow transition now it is very sharp and not user friendly.

<script>

$("body").css("transition","all 3s");
var colors = ["#c11733","#c0392b","#66cc99","#27ae60","#745380"];
function changeBgColor(){
   $("body").css({
        backgroundColor : colors[parseInt(Math.random() * 3)]
      });
}
//changeBgColor();
setInterval(changeBgColor, 3000);

</script>

Blur() doesn't work for this situation?

Here's my code:

<input id="m" autocomplete="off"/>

and I put the following lines in script

$('#m').on('blur', alert('blurred'););
$('#m').on('focus', alert('focused'););

The result is, it will pop up 'blurred' when the page starts. But afterward, it no longer fires the alert('blurred').

More interesting is, the focus() works well.

Thanks for any suggestion or help.

javascript file local import is not working

-projectName
  --Web Pages
    ---web.jsp
  --js

In the console I got something like this

enter image description here

and this my import stament, i download the dataTables and other jquery file in the js folder.

<script src="js/jquery.dataTables.min.js" type="text/javascript"></script>

Jquery autocomplete response and pushing UI[style] content to JSP

i need a solution to my below problem.i want to push on response of Jquery. on pushing the content it must have style in it. please let me know the solution>>>>>>> anyone.

response : function(event, ui) {
            var a = $("#photo").val();
            ui.content.push({
                label : "<i class='fa fa-plus-circle'></i>"+" "+a,
            });

this fontawesome Icon [i class='fa fa-plus-circle'] is not getting
affected in my jsp page.

How to remove noise from a white region, without losing the shape of the white region

Here's the image:

enter image description here

I want to remove the noise within the white region without losing the shape of the white region. I've tried dilation, but that effects the shape of the white region. I've also tried dilation followed by erosion, and it's the same problem - the shape of the white region gets affected.