mardi 19 juillet 2016

How can I find all subclasses of a given class in Python?


I need a working approach of getting all classes that are inherited from the base class in Python.


TensorFlow: product equivalent of tf.add_n


Is there a product equivalent of tf.add_n, returning the elementwise product of a list of tensors?


Javascript Router without hasing


What is the best Javascript or a jquery plugin to enable routing without using hashing like: youtube , facebook , digitalocean and many others


How to request a url from the browser


I would like to receive the address of the site of the active tab in the browser from my application (in Python or Java)

Simplest jQuery Spinner during ajax response loading interval [on hold]


I want to show a spinner image during my ajax call request and its response loading. Can you point out some sample code of jQuery Spinner?

Document.ready won't work


Any idea why this code doesn't work ? I defined a text input field with this ID in the HTML. $('document').ready(function() { $('#inputUsername').keyup(alert("something")); } );

Add key to a dictionary in Python?


Is it possible to add a key to a Python dictionary after it has been created? It doesn't seem to have an .add() method.


ImportError: No module named PyQt4


I installed pyqt4 by using Homebrew. But when I import PyQt4 in python interpreter, It said that "No module named PyQt4". Can somebody help me with that?


ParseError: Bad input on line


Here is part of my code:

sum1 = sum1 + (GTINList[each]*3)
        sum1 = sum1 + (GTINList[1]+GTINList[3]+GTINList[5]+GTINLIst[7])
        remainder = sum1 % 10
        if remainder == 0 :
          print ("Valid GTIN")
          else:

Slimscroll bar very slow in mobile browser


I am using the slimscrollbar plugin. It is working fine in Web Browser, but its very slow in mobile browser. Any solution to increase the speed that work for mobile?

Python Google Photo API


Is there any Google Photo API Client for Python 3.5? Unfortunately, I couldn't find a proper one. If there is no such client - how should I upload photos to Google Photos?

matplotlib: How to assign the dpi of your figure to meet some set maximum file size?


Just wondering if there is a tried and tested method for setting the dpi output of your figure in matplotlib to be governed by some maximum file size, e.g., 15MB.


Other than HTMLTestRunner


I want to generate a report of selenium script which is written in python. I have not used unittest, so is there any other way of generating report other than HTMLTestRunner?


How to use httplib of python to implement SPNEGO enabled client


I can use the following curl command to implement a SPNEGO enabled client, Not sure how to implement that in httplib of python curl -s --negotiate -u:anyUser -X POST <url>

Finding N points in a mesh which are very close to the XZ plane (Python)


I have a 3D mesh which is intersected by 10 XZ planes. I need to find points in the mesh which is close to each plane and then project those points separately.


flask-security make user always signed in


Im trying to make it so a specific user is always logged in using the flask security extension. I cant find any docs on this. Can someone point me in the right direction to start.

Noun phrases with spacy


How can I extract noun phrases from text using spacy?
I am not referring to part of speech tags. In the documentation I cannot find anything about noun phrases or regular parse trees.


jQuery set the percentage of repeating-linear-gradient


The css is as follow

-webkit-repeating-linear-gradient(90deg,#ededed 0%,#ededed 7%,white 7%,white 14%,#ededed 14%,#ededed 21%); 

Is it possible that I am able to set percentage such as 0% or 7% by jQuery?


How do I find out the size of a canvas item in Python/Tkinter?


I want to create some text in a canvas:

myText = self.canvas.create_text(5, 5, anchor=NW, text="TEST")

Now how do I find the width and height of myText?


Why isn't it filter(not None, iterable)?


Since the definition of filter() is to return a list of elements in which the function returns True, wouldn't filter(not None, iterable) make more sense for filtering to a list that only includes items that aren't NoneType?

Python argparse and controlling/overriding the exit status code


Apart from tinkering with the argparse source, is there any way to control the exit status code should there be a problem when parse_args() is called, for example, a missing required switch?


Get value of Json object


i have a object type of JSon Ex:

[{"RowError":"","RowState":2,"Table":[{"ID":"1","item":"2","cate":"tran","sTITLE":"translation"},{"ID":"2","item":"3","cate":"tran1","sTITLE":"translation1"}]

How can i get "Table" in object ? thanks


lundi 18 juillet 2016

How to check if two arrays are equal with JavaScript?


var a = [1, 2, 3]; var b = [3, 2, 1]; var c = new Array(1, 2, 3); alert(a == b + "|" + b == c); demo How can I check these array for equality and get a method which returns true if they are equal? Does jQuery offer any method for this?

Get content between second last and last slash


I have a url like the following

http://localhost:8000/test/

What is the tidiest way of getting test from this using plain javascript/jQuery?


Disable past dates in Jquery Date Time picker


How to disable the previously selected dates in datetime picker. Looking for a solution similar to jQuery Date Picker - disable past dates . This works for datepicker and not datetime picker.


What does `Sizzle.tokenize` do


Sizzle.tokenize is undocumented and there is no comments in the source. What does it do?

The code


what are the rules for iterator invalidation?


Is there a general rule that all modules follow? In my case, I'm using Python xml.etree library Let's say I do this: for el in root.iter('*'): for subel in el: el.remove(subel) Does that break the el iterator?

AWS API Gateway CORS


I am unable to enable CORS on any resources from AWS Api Gateway. I used the "Enable Cors" button present on the web UI: But attempting to use in development or production yields: I'm using jQuery 2.2.4 and the method $.post. What's going wrong?

Order of decorator for abstract method


I have a base class which I have made abstract.

class X(metaclass=ABCMeta):

   @abstractmethod
   @tornado.gen.coroutine
   def cc(self):
      # do stuff

What should the order of the decorators go in? And does it matter?


How to exit when viewing python help like help(os.listdir)


when the help window pops up, what are the basic commands (mac os) to page up/down, end of document and exiting the help screen?

I just had to close my terminal as I couldn't figure it out!


Add no. of days in a date to get next date(excluding weekends)


I have an date, i need to add no. of days to get future date but weekends should be excluded. i.e input date = "9-DEC-2011"; No. of days to add = '13'; next date should be "27-Dec-2011" Here weekends(sat/sun) are not counted.

How can I make SimpleCV show image?


I am using the following code from Simple CV tutorial

logo = Image("simplecv")
logo.show()

But then it shows up a small window but blank, without image.

Could you help me?

Thank you


how to associate a newly created EC2 security group with an instance


How do I add an EC2 instance to a newly created security group? The security group was created with

client = session.client("ec2")
group_id = client.create_security_group(
    DryRun=False,
    GroupName=group_name,
    VpcId=vpc_id,
    Description=description
)

running octave/matlab code in interface mode


If we run a program with -i flag in Python, the program gets executed and we enter interactive mode after executing the script. ( Which can be further used for debugging). Example : python -i exampleProgram.py. Is there a similar method to do the same in Octave?

How to add tons of attributes in an Element with Python and Elementtree?


Is it OK to use the following ?

ET.Element.attrib={'a': '1', 'b': '2', 'c': '3'}

Or do I have to make a for loop using ET.Element.set('x','y') ?


Why -l and -r don't have spaces in them?


Why -l and -r don't have spaces in them when we run pip install -rrequirements?

I was wondering why we don't run pip install -r requirements? (with a space). This allows us to use tab and is more clear.


Draw trees or graph using python from a relationship table


Is there a way to draw a tree structure or graph using python from some relationship(parent/child) table? The child may have more than one parent. For example, |Parent |Child |none |node 1 |none |node 2 |node 1 |node 3 |node 2 |node 3 |node 2 |node 4 This gives node1 node2 / node3 node4

Concatenation of php variable with javascript


var settings = {
  "async": true,
  "crossDomain": true,
  "url": 'https://example.com/something.aspx?i='<? echo urlencode($_GET['id']); ?>,
  "method": "GET",
  "headers": {
    "cache-control": "no-cache",
  }
}

It doesn't work this way, the concatenation is wrong I think. Tried few ways still doesn't work.


Multiline comments in Python


I have recently started studying Python, but I couldn't find how to implement multi-line comments. Most languages have block comment symbols like /* */ I tried this in Python, but it throws an error, so this probably is not the correct way. Does Python actually have a multiline comment feature?

Python Find minimum object using special comparator


So I got my question answered on how to find the minimum value, but what if I want the minimum object? Can we similarly simplify this code? min = 9999 minChild = None for child in currentRoot.children: if child.score < min: min = child.score minChild = child recurseWriteBook(child, depth+1)

Object literal pattern callback and this confusion


var App = {
  method : function (value, callback) {
    console.log(value);  
    if (typeof callback === 'function') {
      //here
      callback.call( this );
    } 
  } 
} 

App.method('Hey there', function(){
  console.log('callback was executed!');
}); 

Why do I can't do callback(), but have to call(this) for the callback?


How to install qrtools for Python on Mac OSX El Capitan 10.11?


How to install qrtools for Python correctly on Mac OSX El Capitan 10.11?

After the installation using brew install zbar and pip install qrtools zbar, I got a segmentation fault 11 while trying to import zbar in Python.


How does Django's Meta class work?


I am using Django which allows people to add extra parameters to a class by using class Meta. class FooModel(models.Model): ... class Meta: ... The only thing I found in Python's documentation was: class FooMetaClass(type): ... class FooClass: __metaclass__ = FooMetaClass However, I don't think this is the same thing.

Get access to all css style properties?


I want to get access to all CSS properties (not only for a specific selector or element but all) through JavaScript.

I want to iterate through all properties of the .style collection.

How can i do this?


code using the Spark on pyspark


I have problem in pyspark. I have executed just these lines on Spark using pyspark as given below, it gives me following error, >>> text_file=sc.textFile("/Users/Aroon/spark/Scala/word") Traceback (most recent call last): File "", line 1, in NameError: name 'sc' is not defined.

What is an elegant way to convert the result of [x for x in y] from list to a regular variable?


What is an elegant way to convert the result of [x for x in y] from list to a regular variable? result= [x for x in range(10) if x==7] The result of the above will be [7]. I am now using result=result[0] but ...it does not look right :-) thanks

dimanche 17 juillet 2016

Selenium error - ConnectionResetError: [WinError 10054] An existing connection was forcibly closed by the remote host


I was using the selenium module but all of a sudden I get this error ConnectionResetError: [WinError 10054] An existing connection was forcibly closed by the remote host here is my simple code that gives me the error from selenium import webdriver browser = webdriver.Firefox() browser.get('https://www.instagram.com/')

Mobile navigation jquery


I have made a mobile navigation with css and jquery. when you click on the navigation it pops out the ul list. But when it's activated it scrolls down the content from another div except for the div itself, how do i prevent it from doing that?

`


Python regex recursion


I am trying to match brackets using regex in python:

(a (dcsd)) () 

I dont have internet on my desktop at the moment so I cant download new libraries. What is the best way of doing this when regex has no recursive features in python?


How to I change TKinter canvas line from dash to solid?


In my Python script, I initially created a canvas line as solid. Then under a certain event, I changed the line to dash using the syntax below.

self.canvas.itemconfig(line, dash=(4, 4))

What is the command to change it back to a solid line?


Server-side processing DataTable


Can you please provide me an example on how to use server side pagination using Spring MVC. In my script I have. oTable = $('#example2').dataTable({ "bJQueryUI": true, "sPaginationType": "full_numbers", "aLengthMenu":[10,20,40,60,80,100], 'iDisplayLength': 10, "processing": true, "serverSide": true, 'sAjaxSource': 'test?firstDate=${firstDate}&secondDate=${secondDate}', }); $( ".DataTables_sort_icon " ).css( "float" , "right");

setuptools 'entry_points' parameter usage


Looking through some python code, ive found an argument entry_points to the setuptools.setup function. I cant see this argument in any of the API docs for setuptools / distutils. Can anyone clarify what format this parameter should take, or even better, where its defined in the API docs?


Display a list of items that can selected / unselected (without checkboxes)


I want to display a list of items. The user should be able to select / unselect by just tapping on the item. It should work just like a checkbox. The only difference is that the entire row that contains this item must be clickable. is there a UI element that support this?


Round a Floating Point Number Down to the Nearest Integer?


As the title suggests, I want to take a floating point number and round it down to the nearest integer. However, if it's not a whole, I ALWAYS want to round down the variable, regardless of how close it is to the next integer up. Is there a way to do this?


How to loop through array in jQuery?


I am trying to loop through an array. I have the following code:

 var substr = currnt_image_list.split(','); //This will split up 21,32,234,223,

Am trying to get all the data out of the array. Can some one lead me in the right path please?


Best solution to replace mousedown in mobil devices


Am trying to find a way to minimize my ui with smartways of navigation on desktop and mobile devices. What is the best solution to replace mousedown in mobil devices http://codepen.io/shaikeomra/pen/XKNBVX $(document).mouseup(function(e){ if(mouse_down) { // mouse_down = false; $("#header").animate({height: 46},300); $("#menu").removeClass("show"); $(".pullmenu-icon").removeClass("hide"); //

Which Python 2.7.x Version contains the fix for issue1625


I think I have a Python2.7 installation where this issue is still alive:

http://bugs.python.org/issue1625 (bz2.BZ2File doesn't support multiple streams)

Which Python 2.7 version contains the fix? I could not find it on above page.


accept ssl cert with marionette firefox webdrive python splinter


when using python splinter firefox 47 marionette new webdriver, it gives certificate error when access the website i want, i tried to accept ssl certs with

browser = Browser('firefox', capabilities = {'marionette': True, 'acceptSslCerts': True})

or using trustAllSSLCertificates instead of acceptSslCerts, but still gives me certificate error, what is the problem?


How to detect slide direction in Slick Carousel onBeforeChange?


How can I know what direction the carousel are going on the event onBeforeChange. right or left?

    $('.foo').slick
        infinite: false
        onBeforeChange: (e) ->
            if right
                do_this()
            if left
                do_that()

Slick Carousel


Exclude certain indices from a KFold split in Python SKlearn


I am using SKlearn KFold as follows:

        kf = KFold(10000, n_folds=5, shuffle=True, random_state=88)

However, I want to exclude certain indices from the training folds (only). How can this be achieved? Thanks.

I wonder if this can be achieved by using sklearn.cross_validation.PredefinedSplit?


Using Javascript to add a span around a decimal value


var value = 2.00

How can I add a span tag around the '.00', so that on my page I would end up with:

2<span>.00</span>

Please note that the '00' can be a different value. Depends on the data being injected.


Bring variables with increasing number in the name into a numpy array in Python


I have a big number of variables that have an increasing number in their name:

var0 = 2
var1 = 6
...
var999 = 19

Is there an easy way (maybe with a loop) to create a numpy array that contains the values of the variables as elements?

list[0] = 2
list[1] = 6
...
list[999] = 19

Accessing item in tuple nested in dictionary python


So I'm a little confused about the dictionary this function returns. (The endpoint_pose function) It seems to be a dictionary, with nested dictionary or tuple I am not sure. What the function returns is this {'position': Point(x=0.7938064310002948, y=0.4000015952566877, z=0.28522708748065545), 'orientation': Quaternion(x=-0.18674837754140436, y=0.7484662663927322, z=-0.5955181308876427, w=0.22423524999844527)} How can I access the z coordinate position?

How to get __init__() to raise a more useful exception instead of TypeError when incorrect # of arguments?


I have a class with an init that takes many arguments--some required, some not. If one of the needed arguments is not supplied, you may get a TypeError, with an unhelpful message like 'requires at least 10 arguments (14 given)'. I would like to have a custom TypeError subclass that actually informs the user of which arguments are missing.

How to initialize an expression in Pyomo


from pyomo.environ import *
s = [1,2,3,4]
model = ConcreteModel()
model.x=[s,domain=NonNegativeReals]
def constraint1(model,i):
    expr = []
    if i>=2:
        expr += x[i]
    return expr
model.cons = Constraint(s,rule=cosntraint1)

This doesn't work because the initialization of expression expr=[] is not working in Pyomo, then what should I modify the code?


Defining the midpoint of a colormap in matplotlib


I want to set the middle point of a colormap, ie my data goes from -5 to 10, i want zero to be the middle. I think the way to do it is subclassing normalize and using the norm, but i didn't find any example and it is not clear to me, what exactly i have to implement.


What is the best way to integrate numpy into a meteorjs web app?


I've just started to poke around MeteorJS and it looks great. However the app I'm starting to build has a scientific component which i would prefer to implement using numpy/scipy/pandas.

Is there an idiomatic approach to leveraging a computationally intensive (I'm also toying with a separate app using OpenCV) component in conjunction with MeteorJS?


How to read and store values from a text file into a dictionary, python


I'm trying to figure out how to open up a file and then store it's contents into a dictionary in python 2.7+, I want it to look like this , with key string, and value int

d = {"a": 1 "c": 2, "e": 3}

I looked at other posts here, but I wasn't able to figure it out...


jQuery/JS - 360 degree spherical viewer


I am trying to find a plugin that works as viewer for 360 spherical such as Facebook does 360 degree Photo/video. Is there a plug in I can use? I have been looking around but I can only find 360 viewers plugins but not spherical.


Jquery break line between data fields


I tried to break line between fields, but nothing i red on previous cases has worked for me : "
" "n"

$(function() {
    var body = $(document.body);
    for (var i = 0; i `enter code here`< data.length; i++) {
        $('<div></div').text(data[i].name + " " + data[i].age + " n" + data[i].email).appendTo(body);

    }
});

samedi 16 juillet 2016

how to load pretrained LSTM models weights in Tensorflow


I want to implement a LSTM model with pretrained weights in Tensorflow. These weights may come from Caffee or Torch.
I found there are LSTM cells in file rnn_cell.py, such as rnn_cell.BasicLSTMCell and rnn_cell.MultiRNNCell. But how can I load the pretrained weights for there LSTM cells.


Python - Saving text file without scientific notation values


Attempting to save two arrays together as a text file.

import numpy as np

np.savetxt('NormalizedData.txt',  np.transpose([Wavle2,Intscale2P]),delimiter=',')

returns

3.455400000000000205e+02,0.000000000000000000e+00
3.457599999999999909e+02,8.388047138047138862e-02
3.459800000000000182e+02,8.425925925925924209e-02

and so on.

How do I specify python not to do this?


How can I adjust the Bootstrap Carousel Slide Delay


I am trying to adjust the delay time of bootstrap slider. How can I adjust that?

I've been following this guide, but have been unable to adjust the interval between slides.

http://bootsnipp.com/snippets/featured/responsive-bs-carousel-with-hero-headers

Any help would be appreciated.


import sklearn not working in PyCharm


I installed numpy, scipy and scikit-learn using pip on mac os. However in PyCharm, all imports work except when i try importing sklearn. I tried doing it in the Python shell and it worked fine. Any ideas as to what is causing this? Also, not sure if it is relevant, but i installed scikit-learn last. The error I receive is unresolved reference

What is the fastest way to bulk load a large CSV file into MSSQL using Python?


What is the fastest way to import data into MSSQL using Python with these requirements:

  1. Large file (too big for memory, no row based inserts).
  2. Minimal logging.
  3. CSV file.
  4. CSV file column may contain single and double quotes.
  5. CSV file Column may contain line breaks.

Thanks.


How to use jquery selector to get the following text?


Suppose the website's html looks like this.

<img src="pic/helloworld_123.jpg" width="48" border="0" alt="" title="">

How to use jquery selector to get the following text?

helloworld_123.jpg

Thx

I tested this but it doesn't work.

$("img[src*='']").text();

split every 50,000 lines and write file in python


I read files which contains 75,151 lines. I want to split every 50,000 lines. So I made 2 files, one files have 50,000 lines and the other file has 25,151 lines. I made code like this (INSERT_NUMBER : 50,000) for index, data in enumerate(lines): if ((index % INSERT_NUMBER) == 0 and index != 0) or (index == (lines- 1)) : made file .... which is the better way to split every 50,000 lines and make new files ?

python-writing q as a function of i in a for loop


I'm completely new to python so forgive me if this question is stupid.I am try to code for a Fibonacci sequence and wanted to know if there is a way for me to write q as a function of i in a for loop. like:

 for i in range (1,x): 
    q(i)=q(i-1)+q(i-2)

Jquery onBlur pad zeros from the left into a number


How can i using jquery to pad zeros from the left into a number to complete eleven digits just in case it did not have yet eleven digits?

How can i find the only one element i want to apply the eleven zeros? $(#myid) ? instead of input?

$(document).on('blur keyup', 'input', function() {
    padElevenZeros( $(this) );
});

Save and create images using python?


I was going to create ms-paint clone but I am not sure how to save images to the computer with tkinter. How could I make a program where I could create my own images and save them to my computer. Some other questions talk about using gif's in python but none of them talk about saving a new image to a pc.


How can I output a dictionary in a class?


So I got a class like this:

class Useraccount():

def __init__(self, saving, checking, PIN):
    self.save = saving
    self.check = checking
    self.passwd = PIN

I want a output like this:

>>> a = Useraccount(2000,3000,1234)
>>> a
>>> {1234:[2000,3000]}

How to achieve this, please help me out.


Add a play count to database using ajax and jquery


When a user clicks .play it should add a play count if it doesn't have class alreadyplayed and then add class .alreadyplayed I am new to AJAX and cant seem to make it work.

$(".play").on('click', function () { 
if (!$(this).hasClass('alreadyplayed')) {
    $.ajax({
    type:'post',
    url:'addplay.php',
    data: songid = $(this).attr('sound_id'),
    }).done {
    $(this).addClass('alreadyplayed');
    }
}); 

cannot use pexpect of python in cygwin


I was trying to use pexpect in cygwin, but failed. I try to install it like: pexpect-4.1>python ./setup.py install

But when I run the examples inside pexpect-4.1. It outputs:

Traceback (most recent call last):
  File "./examples/uptime.py", line 54, in <module>
    p = pexpect.spawnu('uptime')
AttributeError: module 'pexpect' has no attribute 'spawnu'

more compact way of checking if all items in a particular row are True or False


Given an example dataframe, I want to check if all items in a particular row are false:

df = pd.DataFrame({'test':[1,2,False,4],'this':[2,1,False,True]})

This is how I've managed to do it, but I'm sure there is a "better" more compact and cleaner way to do this:

all(df.ix[2:2:,].isnull().ix[2])

jQuery .html() is very slow for updating options in a dropdown


I tried to use jQuery's html() function to update the selection for a dropdown, but the .html() function takes over 10 seconds for a long "options" string.

How can I make it run faster?

<select class="dropdown">
    ...
</select>

<script>
    var options = "...";
    $('.dropdown').html(options);
</script>

how to export a table dataframe in pyspark to csv?


I am using spark-1.3.1 (pyspark) and I have generated a table using a SQL query. I now have an object that is a DataFrame. I want to export this DataFrame object (I have called it "table") to a csv file so I can manipulate it and plot the columns. How do I export the DataFrame "table" to a csv file?

Thanks!


Function in scapy-python(ip and mac-address)


The following is my function which throws an error as mentioned below

def get_mac(ip = ""):
    arp_packet = sr(ARP(op = ARP.who_has ,pdst = ip), timeout = 2, verbose = False) 
    mac_address = arp_packet[ARP].hwsrc
    return mac_address

the answer:

IndentationError: unindent does not match any outer indentation level

someone knows why?


Checking for new elements on a existing webpage


What would be the best way to check for new elements on a specific part of a webpage, looping infinitely? When a new element is added/found, the script continues.

I'm currently thinking about using function checkDOMChange() for this purpose, but i'm not sure if it would work.

As you can see, i'm new to JavaScript and coding in general.


Show thumbnails for video media in fancybox with thumbnail helper?


I am using fancybox and have a lightbox with video and stills. My thumbnail helper only shows black thumbs for my videos. I like the thumbnail helper in general, but I need the videos to also have thumbnails if I'm going to keep it. Does anyone know how to make this work? Here is the page for reference: www.staceystormes.com. Thanks so much in advance! =)

Split string with brace to become parameter


If I have a input value "a[123],b[456],c[789]" and I want to return as "a=123&b=456&c789"

I've tried below code but no luck.. Is there a correct way to implement this?

var str = "a[123],b[456],c[789]"
var string = (str).split(/[|,|]/);

alert(string);

Chrome Extensions: Any way to tell when a key is pressed and held?


I'm currently developing an extension for chrome that takes action based on shortcut keys for specific web pages. Right now I'm using the "command" API to tell when a shortcut key is pressed ( https://developer.chrome.com/extensions/commands ). Is there any way to tell if a key is pressed and held? I only want this specific action to take place when that is the case.

Chaining and queuing ajax requests using jquery deferred


I have a clunky ajax queue that uses setTimeout and a global flag:

var InProgress = false;

function SendAjax(TheParameters) {

  if (InProgress) {
     setTimeout(function () { SendAjax(TheParameters) } , 500) 
  }

  InProgress = true;

  $.ajax({
    ...
    data: TheParameters,
    complete: InProgress = false
  });
}

How can I rewrite this using a queuing mechanism so that the requests trigger one after the other in the order they're received?

Thanks.


Image loading issue on website using php codeigniter?


i hosted application live and application has many images. Application has issue to load whole images so want to load first all content and after that images load.

Application has a carousel slider of products and when i scroll carousel, content already loaded but images load when i want to see next products.

So please suggest me how to do this ?


saving list values when terminating python program


I am doing some test, runing 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?


vendredi 15 juillet 2016

How to use imdbpy using python?


I am using imdbpy to get the ratings of movies.I have succesfully installed the imdbpy but running into problem while running this small code. here is the code:

from imdb import IMDb
ia = IMDb()
the_matrix = ia.get_movie('0133093')
print the_matrix['director']

error:

from imdb import IMDb
ImportError: cannot import name IMDb

jquery library know when new day is coming


I wonder how can detect or know when new day is coming by using jquery or others jquery library. For examples: Assume, right now is 2016/06/23 23:59:50. And when second come to 2016/06/24 00:00:00, jquery can detect an event. I know we can use setTimeOut or setInterval and check every seconds when new day is coming. But i don't want to use these methods above, what methods of jquery do we detect ?

setinterval not working to change image src


Wondering why the following code will not change my img src. The commented out example works just fine. And the alert triggers every 4 seconds. Replacing the src just wont work inside the set interval function.

$(document).ready(function(){
    $(".samples_1_1").on("click", function(){
        alert('asdf');
        //$(this).attr("src", "../../static/results/samples_1_2.png");
        setInterval(function() {
          alert('alert 1');
          $(this).src("src", "../../static/results/samples_1_2.png");        
        }, 4000);
      });
    });

Shadow status is out of sync in aws iot how to resolve


I am working on aws iot and able to get the shadow state updated by the terminal via shell script .But i am able to get root@raspberrypi:~# ./aws_subscribe.py Connected with result code 0 and also in aws iot home i am getting out of sync error The is attached below. I followed the following link


get request which is come from iframe after the script is loaded dynamically


how to record the request which is come from iframe that script tag is loaded dynamically using performance.getEntriesByType("resource")(Resource Timing API). That script tag also have some links to load.I want to get all the request data when the iframes is completely loaded. when i was tried i cant get that request which is come from script source data


how to clear form after successful submit ajax


I would like to make the contact form disappear after successful submission but am not sure how to go about it. Any assistance would be appreciated.

jQuery(document).ready(function($) {
$("#ajax-contact-form").submit(function() {

        var str = $(this).serialize();

        $.ajax({
            type: "POST",
            url: "contactfinal.php",
            data: str,
            beforeSend: function() {
                $("#submit").hide();
                 $("#loading").show();
                  },
            success: function(response) {
               $('#error').html(response);
                $("#submit").show();
                $("#loading").hide();

            }
        });
        return false;
    });
});

ATOM - Pylama Path


I have installed Linter Python packages in ATOM Tool. This image pops up everytime i try to save my codes.

enter image description here

However i'm able to compile my *.py files. I'm i missing anything here, Please help.

Thanks..


Ember.js: How to assert event unbound in component test?


In component code like: didInsertElement() { this.$('.something').on(//...); }, willDestroyElement() { this.$('.something').off(//...); } You have the method of querying for events $._data(this.$('.something')[0], 'events'), but when destroyed, the element is gone. Is there a way to assert in test that the event was actually unbound before destroyed? Is there a way to query for all events on the page then somehow filter for the one in question?

TypeError: 'undefined' is not a function (evaluating '$(document)')


  1. I'm using a WordPress site.
  2. I'm including this script in the header.

When the script loads, I get this error:

TypeError: 'undefined' is not a function (evaluating '$(document)')

I have no idea what is causing it or what it even means.

In firebug, I get this: $ is not a function


How to split string and map each character into dictionary [duplicate]


This question already has an answer here:

Suppose i have a string like 'value=sahi' and i want it like {1:s,2:a,3:h,4:i} is there any function to do like this.


Random time between given hours using epoch time format


I would like to have a random time from given hours range, using epoch time format. For example, I have this:

start_time = int(time.time())
end_time = start_time + 5184000    # 60 days
random_time = random.randint(start_time, end_time)

And I want to get random time from 9am to 9pm only. What is the simplest and nicest way to achieve this in Python?


How to send an e-mail with already logged in gmail?


Is it possible to send an email using my gmail already logged in on chrome, to send an email?

Other people have written code for sending emails but they require the code to have your email address and password, would it be possible for the script to use my already logged in gmail as so there would not be my email address or password in the python file?


how to convert a jquery load method to plain javascript, without added libraries?


i have this working ajax code:

$(function(){
  $('#post-list a').click(function(e){
    var url = $(this).attr('href');
    $('#ajax-div').load(url+ " #post");
    e.preventDefault();
  });
});

how do i convert it to plain JavaScript without jquary, or any other libraries? i believe it has something to do with XMLHttpRequest.


Python - How to scale selected values in array?


I'm trying to normalize a certain range of number in a data set. For context, I'm trying to fit the blue jagged line on the left part of the graph (before 550 nm) so that it "fits" the green line. Everything after that point is perfectly fine. Is their a way to where I can just select a certain range of my array and scale it while leaving the rest of the data un-normalized?

useing regular expression for column filter


I have a pandas DataFrame that contains a year and a title. Some of rows.name are Batman, Catman etc. I am trying to get all rows of the format .*man, using the following expression:

t[t.title & re.search(r'.*man', t.title)]

This Fails. Is there an idiomatic way to accomplish this?


grep a specific value when the matching criteria happens twice in the line


There are two lengths in the following line. I want to extract the value 46 and add 16 to it.

1466352405.455975 IP (tos 0x0, ttl 64, id 0, offset 0, flags [DF], proto UDP (17), length 46) 192.168.52.53.32769 > 192.168.52.54.9600: UDP, length 18

I tried grep 'slength' | cut -d: -f1 but it doesn't give the correct result. I expect to obtain 46 and add 16 to it. So final value should be 64.

Thanks


Add class if child element not present


If this works when a class is present...

$('.priority').children('.no-priority').addClass('normal');

How would I add a class if the child class .no-priority is missing?

Tried code below which does not work

if (!$('.priority').children('.no-priority')) {
 $('.priority').addClass('prioritised');
 }

Neither does

$('.priority').not('.no-priority').addClass('prioritised');

How can i make my signup form using api and ajax to direct users to their email for verification?


if i have a simple CRUD API and jQuery-ajax app running to add (post) users (sign up :
name-email ).
How can i make my app while adding new users to direct them to their email in order to verify the signup via a clickable link and that link will confirm the new data (user)?

Any reply, links or hints will be highly appreciated. Thank you very much.
Refo.


How can i connect to a network SSID with a py script


I've tried googling this but nothing came up about connecting to a network SSID with a python script What I mean is when you open the script up it comes up with a

ssid = raw_input("SSID: ")

so you enter the network name for example : BTHub5-F2Q5 then it will detect it in your range And try to connect I can sort the password bit out.


Pandas conditional creation of a series/dataframe column


I have a dataframe along the lines of the below:

    Type       Set
1    A          Z
2    B          Z           
3    B          X
4    C          Y

I want to add another column to the dataframe (or generate a series) of the same length as the dataframe (= equal number of records/rows) which sets a colour green if Set = 'Z' and 'red' if Set = otherwise.

What's the best way to do this?


How does `interp1d` in scipy handle ties


The documentation for scipy.interpolate.interp1d is silent on what happens when there are ties in the x argument. My experimenting suggests that it returns the rightmost one when that exact x value is requested and uses the closest one when interpolating:

from scipy.interpolate import interp1d
temp = interp1d([0, 1, 1, 2], [1, 2, 3, 4])
temp(0.5)  # 1.5
temp(1)  # 3.0
temp(1.5)  # 3.5

Is this guaranteed by the design of the interpolator?


Datatables Sorting Styles being incorrectly applied to header


I am having an issue after updating from 1.9 to 1.10 in the the header sorting styles seem to be applied to both and the inside the sort_wrapper div which is inside the this is causing a dark background to cover the entire head () as opposed to in 1.9 where it was only applied it inside the sort wrapper () I have tried setting "orderClasses": false in the init object but it seems to make no difference Any Ideas?

I need to ask user for inputs and display it on a common interface. The terminal should be like :


Word: _ _ _ H _ N // This is the common interface

Used: Z Q L A

HANG|MAN

Please guess the first letter: Z

Please guess the next letter: Q

Please guess the next letter: H

Please guess the next letter: N

I have the interface ready using stdout flush but cant figure out how to take input in such a manner


Jquery infinite scroll with url change


I want to use infinite scroll with url change.

The functionality example is as follows.

http://timesofindia.indiatimes.com/tech/tech-news/Google-Facebook-quietly-move-toward-automatic-blocking-of-extremist-videos/articleshow/52912908.cms

I have tried clever infinite scroll, but it's not working properly also the javascript in the ajax content is also not get parsed.

Please guide how to implement it. Thanks in advance


jeudi 14 juillet 2016

Using a pandas DataFrame to get the count of the 10th most frequent value


I have a DataFrame that contains entries of place_ids such as:

place_id
11111
11111
22222
33333
44444
44444
...

I would like to get the count of the 10th most frequent value.

Here's what I've come up with:

print df.place_id.value_counts().nlargest(10).tail(1).values[0]

This seems like too much work. Is there an easier way to get the count of the 10th most frequent place_id?


Python - Opening txt file, Invalid literal for float()


Just trying to open this data set in txt format.

400.,41.7693
403.977686150861,42.68129270405837
408.3434392432695,43.86688321933424
412.61217560029104,45.59966935704514
416.4928450157652,48.72324436844505
420.9556148435605,51.64162102143182
423.86611690516617,53.534005882352936
427.0676691729323,56.2927838121295
431.43342226534077,59.73555626994983
435.31409168081495,60.85274733242134
439.291777831676,64.52351796625626
442.68736357021584,67.25949607843137
446.56803298569,68.92388276333789
450.73975260732476,71.29506379388965
454.7174387581858,72.41225485636114
458.21004123211253,73.68904464204286
462.4787775891341,75.5130300501596
466.6504972107689,76.72142038303693
470.2401164200825,77.72461235750114
473.73271889400917,78.63660506155951
477.61338830948335,79.57139758321932
481.9791414018918,80.64298901048792

When trying to open in...

with open('SunData.txt') as I:
    data = I.read()
data = data.split('n')
WaveData = [float(row.split()[0]) for row in data] 
IntData = [float(row.split()[1]) for row in data]  

I'm returned with this error,

invalid literal for float(): 400.,41.7693

How do I correct this error?


Beautifulsoup : Is there a difference between .find() and .select() - python 3.xx


Best

I've a simple question :

when you use Beautiful Soup to scrape a certain part of a website, you can use data.find() / data.findAll() or data.select()

Now the question is. Is there a significant difference between the .find() and the .select() methodes? (e.g. in performance or flexibility, or ...)

or are they just the same?

Kind regards


How can I get the value of the EC2 instance tag "Name" with boto?


I'm working from the instance id. I can get the tags, but I can't figure out how filter on both the instance id and the tag "Name" or index in and return the value of the tag called "Name" I ended up grabbing all tags and iterating over them till I find the one I want, which can't possibly be right. tags = conn.get_all_tags({'resource-id': instance_id}) for tag in tags: if 'Name' in tag.name: name = tag.value

How can I change the linecolor if y-value changes


I'm using pylab to plot some graphs Say I want to plot this:

x = [0,1,2,3,4,5,6,7,8,9,10]
y = [0,0,0,1,1,0,0,1,0,0,0]

plt.plot(x,y,'g')
plt.show()

But every time [y = 1] I want to change the color of the line to red.

Is this possible?

Sketch of what I want to accomplish


Disable datepicker past date & time


I'm using datepicker and i like people not be able to select date and time previous to the present day. I used "minDate: 0" to disable the past date but is there a way to disable past time. For example, if the current time is 5am, i do not want people to select 3 or 4 am of the same day. This is my code: var dt; dt = $('#datetimepicker3').datetimepicker({ inline:true, minDate: 0, format:'m/d/Y H:i', formatDate:'d/m/Y' });

ImportError: No module named 'baseapi'


I can`t use the pyfcm module because of bellow error message. How do I fix this error?? >>> from pyfcm import FCMNotification Traceback (most recent call last): File "<pyshell#0>", line 1, in <module> from pyfcm import FCMNotification File "C:Anaconda3libsite-packagespyfcm__init__.py", line 6, in <module> from .fcm import FCMNotification File "C:Anaconda3libsite-packagespyfcmfcm.py", line 1, in <module> from baseapi import BaseAPI ImportError: No module named 'baseapi'

Math behind scipy.ndimage.convolve


While I have already found the documentation on scipy.ndimage.convolve function and I "practically know what it does", when I try to calculate the resulting arrays I can't follow the mathematical formula. Let's take for example:

a = np.array([[1, 2, 0, 0],`
             [5, 3, 0, 4],
             [0, 0, 0, 7],
             [9, 3, 0, 0]])

k = np.array([[1,1,1],[1,1,0],[1,0,0]])

from scipy import ndimage

ndimage.convolve(a, k, mode='constant', cval=0.0)

# Why is the result like this ? 

array([[11, 10,  7,  4], 
       [10,  3, 11, 11],
       [15, 12, 14,  7],
       [12,  3,  7,  0]]) 

I would appreciate a step by step calculation.

Thanks in advance!


Printing a canvas from Tkinter


I have created a canvas with rectangles and labels only which I would like to print. I have only found how to save the canvas to a postscript file like so:

self.canvas.postscript(file="my_drawing.ps", colormode='color')

If necessary I would be happy to just print the whole window if that is easier.

How can I print the canvas?

This program will be used on Windows XP or 7.


How can I tell if a jquery ui dialog query has been initialized?


I have the following code to detect if a jquery ui dialog is open:

if ($("#dialog-myDialog").dialog("isOpen")) {
      return;
}

which works fine but I found a situation where this code get called prior to the dialog being initialized in the first place and this if statement seems to just blow up in this case.

What is the best way to check if a jquery ui dialog has been initialized so I can properly handle this situation.


How to set a 'easeOutBounce' for .scrollTop in jQuery?


I need to set a easeOutBounce for a webpage back-to-top button .

I have below code for .scrollTop but unable to add

{
    duration: 2000,
    easing: "easeOutBounce"
}

Existing .js:

$(document).ready(function() {
    // Show or hide the sticky footer button
    $(window).scroll(function() {
    if ($(this).scrollTop() > 500) {
        $('.back-to-top').fadeIn(200);
    } else {
        $('.back-to-top').fadeOut(200);
    }
});

// Animate the scroll to top
$('.back-to-top').click(function(event) {
    event.preventDefault();

    $('html, body').animate({scrollTop: 0}, 300);
    });
});

Retriving all the rows from a csv file and plotting


I need to retrieve the rows from a csv file generated from the function:

def your_func(row):
    return (row['x-momentum']**2+ row['y-momentum']**2 + row['z-momentum']**2)**0.5 / row['mass']

columns_to_keep = ['#time', 'x-momentum', 'y-momentum', 'z-momentum', 'mass']
dataframe = pd.read_csv("./flash.csv", usecols=columns_to_keep)
dataframe['mean_velocity'] = dataframe.apply(your_func, axis=1)

print dataframe

I got rows up until 29s then it skipped to the last few lines, also I need to plot this column 2 against 1


Unicode output in ipython notebook


I have to work with Unicode (cyrillic) characters in IPython Notebook. Are there any way to output strings in Unicode, not their unicode or utf8 codes? I'd like to have ["АБ","ВГ"] as output in the last two examples below. In [62]: "АБВ" Out[62]: 'xd0x90xd0x91xd0x92' In [63]: u"АБВ" Out[63]: u'u0410u0411u0412' In [64]: print "АБВ" АБВ In [65]: print u"АБВ" АБВ In [66]: print ["АБ","ВГ"] ['xd0x90xd0x91', 'xd0x92xd0x93'] In [67]: print [u"АБ",u"ВГ"] [u'u0410u0411', u'u0412u0413']

Creating a likelihood heatmap given many pairs of x and y values of different lengths?


So I have generated a bunch of data curves (like thousands), say temperature with depth. so have say 1000 arrays of depths and 100 corresponding arrays of temperature (n.b. they are not all the same length)

What I want to do is create a heatmap where the color corresponds to how often one of these data curves had that value at that depth. i.e. how many curves pass through that particular bin.

Could anyone offer advice on how to do this?


Python Error Type [on hold]


Exercise

Is it possible to calculate this formula using a double input?

I know that I could just create an input for all the different variables but I would like to do it this way if possible!

I have searched the forum and documentation but I can't find a solution.

Any help would be much appreciated!


Download a zip file and extract it in memory using Python3


I would like to download a zip file from internet and extract it.

I would rather use requests. I don't want to write to the disk.

I knew how to do that in Python2 but I am clueless for python3.3. Apparently, zipfile.Zipfile wants a file-like object but I don't know how to get that from what requests returns.

If you know how to do it with urllib.request, I would be curious to see how you do it too.


IndentationError expected an indented block


Here is the code.:

def myfirst_yoursecond(p,q):

a = p.find(" ")
b = q.find(" ")
str_p = p[0:a]
str_q = p[b+1:]

if str_p == str_q:
    result = True
else:
    result = False
return result

Here is the error:

Traceback (most recent call last):
File "vm_main.py", line 26, in <module>
import main
File "/tmp/vmuser_ssgopfskde/main.py", line 22
result = False
^
IndentationError: expected an indented block

What's wrong with my code?


How to call multiple jquery function from .cs file?


I have 2 JQuery functions which I want to call from PageLoad event. The current implementation is as under

ScriptManager.RegisterStartupScript(this.Page, this.GetType(), 
"script", "Function1();", true);

ScriptManager.RegisterStartupScript(this.Page, this.GetType(), 
"script", "Function2();", true);

The problem is that, the first function is invoked i.e. Function1 and not Function2.

If I change the order of invocation, then Function2 and not Function1 is called.

How to execute both the functions ?

Thanks in advance.


Error Trying to fsync a Directory


I'm trying to fsync a directory, to ensure that rename operation occurs. The problem that I'm having is that Python keeps returning a permission error, even though I have full permissions for the various folders I've tried this on. directory = r'C:RandomPath' os.access(directory, os.W_OK) os.access(directory, os.X_OK) os.access(directory, os.R_OK) True, True, True fd = open(directory) os.fsync(fd) IOError: [Errno 13] Permission denied: 'C:\Random\Path' Am I doing something wrong, or is there something deeper going on?

A ply parser should partly treat comments


I'm trying to produce a ply parser that does not entirely suppress comments.

The typical def t_comment(self, t): r'(/*(.|n)?*/)|(//.)' t.lineno += t.value.count('n')

only counts lines and suppresses the comments. For most of the cases, this is just fine. But at one specific instance I need the comment. Is there a way to parse only this comment at the special place without having to specify all the other places where a comment can occur?


urllib2 file name


If I open a file using urllib2, like so:

remotefile = urllib2.urlopen('http://example.com/somefile.zip')

Is there an easy way to get the file name other then parsing the original URL?

EDIT: changed openfile to urlopen... not sure how that happened.

EDIT2: I ended up using:

filename = url.split('/')[-1].split('#')[0].split('?')[0]

Unless I'm mistaken, this should strip out all potential queries as well.


jquery isotope resize to handle expanded accordion


I'm using jquery isotope for a sortable text listing of federal regulatory activities. We list each update in a docket and the list per docket can become quite long. I've added Bootstrap simple accordion panels to items with more than two updates to make each item panel's height fairly consistent. When I open an accordion panel, the isotope pane doesn't resize to accommodate the expanded accordion.

Any ideas on how to get the isotope panel to resize height to handle the expanded accordions?

Thanks!


no log file produced


I'm new to logging in Python and have tried to build a basic logger that writes to a file. The problem I have is that the file is not created, yet there are not any errors thrown. Any ideas?

Using Spyder IDE in Anaconda (in case that is applicable)

Code:

import pandas as pd
import logging

format = "%(asctime)s %(message)s"
logging.basicConfig(format=format, level=logging.DEBUG, filename='H://logfile.log')

now = pd.datetime.now()
logging.info("Time Created")

Open sidebar when when user swipes from edges with Hammer.js


In my website I'm using hammer.js to open sidebar menu on swipe left. I've written this code and it's working:

Hammer(document.getElementById("page-content-wrapper")).on("swiperight", function() {
  wrapper.addClass("toggled");
});

But I want to open the sidebar when user swipe left from the left edge of the screen. I've tried these answers - Javascript touch movement, track when user swipes from edges but it didn't work. Any idea how can I implement this? Thanks.


mercredi 13 juillet 2016

Python local variable is changing global variable. Why?


Strange behavior on python. Local variable is changing the global variable.

import numpy as np

xc = np.arange(10)

def func(xc,val=3):
  xc /= val
  return xc

print xc
c = func(xc)
print xc

I can fix it using .copy() function as:

import numpy as np

xc = np.arange(10)

def func(Xg,val=3):
  xc = Xg.copy()
  xc /= val
  return xc

print xc
c = func(xc)
print xc

There's a better another way to avoid this problem?


what gets returned when you return self?


what gets returned when you return 'self' inside a python class? where do we exactly use return 'self'? In the below example what does self exactly returns

class Fib:
'''iterator that yields numbers in the Fibonacci sequence'''

def __init__(self, max):
    self.max = max

def __iter__(self):
    self.a = 0
    self.b = 1
    return self

def __next__(self):
    fib = self.a
    if fib > self.max:
        raise StopIteration
    self.a, self.b = self.b, self.a + self.b
    print(self.a,self.b,self.c)
    return fib

Strip out while(1) prepended to JSON object


I am making an ajax get request, but receive back a JSON object prepended with while(1) eg.

while(1);{"servers":[{"some_data": data, "etc":...}]}

We just started doing this to prevent malicious attacks, but I am not sure how to strip it out so that I can parse the JSON properly.

here is the function I am using for the $.get call

function myFunction() {
    $.get('/v1/servers').success(function(data) {
      data.servers.forEach(function(server){
        presentServer(server);
      });
    });
}

Enumeration function Argument


Python enumeration function enumerate takes one argument start. What is the use of this argument ? If i write some code using this argument it shifts only index e.g. >>a=[2,3,4,5,6,7] >>for index,value in enumerate(a,start=2): ... print index,value ... **2 2** 3 3 4 4 5 5 6 6 7 7 8 8 So index is changed to 2 ,Not Value.Value is still started from first element. Why this is so ? In place of this functionality ,It could be better if value is started from that index rather than starting element. What was the thinking behind the implementation of this ?

Comment out a Python code block [duplicate]


This question already has an answer here: Why doesn't Python have multiline comments? 16 answers Is there a mechanism to comment out large blocks of Python code? Right now, the only ways I can see of commenting out code are to either start every line with a #, or to enclose the code in triple quotes: """. The problem with these is that inserting # before every line is cumbersome and """ makes the string I want to use as a comment show up in generated documentation. After reading all comments, the answer seems to be "No".

Plot a function vertically in Python


Question: How do I to plot a function "in a vertical way" in Python.

Explanation/Clarification: Plotted already is function 1 (red in the figure below). This is a normal "horizontal plot". I need to insert a function plotted vertically as is shown as the blue line in the figure below.

So, something like this:

enter image description here


Cannot get right slice bound for non-unique label when indexing data frame with python-pandas


I have such a data frame df:

a         b
10        2
3         1
0         0
0         4
....
# about 50,000+ rows

I wish to choose the df[:5, 'a']. But When I call df.loc[:5, 'a'], I got an error: KeyError: 'Cannot get right slice bound for non-unique label: 5. When I call df.loc[5], the result contains 250 rows while there is just one when I use df.iloc[5]. Why does this thing happen and how can I index it properly? Thank you in advance!


finding annual averages using pandas in python


my data looks like this

unit  year   SURQ
10001  2012   89
10002  2012   83
10003  2012   88
10001  2013   75
10002  2013   69
10003  2013   59 
10001  2014   36
10002  2014   59
10003  2014   84

I want to find the annual average values for SURQ by unit. For example average SURQ in 2012 for unit 10001 = ???

I tried using pivot tables

avgSURQ = pd.pivot_table(df,index=['year'])

and groupby

avgSURQ = SURQ.groupby('year')

but I think I am getting the syntax wrong so it doesn't work. I am new to python so I might be misunderstanding the examples online.


select a Select option by text with javascript


I have a select box and one string and i would select a option by string. For example string="Volvo" and select box like this:

 <select>
  <option value="v1">Volvo</option>
  <option value="v2">Saab</option>
  <option value="v3">Mercedes</option>
  <option value="v4">Audi</option>
</select> 

Can anyone help me please?


ajaxForm(options) what should be passed to the options?


$(document).ready(function() { var options = { target: '#output1', // target element(s) to be updated with server response beforeSubmit: showRequest, // pre-submit callback success: showResponse // post-submit callback }; $('#myForm1').ajaxForm(options); }); function showRequest(formData, jqForm, options) { var queryString = $.param(formData); alert('About to submit: nn' + queryString); return true; } function showResponse(responseText, statusText) { alert('status: ' + statusText + 'nnresponseText: n' + responseText + 'nnThe output div should have already been updated with the responseText.'); } In the above program what is passed in the option argument?I use the http://jquery.malsup.com/

Save email attachment to file in python 2.7


Hi I have a similar question to this: Getting mail attachment to python file object I want to save all files attachments to files on my hard drive from email. But if I am correct not all parts of multipart email are "real" files (for ex. some images in html part of email). I want to be 100% sure that files I save are attachments. for now I have this: mail = ""; for line in sys.stdin: mail += line; msg = email.message_from_string(mail); for part in msg.walk(): check if is file and save

Scroll a div while using the scrollwheel over another div


Say I have 2 divs side by side. Both are 400px x 400px, and have overflow set to auto. The content inside is taller than 400px so there are vertical scrollbars.

When the mouse is over the div on the left, and the user uses the mousewheel to scroll, I want the other div to scroll, and vice versa.

So basically when a user is using the mousewheel over a certain area, I want to control the scroll of another area respectively.

Is this possible with jQuery?


Store and retrieve chained jquery effects/objects in variable


I want to dynamically change jquery effects by storing the chained objects in a variable and concatenating to selector later, so that i have the latest required effect when it needs to exec. i store a predifined set of jquery chained effects - fadeOut().end().next().fadeIn() - in the data-effect attr, which can change, so i need to reference back to it via a variable to add the effects to $(contentDiv) selector. So something like; $(selector)effect, won't work.

var effects = document.getElementById('effect').getAtttribute('data-effect');
$(contentsDiv).effects;

Indexing matrix with values from vector in theano


I'm working on a cost function in theano and faced the following problem: I have a matrix M (say [[3,4],[5,6]]), a vector v ([0,1]) and I would like to get the vector of entries in M corresponding to the indexes contained in v (here [3,6]). Is there a command to do exactly that? Edit: I ended up doing the following : M[T.arange(v.shape[0]), v], where T.arange(v.shape[0]) is just a vector which entries are integers in the range of the length of v. M needed to be indexed with a list of two vectors

Python Flask on domain


I can add code if needed, but I have an app running using flask. I am hosting a server off of a Pi board, but I don't like how to get to the app you have to use the IP address. I have been trying to read up on how to setup a custom domain so the user can connect and go to 'customdomain.com' to run the app, but everything I have seen hasn't helped me. Very new to this material, but I am assuming someone out there will have helpful guidance.


ERROR - Message: Can't load the profile. Profile Dir... Selenium Web Scraping with Firefox


I am running a web scraper using selenium and from time to time, I

ERROR - Message: Can't load the profile. Profile Dir: %s If you specified a log_file in the FirefoxBinary constructor, check it for details.

I know it means selenium can't open a session but how do I resolve this? Should I put in a retry mechanism with an exponential backoff? Is it a bug in selenium?

I don't know but any help in resolving this issue would be much appreciated. Thanks.


How to Set Class Name? [duplicate]


This question already has an answer here:

How can I set my own class name/description so that when I print the class object, the output is the class name/description specified by me?

class XYZ:
    def __init__(self, max_depth):
        self.max_depth = max_depth

x1 = XYZ(5)
print(x1)

output: XYZ(max_depth=5)


How do I attach event bindings to items on a canvas using Tkinter?


If I'm using a canvas to display data and I want the user to be able to click on various items on the canvas in order to get more information or interact with it in some way, what's the best way of going about this?

Searching online I can find information about how to bind events to tags but that seems to be more indirect then what I want. I don't want to group items with tags, but rather have specific function calls when the user clicks specific items on the canvas.


Uncaught TypeError is not a function on AJAX callback


In my application.js file, I have the following: $(document).ready(function() { /* Activating Best In Place */ jQuery(".best_in_place").best_in_place(); $('.highlight_on_success').bind("ajax:success", function(){$(this).closest('div.social-comment').effect('highlight');}); }); I am using the Best In Place gem, and it gives me the above function to use in my best_in_place call. However, when I use it, I get this error in my JS console: Uncaught TypeError: $(...).closest(...).effect is not a function application.self-440dd817e40548768e9.js:25 How do I fix this and get it work?

How to change the color of a line with different pattern classifications in python


I have a time series dataset that I used a machine learning algorithm to identify distinct patterns. I have that classified but I want to check it visually to see how it did.

How do I make a time series graph with different colors for each pattern classification OR what is the best way to visualize or check for accuracy with time series classification data?

The data basically looks like this

DATE DEMAND CLASSIFICATION June 4 678 1

Generally the classification would look like this 0000000000000000011111111111111111110000000000000000000000000022222222222222222 etc.

Any help?


XPath: Find element that contains text X but not Y


I'm attempting to find a web element using XPath in Selenium for Python. The web element should contain the text "Chocolate" but not include "Dark".

I've tried this syntax but not gotten it to work (be mindful of parantheses):

choco = driver.find_element_by_xpath("//*[text()[contains(., 'Chocolate')] and not[[contains(., 'Dark')]]]")

Here is the same code using line breaks and concatenation for readability:

choco = driver.find_element_by_xpath((
                                    "//*[text()[contains(., 'Chocolate')]" + 
                                    "and not[[contains(., 'Dark')]]]"
                                    ))

Variables in C++ vs Python [duplicate]


This question already has an answer here: “is” operator behaves unexpectedly with integers 10 answers #include <iostream> using namespace std; int main() { int a = 1; int b = 1; printf("%pn",(void*)&a); printf("%pn",(void*)&b); return 0; } Returns 0xbfa7b1c8 and 0xbfa7b1cc However, the equivalent code in python: a = 1 b = 1 print(id(a)) print(id(b)) returns 31093816L and 31093816L. From what I understand, python creates only one instance of 1 and both a and b are pointing to it. What are the pros and cons of the two approaches?

How to instantiate a Vue object in jQuery's ready event function?


I want to instantiate a Vue in $(function () {... but failed. Where is the problem?

<script>
$(function){
var vm = new Vue({
        el: '#vm',
        data: {
            a: "I'm a"
        }
     });
     vm.$set('b', "I'm b")
} 
</script>

HTML part:

<html>
<div id="vm">
 <p >{{ a }}</p>
 <p >{{ b }}</p>
</div>
</html>

Here is a test


Transforming a column in index Python pandas


I have the following DataFrame:

   index    PUBLICO     CLASSIFICACAO_PUBLICO
0   19      143643          1
1   34      111879          2
2   31       50382          3
3   9        49204          4
4   32       37541          5
5   4        36095          6

I need convert the index name column to index column.

For example:

index   PUBLICO     CLASSIFICACAO_PUBLICO
19      143643          1
34      111879          2
31       50382          3
9        49204          4
32       37541          5
4        36095          6

I try use df.set_index('index'), but it didn't work.

The column with the name index previously was the index column the DataFrame, but I used the reset_index, because I needed, now I need to do the reverse.

I apologize for any error. The English isn't my language.


mardi 12 juillet 2016

Trying to read a file in a subdirectory through a module I imported from that subdirectory


So I have a program with one main module that is in a folder with two other folders. Each of those two folders has a module in it that I've imported successfully, but each of those modules is supposed to be able to open and read a file from their respective folders, but it is unable to find the file it is supposed to import. I think it is looking in the main directory for the file to open, how would I make each module look in its own folder for the files to open?


sqlalchemy object is not callable in Flask


I am trying to simply add a database for use in web development with Flask but I keep getting the same error. I am using Pycharm.

from flask import Flask
from flask_sqlalchemy import sqlalchemy
app = Flask(__name__)

db = sqlalchemy(app) #This is where problem is


@app.route('/')
def index():
    return "Hello"

if __name__ == '__main__':
    app.run(debug=True)

When I run it it says that "TypeError: 'module' object is not callable".

Would be great if someone could tell me what's wrong. Thanks.


Using a for loop to assign 40 years of data to separate dataframes, then combining them to one data frame, then sort by year


I have 40 years of data so I was trying to assign each of them to a dataframe individually then store them all in a new dataframe, then sort them. Below is what i have so far

import pandas as pd
from pandas import DataFrame

year = 1976
count = 1

for i in range(0,40):

    df[count] = pd.read_excel('42003h'+str(year)+'.xlsx', sheet_name = 'Sheet1')

    count = count + 1
    year = 1976 + 1

I was given this error

Wrong number of items passed 12, placement implies 1

any help would be appreciated please?


How to call the Android keyboards ok button function in HTML5


I'm using the code below to create a form. Using this in a android device shows a ok button when the keyboard shows up. I've seen alot of questions on how to show different keyboards. Yet i cant seem to find/figure out how to use my own function once this ok button has been clicked using javascript/jquery.

    <form id="AndroidForm">
        <input id="myforminput" type="url" maxlength="20">
    </form>

If anyone has any input about how it can be done, i'd appreciate your help, thanks!


Intercept click event on a button, ask for confirmation, then proceed


Based on a variable SomeCondition, I need to intercept a click event on a button, and ask for confirmation, if they say ok, proceed, otherwise ignore click. So something like: if(SomeCondition) { // disable click on button var isOk = window.confirm("Are you sure?"); if(isOk) { $("#button1").click(); } } Note: button1 has already been wired up with a click event via javascript from an external .js file that I can't change. I don't know what the click event was bound too, so I have to disable the click if SomeCondition is true, then ask for confirmation, then continue with the click.

Removing personal information from the comments in a word file using python


I want to remove all the personal information from the comments inside a word file.

Removing the Authors name is fine, I did that using the following,

document = Document('sampleFile.docx')
core_properties = document.core_properties
core_properties.author = ""
document.save('new-filename.docx')

But this is not what I need, I want to remove the name of any person who commented inside that word file.

The way we do it manually is by going into Preferences->security->remove personal information from this file on save


delaying a function to execute jquery


I want a button pressed, then the button changes style, and a new function loads, after about 1/2 second of the styling.

$(document).on('click', '.capital_answers', function(){
    if(!$('#capital_answers').hasClass('answered')) {
        answer = $(this).attr('data-answer');
        if(answer==1) {
            $(this).addClass('capital_correct');
            $('#capital_answers').addClass('answered');
            capital_correct()
        }
        else {
            $(this).addClass('capital_wrong');
            $('#capital_answers').addClass('answered');
        }
    delay(500).capital_next();  
    }
});

So as you can see I am using the delay() method currently, which helps in no way. What options are there in delaying a function in this manner?


Using regex to deal with escape characters in URLs


I'm in the process of tokenizing strings which contain URLs. Here is the part I use to pick up the URLs:

regex_str = [r'http[s]?://(?:[a-z]|[0-9]|[$-_@.&+]|[!*(),]|(?:%[0-9a-f][0-9a-f]))+']

It picks up "regular" URLs perfectly fine; however some of the URLs look like this:

https://t.co/c1taPXzi4X

How can I modify the regex so that it deals with the escape characters, in order to end up with a complete and clean URL?

Many thanks in advance! :)


jquery form change


In jQuery, is there a simple way to test if ANY of a forms elements have changed?

EDIT: I should have added that I only need to check on a click() event.

EDIT: Sorry I really should have been more specific! Say I have a form. And I have a button with the following:

$('#mybutton').click(function() {
  //here is where is need to test.
  if( FORM has changed ) {
     do something
  }
});

how would I test if the form has changed since it was loaded?


whats wrong with this statement(count from 0-9)


I am trying to get this code to calculate 5 and print numbers by 5's with a while statement of 7, so I want it to loop through, generating a different number 7 times; however, when it gets to a number over 10, I want it to start back over at 0 and ignore the 10.

This is my code:

while z < 7:
firstpickplusfive = int(firstpickplusfive) + 1
counts = counts + 1
if counts == 1:
if firstpickplusfive > 9:
firstpickplusfive = 0
if counts == 5:
print firstpickplusfive
z = int(z) + 1

The code prints the first number, but freezes on printing any others. Why isn't this working?


With jQuery/JavaScript Is it slower to declare variables that will only be used once?


I just want to make sure I understand this basic idea correctly, and no matter how I phrase it, I'm not coming up with completely relevant search results. This is faster: function () { $('#someID').someMethod( $('#someOtherID').data('some-data') ); } than this: function () { var variableOne = $('#someID'), variableTwo = $('#someIDsomeOtherID').data('some-data'); variableOne.someMethod( variableTwo ); } is that correct? I think the question may be "Is declaring variables slower than not declaring variables?" :facepalm: The particular case where I questioned this is running a similarly constructed function after an AJAX call where some events must be delegated on to the newly loaded elements.

How can i pass NULL value in ajax jquery call?


Is there any way to handle null value when doing Ajax Call?

 $.ajax({
            type: "POST",
            url: "Login.aspx/SaveFacebookAutoSignUp",
            data: "{ 'Name':'" + rows[0].name + "', 'EmailId': '" + rows[0].email + "'}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function (msg) {
                alert("You have successfully sign in.");

            }
        });

This is saving "null" value in my DB for EmailId when it is not fetch from other page?

I want to save "NULL" (DB default NULL allow) in DB when it is not having any value?

What is the way to do so?


how to print output in [w*h] format in python


I'm trying to program a code which accepts width , height and a char. print it in a grid [W*H] My code is as follows..

width = int(raw_input("Width of myarray: "))
height = int(raw_input("Height of Array: "))
c= raw_input("Initial char:  ")
a=(width*c), (height*c)
print a

output:

Width of myarray: 3
Height of Array: 3
Initial char:  +
+++++++++

I need the output in [['+', '+', '+'], ['+', '+', '+'], ['+', '+', '+']] this format.


cannot deselect radio button with jquery


I'm having a problem with getting a radio button to deselect. I've got the following buttons: <input type="radio" name="sex" value="Male">Male</input> <input type="radio" name="sex" value="Female">Female</input> <input type="radio" name="sex" value="Unknown">Unknown</input> In the pagebeforeshow I've got: $('input:radio[name=sex]').attr('checked',false); The first time the page displays, no button is selected. I select a button and dismiss then page and when I redisplay the page the radio button is still selected, What am I missing?

Display values from a source in form of tags


I am using Bootstrap tags input plugin. I want to display some values in form of tags on a specified input field. These values are retreived from db most likely in json format. I followed to use add method as shown in the documentation https://bootstrap-tagsinput.github.io/bootstrap-tagsinput/examples but could not make it work.

My fiddle demo is here: https://jsfiddle.net/Lh4jy9d4/90/ $('input #expertise').tagsinput('add', {id: 1, text: 'javascript' })


how use .toggleClass() in this code


hello guys i have this code

panelPlusK.append('<div id="foo">click To change the style</div><br>');

$('#foo').click(function() {
    $('.agario-panel').css({
        'background-color': 'rgba(32, 68, 102, 0.72)',
        'color': '#E91E63',
        'border-color': '#2196F3',
    });
    $('.agario-panel').css({
        'background-color': 'rgba(44, 125, 116, 0.55)',
        'color': '#23ff8d',
    });
});

i want to make it when i click on it then it changes the style but when i reclick on it again then it remove the style ..i saw toggleClass fuction but i dont know how to implemt it there


jQuery validation not using errorPlacement HTML


I have the following jQuery Validation code:

$('form').validate({
    errorElementClass: 'input-validation-error',
    errorClass: 'field-validation-error',
    errorPlacement: function (error, element) {
        error.html('<i class="icon-warning"></i> ' + error.text()).insertAfter(element);
    }
});

Which should be inserting my custom error message html after each element that errors on my page. However I'm finding the plugin doesn't like this and instead overrides whatever I want to put inside the HTML with just the error message itself and removes the <i class="icon-warning"></i>

How can I stop this?


Uncaught TypeError: $template.get is not a function


Guys am getting this error in wordpress when am using a plugin called WpBakery Visual Composer. I am using the latest version of wordpress (4.5), using google chrome latest version and all plugins are updated. I cant seem to be able to add any elements or templates using visual composer. Can someone help me and tell me what could be be going on and how i can fix this error. This is the error i get:

enter image description here


Get all events handlers attached to an element


I need to find all events handlers attached to #mySelect and if the event is created via jQuery I can get it , here alert(e) will show only "change" without "click"

JavaScript :

$("#mySelect").change(function(){
    alert("changed");
})           
$.each($._data(  $("#mySelect")[0], "events" ), function(e) {
    alert(e);
})

Html :

<select id="mySelect" onclick="alert('hello')" >
    <option value="1">option 1</option>
    <option value="2">option 2</option>
    <option value="3">option 3</option>
    <option value="4">option 4</option>
</select>

Running API -In wireshark (follow tcp) i see that not all url appears (appears till opeator &)


I'm writing a python solution on Linux system. I have API that i'm running with "postman" on windows which run great.

However, when i run it via python with wget on linux it seems that the format of the api is not supported. This is the api:

xxxxx/daily?spsId=0011&dateStart=2016-06-19T00:00:00Z&dateEnd=2016-06-20T00:00:00Z

In wireshark i can see that till here it passed "xxxxx/daily?spsId=0011" Probably the & opeartor is the issue?

Thanks in advance

Ohad


request csv format data from url using python


i wana simply send a request to the following url and recive data in csv format and save on the following location,but doest not work!any help will be appreciated

from urllib import  request

my_url='http://real-chart.finance.yahoo.com/table.csv?s=CSV&a=07&b=9&  c=1996&d=05&e=26&f=2016&g=d&ignore=.csv'

def rciveURL(getURL):
response=request.urlopen(getURL)
csv=response.read()
csv_str=str(csv)
mydstination=r'mori.csv'
fx=open(mydstination,"w")
for line in csv_str:
  fx.write(line+"n")
  fx.closed()

  rciveURL(my_url)

Compressing And Decompressing into .txt in python


So i want to create a program that asks the user to compress or decompress and if compress it asks for a sentence and compresses the outcome and if decompress it saves the outcome of that in a .txt too. I have this currently.

import pickle


compressopen = input("Do you want to compress or uncompress: ")
compressopen.lower()

if compressopen == "compress":

    sentence = input("Please enter a sentence: ")
    sentencesplit = sentence.split()

    print(sentencesplit)
    listnew = []

    for x in sentencesplit:
        if x not in listnew:

            listnew.append(x)
    print(listnew)

    postion = []


    for c in sentencesplit:
        (postion.append(listnew.index(c)+1))

elif compressopen == "uncompress":

Folium map not displaying automatically


This is my first time to use folium to display map using python. import folium test_map = folium.Map(location = [0, 0], zoom_start = 10) test_map But it returns <folium.folium.Map object at 0x000000000BC70518> To view the map, I need to save it and open it manually. track_map.save("test_map.html") webbrowser.open("test_map.html") Is there a way or single function to make folium map display automatically in a browser? When I use plotly, plotly.offline.plot(sth) will display the charts in the browser right after the command is entered, can folium do the same thing? Thank you!

In what ways would Python be considered a more stable language than Ruby?


I have been using Ruby for a while and I find that because if its metaprogramming capabilities it makes things harder to debug and 3rd party code can potentially cause bugs in what you would think would be unrelated areas of your application.

Is python's metaprogramming much tamer and as a result it is easier to keep things under control? I'm not sure if stable is the right word for it but just less-magical in nature which results in more maintainable and understadable code.

If someone knows both python and ruby maybe they can explain if this is true?


lundi 11 juillet 2016

Pandas Groupby TimeGrouper and apply


As per this question. This groupby works when applied to my df for a pd.rolling_mean column as follows:

data['maFast']=data['Last'].groupby(pd.TimeGrouper('d'))
                           .apply(pd.rolling_mean,center=False,win‌​dow=10) 

How do I apply the same groupby logic to another element of my df which contains pd.rolling_std and pd.rolling_mean:

data['maSlow_std'] = pd.rolling_mean(data['Last'], window=60) + 
                  2* pd.rolling_std(data['Last'], 20, min_periods=20) 

Python update dictionary into dictionary


I need to build a dictionary and update it in a for loop. loc = {} result = { I get the list of records from database here, which has id and status } for res in result: temp={} temp['id']= res.id temp['status'] = res.status loc.update(temp) # this replaces the values every time, I want append print loc below is the result expected by me: loc = { {'id' : 123 , 'status' : 'available' }, { 'id' : 456 , 'status' : 'unavailable'} } Can someone help me. I tried with : loc = [] # [] this works with loc.append(temp) this gives result as : [{'id' : 123 , 'status' : 'available'},{'id' : 456 , 'status' : 'unavailable'}] But I need the above result with dictionary of dictionaries in python.

Disallow safe mode on launch for Selenium in Python?


I'm trying to launch into a website using a Selenium MWE:

from selenium import webdriver

browser = webdriver.Firefox()
browser.get('http://seleniumhq.org/')

However, it's not working. The process itself hangs until it times out.

I think that the problem is that instead of just launching normally whenever Selenium triggers Firefox it triggers it in safe mode:

enter image description here

Is there a way to disable that behavior?


IBM Buemix - Watson Alchemy- How to refer to a local directory on my laptop


Currently, I am using the following code to do analysis for a website: import json from os.path import join, dirname from watson_developer_cloud import AlchemyLanguageV1 alchemy_language = AlchemyLanguageV1(api_key='YOUR API KEY') url = 'https://developer.ibm.com/watson/blog/2015/11/03/price-reduction- for-watson-personality-insights/' combined_operations = ['page-image', 'entity', 'keyword', 'title', 'author', 'taxonomy', 'concept', 'doc-emotion'] print(json.dumps(alchemy_language.combined(url=url, extract=combined_operations), indent=2)) Can anyone tell me how to refer to a local directory where I am having my own html file for analysis? I tried to use the following code and it is not working: #html ='C:UsersDownloadsPythonname8.htm'

Need help using split function


This function adds up the numbers between zero in a string. For example ('25025') becomes 25+25. However, if I have a 0 at start and/or end of the string of the string argument being sent to test_string, it creates a space in the at the start/end of the list and won't compute. What can I add to this function to make it filter out both 0s and blank spaces?

  def test_one(test_string):
        test = test_string.split("0")
        numbers=[int(x) for x in test]
        print(sum(numbers))

    test_one('2022022022')
    test_one('02022020')
    test_one('25025')

IOError: [Errno 2] No such file or directory: '0.txt'


I am writing a program to read a set of text files from folder "set" to a list.My code for this is

def get_documents():
    path1 = "D:/set/"
    texts = []
    listing1 = os.listdir(path1)
    for file in listing1:
        with open(file,'r') as f:
            lines = f.read().splitlines()
            texts.append(lines)

But this gives me Error as

with open(file,'r') as f:
IOError: [Errno 2] No such file or directory: '0.txt'

There are text files inside D:/set/ namely 0.txt,1.txt,2.txt... What is the reason for this Error?


Rearrange the columns of a pandas DataFrame so that the column with highest total is first


I have this DataFrame:

df = pd.DataFrame({'c1':[1,2,3,4]
                       ,'c2':[2,4,5,6]
                       ,'c3':[5,7,9,10]
                       ,'c4':[-1,3,1,0]
                       ,'c5':[100,1000,1,2]})
df

    c1  c2  c3  c4  c5
0   1   2   5   -1  100
1   2   4   7   3   1000
2   3   5   9   1   1
3   4   6   10  0   2

What I don't know how to do is quickly sort the columns so the column with the highest total c5 comes first, then c3, c2, c1 and c4:

    c1  c2  c3  c4  c5
0   1   2   5   -1  100
1   2   4   7   3   1000
2   3   5   9   1   1
3   4   6   10  0   2

So is there a command to produce the following result (without hard-coding the column names)?

df[['c5', 'c3', 'c2', 'c1' , 'c4']]

    c5  c3  c2  c1  c4
0   100     5   2   1   -1
1   1000    7   4   2   3
2   1   9   5   3   1
3   2   10  6   4   0

Change user agent used with robotparser in Python


I am using the robotparser from the urlib module in Python to determine if can download webpages. One site I am accessing however returns a 403 error when the robot.txt file is accessed via the default user-agent, but correct response if e.g. downloaded via requests with my user-agent string. (The site also gives a 403 when accessed with the requests packages default user-agent, suggesting they are just blocking common/generic user-agent strings, rather than adding them to the robot.txt file).

Anyway, is it possible to change the user-agent in the rootparser module? Or alternatively, to load in a robot.txt file downloaded seperately?


Aligning Kivy objects using pure Python


I can't seem to figure out alignment using pure Python code. My understanding is that we reference root to get relational alignment. However, I haven't been able to get it to work. This code compiles, runs, and then places the button in the bottom left corner. At the 0,0 coords. What am I missing here?

class ContainerView(FloatLayout):
    def __init__(self, **kwargs):
        super(ContainerView, self).__init__(**kwargs)

    def build(self):
        new = Button()
        new.text = "username"
        new.size = (50,50)
        new.color = [3/255,50/255,155/255,1]
        new.size_hint = [0.5,0.5]
        new.center = self.center ###This line
        self.add_widget(new)


class ScoreboardApp(App):
    def build(self):
        cView = ContainerView()
        cView.build()
        return cView

Python: concurrent.futures: cancel not possible


This little snippets prints False import subprocess from concurrent import futures with futures.ThreadPoolExecutor(max_workers=1) as executor: future=executor.submit(subprocess.call, ['sleep', '2']) print(future.cancel()) According to the docs this means "future can't be canceled": https://docs.python.org/3/library/concurrent.futures.html#concurrent.futures.Future.cancel cancel(): Attempt to cancel the call. If the call is currently being executed and cannot be cancelled then the method will return False, otherwise the call will be cancelled and the method will return True. Is there a way to cancel the future although the cancel() methods tells me it can't be canceled? I am running the backport on Python 2.7

Different way for php and jquery for better work


I am new here and I learned a lot on w3 schools and similar websites about languages. Now I have few question for you guys. Questions are small so I will ask two in one asking:

For php: What is the best different way for security reasons by getting data by post or get.

$post_id = mysqli_real_escape_string($con, $_POST['id']);

$get_id = mysqli_real_escape_string($con, $_GET['id']);

For jquery: What is best different way for getting info from database without reload or is there anyone.

setInterval(function(){
        $('#container').load('file.php')
    }, 1000);

CORS: origin is not allowed access [duplicate]


This question already has an answer here:

I got this error when doing an ajax call to an endpoint

Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8888' is therefore not allowed access.

but why in POSTMAN I tried with the same params and endpoint there's no problem getting the data?


Why is it giving me the error, "the JSON object must be str, not 'bytes'", and how do I fix it?


I was following a tutorial about how to use JSON objects (link: https://www.youtube.com/watch?v=Y5dU2aGHTZg). When they ran the code, they got no errors, but I did. Is it something to do with different Python versions or something?

from urllib.request import urlopen
import json

def printResults(data):
    theJSON = json.loads(data)
    print (theJSON)

def main():
    urlData ="http://earthquake.usgs.gov/earthquakes/feed/v1.0/summary/2.5_day.geojson"

    webUrl = urlopen(urlData)
    print(webUrl.getcode())
    if (webUrl.getcode()==200):
        data = webUrl.read()
        printResults(data)
    else:
        print ("You failed")

main()

Pandas mean across multiple columns


I have a dataframe which I created using numpy arrays (MnthIdx, Val1, Val2, Val3) as:

import pandas as pd
import numpy as np

dfout3 = pd.DataFrame({'Idx': MnthIdx,
                       'Col1': Val1,
                       'Col2': Val2,
                       'Col3': Val3)})

MeanTable1 = pd.pivot_table(dfout3, index=['Idx'], values=['Val1'], aggfunc=[np.mean])
MeanVal1 = np.asarray(MeanTable1['mean'])
MeanTable2 = pd.pivot_table(dfout3, index=['Idx'], values=['Val2'], aggfunc=[np.mean])
MeanVal2 = np.asarray(MeanTable2['mean'])
MeanTable2 = pd.pivot_table(dfout3, index=['Idx'], values=['Val3'], aggfunc=[np.mean])
MeanVal3 = np.asarray(MeanTable3['mean'])

Is it possible that I can do the above 3 steps in 1 steps only.


Why use jQuery on() instead of click()


Currently with jQuery when I need to do something when a Click occurs I will do it like this...

$(".close-box").click( function() {
    MoneyBox.closeBox();
    return false;
});

I was looking at some code someone else has on a project and they do it like this...

$(".close-box").live("click", function () {
    MoneyBox.closeBox();
    return false;
});

Notice it seems to do the same thing as far as I can tell except they are using the live() function which is now Deprecated and jQuery docs say to use on() instead but either way why use live/on() instead of my first example?


Having a model to relate to several different models


I have a simple notification model:

class Notification(models.Model):
    user = models.ForeignKey(User)
    sender = models.ForeignKey(User)
    model = '''What to put here?'''
    comment = models.CharField(max_length=200)
    created = models.DateTimeField(auto_now=False,auto_now_add=True)

I need the notification to relate to several different models, for example; posts, user follows, etc

Is there anyway in django you can relate to several models instead of creating a notification model for each one?

I want to avoid models like this: PostLikeNotification, UserFollowNotification, etc.

So does django have this functionality? I couldn't find it anywhere in the docs.


pandas dataframe- replace row values


I have a dataframe with four columns (see input dataframe below). I need to check if Meta column has pattern relation (example M_relation) then add number from relation column to the meta column value. How this can be done in pandas?

Input dataframe:

--------------------------------------

    Entry1 | Relation | Entry2 | Meta |

--------------------------------------

E11 | R_31 | E21 | M_xxx |

E12 | R_21 | E51 | M_relation |

E33 | R_21 | E51 | M_yyy |

E44 | R_41 | E46 | M_relation |

Output:

--------------------------------------
Entry1 | Relation | Entry2 | Meta |
--------------------------------------

E11 | R_31 | E21 | M_xxx |

E12 | R_21 | E51 | M_relation_21 |

E33 | R_21 | E51 | M_yyy |

E44 | R_41 | E46 | M_relation_41 |
--------------------------------------

reading and doing calculation from .dat file in python


I need to read a .dat file in python which has 12 columns in total and millions of lines of rows. I need to divide column 2,3 and 4 with column 1 for my calculation. So before I load that .dat file, do I need to delete all the other unwanted columns? If not, how do I selectively declare the column and ask python to do the math?

an example of the .dat file would be

time mass x y z - - - - -

1     1   1  1  1 ---------
 2    2   2  2  2 ---------

I am new to python , so a little instruction to open , read and calculation would be appreciated.


jQuery run through multiple if statements then continue


just doing a little little sign up page, and im trying to make it check each field if it has a value if not it will add the class of .error but if all 3 inputs have a value then display the success page

$(".btn").click(function() {
    //Check to see if the inputs have any data
    if ($('.username-input').val() == '') {
        $(this).addClass('error');
    }
    else if ($('.password-input').val() == '') {
        $(this).addClass('error');
    }
    else if ($('.email-input').val() == '') {
        $(this).addClass('error');
    }

    //if all inputs have data open up success page and close it.
    $(".btn").click(function() {
        $(".success-wrapper").animate({
            bottom: "0%"
        }, 'slow');
    });
    $(".close").click(function() {
        $(".success-wrapper").animate({
            bottom: "-100%"
        }, 'slow');
    })
});;

jquery animation to slide left and back


I have the following jquery. What i am trying to do is when i scroll down my page pass 900px a div slides out from the left and when i scroll up pass 900px it slides left out of view. right now if slides out when i am at the bottom of the page and if i scroll back up it does not slide in. i just cant figure what i am doing wrong. i would really appreciate some direction.

$(window).scroll(function() {               
   var content = $(window).scrollTop();
        if (content < 950){
            $('.float-menu').animate({left: '-100px'},800);
            } else {
       if (content > 950) {
           $('.float-menu').animate({left: '0px'},500);
       }

  }

});


gif spinner doesn't appear when submitting form using ajax


I am trying to add a loading gif to my form when the user clicks the submit button using ajax and I want to also disable the submit button. I have tried it this way but it doesn't work. My button does have an ID of 'submit'

 <script type="text/javascript">                                 
// we will add our javascript code here
jQuery(document).ready(function($) {

    $("#ajax-contact-form").submit(function() {
        var str = $(this).serialize();

        $.ajax({
            type: "POST",
            url: "contactfinal.php",
            data: str,
            success: function(response) {
 $('submit').html('<img src="img/ajax-loader.gif" /> &nbsp; sending...').attr('disabled', 'disabled');
                $('#error').html(response);

            }
        });
        return false;
    });
});
</script> 

Empty formData on IE10/11/Edge jQuery


Hello I have such code which works great on every browsers except Internet Explorer 10/11 and Edge.

$(this).on('submit', '.modal-form', function(event) {
    var $form = $(this);
    var $target = $($form.attr('data-target'));
    var $formData = new FormData(this);

    if(event.handled !== true) {
        $.ajax({
            headers: {'X-CSRF-TOKEN': $(this).find('input[name=_token]').val() },
            type: $form.attr('method'),
            url: $form.attr('action'),
            data: $formData,
            processData: false,
            contentType: false,

          success: function(data, status) {
                console.log("success");
          }
        });
        event.handled = true;
    }
    event.preventDefault();
});

I'm using it to post forms in ajax modal windows on my systems. But on Microsoft browsers formData is empty. On server side all inputs are missing. I'm using jQuery 1.11.3


ASP.NET MVC display image from json result


Image is not displaying from json result value. Below is my Controller Action and Jquery

$.post('/User/Comment/',{commentId=Id},function(data){

  $("#cbox").append("<img src="'+data.ImagePath+'" />")

});

Controller:

public ActionResult Comment(string commentId){
     var data=(from p in db.commentdb
     join q in db.profileImage
     on p.Email equals q.Email
     where p.commentId==commentId
     select new
    {
     Name=p.Fullname,
     Comment=p.Comment
     ImagePath=q.ImagePath
     });
    return Json(data,jsonrequestbehavior.allowget)
   }

Please help to fix this. Just I need to display image on razor view based on json return image path


I need assistance with emergency landing


The parent div's background-color is not working ,and I cannot find out the issue why. But it shows up when I put the rest of the children div in comment. Here is the css code.

*{margin:0%;}  

/spacing and neatiness/ body{background-color:blue;}

#head{background-color:orange;
   height:20%;
   width:100%;
   position:relative;}

#menu{position:absolute;
    top:0%;
    left:70%;}

 #menu1{position:absolute;
     top:0%;
     left:0%;}

 li{list-style-type:none;
 border:5px outset gray;
 float:left;
 margin:5px;
 border-radius:10px;
 width:100px;
 background-color:#00ff00;
 text-align:center;}

 a{text-decoration:none;
display:block;}

  a:hover{border:5px inset gray;
      background-color:gray;}

  a:visited{border:none;
        background-color:blue;
        color:white;}

Thanks

dimanche 10 juillet 2016

PyGObject - left-click menu on a status icon


I'm starting to write a small panel applet for Gnome and I'd like the user to be able to left-click on the status icon to see some options and information e.g. similar to sound icon in Gnome 3, where you can set volume via left-click while set preferences via right-click. Right-click code is this:

statusicon.connect("popup-menu", right_button_click)

where right_button_click is the name of the function that gets called on right-click event. The important part is "popup-menu". What would be alternative for setting left-click event?


Pandas: Can pandas groupby filter work on original object?


Starting with this question as base.

Python Pandas: remove entries based on the number of occurrences

data = pandas.DataFrame(
    {'pid' : [1,1,1,2,2,3,3,3],
     'tag' : [23,45,62,24,45,34,25,62],
     })

   #    pid  tag
   # 0    1   23
   # 1    1   45
   # 2    1   62 
   # 3    2   24
   # 4    2   45
   # 5    3   34
   # 6    3   25
   # 7    3   62

   g = data.groupby('tag')
   g.filter(lambda x: len(x) > 1) # filters out lengths > 1. 

  #     pid  tag
  #  1    1   45
  #  2    1   62
  #  4    2   45
  #  7    3   62


 #This would create a new object g: 
 g  =   g.filter(lambda x: len(x) > 1) #where g is now a dataframe. 

I was wondering is there a way to filter out 'groups' by deleting them from original object g. And, would it be faster than creating a new groupby object from filtered groupby.