jeudi 13 août 2015

TypeError: 'CommandCursor' object has no attribute '__getitem__'

I am getting this TypeError when trying to access Bottle's rest api through Apache server, but it's working properly with Bottle's WSGI server.

Mongodb sample data:

 "_id" : ObjectId("55c4f21782f2811a08b7ddbb"),
 "TestName" : "TestName1",
 "Results" : [
     {
             "Test" : "abc",
             "Log" : "Log information"
     },
     {
             "Test" : "xyz",
             "Log" : "Log information"
     },
]

I want to fetch only those records/sub document where Results.Test="abc"

My Bottle API code:

@route('/TestSampleApi',method='GET')
def GetTestData():
    #request.json will have data passed in url
    pipe = [
            {"$match":{"Results": {"$elemMatch": {'Test':'abc'}}}}, 
                { "$unwind" :"$Results"},
                { "$match": { "Results.Test":'abc'}},
                { "$group" : { "_id" : "$_id", "Results" : { "$addToSet" : "$Results" } }}
            ]           
            res = collection.aggregate(pipeline=pipe)
            get_record=res['result']   #getting TypeError in this line 

    response.set_header('Content-Type',  'application/json')
    return dumps(get_record, indent=4)

Above code working properly with curl -i GET "http://localhost:8080/TestSampleApi?Test=abc"
But not working with apache: curl -i GET "http://HOST_NAME/TestSampleApi?Test=abc"



via Chebli Mohamed

How to group an array by multiple keys?

I'd like a function that can group a list of dictionaries into sublists of dictionaries depending on an arbitrary set of keys that all dictionaries have in common.

For example, I'd like the following list to be grouped into sublists of dictionaries depending on a certain set of keys

l = [{'name':'b','type':'new','color':'blue','amount':100},{'name':'c','type':'new','color':'red','amount':100},{'name':'d','type':'old','color':'gold','amount':100},{'name':'e','type':'old','color':'red','amount':100},
{'name':'f','type':'old','color':'red','amount':100},{'name':'g','type':'normal','color':'red','amount':100}]

If I wanted to group by type, the following list would result, which has a sublists where each sublist has the same type:

[[{'name':'b','type':'new','color':'blue','amount':100},{'name':'c','type':'new','color':'red','amount':100}],[{'name':'d','type':'old','color':'gold','amount':100},{'name':'e','type':'old','color':'red','amount':100},
{'name':'f','type':'old','color':'red','amount':100}],[{'name':'g','type':'normal','color':'red','amount':100}]]

If I wanted to group by type and color, the following would result where the list contains sublists that have the same type and color:

[[{'name':'b','type':'new','color':'blue','amount':100}],[{'name':'c','type':'new','color':'red','amount':100}],[{'name':'d','type':'old','color':'gold','amount':100}],[{'name':'e','type':'old','color':'red','amount':100},
{'name':'f','type':'old','color':'red','amount':100}],[{'name':'g','type':'normal','color':'red','amount':100}]]

I understand the following function can group by one key, but I'd like to group by multiple keys:

 def group_by_key(l,i):

      l = [list(grp) for key, grp in itertools.groupby(sorted(l, key=operator.itemgetter(i)), key=operator.itemgetter(i))]

This is my attempt using the group_by_function above

 def group_by_multiple_keys(l,*keys):
      for key in keys:
          l = group_by_key(l,key)
          l = [item for sublist in l for item in sublist]
      return l 

The issue there is that it ungroups it right after it grouped it by a key. Instead, I'd like to re-group it by another key and still have one list of sublists.



via Chebli Mohamed

Solving a system of Quadratic Equations

I am doing a cryptography program in python...I'll give you the summary.

It consists in reading a random phrase, like: "HELLO". Then it assigns it's respective ASCII equal like:

H=72, E=79.

Then, using Pythagoras' Theorem, it creates two numbers C1 and C2, like this:

C1 = sqrt(A^2 + (A+B)^2);
C2= sqrt(B^2 + (A+B)^2)

where, in this case A = H and B = E. That would be the encryption part, but I am having problems solving the system, which will act as the decryptor.

Now here is the question:

How can I solve this system using python?

C1 = sqrt(A^2 + (A+B)^2); 
C2 = sqrt(B^2 + (A+B)^2);

Of course only C1 and C2 are known.

Do I need a new module? Which one?



via Chebli Mohamed

Increasing INSERT Performance in Django For Many Records of HUGE Data

So I've been trying to solve this for a while now and can't seem to find a way to speed up performance of inserts with Django despite the many suggestions and tips found on StackOverflow and many Google searches.

So basically I need to insert a LOT of data records (~2 million) through Django into my MySQL DB, each record entry being a whopping 180KB. I've scaled my testing down to 2,000 inserts yet still cant get the running time down to a reasonable amount. 2,000 inserts currently takes approximately 120 seconds.

So I've tried ALL of the following (and many combinations of each) to no avail:

  • "Classic" Django ORM create model and .save()
  • Single transaction (transaction.atomic())
  • Bulk_create
  • Raw SQL INSERT in for loop
  • Raw SQL "executemany" (multiple value inserts in one query)
  • Setting SQL attributes like "SET FOREIGN_KEY_CHECKS=0"
  • SQL BEGIN ... COMMIT
  • Dividing the mass insert into smaller batches

Apologizes if I forgot to list something, but I've just tried so many different things at this point, I can't even keep track ahah.

Would greatly appreciate a little help here in speeding up performance from someone who maybe had to perform a similar task with Django database insertions.

Please let me know if I've left out any necessary information!



via Chebli Mohamed

Pause/restart and volume control buttons in a GUI to control the audio recording by using python

I currently have a program to collect sound signal from a mic and play the wave form at real-time on python.I am thinking to add some buttons in a GUI for it. Something like pause and restart buttons. Users can control the sound recording by mouse click on these buttons to stop or restart real-time wave display. And the volume control buttons to increase or reduce the volume of output.

Here is the code:

import pyaudio
import tkinter as tk
import wave
import threading
import queue

import matplotlib.pyplot as plt
import matplotlib.animation as animation
import matplotlib.lines as line
import numpy as np
from scipy import fftpack
from scipy import signal
    CHUNK = 1024
    FORMAT = pyaudio.paInt16
    CHANNELS = 1

    RATE = 44100
    RECORD_SECONDS = 5
    WAVE_OUTPUT_FILENAME = "output.wav"
    data =[]
    Recording=False
    FFT_LEN = 128
    frames=[]
    counter=1

    #GUI
    class Application(tk.Frame):
        def __init__(self,master=None):
            tk.Frame.__init__(self,master)
            self.grid()
            self.creatWidgets()

        def creatWidgets(self):
            self.quitButton=tk.Button(self,text='quit',command=root.destroy)
            self.quitButton.grid(column=1,row=3)


    #Matplotlib
    fig = plt.figure()
    rt_ax = plt.subplot(212,xlim=(0,CHUNK), ylim=(-10000,10000))
    fft_ax = plt.subplot(211)
    fft_ax.set_yscale('log')
    fft_ax.set_xlim(0,CHUNK/2 + 1)
    fft_ax.set_ylim(1,100000000)
    rt_ax.set_title("Real Time")
    fft_ax.set_title("FFT Time")
    rt_line = line.Line2D([],[])
    fft_line = line.Line2D([],[])

    rt_data=np.arange(0,CHUNK,1)
    fft_data=np.arange(0,CHUNK/2 + 1,1)
    rt_x_data=np.arange(0,CHUNK,1)
    fft_x_data=np.arange(0,CHUNK/2 + 1,1)

    def plot_init():
        rt_ax.add_line(rt_line)
        fft_ax.add_line(fft_line)
        return fft_line,rt_line,

    def plot_update(i):
        global rt_data
        global fft_data

        rt_line.set_xdata(rt_x_data)
        rt_line.set_ydata(rt_data)

        fft_line.set_xdata(fft_x_data)
        fft_line.set_ydata(fft_data)
        return fft_line,rt_line,


    ani = animation.FuncAnimation(fig, plot_update,
                                  init_func=plot_init, 
                                  frames=1,
                                  interval=30,
                                  blit=True)


    # pyaudio
    p = pyaudio.PyAudio()
    q = queue.Queue()

    def audio_callback(in_data, frame_count, time_info, status):
        global ad_rdy_ev

        q.put(in_data)
        ad_rdy_ev.set()
        if counter <= 0:
            return (None,pyaudio.paComplete)
        else:
            return (None,pyaudio.paContinue)


    stream = p.open(format=FORMAT,
            channels=CHANNELS,
            rate=RATE,
            input=True,
            output=False,
            frames_per_buffer=CHUNK,
            stream_callback=audio_callback)


    if Recording:
        wf = wave.open(WAVE_OUTPUT_FILENAME, 'wb')
        wf.setnchannels(CHANNELS)
        wf.setsampwidth(p.get_sample_size(FORMAT))
        wf.setframerate(RATE)

    print("Start Recording")
    stream.start_stream()

    #processing block

    window = signal.hamming(CHUNK)

    def read_audio_thead(q,stream,frames,ad_rdy_ev):
        global rt_data
        global fft_data

        while stream.is_active():
            ad_rdy_ev.wait(timeout=1000)
            if not q.empty():
                #process audio data here
                data=q.get()
                while not q.empty():
                    q.get()
                rt_data = np.frombuffer(data,np.dtype('<i2'))
                rt_data = rt_data * window
                fft_temp_data=fftpack.fft(rt_data,rt_data.size,overwrite_x=True)
                fft_data=np.abs(fft_temp_data)[0:fft_temp_data.size/2+1]
                if Recording :
                    frames.append(data)
            ad_rdy_ev.clear()

    ad_rdy_ev=threading.Event()

    t=threading.Thread(target=read_audio_thead,args=(q,stream,frames,ad_rdy_ev))

    t.daemon=True
    t.start()

    plt.show()
    root=tk.Tk()
    app=Application(master=root)
    app.master.title("Test")
    app.mainloop()

    stream.stop_stream()
    stream.close()
    p.terminate()

    print("* done recording")
    if Recording:
        wf.writeframes(b''.join(frames))
        wf.close()



via Chebli Mohamed

Django helper application's static files not found in admin pages?

Ce résumé n'est pas disponible. Veuillez cliquer ici pour afficher l'article.

Installing a .whl Python package into a specific directory other than the default

I am trying to install the 64 bit version of ntlk, which comes in a .whl file, in a different directory than the standard python34/Lib folder. I am using windows 10 64 bit and python 3.4 64 bit.

I first tried using the instructions in this question (which worked for other modules):

Install a python package into a different directory using pip?

The command I typed into cmd was:

py -m pip install --install-option="--prefix=$PATH_NAME" nltk-3.0.4-py2.py3-none-any.whl

It promptly gave me the following error:

UserWarning: Disabling all use of wheels due to the use of --build-options / --global-options / --install-options.

It appears that I can't install WHL files using the --install-option. Is there an alternate way I can install the .whl package in a non default directory?

Edit: I marked this as solved because the proposed solution allows me to do what I need in my own use case. However, it doesn't completely answer the question due to inherent limitations in using --root to choose an alternate directory. There is technically no correct solution to this problem, see the answer's comments for details.



via Chebli Mohamed

Pandas groupby and describe flags AttributeError

I have a bunch of data stored in vals. The indices are monotonic, but not continuous. I'm attempting to do some analysis on histograms of the data, so I've created the following structure:

hist = pd.DataFrame(vals)

hist['bins'] = pd.cut(vals, 100)

This is data taken from an experimental instrument and I know that some of the bins have only 1 or 2 counts in them, which I'm trying to remove. I've tried using groupby as follows and get the following error (Full traceback included at the end of the note):

hist.groupby('bins').describe()

AttributeError: 'Categorical' object has no attribute 'flags' 

However, when I do the following, the error does not show up and I get the expected result:

In[]:  hist.index = hist.bins
In[]:  hist['bins'] = hist.index
In[]:  desc = hist.groupby('bins').describe()
In[]:  desc.index.names = ['bins', 'describe']

Out[]: **describe with MultiIndex for rows.**

If I don't include the second line hist['bins'] = hist.index, I still get an AttributeError: 'Categorical' object has no attribute 'flags' and to the best that I can tell, the traceback is identical.

Can someone explain what the flags are and why they only seem to work when I set the index to bins and then replace the bins by the version stored in the index?

My end goal is to remove the data for bins with counts <= 6. If someone has an easier workaround than the way I'm going after it, I'd also be grateful.

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-11-f606a051f2e4> in <module>()
----> 1 hist.groupby('bins').describe()

C:\Users\balterma\AppData\Local\Enthought\Canopy\App\appdata\canopy-1.4.1.1975.win-x86_64\lib\site-packages\IPython\core\displayhook.pyc in __call__(self, result)
    245             self.start_displayhook()
    246             self.write_output_prompt()
--> 247             format_dict, md_dict = self.compute_format_data(result)
    248             self.write_format_data(format_dict, md_dict)
    249             self.update_user_ns(result)

C:\Users\balterma\AppData\Local\Enthought\Canopy\App\appdata\canopy-1.4.1.1975.win-x86_64\lib\site-packages\IPython\core\displayhook.pyc in compute_format_data(self, result)
    155 
    156         """
--> 157         return self.shell.display_formatter.format(result)
    158 
    159     def write_format_data(self, format_dict, md_dict=None):

C:\Users\balterma\AppData\Local\Enthought\Canopy\App\appdata\canopy-1.4.1.1975.win-x86_64\lib\site-packages\IPython\core\formatters.pyc in format(self, obj, include, exclude)
    150             md = None
    151             try:
--> 152                 data = formatter(obj)
    153             except:
    154                 # FIXME: log the exception

C:\Users\balterma\AppData\Local\Enthought\Canopy\App\appdata\canopy-1.4.1.1975.win-x86_64\lib\site-packages\IPython\core\formatters.pyc in __call__(self, obj)
    479                 type_pprinters=self.type_printers,
    480                 deferred_pprinters=self.deferred_printers)
--> 481             printer.pretty(obj)
    482             printer.flush()
    483             return stream.getvalue()

C:\Users\balterma\AppData\Local\Enthought\Canopy\App\appdata\canopy-1.4.1.1975.win-x86_64\lib\site-packages\IPython\lib\pretty.pyc in pretty(self, obj)
    360                             if callable(meth):
    361                                 return meth(obj, self, cycle)
--> 362             return _default_pprint(obj, self, cycle)
    363         finally:
    364             self.end_group()

C:\Users\balterma\AppData\Local\Enthought\Canopy\App\appdata\canopy-1.4.1.1975.win-x86_64\lib\site-packages\IPython\lib\pretty.pyc in _default_pprint(obj, p, cycle)
    480     if getattr(klass, '__repr__', None) not in _baseclass_reprs:
    481         # A user-provided repr.
--> 482         p.text(repr(obj))
    483         return
    484     p.begin_group(1, '<')

C:\Users\balterma\AppData\Local\Enthought\Canopy\User\lib\site-packages\pandas\core\base.pyc in __repr__(self)
     62         Yields Bytestring in Py2, Unicode String in py3.
     63         """
---> 64         return str(self)
     65 
     66 

C:\Users\balterma\AppData\Local\Enthought\Canopy\User\lib\site-packages\pandas\core\base.pyc in __str__(self)
     42         if compat.PY3:
     43             return self.__unicode__()
---> 44         return self.__bytes__()
     45 
     46     def __bytes__(self):

C:\Users\balterma\AppData\Local\Enthought\Canopy\User\lib\site-packages\pandas\core\base.pyc in __bytes__(self)
     54 
     55         encoding = get_option("display.encoding")
---> 56         return self.__unicode__().encode(encoding, 'replace')
     57 
     58     def __repr__(self):

C:\Users\balterma\AppData\Local\Enthought\Canopy\User\lib\site-packages\pandas\core\frame.pyc in __unicode__(self)
    507             width = None
    508         self.to_string(buf=buf, max_rows=max_rows, max_cols=max_cols,
--> 509                        line_width=width, show_dimensions=show_dimensions)
    510 
    511         return buf.getvalue()

C:\Users\balterma\AppData\Local\Enthought\Canopy\User\lib\site-packages\pandas\core\frame.pyc in to_string(self, buf, columns, col_space, colSpace, header, index, na_rep, formatters, float_format, sparsify, index_names, justify, line_width, max_rows, max_cols, show_dimensions)
   1340                                            max_rows=max_rows,
   1341                                            max_cols=max_cols,
-> 1342                                            show_dimensions=show_dimensions)
   1343         formatter.to_string()
   1344 

C:\Users\balterma\AppData\Local\Enthought\Canopy\User\lib\site-packages\pandas\core\format.pyc in __init__(self, frame, buf, columns, col_space, header, index, na_rep, formatters, justify, float_format, sparsify, index_names, line_width, max_rows, max_cols, show_dimensions, **kwds)
    345             self.columns = frame.columns
    346 
--> 347         self._chk_truncate()
    348 
    349     def _chk_truncate(self):

C:\Users\balterma\AppData\Local\Enthought\Canopy\User\lib\site-packages\pandas\core\format.pyc in _chk_truncate(self)
    410             else:
    411                 row_num = max_rows_adj // 2
--> 412                 frame = concat((frame.iloc[:row_num, :], frame.iloc[-row_num:, :]))
    413             self.tr_row_num = row_num
    414 

C:\Users\balterma\AppData\Local\Enthought\Canopy\User\lib\site-packages\pandas\tools\merge.pyc in concat(objs, axis, join, join_axes, ignore_index, keys, levels, names, verify_integrity, copy)
    752                        keys=keys, levels=levels, names=names,
    753                        verify_integrity=verify_integrity,
--> 754                        copy=copy)
    755     return op.get_result()
    756 

C:\Users\balterma\AppData\Local\Enthought\Canopy\User\lib\site-packages\pandas\tools\merge.pyc in __init__(self, objs, axis, join, join_axes, keys, levels, names, ignore_index, verify_integrity, copy)
    884         self.copy = copy
    885 
--> 886         self.new_axes = self._get_new_axes()
    887 
    888     def get_result(self):

C:\Users\balterma\AppData\Local\Enthought\Canopy\User\lib\site-packages\pandas\tools\merge.pyc in _get_new_axes(self)
    957                 new_axes[i] = ax
    958 
--> 959         new_axes[self.axis] = self._get_concat_axis()
    960         return new_axes
    961 

C:\Users\balterma\AppData\Local\Enthought\Canopy\User\lib\site-packages\pandas\tools\merge.pyc in _get_concat_axis(self)
   1009 
   1010         if self.keys is None:
-> 1011             concat_axis = _concat_indexes(indexes)
   1012         else:
   1013             concat_axis = _make_concat_multiindex(indexes, self.keys,

C:\Users\balterma\AppData\Local\Enthought\Canopy\User\lib\site-packages\pandas\tools\merge.pyc in _concat_indexes(indexes)
   1027 
   1028 def _concat_indexes(indexes):
-> 1029     return indexes[0].append(indexes[1:])
   1030 
   1031 

C:\Users\balterma\AppData\Local\Enthought\Canopy\User\lib\site-packages\pandas\core\index.pyc in append(self, other)
   4603             arrays = []
   4604             for i in range(self.nlevels):
-> 4605                 label = self.get_level_values(i)
   4606                 appended = [o.get_level_values(i) for o in other]
   4607                 arrays.append(label.append(appended))

C:\Users\balterma\AppData\Local\Enthought\Canopy\User\lib\site-packages\pandas\core\index.pyc in get_level_values(self, level)
   4239         unique = self.levels[num]  # .values
   4240         labels = self.labels[num]
-> 4241         filled = com.take_1d(unique.values, labels, fill_value=unique._na_value)
   4242         values = unique._simple_new(filled, self.names[num],
   4243                                     freq=getattr(unique, 'freq', None),

C:\Users\balterma\AppData\Local\Enthought\Canopy\User\lib\site-packages\pandas\core\common.pyc in take_nd(arr, indexer, axis, out, fill_value, mask_info, allow_fill)
    829         out_shape[axis] = len(indexer)
    830         out_shape = tuple(out_shape)
--> 831         if arr.flags.f_contiguous and axis == arr.ndim - 1:
    832             # minor tweak that can make an order-of-magnitude difference
    833             # for dataframes initialized directly from 2-d ndarrays

AttributeError: 'Categorical' object has no attribute 'flags' 



via Chebli Mohamed

unpy2exe error: AttributeError: 'module' object has no attribute 'openssl_md_meth_names'

I am trying to use unpy2exe to, what else, undo py2exe. I need some help. I can run it with the proper inputs, or just the EXE, and i get the below error. Full log:

Traceback (most recent call last):
  File "C:\hexdecenc\unpy2exe.py", line 9, in <module>
    import pefile
  File "C:\hexdecenc\pefile.py", line 41, in <module>
    import hashlib
  File "C:\Python27\lib\hashlib.py", line 138, in <module>
    _hashlib.openssl_md_meth_names)
AttributeError: 'module' object has no attribute 'openssl_md_meth_names'

If anyone has any suggestions, PLEASE PLEASE help!



via Chebli Mohamed

Get probable input based on a given output in a neural network

I'm starting to learn neural networks, and I just made a program that learned how to recognize handwritten digits with pretty good accuracy (trained with backpropagation). Now I want to be able to see what the network thinks a perfect number looks like (essentially getting a pixel array which produces a desired number but is not from the dataset). My research has come up empty, but I posted on another site and was suggested to look at backpropagating to the input. I don't have much of a math background, so could someone point me in the right direction on how to implement that (or any other method of achieving my goal)?



via Chebli Mohamed

confused about looping through lists in python

Dear StackOverFlow, I just starting learning python, and I'm a little confused when it comes to looping through lists. I have been using Python.org's official python tutorial to learn. In section 4.2 on this page http://ift.tt/PzkDST, in the last example they write this code:

for w in words[:]:
    if len(w) > 6:
        words.insert(0, w)

The part that confuses me is for w in words[:]: Maybe I need to read their description a little better, but I can't seem to figure out why the previous code works and this doesn't:for w in words:. I guess it confuses me because when i type words[:] in the interpreter I get the same result when i type words in the interpreter. If you could shed some light on this topic, I would be very grateful.



via Chebli Mohamed

With Python's boto, how can I get the contents of an encrypted file?

With an unencrypted file, I can do the following:

key = s3_bucket.get_key(path)
value_as_string = key.get_contents_as_string()

But if the file's encrypted, I need to change something about that. I can't figure out what from reading the docs. What do I change?

I know the master symmetric key, which is a string like 30 chars or so long.



via Chebli Mohamed

django deployment using ubuntu ec2 (bitnami)

I'm trying to deploy my django app. I have it hooked up to an Ubuntu ec2 with bitnami on a amazon EC2 server.

1. How do I access my local deployment of the app inside my ec2?: I connect to my ec2 via my macbook terminal. I run python manage.py runserver inside the terminal and it says it's connected to the localhost of the ec2. Great. But how do I access the localhost of the ec2 at the 127.0.0.1:8000 website when I only can talk to it through terminal?

2. I'm having trouble setting up my templates: I keep getting the error Template does not exist

The template-loader postmortem showed:

Django tried loading these templates, in this order:

Using loader django.template.loaders.filesystem.Loader:

Using loader django.template.loaders.app_directories.Loader:

/opt/bitnami/apps/django/lib/python2.7/site-packages/http://ift.tt/1hAv5aE (File does not exist)

/opt/bitnami/apps/django/lib/python2.7/site-packages/http://ift.tt/1L9LU61 (File does not exist)

Thanks.



via Chebli Mohamed

Passing in params to \N{name} unicode string

My question is; Do we in python have a workaround for passing in named params into an escaped unicode segment? for example

print u"No... haha {name} is a \N{MALE SIGN}".format(name = 'lisa', gender = 'MALE')

to

print u"No... haha {name} is a \N{{gender} SIGN}".format(name = 'lisa', gender = 'MALE')



via Chebli Mohamed

R quantile on frequency values

I'd like to get quantiles on frequency values. For example, suppose I have data like the following:

length frequency
1      13    # There are 13 length 1 items.
2      20    # There are 20 length 2 items.
8      17
10     25
...
[10000+ more entries in file]

So I'd like to get quantiles for certain values like 0.05, 0.10, 0.50, 0.90, 0.95, 0.99. Also, I'd like to get the rank of a certain length. How can I do that on R or on Python?



via Chebli Mohamed

Python Tkinter Breaks OS X Trackpad Gestures

So I'm using Tkinter in a script that I'm making, and I've noticed that after running my script, my trackpad gestures don't work until I run killall Dock in Terminal.app.

This doesn't happen if I comment out the tkinter code from my script.

Here's the relevant bits of Python code I'm using.

from Tkinter import Tk
from tkFileDialog import askopenfilenames

Tk().withdraw() # avoid blank tk window opening
files = askopenfilenames(title='Select all logs you would like to compile.')



via Chebli Mohamed

PyMySQL3 and SQLAlchemy

I have a simple script I'd like to run

connection_string = 'mysql+pymysql://example@example.com'
engine = sa.create_engine(connection_string)
connection = engine.connect()

query = """
    select distinct n.listname, n.notes
    from notes n 
    join run r on n.start = r.start
    where r.branch = 'B_HEAD' 
    and r.start > '2015-08-01' 
    and n.notes like '%ug%';"""
result = connection.execute(query)
for row in result:
    print("listname: {} | notes: {}".format(row['listname'], row["notes"]))

The problem is that PyMySQL isn't Python3 compatible. There is, however, a PyMySQL3.

but if I try to use that module as my connector I get

sqlalchemy.exc.NoSuchModuleError: Can't load plugin: sqlalchemy.dialects:mysql.pymysql3

Is there a simple way to make SQLAlchemy and PyMySQL3 play nice? Baring that is there a way to create custom connectors for SQLAlchemy?



via Chebli Mohamed

installing scipy can't find fortran mac

I'm having huge troubles installing scipy.

When i run: pip install scipy

I get:

Requirement already satisfied (use --upgrade to upgrade): scipy in 
/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python

However when i do import scipy in python I get the no module called scipy error.

When i try via easy_install scipy, it starts downloading and then gives me:

error: Setup script exited with error: library dfftpack has Fortran sources but no Fortran compiler found

When i try to install gfortran via brew I get: brew gfortran

Error: No available formula for gfortran 
GNU Fortran is now provided as part of GCC, and can be installed with:
brew install gcc

But when i try to do that I get:

(py)Shopkicks-MacBook-Air-12:shopkick markthornburg$ brew install gcc
Warning: gcc-5.2.0 already installed, it's just not linked

What am I doing wrong?



via Chebli Mohamed

Drag and drop file from OSX finder to PyQt4 application

I've got an app view I'm putting together with PyQt4, and am implementing a drag and drop feature on a QWebView.

I've got drag and drop working, except that when I drop a folder or file, it gives me some sort of OSX temporary filename (see /.file/id=6571367.6613253/), instead of the actual name and location. I'm wondering, is there any way to extrapolate the real directory or filename with full system path, or worst case at least can I operate on this temporary locator?

I do see an actual .file file on the root directory.

#!/usr/bin/env python
from PyQt4.QtCore import *
from PyQt4.QtGui import *
from PyQt4.QtWebKit import *

    class MainView(QWebView):

        def __init__(self):
            QWebView.__init__(self)
            self.loadFinished.connect(self._result_available)
            self.setAcceptDrops(True)

        def _result_available(self, ok):
            frame = self.page().mainFrame()

        def dragEnterEvent(self, event):
            if event.mimeData().hasUrls:
                event.accept()
            else:
                event.ignore()

        def dragMoveEvent(self, event):
            if event.mimeData().hasUrls:
                event.setDropAction(Qt.CopyAction)
                event.accept()
            else:
                event.ignore()

        def dropEvent(self, event):
            if event.mimeData().hasUrls:
                event.setDropAction(Qt.CopyAction)
                event.accept()
                for url in event.mimeData().urls():
                    print QUrl(url.path())
            else:
                event.ignore()



via Chebli Mohamed

python reverse iterator vs. generator behavior

Why does removing items a list break reversed objects? It doesn't break gen-exprs, and appending to or modifying the list doesn't break the reversed object, and it obviously points to the original object, so why can't it give a truncated version? Perhaps some examples can clarify:

l = [1, 2, 3, 4]
r = reversed(l)
g = (i for i in l)
l.pop()  # returns 4
l   # returns [1, 2, 3]

for i in g:print(i)  # prints 1 2 3 (on separate lines)
for i in r:print(i)  # prints ...nothing

r = reverse(l)
g = (i for i in l)
l[1] = 4
for i in g:print(i)  # prints 1 4 3 (on separate lines)
for i in r:print(i)  # prints 3 4 1 (on separate lines)

r = reversed(l)
g = (i for i in l)
l.append(5)
l  # returns [1, 4, 3, 5] just to keep you on your toes

for i in g:print(i)  # prints 1 4 3 5 (on separate lines)
for i in r:print(i)  # prints 3 4 1   (on separate lines)

So - if the genexpr is smart enough to point to the object, and just respond to however the object has changed, why doesn't reversed? It obviously doesn't make a copy, otherwise it wouldn't "fail" on the first situation, and it wouldn't pick up the 4 in the second. So it must point to the object. Why can't it just start from index -1 and work backwards?



via Chebli Mohamed

Modify subset of elements within original python list

I see how list comprehensions are good at returning subsets of lists or even across the board remappings if no condition is set. However the filtering conditions will return values in a list that may be smaller than the filtered list. How can I take the positions of the returned values and change those elements conditionally?

Here's a simple example,

>>> v = ['a' , 'b' , 'c' , 'd' , 'f' , 'k' , 'g' , 'a', 'd']
>>> t = ['a', 'k']

How can I modify the elements of v in t to map to new a new value, say 'z', to yield something like

>>> v = ['z' , 'b' , 'c' , 'd' , 'f' , 'z' , 'g' , 'z', 'd']

There's many questions on SO with people coming from Matlab looking to do the equivalent of logical indexing, but mainly just for the purposes of selecting elements and not modifying them inplace as I wish to do. I'd like to do the equivalent of logical indexing for the purposes of modifying filtered elements.

I just found out too that I cannot provide multiple indexes as well to a Python list. I'm using Python 3.

>>> v[ [1,3] ] = 'z'
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: list indices must be integers, not list
>>> v[ 1:3 ] = 'z'
>>> v
['a', 'z', 'd', 'f', 'k', 'g', 'a', 'd']

filter works to give me an iterable of the actual objects, but I can't figure out how to modify the elements they point to.

>>> v = ['a' , 'b' , 'c' , 'd' , 'f' , 'k' , 'g' , 'a', 'd']
>>> t = ['a', 'k']
>>> p = filter(lambda x: x in t, v)
>>>
>>> for elem in p :
...    print(elem)
...
a
k
a
>>>
>>> for elem in p :
...    p = 'z'
...
>>>
>>> for elem in p :
...    print(elem)
...
>>>



via Chebli Mohamed

Django 1.8 template's url tag TypeError

I am trying to learn how to use the Django template's url tag to make my code more generic but I am having some exception being raised.

Exception Type:     TypeError
Exception Value:    argument to reversed() must be a sequence

Here is my global urls.py

from django.conf.urls import include, url
from django.contrib import admin

urlpatterns = [
    url(r'^admin/', include(admin.site.urls)),
    url(r'^polls/', include('polls.urls'))
]

Here is my app urls.py

from django.conf.urls import url
from . import views

urlpatterns = {
    url(r'^$', views.index, name='index'),
    url(r'^(?P<id>[0-9]+)/$', views.detail, name='detail'),
    url(r'^(?P<id>[0-9]+)/results/$', views.results, name='results'),
    url(r'^(?P<id>[0-9]+)/vote/$', views.vote, name='vote')
}

And here is one template where I am trying to use the feature

{% if latest_question_list %}
  <ul>
    {% for question in latest_question_list %}
      <li><a href="{% url 'polls:detail' question.id %}">{{ question.content }}</a></li>
    {% endfor %}
  </ul>
{% else %}
  <p>No polls are available.</p>
{% endif %}

I have been looking for this for hours, and I seem to follow all the guidelines to make this work, but of course something must be wrong.



via Chebli Mohamed

How to export a fit done with gam in R?

Is there any way I can export a fitting performed with gam?

fit <- gam(y~s(x1)+s(x2), data = data)

I want to use the function in C or Python but I don't know if this is possible.

I know I can get the coefficients fit$coefficients but I don't know anything about the smoothers s(x1) and s(x2).

Second, can I do a fitting this way?

fit <- gam(y~s(x1)+s(x2)+s(x1/x2), data = data)



via Chebli Mohamed

using uuid and bcrypt with django not generating unique values

building a uuid then hashing it with bcrypt ends up generating an object with the same value in auth_secret(uuid4() is not generating a unique value for each new instance) every time one is initialized. Here is the terminal output

>>> from quickstart.models import FarmUserAuthentication
>>> c = FarmUserAuthentication('as')
>>> d = FarmUserAuthentication('asdfs')
>>> c
<FarmUserAuthentication:  $2a$12$euUMcvhPwPsS7SQgiOVGNeWr792cq.tKONl9bTVjY3nvrxpczPqs6>
>>> d
<FarmUserAuthentication:  $2a$12$euUMcvhPwPsS7SQgiOVGNeWr792cq.tKONl9bTVjY3nvrxpczPqs6>

here is my code in models.py

class FarmUserAuthentication(models.Model):
    auth_id = models.CharField(primary_key = True, max_length = 10)
    hash = bcrypt.hashpw(str(uuid.UUID4()), bcrypt.gensalt())
    auth_secret = models.CharField(max_length=100, default= hash, editable=False)



via Chebli Mohamed

Looping and returning all values in a dictionary

Whenever I execute the code below it only returns one total_hours instead of all hours in the value arrays

worker_hours = {'John': [8,8,4,3,8],
                'Leo': [5,6,7,8,9],
                'Sammy': [4,5,6,8,8],
                'Ken': [8,8,8,8,8]}

def calc_check(worker_list):
    worker = ''
    total_hours = 0
    for worker in worker_list:
        total_hours = sum(worker_list[worker]) * 13
    return total_hours

print(calc_check(worker_hours))



via Chebli Mohamed

Optimize with python scipy.optimize.minimize

I have a question regarding optimization with scipy. I would like to optimize the schedule of a pump storage plant. Basically there are 96 known prices (for each quarter of the day) and the model should decide whether to (1) pump, (2) turbine or (3) do nothing for each respective quarter. Thereby, there are some bounds for X: -100

To start I tried the following:

from scipy.optimize import minimize
prices=np.array([[1.5,50,30]])
xp =np.array([[1.5,50,30]])

fun = lambda x: xp* prices #here xp and prices should be matrices

cons = ({'type': 'ineq', 'fun': lambda x:  (xp*0.25)<=500},
    {'type': 'ineq', 'fun': lambda x: (xp*0.25)>=0})

bnds = ((0, None), (0, None), (0, None))

res = minimize(fun, (2, 0,0), method='SLSQP', bounds=bnds, constraints=cons)

However, this throws an error:

ValueError: all the input arrays must have same number of dimensions

I have no clue why this error appears. Can somebody give me a hint?

Thank you!



via Chebli Mohamed

Idiomatic list of all natural numbers

I am trying to create a generator that will return the natural numbers in order. This is used to enumerate another generator which will exit upon StopIteration, which seems like the easiest way to do it. However, I cannot find an idiomatic way of creating this generator:

def numbers():
    i = 0
    while True:
        yield i
        i += 1

q = Queue.Queue()
for i in numbers():
    try:
        q.put((i, my_generator.next()))
    except StopIteration:
        break

This does work, but it seems unpythonic to use a while True: in this way.

Is there a standard library function to iterate over the natural numbers?



via Chebli Mohamed

Interactive plots placement in ipython notebook widget

I've got two plots which I'd like to make interactive with ipython notebook widgets. The code below is a simplified sample of what I'm trying to do.

import matplotlib.pyplot as plt
import IPython.html.widgets as wdg

def displayPlot1(rngMax = 10):
    plt.figure(0)
    plt.plot([x for x in range(0, rngMax)])

wdg1 = wdg.interactive(displayPlot1, rngMax = wdg.IntSlider(20))

def displayPlot2(rngMax = 10):
    plt.figure(1)
    plt.plot([x**2 for x in range(0, rngMax)])

wdg2 = wdg.interactive(displayPlot2, rngMax = wdg.IntSlider(10))

wdg.ContainerWidget([wdg.HTML("""<h1>First Plot</h1>"""),
                     wdg1, 
                     wdg.HTML("""<h1>Second Plot</h1>"""), 
                     wdg2])

The first problem is that it displays all the widgets first, and two plots one after another at the end:

title1
widget1
title2
widget2
plot1
plot2

I'd like to have:

title1
widget1
plot1    
title2
widget2
plot2

Also it seems the whole output gets overwritten as soon as I touch any of the sliders, and displays one plot only (the one I'm changing).

How do I fix this problem? (I potentially can do it if I separate them into two different cells, however I'm planning to do something more complex and it needs to be in one cell eventually)



via Chebli Mohamed

Compare lines in two .txt files, print out new line for not contained words

I have the following piece of code that, for every line in textfile1, searches textfile2 and if the line is contained in textfile2 prints out the corresponding line of textfile2. I want to however, print out new line for every line not contained in textfile2. Here is the code:

def readline():
with open("textfile1.txt") as file, open("textfile2.txt") as file2:
    string = set(map(str.rstrip,file))
    for line in file2:
        spl = line.split(None, 1)[0]
        if spl in string:
            print(line.rstrip())    
        else:              ##if spl not in string print new line
            print("\n")

It doesn't work as I expect (doesn't print out any new lines), what may be the problem or any alternative solutions?

Sample Textfile1:

'
a
aa
ab
abandon
abandonaudiofocus
abandonsession
abort
abortablehttprequest
abortanimation
abortcaptures
abortconnection
abortpolicy
abortrequest
abs

Sample Textfile2:

'                |            22624
a                |               91
aa               |                7
ab               |                6
abort            |                8
abortanimation   |                5
abs              |              131
abslistview      |              115
absolutelayout   |               50
absolutesizespan |                6
abstracthttpentity |                2
abstractlist     |                1
abstractmap      |                4
abstractselector |                1
abstractset      |                2

Textfile1 includes many more words and it contains all the words in textfile2.



via Chebli Mohamed

2 fields from different models in a form

I have a form that works perfectly fine
models.py:

class Location(models.Model):
    title = models.CharField(max_length=300)
    description = models.TextField(null=True, blank=True)
    address = models.TextField(null=True, blank=True)

class Review (models.Model):
    location = models.ForeignKey(Location)
    description = models.TextField(null=True, blank=True) 

views.py:

class Create(CreateView):
  model = coremodels.Review
  template_name = 'location/test.html'
  fields = '__all__'
  def form_valid(self, form):
    form.save()
    return HttpResponseRedirect('')

    return super(Create, self).form_valid(form)

html:

<form action="" method="post">{% csrf_token %}
    {{ form}} 
    <input type="submit" value="Create" />
</form>

When I open the site I can select a location and give a review over the create button. However, now I am dependent on the prefilled values in the Location class. What if I want that a user can directly create a description as well as a title of the location (I don't want the title to be in class Review) I already tried looking for this in the docs but couldn't find anything. Somewhere I read that I could create two different forms that handle to different things but I'm not sure how to merge that all in the class Create. Is there something like model = coremodels.Review & coremodels.Location and then in the html I could do

{{form.title}}
{{form.description}}  

Anyone any ideas or search terms I could look for?

Thanks !



via Chebli Mohamed

Compile Python Code In Obj-C

Hello this question is a little broad but i'm just looking for some basic information.

I have seen multiple I-pad apps that can run simple python code from an app. I just wanted to know how they do this. I know it is possible to run python code embedded in an iOS app but I am confused as to how. Is there any library that would allow me to run embedded python code. I would also like to know what pyobjc really does because I have not seen a full build or what objp does.

I know this is asking for a lot but thank you so much.



via Chebli Mohamed

Is that possible to "recover" UTC time given local time and geometrical time shift?

I now have server local time and a hour shift to UTC(say +5, -8, etc), how can I recover it to UTC?

Note that it's not as intuitive as it is because of summer time. Currently I am in EDT, which should be UTC+5, but in fact, in summer, we only +4. And unfortunately I don't (want to) know the timezone of the server so I am not sure whether it's possible to calculate the UTC with given info.

My target language is python, but if an solution exists, the language itself shouldn't be a big problem.

Why I have such restriction, is because of this. It just doesn't return a good text timezone description instead of a number.

following is a real element in practice from my server:

<RegionalSettings>
  <Language>1033</Language>
  <Locale>1033</Locale>
  <AdvanceHijri>0</AdvanceHijri>
  <CalendarType>1</CalendarType>
  <Time24>False</Time24>
  <TimeZone>300</TimeZone>
  <SortOrder>2070</SortOrder>
  <Presence>True</Presence>
</RegionalSettings>

notice here the timezone field

<TimeZone>300</TimeZone>

it's in minutes, so it tells me I am somewhere in UTC+5, but not a honest timeshift to UTC.



via Chebli Mohamed

ReadtheDoc doens't automatically generate py-modindex.html

I am using sphinx to document my project. The build-in index.rst file has:

Indices and tables
------------------

* :ref:`genindex`
* :ref:`modindex`
* :ref:`search`

which automatically generate a py-modindex.html page. This functions very good on my local machine.

So I am trying to host the doc on readthedoc.org. But, what readthedoc do is go to my github, locate the conf.py, generate all html. But since

* :ref:`modindex` 

requires all module importable from local, they may not did that. Hence I cannot see the py-modindex.html page. Any idea how to bring it back?

This is my readthedoc page: http://ift.tt/1IP7Osn

This the page I want (but it's not on): http://ift.tt/1J7eHsu

This is github project page: http://ift.tt/1IP7M3F



via Chebli Mohamed

Python3's super and comprehensions -> TypeError?

Using python3's super in a comprehension seems to always result in TypeError: super(type, obj): obj must be an instance or subtype of type (but using python 2's super does work as expected)

class A(object):
    def __repr__(self):
         return "hi!"  

class B(A):
    def __repr__(self):
         return "".join(super().__repr__() for i in range(2))  

repr(B())
#output: <repr(<__main__.B at 0x7f70cf36fcc0>) failed: TypeError: super(type, obj): obj must be an instance or subtype of type>

class C(A):
    def __repr__(self):
        s = ''
        for i in range(4):
            s += super().__repr__()
        return s     

repr(C())
#output: hi!hi!hi!hi!

class D(A):
    def __repr__(self):
        return "".join(super(D,self).__repr__() for i in range(4))

repr(D())
#output: hi!hi!hi!hi!

So, why does new super() fail in generator comprehensions?

Addendum:

In [28]: class E(A):
   ....:     def __repr__(self):
   ....:         def inner():
   ....:             print(repr(__class__))
   ....:         inner()
   ....:         return ''
In [29]: repr(E())
<class '__main__.E'>
Out[29]: ''

In [30]: class F(A):
   ....:     def __repr__(self):
   ....:         return "".join([super().__repr__() for i in range(4)])
   ....:     

In [31]: repr(F())

TypeError: super(type, obj): obj must be an instance or subtype of type



via Chebli Mohamed

Face detection errors in cv2

Lately I've been trying to write a simple program that can detect a face. I've never done this before so it was more of a warm up for me to get the hang of it. But I keep getting errors with every different sample I try. I've even copied samples straight off of the OpenCV website and I still got nothing but errors that don't make sense to me.

I copied my code exactly from this website http://ift.tt/1DOaMkl

and I'm getting this error

OpenCV Error: Assertion failed (scn == 3 || scn == 4) in cvtColor, file /build/buildd/opencv-2.4.9+dfsg/modules/imgproc/src/color.cpp, line 3737 Traceback (most recent call last): File "test.py", line 8, in gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) cv2.error: /build/buildd/opencv-2.4.9+dfsg/modules/imgproc/src/color.cpp:3737: error: (-215) scn == 3 || scn == 4 in function cvtColor



via Chebli Mohamed

Running Python script with oauth2 via matlab

I'm trying to run a Python script that updates a Google spreadsheet with values calculated with Matlab. I'm using the gspread 1 API, which uses oauth2. Running straight Python, I'm able to download and modify spreadsheets without a problem. When I try to run the script in Matlab, I get the following error when I try to authorize the credentials:

Python Error: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:600)

Any ideas about what I could do to solve this? I suppose the workaround would be to just save the data from Matlab and import the .mat file into Python.



via Chebli Mohamed

Multiple Replacements Honoring Capitalization and Punctuation

I'm attempting to create a script that replaces keywords found in body with <strong> tags. <strong>keyword</strong>

The problem is words can be capitalized or have punctuation like dog's toy (whereas I'd be aiming for dog, the strong tag would cut off 's)

I'm trying to create an efficient and dynamic replacer that works as described.

So far this is what I have:

def strongwords(text, dict):
    rc = re.compile('|'.join(map(re.escape, dict)))
    def translate(match):
        return dict[match.group(0)]
    return rc.sub(translate, text)

Unless I create a HUGE dict with every possibility (as described above) and expend resources on find/replace, I do not see this working as desired.

Is there a pythonic way to do this with a proven regex recipe? Perhaps a package or module has been designed for this?



via Chebli Mohamed

enumerate range with steps in python?

I want something that should look like this but it probably looks quite different:

for i, idx in enumerate(range (0, length, step)):
# do something

Basically, i need to enumerate all the occurrences of "step" in the range to use as an index when iterating.

Downvoter care to explain why?



via Chebli Mohamed

Pytest additional argument that allows tests run in parallel properly

I am using pytest and wish to use both -s (to disable all capturing) and -n NUM to allow multiple tests run at the same time. Each of them works well alone but when I use both of them together, I got error messages "redirected Stdin is pseudofile, has no fileno()", which I believe means that -s loses its function.

Would anyone tell me how to fix this error?



via Chebli Mohamed

How to retrieve the most recent variable and delete all other others (pandas)

I'm trying to get the latest occurrence of an ID Name and I want to delete every other occurrence that happened before that time.

    ID Name     Comment        Time
0     W12D0       Fine     12:17:37
1     W12D0     Random     12:20:10
2     W12D0       What     12:21:06
3     W12D4       Fine     08:20:14
4     W12D5     Random     10:11:12
5     W12D5       Fine     11:37:02
..      ...        ...         ....

For example (according to the data above), the 'ID Name', 'W12D0', is associated with 3 occurrences: 12:17:37 , 12:20:10 , 12:21:06

I want to only keep the row associated to that ID Name's latest time (in this case, it's 12:21:06). Every other row with W12D0 will be deleted. Essentially, I want something like this:

    ID Name     Comment        Time
0     W12D0       What     12:21:06
1     W12D4       Fine     08:20:14
2     W12D5       Fine     11:37:02
..      ...        ...         ....

How would I go about doing this?



via Chebli Mohamed

Pandas groupby and describe flags AttributeError

I have a bunch of data stored in vals. The indices are monotonic, but not continuous. I'm attempting to do some analysis on histograms of the data, so I've created the following structure:

hist = pd.DataFrame(vals)

hist['bins'] = pd.cut(vals, 100)

This is data taken from an experimental instrument and I know that some of the bins have only 1 or 2 counts in them, which I'm trying to remove. I've tried using groupby as follows and get the following error (Full traceback included at the end of the note):

hist.groupby('bins').describe()

AttributeError: 'Categorical' object has no attribute 'flags' 

However, when I do the following, the error does not show up and I get the expected result:

In[]:  hist.index = hist.bins
In[]:  hist['bins'] = hist.index
In[]:  desc = hist.groupby('bins').describe()
In[]:  desc.index.names = ['bins', 'describe']

Out[]: **describe with MultiIndex for rows.**

If I don't include the second line hist['bins'] = hist.index, I still get an AttributeError: 'Categorical' object has no attribute 'flags' and to the best that I can tell, the traceback is identical.

Can someone explain what the flags are and why they only seem to work when I set the index to bins and then replace the bins by the version stored in the index?

My end goal is to remove the data for bins with counts <= 6. If someone has an easier workaround than the way I'm going after it, I'd also be grateful.

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-11-f606a051f2e4> in <module>()
----> 1 hist.groupby('bins').describe()

C:\Users\balterma\AppData\Local\Enthought\Canopy\App\appdata\canopy-1.4.1.1975.win-x86_64\lib\site-packages\IPython\core\displayhook.pyc in __call__(self, result)
    245             self.start_displayhook()
    246             self.write_output_prompt()
--> 247             format_dict, md_dict = self.compute_format_data(result)
    248             self.write_format_data(format_dict, md_dict)
    249             self.update_user_ns(result)

C:\Users\balterma\AppData\Local\Enthought\Canopy\App\appdata\canopy-1.4.1.1975.win-x86_64\lib\site-packages\IPython\core\displayhook.pyc in compute_format_data(self, result)
    155 
    156         """
--> 157         return self.shell.display_formatter.format(result)
    158 
    159     def write_format_data(self, format_dict, md_dict=None):

C:\Users\balterma\AppData\Local\Enthought\Canopy\App\appdata\canopy-1.4.1.1975.win-x86_64\lib\site-packages\IPython\core\formatters.pyc in format(self, obj, include, exclude)
    150             md = None
    151             try:
--> 152                 data = formatter(obj)
    153             except:
    154                 # FIXME: log the exception

C:\Users\balterma\AppData\Local\Enthought\Canopy\App\appdata\canopy-1.4.1.1975.win-x86_64\lib\site-packages\IPython\core\formatters.pyc in __call__(self, obj)
    479                 type_pprinters=self.type_printers,
    480                 deferred_pprinters=self.deferred_printers)
--> 481             printer.pretty(obj)
    482             printer.flush()
    483             return stream.getvalue()

C:\Users\balterma\AppData\Local\Enthought\Canopy\App\appdata\canopy-1.4.1.1975.win-x86_64\lib\site-packages\IPython\lib\pretty.pyc in pretty(self, obj)
    360                             if callable(meth):
    361                                 return meth(obj, self, cycle)
--> 362             return _default_pprint(obj, self, cycle)
    363         finally:
    364             self.end_group()

C:\Users\balterma\AppData\Local\Enthought\Canopy\App\appdata\canopy-1.4.1.1975.win-x86_64\lib\site-packages\IPython\lib\pretty.pyc in _default_pprint(obj, p, cycle)
    480     if getattr(klass, '__repr__', None) not in _baseclass_reprs:
    481         # A user-provided repr.
--> 482         p.text(repr(obj))
    483         return
    484     p.begin_group(1, '<')

C:\Users\balterma\AppData\Local\Enthought\Canopy\User\lib\site-packages\pandas\core\base.pyc in __repr__(self)
     62         Yields Bytestring in Py2, Unicode String in py3.
     63         """
---> 64         return str(self)
     65 
     66 

C:\Users\balterma\AppData\Local\Enthought\Canopy\User\lib\site-packages\pandas\core\base.pyc in __str__(self)
     42         if compat.PY3:
     43             return self.__unicode__()
---> 44         return self.__bytes__()
     45 
     46     def __bytes__(self):

C:\Users\balterma\AppData\Local\Enthought\Canopy\User\lib\site-packages\pandas\core\base.pyc in __bytes__(self)
     54 
     55         encoding = get_option("display.encoding")
---> 56         return self.__unicode__().encode(encoding, 'replace')
     57 
     58     def __repr__(self):

C:\Users\balterma\AppData\Local\Enthought\Canopy\User\lib\site-packages\pandas\core\frame.pyc in __unicode__(self)
    507             width = None
    508         self.to_string(buf=buf, max_rows=max_rows, max_cols=max_cols,
--> 509                        line_width=width, show_dimensions=show_dimensions)
    510 
    511         return buf.getvalue()

C:\Users\balterma\AppData\Local\Enthought\Canopy\User\lib\site-packages\pandas\core\frame.pyc in to_string(self, buf, columns, col_space, colSpace, header, index, na_rep, formatters, float_format, sparsify, index_names, justify, line_width, max_rows, max_cols, show_dimensions)
   1340                                            max_rows=max_rows,
   1341                                            max_cols=max_cols,
-> 1342                                            show_dimensions=show_dimensions)
   1343         formatter.to_string()
   1344 

C:\Users\balterma\AppData\Local\Enthought\Canopy\User\lib\site-packages\pandas\core\format.pyc in __init__(self, frame, buf, columns, col_space, header, index, na_rep, formatters, justify, float_format, sparsify, index_names, line_width, max_rows, max_cols, show_dimensions, **kwds)
    345             self.columns = frame.columns
    346 
--> 347         self._chk_truncate()
    348 
    349     def _chk_truncate(self):

C:\Users\balterma\AppData\Local\Enthought\Canopy\User\lib\site-packages\pandas\core\format.pyc in _chk_truncate(self)
    410             else:
    411                 row_num = max_rows_adj // 2
--> 412                 frame = concat((frame.iloc[:row_num, :], frame.iloc[-row_num:, :]))
    413             self.tr_row_num = row_num
    414 

C:\Users\balterma\AppData\Local\Enthought\Canopy\User\lib\site-packages\pandas\tools\merge.pyc in concat(objs, axis, join, join_axes, ignore_index, keys, levels, names, verify_integrity, copy)
    752                        keys=keys, levels=levels, names=names,
    753                        verify_integrity=verify_integrity,
--> 754                        copy=copy)
    755     return op.get_result()
    756 

C:\Users\balterma\AppData\Local\Enthought\Canopy\User\lib\site-packages\pandas\tools\merge.pyc in __init__(self, objs, axis, join, join_axes, keys, levels, names, ignore_index, verify_integrity, copy)
    884         self.copy = copy
    885 
--> 886         self.new_axes = self._get_new_axes()
    887 
    888     def get_result(self):

C:\Users\balterma\AppData\Local\Enthought\Canopy\User\lib\site-packages\pandas\tools\merge.pyc in _get_new_axes(self)
    957                 new_axes[i] = ax
    958 
--> 959         new_axes[self.axis] = self._get_concat_axis()
    960         return new_axes
    961 

C:\Users\balterma\AppData\Local\Enthought\Canopy\User\lib\site-packages\pandas\tools\merge.pyc in _get_concat_axis(self)
   1009 
   1010         if self.keys is None:
-> 1011             concat_axis = _concat_indexes(indexes)
   1012         else:
   1013             concat_axis = _make_concat_multiindex(indexes, self.keys,

C:\Users\balterma\AppData\Local\Enthought\Canopy\User\lib\site-packages\pandas\tools\merge.pyc in _concat_indexes(indexes)
   1027 
   1028 def _concat_indexes(indexes):
-> 1029     return indexes[0].append(indexes[1:])
   1030 
   1031 

C:\Users\balterma\AppData\Local\Enthought\Canopy\User\lib\site-packages\pandas\core\index.pyc in append(self, other)
   4603             arrays = []
   4604             for i in range(self.nlevels):
-> 4605                 label = self.get_level_values(i)
   4606                 appended = [o.get_level_values(i) for o in other]
   4607                 arrays.append(label.append(appended))

C:\Users\balterma\AppData\Local\Enthought\Canopy\User\lib\site-packages\pandas\core\index.pyc in get_level_values(self, level)
   4239         unique = self.levels[num]  # .values
   4240         labels = self.labels[num]
-> 4241         filled = com.take_1d(unique.values, labels, fill_value=unique._na_value)
   4242         values = unique._simple_new(filled, self.names[num],
   4243                                     freq=getattr(unique, 'freq', None),

C:\Users\balterma\AppData\Local\Enthought\Canopy\User\lib\site-packages\pandas\core\common.pyc in take_nd(arr, indexer, axis, out, fill_value, mask_info, allow_fill)
    829         out_shape[axis] = len(indexer)
    830         out_shape = tuple(out_shape)
--> 831         if arr.flags.f_contiguous and axis == arr.ndim - 1:
    832             # minor tweak that can make an order-of-magnitude difference
    833             # for dataframes initialized directly from 2-d ndarrays

AttributeError: 'Categorical' object has no attribute 'flags' 



via Chebli Mohamed

Add a word at the end of elements of a list

I have the list:

mylist = ["all dogs go", "why does one", "fell down so hard I"]

Is there a function that will allow me to add the word "moo" to the end of all elements in mylist?



via Chebli Mohamed

Please help fix this code [on hold]

I found this code on this website but it doesn't work at all, I've been trying to fix it for a while now but I can't seem to do it. Please help fix this code so I can see how it works. Here is the code:


import random


numberofgames = raw_input("How many games do you want to play?")


print "Please choose rock , paper , scissors , lizard, or spock (in lower case please)" choice = raw_input("What do you choose? ") player_choice = str(choice) def name_to_number(name): if name == "rock": name = 0 return name elif name == "spock": name = 1 return name elif name == "paper": name = 2 return name elif name == "lizard": name = 3 return name elif name == "scissors": name = 4 return name


def number_to_name(number): if number == 0: number = "rock" return number elif number == 1: number = "spock" return number elif number == 2: number = "paper" return number elif number == 3: number = "lizard" return number elif number == 4: number = "scissors" return number


try: computer_choice = random.randrange(5) player_number = name_to_number(player_choice) print "Player choice is: " + player_choice print "Computer choice is: " + number_to_name(computer_choice) difference = (int(player_number) - computer_choice) % 5 draws = 0 playerwins = 0 computerwins = 0 if difference in [1, 2]: print "Player wins!" playerwins = playerwins + 1 elif difference == 0: print "Player and computer tie!" draws = draws + 1 else: print "Computer wins!" computerwins = computerwins + 1

print "Wins: " + str(playerwins) + "\n" + "Draws: " + str(draws) + "\n" + "Losses " + str(computerwins) while playerwins + draws + computerwins <= numberofgames: main()

except TypeError: print "Sorry, please read the directions and type rock, paper, scissors, spock, or lizard in lowercase."

This is where I found it: Python Rock Paper Scissors Lizard Spock keeping score



via Chebli Mohamed

How does web client request visualization session from ParaViewWeb launcher?

I have a Pyramid web application on which I would like to embed an iFrame displaying an instance of ParaViewWeb's visualizer so users can display VTU files remotely.

I have successfully done so while running the application on my own workstation by calling a subprocess from Python that executes ParaViewWeb's Quick Start method and returns the URL to JavaScript for iFrame generation.

http://ift.tt/1h7Ttk4

However, in order to accommodate multiple users, ParaViewWeb's documentation indicates that

the server must provide a single entry point to establish a connection, as well as a mechanism to start a new visualization session on demand

for which it suggests using Apache as the front-end application and a python launcher to start the process for each session.

Conveniently, I have a "freshly installed Ubuntu Desktop 14.04 LTS" so I used the following guide to configure both the launcher and Apache:

http://ift.tt/1J3mNy5

Ok so I'm pretty sure I am missing something major here, but once the launcher is started with /data/pvw/bin/start.sh... how do I then submit the request with information regarding what app to use (visualizer) and what data directory to load???



via Chebli Mohamed

Error handling with imap_unordered in python multiprocessing

I'm trying to use pool.imap_unordered from python multiprocessing to query an external service. What I would like to do is split the input into smaller tasks if one fails. Right now I've got something like the following:

results = []
for result in pool.imap_unordered(query_service, tasks):
    results.append(result)

Does imap_unordered reraise exceptions, is result an exception if a child task fails or does it just retry continuously?



via Chebli Mohamed

How to change legend bar in Matplotlib?

When plotting matrix with imshow in Matplotlib, how to change colorbar legend bar size, location, font and other parameters?

Here I created an example code

import numpy as np
import matplotlib
import matplotlib.pyplot as plt
%matplotlib inline

def plot_matrix(mat, title='example', cmap=plt.cm.Blues):
    plt.imshow(mat, interpolation='nearest', cmap=cmap)
    plt.grid(False)
    plt.title(title)
    plt.colorbar()

data = np.random.random((20, 20))

plt.figure(figsize=(8,8))
plt.tick_params(axis='both', which='major', labelsize=12)

plot_matrix(data) 

enter image description here

In a real use case, I got complex labels and the legend bar becomes much higher then the matrix itself. I want to change the legend bar to make the plot more efficiently use the space.

I found a documentation for the matplotlib.pyplot.colorbar, however have not figure out a good way to set the size, location and font size for the color legend bar.



via Chebli Mohamed

Python compare dictionary to dictionary of conditions

I have an iterator (millions of rows) that gives me a dictionary that need to be compared against a dictionary of conditions to find matches.

Here is my code:

conditions={"port":"0-20", "ip":"1.2.3.4", "protocol":"1,7",
            "timestamp":">143990000", "server":"mario"}

for rec in imiterator(): # Very large number of rows
    # rec examples {"ip":"1.7.1.1", "timestamp":1434000,
    #              "port":129,"server":("mario","bruno"), 
    #              "protocol":"1","port":19"}

    if check_conditions(rec, conditions):
       print(json.dumps(rec))

Note the columns in rec can be int, long, string, tuple.

I need to find a real high performance way to do the matches. Any ideas?

I thought about using map and converting the conditions to lambda functions that should match and doing an AND operation of all the conditions. Would this be faster?



via Chebli Mohamed

Python evaluating a local fabric curl command

Seems like this should work but it doesn't really. I've played around with various methods like using range, seeing if the expression evaluates to True, etc. I use local to run the command locally with fabric.

This is what it looks like now:

def test_health_check():
    test = local('curl -I -sL -w "%{http_code} %{url_effective}\\n" --user username:username --location-mylocation "http://ift.tt/1TxM5iO" -o /dev/null | cut -d " " -f 1')
    if test == 200:
        print "success"
    else:
        print "failure"

If I set the if test portion to if test >= 200: then it evaluates True but evaluates false for anything else. I want to be able to return True if the range is 200 thru 302. Also, is there a better way of doing this?



via Chebli Mohamed

How can I verify this URL directs to an image?

I'm working on a service, written in Python which, at one point, downloads images from given URLs and stores them on a server.

This service does a check of the content-type returned from the URL and only downloads the image if it's content-type is 'image/jpeg', etc.

I recently came up against an interesting problem with the following URL: http://ift.tt/1faJokl

This URL, when opened in a browser, displays an encoded string of some sort.

When used as the 'src' of an image tag, it renders an image.

<html>
<body>
  <img src = 'http://ift.tt/1faJokl'>
</body>
</html>

The content-type of this URL is text/html

Is there any way, in Python, for me to identify that this URL directs to an image which can be used as a 'src'?



via Chebli Mohamed

OpenCV Python equalizeHist colored image

I need to do a histogram equalization for a colored image.

First I convert the colored image to gray and give it to the equalizeHist function:

image = cv2.imread("photo.jpg")
image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
cv2.equalizeHist(image)
cv2.imshow("equalizeHist", image)
cv2.waitKey(0)

But after this I need to convert the image back to RGB; how can i do that?



via Chebli Mohamed

samedi 1 août 2015

Auto Load and Refresh Div 500 internal server error

I am trying to make a refresh div every x second. But i have one problem.

I am trying to refresh div with the following code:

<script type="text/javascript">
var auto_refresh = setInterval(
   function () {
     $('#test').load('updates.php').fadeIn("slow");
   }, 10000); // refresh every 10000 milliseconds
</script>

html and php incldue:

<div class="container" id="test">
  <?php include("updates.php");?>
</div>

The problem is Chrome Developer Console said:

GET http://localhost:8888/updates.php 500 (Internal Server Error)

Note: My php file is in root folder and also i still try / from the ajax URL.

What is the problem here? What i need to do to fix that error? anyone can help me in this regard ?

Passing local storage item to ajax

We have this code:

$.ajax({
            url:    localStorage.getItem("isntagram link"),
            // url: "http://ift.tt/1SrlseV",
            method: 'GET',
            dataType: 'jsonp',

Inside the local storage is a url to a JSON feed, the same link as the commented out url. The commented out code works but calling the same link from local storage is not. Thanks in advance

collapsible list with dynamically loaded content

I have tried all kinds of lists I found all over the internet, but none of them seem to properly work. I think te reason for this might be the fact that the content of the list is dynamiccally loaded (with jquery ajax).

On $(document).ready I load the list and append the html data to the div.

After that I try to make the list collapsible (the list is nested, it's a navigation for a database).

My best try so far:

$(document).ready(function(){
    loadnavigation(); //to load the li items//
    fold();
})

function fold(){
function fold1(){
        $("#container").on("click", "#nav > li", function(){

                $(this).children().toggleClass("hide");

        });
}

function fold2(){
        $("#container").on("click", "#nav > li > ul > li", function(){
                $(this).children().toggleClass("hide");
                
        });
}
fold1();
fold2();
}
The navigation is loaded and the most upper ul has the id 'nav'. On document.ready I add the class 'hide to #nav>li>ul and #nav>li>ul>li>ul, so the li items are set to hide by default. The problem with this list however is that if you click a link or a deeper down li item in the tree, it registers this also as a click on the levels above.

Is there a way to fix this? Or a better (cleaner) way to make collapsible nested lists with dynamic content?

ajax success function not firing after json return from controller in entity frame work 6

In the controller returning a json like below return Json(lstCountry, JsonRequestBehavior.AllowGet);

but always returning error: is fired from ajax why? My ajax code is : $.ajax({ type: "POST",

        url: "/Country/Update",
        data: { id:$('#id').val(), name:$('#country').val() },

        dataType: 'json',
        async: true,
        cache: false,
        success: function (data, status, jqXHR) {
            alert("success");
            //$.each(data, function (index, customer) {
            //    alert(customer.Name + " " + customer.UserName);
            //});
        },
        error: function (jqXHR, textStatus, errorThrown) {

            if (typeof (console) != 'undefined') {
                alert("oooppss");
            }
            else { alert("something went wrong"); }
        }
    });
});

XML Http Request: CORS issue

Hi I've been working on an angularjs app on plnkr, and I'm pulling data from a remote server to the app. Initially I had problems accessing the xml file because of the CORS issue, the cross-domain restriction, but I enabled CORS. The app now works on plnkr, but when I try to run it on the browser, the console gives me the same error, except with an additional note at the end.

The error:

`XMLHttpRequest cannot load http://ift.tt/1M35ggf. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access. The response had HTTP status code 403.`

The "the reponse had HTTP status code 403" bit seems to be new. What's going on? Why does it work on plnkr and not in browser? What do I need to do to fix it? Any help is appreciated.

How to Get Ajax value

I am using ajax call for my onclick event in a table. I am returning an object from controller. And I need to show that value in alert.

My page table td as follows,

    <td onClick="img('${matched.transaction.id}')" id="ss"><input class="group_btn" type="submit" name="submit"
                                            value="View" id="groupbtn" style="vertical-align: super;" /></td>

Ajax call written in script,

    <script>
        function img(trId) {
            $.ajax({
                type : "GET",
                async : false,
                url : "getImage.htm",
                data : "trId=" + trId,
                success : function(data) {
                    obj = jQuery.parseJSON(data);
                }
            });
        }

    </script>

my controller class, which returns the value,

    public class GetImageController extends AbstractController {

        @Resource
        private CommonRepository commonRepository;

        public ModelAndView handleRequestInternal(HttpServletRequest request,
                HttpServletResponse response) throws Exception {
            ModelAndView modelAndView = new ModelAndView("ajax_foo");       
            String trId = request.getParameter("trId");     
            if (!trId.equals("")) {
                return save(request, response);
            }
            return save(request, response);
        }

        ModelAndView modelAndView = new ModelAndView();

        private ModelAndView save(HttpServletRequest request,
                HttpServletResponse response) throws Exception {

            String trId = request.getParameter("trId");     
            TransactionDocument trDoc = commonRepository.find(TransactionDocument.class, "transactionId", Long.parseLong(trId));
            Document doc = commonRepository.find(Document.class, "id", trDoc.getDocumentId());      
            String imagePath = doc.getDocPathServer();
            String imageName = imagePath
                    .substring(imagePath.lastIndexOf("/") + 1);
            String imageUrl = new AWSS3Helper().doGenerateUrl(imageName);   

            System.out.println("imageUrl-----"+imageUrl);       

            modelAndView.addObject("imageUrl", imageUrl);

            return modelAndView;
        }   

    }

I just want to show the imageUrl value in javascript alert. I am able to see the value in catalina.out(sysout).

can anyone tell me a way on how to show that value in alert?

Stop form submission if textfield is empty

Trying to stop a form submission when textfield is empty. But with my current script even when the textfield is empty and you should and check the database you can see a newly inserted empty records

$(document).ready(function(){

    $("#form1").on('submit',function(event){
        event.preventDefault();

if ($("#username").val() != '') {
    }
        data = $(this).serialize();
        $.ajax({
        type: "POST",
         url: "username.php",
        data: data
        }).success(function() {
        $("input[type=text]").val("");


        });
    });
});

prevent caching of xmlhttp request

I have a javascript that retrieves a JSON through an ajax request. My problem is that the browser starts caching the response to this request, so I don't actually get the latest data from the server, but instead an older cached version.

    $.getJSON( self.data('pathAllGet'), function( json ) {
        self.data('galleryData',json);
        self.data(render(self));
    });

How to push data to array using ajax

I have a page listing products - each having an add to cart button. Using the data attribute in the button, I need push the offerId string into an existing array. The expected result after adding multiple products to the cart would be to return an array with all the offerIds. Currently, if I print_r the offerIdArray, it only shows the latest button's offerId.

Thoughts?

$(document).ready(function () {               

    $(".addtocart button").click(function () {

        var offerIdArray = []; 
        var offerId = $(this).attr("data-offerId");                                         

        $.post("controller/create-cart.php",
            {                                
                offerIdArray: offerIdArray.push(offerId)
            },
        function (data) {
            $('body').append(data);
        });                  
    });
});

yii show error 404 Unable to resolve the request "js/ajaxuploadcarphotomain.php"

I web works fine previously until yesterday I get this error on my image upload function.

Error 404
Unable to resolve the request "js/ajaxuploadcarphotomain.php"

but when i manually access to the link, the page returns result 'File size is too big'.

<script type="text/javascript" src="<?php echo Yii::app()->request->baseUrl; ?>/js/ajaxupload.js"></script>
<form action="js/ajaxuploadcarphotomain.php" method="post" name="sleeker" id="sleeker" enctype="multipart/form-data">
        <input type="hidden" name="maxSize" value="3000000" />
        <input type="hidden" name="maxW" value="800" />
        <input type="hidden" name="fullPath" value="images/carphoto/" />
        <input type="hidden" name="relPath" value="../images/carphoto/" />
        <input type="hidden" name="colorR" value="255" />
        <input type="hidden" name="colorG" value="255" />
        <input type="hidden" name="colorB" value="255" />
        <input type="hidden" name="maxH" value="600" />
        <input type="hidden" name="filename" value="filename" />
        <p><input id="id_car_main_photo" class="btn-link" type="file" name="filename" onchange="ajaxUpload(this.form,'<?php echo Yii::app()->request->baseUrl; ?>/js/ajaxuploadcarphotomain.php?filename=name&amp;maxSize=3000000&amp;maxW=800&amp;fullPath=images/carphoto/&amp;relPath=../images/carphoto/&amp;colorR=255&amp;colorG=255&amp;colorB=255&amp;maxH=600','upload_area','File Uploading Please Wait...&lt;br /&gt;&lt;img src=\'../images/loader_light_blue.gif\' width=\'128\' height=\'15\' border=\'0\' /&gt;','&lt;img src=\'images/error.gif\' width=\'16\' height=\'16\' border=\'0\' /&gt; Error in Upload, check settings and path info in source code.'); return false;" /></p>
</form>

what is the root cause for this issue?

My .htaccess

RewriteEngine on

# if a directory or a file exists, use it directly
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d

# otherwise forward it to index.php
RewriteRule . index.php

Directory

css
protected
js
.htaccess

I cannot access www.example.com/js but http://ift.tt/1KHgFPw can

Uncaught TypeError: Cannot read property 'ajax' of undefined When I'm trying to send data to url

I have created a form to get feedback from user, I'm simply trying to send form data to url. but I'm getting this error. Uncaught TypeError: Cannot read property 'ajax' of undefined

thank you in advance.

 function sendData(){

            $.ajax({
                url: "www.yashkjhsah.php",

                type: "POST",

                async: true,

                data: $(".contacts_form").serialize(),

                dataType: "html",

                success: function(data) 
                 {
                alert(data);

                if(data!="Error in Insert Query!")
                {
                    alert("Thank you for Enquiry we will send answer in your Mail.");
                }
                else
                {
                alert("Error while saving the data");
                }
                 }
             });

}

trying to send data to a server and receive a response then proceed to display it

I am trying to send data to a server and receive a response then proceed to display it. But I keep getting The following error: Uncaught TypeError: Cannot use 'in' operator to search for '2448' in

My PHP CODE:

<?php

header('Access-Control-Allow-Origin: *'); include ('connection.php');

$album = $_POST["album"];

$sql = " SELECT album.id as album, album.name as album_name, track.name as title, track.number as track_number, track.lyric as lyrics, track.details as track_url, artist.profile as artist, image.url as image

    FROM album 
    INNER JOIN track ON
    album.id = track.album_id
    INNER JOIN image ON
    image.details = album.id
    INNER JOIN artist ON
    artist.id = album.artist_id

    WHERE album.id='".$album."' ORDER BY track.number ASC";

$result = mysql_query($sql) or die ("Query error: " . mysql_error());

$records = array();

while($row = mysql_fetch_assoc($result)) {
$records[] = $row;
}


mysql_close($con);

echo $_POST['jsoncallback'] . '(' . json_encode($records) . ');';

?>

MY AJAX CALL:

function load_album_tracks(album_id){
    document.getElementById("track_titles").innerHTML = "";
    alert(album_id);
$.ajax ({
    type:'POST',
    data:  {album:album_id},
    dataType: 'jsonp',
    jsonp: 'jsoncallback',
    url: 'http://ift.tt/1LWaXe6',
    success: function(data){
        console.log(data);
    $.each(data, function(i,item){ 
    var track = /** DISPLAY RESULTS **/;    
    document.getElementById("track_titles").innerHTML += track;
    });

},
 error: function(data){
            alert("Couldn't Load Tracks");  
            }
        });

}

Adding Sign In/Sign Up into rails app

I am trying to integrate SignIn / SignUp into my rails application.
Currently i have Two API's for Sign In and Sign Up (Maintained by other team). These API's will take care of validations and stuff at their end and send me success/failure response back.

I am aware that we can have a custom SignIn/SignUp form and send the details to that particular API's. I want to know the best and if possible easiest way to integrate SignIn/SignUp page into my App. I am not sure of any other cool way to do it ? like hosted library kind of or anything ?

how to make ajax calls continuously for 5 seconds once

how to make ajax calls continuously for 5 seconds once. I have used set Timeout like below,

setTimeout(function()
{
function();
}, 200);

But it use more db connection.can anyone tell me an effective way to call a function continuously for 5 seconds once.

looking for a ajax gellery plugin

I am new on this site. I am a new web designer. Actually finding a jquery or jquery ajax images plugin plugin ,On top of the image have three link to animate images. When the users clik the link the images will show new image without full page loading,when the old image show new images ,that will show some effective animation.

current params and AJAX in rails

In my project it needs to add countries, regions, cities. Previously treated several cities and all. Each city had a link of this kind:

link_to "Moscow", params.merge(city_name: "moscow")

and I get

www.site.com/moscow. (when params = {"controller"=>"index", "action"=>"index", "city_name"=>"moscow"})

But now I'm using Ajax to select a city from the regions (states). Сorny, send state_id - I get a list of cities in the state.

But after AJAX - sending data to the controller the current params changed. (before: {"controller"=>"index", "action"=>"index"}, after: {"action"=>"get_list_cities", "controller"=>"states", "id"=>"4315"}). And my construction with params.merge(city_name: "moscow") does not work any more.

Is it possible to roll back both params or work with Ajax, without changing the params?

I understand that it is possible to use another method of formation of links to each city, but this a way like .merge is very convenient and concise for me.

UPDATE:

url_for(params.clear.merge(Rails.application.routes.recognize_path(request.referer))) - don't work !

UPDATE 2:

link_to area.name, "#", remote: true,  data: {toggle: "tab", ajax_path: get_list_cities_path(area), value: "#{area.id}"}

def get_list_cities
    @cities = Area.find(params[:id]).cities.where(status: true)
    respond_to do |format|
      format.js
    end
   end

$('ul.nav').on 'click', 'li > a', (e) ->
        e.preventDefault()
        $(this).parent().siblings().removeClass 'active'
        $(this).parent().addClass 'active'
        $.ajax
          url: $(this).data('ajax-path')
          type: 'GET'
          dataType: 'script'

jQuery returns undefined while filtering AJAX reponse

I'm attempting to figure out AJAX in jQuery and am trying to extract the contents of one element on the page and inject it into another. Here's a test scenario I've been playing around with:

1st page:

...
    <script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
    <script src="script.js"></script>
</head>
<body>
    <button>Load it!</button>
    <div class="content"></div>
...

2nd page:

...
<div class="container">
    <h1>Hello World!</h1>
    <div class="text">
        <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Qui nulla impedit a nostrum eos voluptas, quidem cum, consequatur suscipit voluptate officia sapiente laboriosam similique dignissimos praesentium obcaecati, nemo commodi, laborum!</p>
    </div>  
</div>
...

script file from 1st page:

$(function(){
    $('button').on('click', function(){
        $.ajax({
            url: "ajax/index.html"
        }).done(function(response){
            $('.content').html($(response).find('.container').html());
        });
    });
});

Several posts on stack exchange like this one and this one have indicated that this is the direction I should be going in to grab 1 element's HTML from another page using AJAX. However, upon running the code on the first page, the contents from .container are not returned, and passing those jQuery methods to console.log() as so (console.log($(response).find('.container').html());) returns undefined to the console. What's wrong here?

Also, yes, I realize that using .load() is an option here, but I'd really like to learn how to use the AJAX method for jQuery as I believe it gives the programmer more find-tuned control.