text:
Q: Exporting a cellular automaton data to csv in Python I've been working in Reaction-Diffusion cellular automata with the cellpylib library for a course in my university (I wrote it all in one script so you don't have to install/download anything). I'd like to save the evolution of the automata data to a csv file to run some statistics. That is, I'd like to save the data in columns where the first column is 'number of "1"' and the second column: 'time steps'.
Thus, I need help in:
(1) Creating a variable that saves the amount of '1' per time step (I think so).
(2) I need to export all that data to a csv file (number of "1" and the corresponding iteration, from 1 to time_steps in the code below).
The code is the following.
#Libraries
import matplotlib
matplotlib.matplotlib_fname()
import matplotlib.pyplot as plt
import matplotlib as mpl
import matplotlib.animation as animation
import numpy as np
import csv

# Conditions
#############################
theta = 1              # this is the condition for Moore neighbourhood
Int = 100              # this is the iteration speed (just for visualization)
time_steps = 100       # Iterations
size = 8               # this is the size of the matrix (8x8)
#############################

# Definitions
def plot2d_animate(ca, title=''):
    c = mpl.colors.ListedColormap(['green', 'red', 'black', 'gray'])
    n = mpl.colors.Normalize(vmin=0,vmax=3)
    fig = plt.figure()
    plt.title(title)
    im = plt.imshow(ca[0], animated=True, cmap=c, norm=n)
    i = {'index': 0}
    def updatefig(*args):
        i['index'] += 1
        if i['index'] == len(ca):
            i['index'] = 0
        im.set_array(ca[i['index']])
        return im,
    ani = animation.FuncAnimation(fig, updatefig, interval=Int, blit=True)
    plt.show()

def init_simple2d(rows, cols, val=1, dtype=np.int):
    x = np.zeros((rows, cols), dtype=dtype)
    x[x.shape[0]//2][x.shape[1]//2] = val
    return np.array([x])

def evolve2d(cellular_automaton, timesteps, apply_rule, r=1, neighbourhood='Moore'):
    _, rows, cols = cellular_automaton.shape
    array = np.zeros((timesteps, rows, cols), dtype=cellular_automaton.dtype)
    array[0] = cellular_automaton

    von_neumann_mask = np.zeros((2*r + 1, 2*r + 1), dtype=bool)
    for i in range(len(von_neumann_mask)):
        mask_size = np.absolute(r - i)
        von_neumann_mask[i][:mask_size] = 1
        if mask_size != 0:
            von_neumann_mask[i][-mask_size:] = 1

    def get_neighbourhood(cell_layer, row, col):
        row_indices = [0]*(2*r+1)
        for i in range(-r,r+1):
            row_indices[i+r]=(i+row) % cell_layer.shape[0]
        col_indices = [0]*(2*r+1)
        for i in range(-r,r+1):
            col_indices[i+r]=(i+col) % cell_layer.shape[1]
        n = cell_layer[np.ix_(row_indices, col_indices)]
        if neighbourhood == 'Moore':
            return n
        elif neighbourhood == 'von Neumann':
            return np.ma.masked_array(n, von_neumann_mask)
        else:
            raise Exception("unknown neighbourhood type: %s" % neighbourhood)

    for t in range(1, timesteps):
        cell_layer = array[t - 1]
        for row, cell_row in enumerate(cell_layer):
            for col, cell in enumerate(cell_row):
                n = get_neighbourhood(cell_layer, row, col)
                array[t][row][col] = apply_rule(n, (row, col), t)
    return array

def ca_reaction_diffusion(neighbourhood, c, t):
    center_cell = neighbourhood[1][1]
    total = np.sum(neighbourhood==1)
    if total >= theta and center_cell==0:
            return 1
    elif center_cell == 1:
            return 2
    elif center_cell == 2:
            return 3
    elif center_cell == 3:
            return 0
    else:
            return 0

# Initial condition
cellular_automaton = init_simple2d(size, size, val=0, dtype=int)

# Excitable initial cells
cellular_automaton[:, [1,2], [1,1]] = 1

# The evolution
cellular_automaton = evolve2d(cellular_automaton,
                              timesteps=time_steps,
                              neighbourhood='Moore',
                              apply_rule=ca_reaction_diffusion)

animation=plot2d_animate(cellular_automaton)

Explanation of the code:
As you can see, there are 4 states: 0 (green), 1 (red), 2 (black) and 3 (gray). The way the automata evolves is with the cellular_automaton conditions. That is, for example, if a center cell has a value of 0 (excitable cell) and at least one cell (theta value) on its Moore neighbourhood is in state 1, in the following time step the same cell will be at state 1 (excited).
To notice:
The configuration of this matrix is toroidal, and the definitions are taken from the cellpylib library.
I've been stuck with this for over a week, so I'd really appreciate some help. Thanks in advance!

A: I am not well-experienced in this subject matter (and I was not fully clear on what you intended for me to do). I went through and implemented the counting of the specific "0", "1", "2" and "3" value cells in "evolve2d" function.  This code should be viewed as "starter code"; whatever specifically you are trying to do should piggyback off of what I have given you. Additionally, this task could have been accomplished through some better code design and definitely, better planning of your function locations (as part of better coding practice and overall cleaner code that is easy to debug). Please peruse and UNDERSTAND the changes that I made.
#Libraries
import matplotlib
matplotlib.matplotlib_fname()
import matplotlib.pyplot as plt
import matplotlib as mpl
import matplotlib.animation as animation
import numpy as np
import csv

# Conditions
#############################
theta = 1              # this is the condition for Moore neighbourhood
iter_speed = 100              # this is the iteration speed (just for visualization)
time_steps = 100       # Iterations
size = 8               # this is the size of the matrix (8x8)
#############################

# Definitions
def plot2d_animate(ca, title=''):
    c = mpl.colors.ListedColormap(['green', 'red', 'black', 'gray'])
    n = mpl.colors.Normalize(vmin=0,vmax=3)
    fig = plt.figure()
    plt.title(title)
    im = plt.imshow(ca[0], animated=True, cmap=c, norm=n)
    i = {'index': 0}
    def updatefig(*args):
        i['index'] += 1
        if i['index'] == len(ca):
            i['index'] = 0
        im.set_array(ca[i['index']])
        return im,
    ani = animation.FuncAnimation(fig, updatefig, interval=iter_speed, blit=True)
    plt.show()
#############I ADDED EXTRA ARGUMENTs FOR THE FUNCTION BELOW
def get_neighbourhood(cell_layer, row, col, r = 1, neighbourhood = "Moore"):
    row_indices = [0]*(2*r+1)
    for i in range(-r,r+1):
        row_indices[i+r]=(i+row) % cell_layer.shape[0]
    col_indices = [0]*(2*r+1)
    for i in range(-r,r+1):
        col_indices[i+r]=(i+col) % cell_layer.shape[1]
    n = cell_layer[np.ix_(row_indices, col_indices)]
    if neighbourhood == 'Moore':
        return n
    elif neighbourhood == 'von Neumann':
        return np.ma.masked_array(n, von_neumann_mask)
    else:
        raise Exception("unknown neighbourhood type: %s" % neighbourhood)

def init_simple2d(rows, cols, val=1, dtype=np.int):
    x = np.zeros((rows, cols), dtype=dtype)
    x[x.shape[0]//2][x.shape[1]//2] = val
    return np.array([x])
#Inner functions was moved due to bad coding practice. Arguments were also changed. Make sure you understand what I did.
def evolve2d(cellular_automaton, timesteps, apply_rule, r=1, neighbourhood='Moore'):
    _, rows, cols = cellular_automaton.shape
    array = np.zeros((timesteps, rows, cols), dtype=cellular_automaton.dtype)
    array[0] = cellular_automaton

    von_neumann_mask = np.zeros((2*r + 1, 2*r + 1), dtype=bool)
    for i in range(len(von_neumann_mask)):
        mask_size = np.absolute(r - i)
        von_neumann_mask[i][:mask_size] = 1
        if mask_size != 0:
            von_neumann_mask[i][-mask_size:] = 1
    #################################################
    #These lists keep track of values over the course of the function:
    Result_0 = ["Number of 0"]
    Result_1 = ["Number of 1"]
    Result_2 = ["Number of 2"]
    Result_3 = ["Number of 3"]
    #################################################
    for t in range(1, timesteps):
    #################################################
        #This dictionary keeps track of values per timestep
        value_iter_tracker = {0: 0, 1: 0, 2: 0, 3: 0 }
    #################################################
        cell_layer = array[t - 1]
        for row, cell_row in enumerate(cell_layer):
            for col, cell in enumerate(cell_row):
                n = get_neighbourhood(cell_layer, row, col)
                ################################################
                res = apply_rule(n, (row, col), t)
                value_iter_tracker[res]+=1
                array[t][row][col] = res
                ################################################
        print(value_iter_tracker)
        ########################################################
        #Now we need to add the results of the iteration dictionary to the corresponding
        #lists in order to eventually export to the csv
        Result_0.append(value_iter_tracker[0])
        Result_1.append(value_iter_tracker[1])
        Result_2.append(value_iter_tracker[2])
        Result_3.append(value_iter_tracker[3])
        ########################################################
    ############################################################
    #function call to export lists to a csv:
    timesteps_result = list(range(1, timesteps))
    timesteps_result = ["Time Step"] + timesteps_result
    #If you don't understand what is going on here, put print statement and/or read docs
    vals = zip(timesteps_result, Result_0, Result_1, Result_2, Result_3)
    write_to_csv_file(list(vals))
    ############################################################

    return array

################################################################################
#THIS CODE IS FROM:
#https://stackoverflow.com/questions/14037540/writing-a-python-list-of-lists-to-a-csv-file
import pandas as pd
def write_to_csv_file(data):
    data = [list(x) for x in data]
    my_df = pd.DataFrame(data)
    my_df.to_csv('output1.csv', index=False, header=False)
################################################################################

def ca_reaction_diffusion(neighbourhood, c, t):
    center_cell = neighbourhood[1][1]
    total = np.sum(neighbourhood==1)
    if total >= theta and center_cell==0:
            return 1
    elif center_cell == 1:
            return 2
    elif center_cell == 2:
            return 3
    elif center_cell == 3:
            return 0
    else:
            return 0

# Initial condition
cellular_automaton = init_simple2d(size, size, val=0, dtype=int)

# Excitable initial cells
cellular_automaton[:, [1,2], [1,1]] = 1

# The evolution
cellular_automaton = evolve2d(cellular_automaton,
                              timesteps=time_steps,
                              neighbourhood='Moore',
                              apply_rule=ca_reaction_diffusion)

animation=plot2d_animate(cellular_automaton)

I have left comments that should clarify the changes that I made. Essentially, when you call the evolve2d function, a csv file called "output1.csv" is created with the timestep results. I used the pandas package to write the data into a csv but other methods could have been used as well. I will leave it to you to take advantage of the changes that I made for your use. Hope this helps.


text:
Q: SelectListItem and linq any and select statement My CarFormat object has Name and Id property. I'm fetching all carformats which ClientId is equal to the one I passing inside method. I'm doing like this
 var carFormats = this.carRepository.All()
                .Where(x => x.CarFormat.Any(c => c.Car.Id == someVar.CarId))
                .Select(x=>x.CarFormat).AsEnumerable();

this returns me a list of CarFormat objects.
This object has properties Name and Id. After I add SelectListItem CarFormats as property inside my viewmodel I tried to bind this enumerable list of resources into select list
myViewModel.CarFormats = new SelectList(carFormats, "Id", "Name");

but I'm getting databinding exception DataBinding: `

'System.Collections.ObjectModel.ReadOnlyCollection1[[xxxxx,   xxxxxx,
  Version=1.0.0.0, Culture=neutral,   PublicKeyToken=null]]' does not
  contain a property with the name   'Name'.

When I projection to use only first item from the list everything works, except I need this for all objects not just first
myViewModel.CarFormats = new SelectList(carFormats.First(), "Id", "Name");

A: Change your query to
 var carFormats = this.carRepository.All()
            .Where(x => x.CarFormat.Any(c => c.Car.Id == someVar.CarId))
            .SelectMany(x=>x.CarFormat).AsEnumerable();

to use SelectMany
Some resources

*

*Linq - SelectMany Confusion

*Difference Between Select and SelectMany

A: The property in your class is a single select list item:
SelectListItem CarFormats

Which is why it works when you call .First() on the collection.
You are trying to set it with a value of multiple items:
myViewModel.CarFormats = new SelectList(carFormats, "Id", "Name");

Set the property in your view model class to a select list:
public SelectList CarFormats { get; set; }

A: I think you just missing a .ToList()
myViewModel.CarFormats = new SelectList(carFormats.ToList(), "Id", "Name");

redpajama_set_name: RedPajamaStackExchange


text:
Q: How do I convert System::WideString to a char* and vice versa? I have a situation where I need to compare a char* with a WideString.
How do I convert the WideString to a char* in C++?

A: You can use the wcstombs function.
size_t wcstombs( char * mbstr, const wchar_t * wcstr, size_t max );

A: See WideCharToMultiByte() and MultiByteToWideChar().

A: To compare a System::WideString object with a char* (as the question body says you want to do), you can create a new WideString object from the pointer and then use ordinary == operator. The class has several constructors, including one for const char*.
char* foo = ...;
WideString bar = ...;
if (WideString(foo) == bar)
  std::cout << "They're equal!\n";

In fact, as long as the WideString object is on the left, you don't even need the constructor call because the pointer will be converted automatically.
if (bar == foo) { ... }

To convert a WideString to a char* (as the question title says you want to do), you might consider using the AnsiString type. They're convertible between each other. To get the ordinary pointer, call the c_str method, just like you would with std::string.
WideString bar = ...;
AnsiString foo = bar;
std::cout << foo.c_str();

A: Not possible. Actually, you mixed two different concepts:

*

*Widestring implies a buffer in UTF-16 encoding.

*char* may contain anything, from UTF-8 to ASCII-only text (in which case, this is convertable only if your widestring does not contain non-ASCII characters).

Please see my answer to https://stackoverflow.com/questions/1049947/should-utf-16-be-considered-harmful about how to properly handle text.


text:
Q: Trying to set child component's height to ancestors height I have components set up that render as shown in the image below.

This is MainComponent which renders the div with class 'content'
<shared-top-control-bar></shared-top-control-bar>
<div class="content">
  <router-outlet></router-outlet>
</div>
<shared-footer-bar></shared-footer-bar>

The div with class content is reported properly with a height of 907px.
When the PointOfSale (app-point-of-sale) component is rendered, it's content is about 6.4k px in height and so app-point-of-sale has a height of 6.4k px. So when setting the height of the pos-wrapper div to 100%, it sets the height to 6.4k px when I really want it to be 907px.
I'm pretty new to CSS and angular. I could just use a service to track the height and inject the service to the components that need it. Just looking to see if there is a CSS way to do it.
Thanks

A: inside the nested component if you make a div which has the style of 100% it will take the height of the parent container.
https://stackblitz.com/edit/angular-17vrmg
Take a look at this example.


text:
Q: External keyboard modifiers with Sierra stopped working (when typing non-modifier key on MacBook Pro Retina) When I upgraded to Sierra, my shift key on the external keyboard stopped working when I press a key on my MacBook Pro Retina's keyboard.
I have a setup where my left hand is using the external keyboard (to avoid pain due to chest compression), while my right hand is on the MacBook's keyboard.
Now when I press the left shift and a letter on the MacBook keyboard, the
letter does not come capitalized. In El Capitan (and all other versions) this worked...
Any hints?
EDIT:

*

*it's not just shift. It's command, alt, shift, control.

*the modifier keys do work physically (when used with other keys on the same keyboard).

A: [SOLUTION!] Ha!!! Now it started working. Replying to my own question (related to Skeleton Bow's answer/suggestion - thanks) : Looks like Karabiner Elements kicked it the right way somehow. Even though I did not exactly change anything relevant, just installed it and opened it. Maybe the fact of installing /using karabiner forces sierra to use the old ways of handling modifier keys? Big thanks to @Skeleton Bow for the help in troubleshooting and for suggesting Karabiner Elements!

A: It might be that the shift on that keyboard does not work anymore. In that case, you should use another button as the shift button. You could try, for example, remapping the caps lock button (or some other button if you want to keep its functionality) to the left shift button using Karabiner Elements (courtesy of Tim for showing me this!). This will enable you to press the caps lock button on the external keyboard to emulate the shift button's functionality.


text:
Q: Restangular PUT attaches _id two times for no reason Iam using Restangular on the clientside with _id as Id field. Sadly Restangular generates wrong URLs, maybe you could say me where the error is?
Restangular.all('/users').one(id).get().then(functon(results) {
    $scope.data = results;
})

After the user edited the data:
$scope.save = function() {
     $scope.data.put().then(...);
};

This very simple sample generates the following URL with the id twice. I have no idea what went wrong. :(
PUT /users/537283783b17a7fab6e49f66/537283783b17a7fab6e49f66

A: Solved it by changing the Request workflow of Restangular.
I don't now why, but this approad does not work:
Restangular.all('/users').one(id).get() ... result.put();

But this does:
Restangular.one('/users/',id).get() ... result.put();

Also it is important to tell Restangular that you were using _id instead of id:
angular.module('App').config(function(RestangularProvider, AppSettings) {
  RestangularProvider.setRestangularFields({id: "_id"});
});


text:
Q: Installing Ubuntu from a USB Stick, from Windows10 First of all, I'll say I'm actually very clueless regarding "computer stuff", that's why I'm asking this question from scratch, since related questions/answers I've seen here and on other sites I couldn't really understand (read 'understand' as trying for ~4 hours and arriving at no results) and/or they didn't work for me. I won't talk about what I already tried because I'm willing to try those options again since this was several months ago. Eventually I gave up on this and continued to use Windows.
I'm interested in setting up dual boot for Windows10 64bits (my current OS) and Ubuntu 20.04 LTS Desktop. I've bought a USB Stick with 16GB of storage space and followed this tutorial: https://ubuntu.com/tutorials/create-a-usb-stick-on-windows#1-overview
When I restart my computer and boot it from the USB Stick, I get the following error message:

SYSLINUX 6.03 EDD 2014-10-06 Copyright (C) 1994-2014 H. Peter Anvin et al
Failed to load ldlinux.c32
Boot failed: please change disks and press a key to continue.

A: Ubuntu Install Quick Start
The guide that you used is not the best guide. Following the screen shots, such as using Free Dos, can create problems. The following step by step guide is as simple as it gets:

*

*Download Ubuntu 20.04 https://ubuntu.com/download/desktop

*Start with a USB of at least 4GB formatted FAT32.

*If using Windows, download Rufus. https://rufus.ie/.

*Double click the Rufus .exe file. (No need to install).

*

*Select USB Device and Ubuntu ISO file for Boot Selection.

*Stretch the Persistent partition size slider about half way.

*Confirm your Rufus looks exactly like the screen shot except for the Device name and position of the Persistence slider.

*Select START.

*When Rufus is done you can use USB to install Ubuntu to BIOS or UEFI machine.


text:
Q: Why doesn't GNOME respect OnlyShowIn=KDE; in .desktop files? I have both KDE and GNOME desktop environments installed on Ubuntu 10.10. When I add the entry OnlyShowIn=GNOME; in a .desktop file, the application doesn't appear in the KDE menu.
However, when I add OnlyShowIn=KDE; the file still appears in the GNOME menu. Does anyone know why this isn't working? Does anyone have a workaround?

A: Try running sudo update-desktop-database after you make any changes to the .desktop files.

A: I don't know about the whole Gnome story but you could use this in the meanwhile:
Gnome Menu Extended (Debian package)
There's a KDE version too: K Menu Gnome (Debian package)
Hint: read the Breaking news section in the first link. ;)


text:
Q: A 'hello world' example for a major mode in Emacs? Can anyone provide me with a hello world example for a major mode in emacs?
I guess it's a beginner question, still I really like to write a major mode, both to learn emacs and elisp, as to be able to use customization to the fullest.
What I have done so far (and is working) :

*

*wrote a file sample-mode.el and put it in a lisp dir

*called in .emacs (require 'sample-mode)

*wrote some defuns in it, and provided it at the end (provide 'sample-mode)
But still it doesn't seem to be activated, I cannot call it with M-sample-mode.
So how to do that? And can anyone provide me with a very very simple Hello World like working sample?

A: there are several examples around the Web like this.
I can also recommend you several Emacs book:

*

*Learning GNU Emacs (the best imho)

*Writing GNU Emacs Extensions

*the official GNU Emacs lisp reference/manual

A: Well, let's start with this answer, which uses define-generic-mode.
Flesh it out with some comment characters like: /* */, some keywords: hello hi etc., re-use the face from the original answer, a file extension .hello, and a function call to do further customization.
There's the additional line to get autoloading working, but you have to generate the loaddefs.el file.  That's more advanced than hello world.
And, you end up with this:
(make-face 'my-date-face)
(set-face-attribute 'my-date-face nil :underline t)
(set-face-attribute 'my-date-face nil :family "times")
(set-face-attribute 'my-date-face nil :slant 'normal)
(set-face-attribute 'my-date-face nil :height '340)

;;;###autoload
(define-generic-mode hello-world
  '(("/*" . "*/"))                           ; comment characters
  '("hello" "hi" "howdy" "greetings" "hola") ; keywords
  '(("\\([0-9]+/[0-9]+/[0-9]+\\)"
     (1 'my-date-face)))                ; font lock
  '("\\.hello$")                        ; auto-mode-alist
  '(hello-world-special-setup)          ; function-list
  "An example major mode.
We have comments, keywords, a special face for dates, and recognize .hello files.")

(defun hello-world-special-setup ()
  "Some custom setup stuff done here by mode writer."
  (message "You've just enabled the most amazing mode ever."))

A: The Elisp manual introduces major modes pretty well, and it includes a node that presents "hello-world" examples. At least that is the intention, I think.
Those examples might not cover everything you are looking for. In that case, consider requesting whatever you think is missing that would help users more. To do that, use M-x report-emacs-bug (that is for enhancement requests also).

A: Ok, after some more googling I am at least one step furhter :
(define-derived-mode sample-mode ...)

since the providing isn't defining the mode as I thought first..
This I found on :
http://xahlee.org/emacs/elisp_syntax_coloring.html
A very very nice site for emacs-lovers.
With the help of that : I have made a HelloWorld example myself now : It's a (as small as possible) Csharp mode.  I have used Euler1 as example rather than HelloWorld.  The files you need to know about are :

*

*the file the mode will be applied on  Euler1.cs

*the .emacs

*and of course the mode itself

Since a pic is worth, at least a bunch of words : all files on 1 screen :

But since this nice pic seems to disappear half the time (anyone a clue? Open in new tab always brings it on, and the url is ok) some words too :-) :

*

*The mode : cs-mode.el

(setq myKeywords
 '(("WriteLine" . font-lock-function-name-face)
   ("public\\|static\\|void\\|int\\|for\\|if\\|class"
. font-lock-constant-face)))

(define-derived-mode cs-mode fundamental-mode
  (setq font-lock-defaults '(myKeywords)))

(provide 'cs-mode)

*The .emacs, that makes the .cs files open in the right mode :

;; cs
(require 'cs-mode)
(add-to-list 'auto-mode-alist '("\\.cs\\'" . cs-mode))

And thats all : the cs-code itself is useless her, cause it won't show the effect of coloring the key-words.  To see that see the pic, or open the pic in another tab/window.
Cheers, ph


text:
Q: Mounted samba share - how to check if it is online I need to check if mounted is online in script.
and complete that check in maximum time of 1 second.
I tried:

*

*smbclient -L -U user%pass - but it takes too much time, and makes a trash in destination serwer logfile because of relogin

*stat /mnt/samba/file - but it stucks when the samba share is offline
Maybe one of You will help to find another way to complete that?
Destination samba is using SMB3.0 protocole.
Regards

A: From programmatic viewpoint it's harder than it seems.
To check for sure I'd say you have to create a file there or try to read a directory.
However linux doesn't support asynchronous open system call
And the same is the reason why utilities are hung for a long timeout (which should be about 2 minutes I guess, it's TCP-death minimum timeout)
So if you are going to implement this you should impose some smaller timeout, trying to make stat or open call on a destination folder and just terminate the thread (or send a signal there) when the timeout is expired.


text:
Q: How to place an object as an item of a Javascript array? I have a code that returns the following list from an API:
0: {idProcess: 491, serviceName: 'Testing', UserName: 'Mark', status: 'Delayed', idClient: 1, …}
1: {idProcess: 517, serviceName: 'FGTS Total', UserName: 'Joseph', status: 'Ok', idClient: 1, …}
2: {idProcess: 493, serviceName: 'Testing', UserName: 'Mark', status: 'Delayed', idClient: 1, …}
3: {idProcess: 519, serviceName: 'Portability', UserName: 'Joseph', status: 'Ok', idClient: 1, …}
4: {idProcess: 490, serviceName: 'Deed', UserName: 'Philip', status: 'Delayed', idClient: 1, …}
5: {idProcess: 492, serviceName: 'Approval', UserName: 'Philip', status: 'Delayed', idClient: 1, …}
6: {idProcess: 510, serviceName: 'Financing', UserName: 'John', status: 'Delayed', idClient: 1, …}
7: {idProcess: 515, serviceName: 'Aprovacao', UserName: 'John', status: 'Delayed', idClient: 1, …}
8: {idProcess: 518, serviceName: 'Zzz', UserName: 'Marcio ', status: 'Ok', idClient: 1, …}
9: {idProcess: 19, serviceName: 'Deed', UserName: 'Marcio ', status: 'Delayed', idClient: 1, …}
10: {idProcess: 13, serviceName: 'Deed', UserName: 'Mark', status: 'Ok', idClient: 1, …}
11: {idProcess: 12, serviceName: 'Financing', UserName: 'Mark', status: 'Delayed', idClient: 1, …}
12: {idProcess: 514, serviceName: 'Approval', UserName: 'Joseph', status: 'Delayed', idClient: 1, …}
13: {idProcess: 489, serviceName: 'Consortium', UserName: 'Mark', status: 'Ok', idClient: 1, …}
length: 14

Each object within this array I will call PROCESS, I needed to get each of these service names and store it in another list, as well as the amount of each serviceName that appears in the list. I managed to do this using the code below:

  let servicesList= [];
  resp.forEach((item) => {
    const service = servicesList.find(
      (serv) => serv.serviceName === item.serviceName
    );
    if (service) {
      service.quantity++;
    } else {
      servicesList.push({
        serviceName: item.serviceName,
        quantity: 1,
      });
    }
  });

This code snippet returned me another list like this:
0: {naneService: 'Testing', quantity: 2}
1: {nameService: 'FGTS Total', quantity: 1}
etc...

I now need to insert each PROCESS of this list corresponding to nameService as one more item in the second array created and I don't know how to do that, below is a model of how I would like the new list to be:
[
{nameService: "Testing", quantity: 2, process: [{idProcess: 491, nameService:
'Testing', UserName: 'Mark', status: 'Delayded', idClient: 1, …}, {idProcess: 493,
ServiceName: 'Testing', Username: 'Mark', status: 'Delayed', idClient: 1, …}]
nameService: "FGTS Total", quantity: 1, process: [{idProcess: 517, serviceName: 'FGTS Total',
UserName: 'Joseph', status: 'Ok', idClient: 1, …}]}
  ]

A: I think you can utilize your existing loop for this.
      let servicesList= [];
      resp.forEach((item) => {
        const serviceIndex = servicesList.findIndex(
          (serv) => serv.serviceName === item.serviceName
        );
        if (serviceIndex>=0) {
          serviceList[serviceIndex].quantity++;
serviceList[serviceIndex].process.push(item)
        } else {
          servicesList.push({
            serviceName: item.serviceName,
            quantity: 1,
          });
        }
      });

A:

// simplified response example
const resp = [{id: 1, nameService: 'alpha'}, {id: 2, nameService: 'beta'}, {id: 3, nameService: 'alpha'}]

// grouping processes by their nameService
const groups = {}
resp.forEach(process => {
  const group = groups[process.nameService]
  if (group) {
    group.quantity += 1;
    group.processes.push(process)
  } else {
    groups[process.nameService] = {
      quantity: 1,
      nameService: process.nameService,
      processes: [process]
    }
  }
})

const result = Object.values(groups)
console.log(result)

A: array.reduce() is what you are looking for:
const processes = [...yourArray];

const newProcesses = processes.reduce((acc, process) => {
  if (acc.some((item) => item.serviceName === process.serviceName)) {
    return acc;
  }

  const matchingProcesses = processes.filter((item) => item.serviceName === process.serviceName);

  return [
    ...acc,
    {
      serviceName: process.serviceName,
      quantity: matchingProcesses.length,
      process: matchingProcesses
    }
  ]
}, []);


text:
Q: Segmentation fault in array defined function When I am using a fortran function defined with an array and trying to access the function inside another routine, that is giving segmentation fault. Below is my code.
module abcd
implicit none
contains

real*8 function f(x)
real*8,intent(in)::x(:)
f=sum(x)
end function f

real*8 function funco(f,n)
real*8,external::f
integer,intent(in)::n  !dimension of array to be used with f
real*8::y(n)
y=1
funco=f(y)
end function funco

end module abcd

use abcd
implicit none

write(*,*) funco(f,10)
end

Here, I have explicitly defined the array y inside funco, still segmentation fault is coming. My original program is required to use a function that behaves like the function funco. I gave this small example for demonstrating my issue.


text:
Q: $status in Fish prompt always prints 0 I tried to add $status to my prompt in the fish shell but it always prints 0.
This question was asked on irc a while back and i'm surprised there wasn't a answer here so i thought i'd post it here as well.

A: This is because any function / command you call from within your prompt will reset the value. To make it work assign the value to another variable as the first thing you do in your fish_prompt or fish_right_prompt function.
function fish_prompt  --description 'Write out the prompt'
     set -l _display_status $status

     ...

     printf '%s' $_display_status
end


text:
Q: Responsive layout is not working? I am using bootstrap simple html code.but in mobile view its not coming properly.I am not finding any problem in my code.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
 <link class="cssdeck" rel="stylesheet" href="css/bootstrap.css">
 <link rel="stylesheet" href="css/bootstrap-responsive.css" class="cssdeck">

 <title>Doctor Log In</title>

Login

Create Account

      <form class="form-horizontal" action='dash_board.html' method="POST">
       <fieldset>

         <legend class="">Login</legend>

         Username

          <input type="text" id="username" name="username" placeholder="" class="input-xlarge">

         Password

          <input type="password" id="password" name="password" placeholder="" class="input-xlarge">

          <button class="btn btn-success">Login</button>

       </fieldset>
      </form>

      <form id="tab">
       Username
       <input type="text" value="" class="input-xlarge">
       First Name
       <input type="text" value="" class="input-xlarge">
       Last Name
       <input type="text" value="" class="input-xlarge">
       Email
       <input type="text" value="" class="input-xlarge">
       Address
       <textarea value="Smith" rows="3" class="input-xlarge">
                        </textarea>

        <button class="btn btn-primary">Create Account</button>

      </form>

        Copyrights 2013. All Rights Reserved.

        G3 Soft Tech Pvt. Ltd.

For responsive view I'm using bootstrap-responsive.css and the path is correct. Any solution will be great.

A: Add this in the HEAD section of your HTML --
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">

Explanation:
This tells smaller device browsers how to scale the page. You can read more about this here: https://developer.apple.com/library/safari/documentation/AppleApplications/Reference/SafariWebContent/UsingtheViewport/UsingtheViewport.html

A: You should be placing your JavaScript core files from Bootstrap at the bottom of the page right before the the closing  tag :-) Like This:

I'm also wondering why you have this:
class="cssdeck" src="css/jquery.min.js" A JavaScript file placed in your CSS folder? That path might have something to do with it...
class="cssdeck" src="js/bootstrap.min.js"
Not sure why you are defining a class for your script: This is correct below:
script type="text/javascript" src="js/bootstrap.min.js"


text:
Q: Measure polynomial arc-length between given range Is there a way to measure the arc-length of a curve created by a 4-degrees polynomial, between a given range?
For example, I want to measure the length of the polynomial $-\frac{1}{200}x^3+x+1$ between [0,10] (the blue line in the image below):

This is just an example, the only thing I know is that the range always starts at $x=0$, and the polynomial is a 4-degree polynomial. Is there a formula to measure the arc-length of the section?

A: The way to calculate arc-length of a curve given parametrically is to integrate speed, where speed is the magnitude of the velocity vector.
For a function $f(x)$ on an interval $[a, b]$, the parametric curve is
$$t \to (t, f(t)),$$
the velocity is
$$t \to (1, f'(t)),$$
the speed is
$$t \to \sqrt{1+\left(f'(t)\right)^2},$$
and the arc-length is therefore
$$\int_a^b \sqrt{1+\left(f'(t)\right)^2}\mathrm{dt}.$$
So for your example, $f(x) = -\frac{1}{200}x^3+x+1$, $f'(x) = -\frac{3}{100}x^2+1$, and the arclength between $0$ and $10$ is
$$\int_0^{10} \sqrt{1+\left(1-\frac{3t^2}{200}\right)^2}\mathrm{dt}.$$
I don't know whether that integral can be solved analytically, but it is worth noting that if you just need the number, Wolfram Alpha does the algebra of deriving the integrand for you.

A: This may be a dumb question, but isn't $\int_{a}^{b}\sqrt{1+(1- 3t^2/200)^2 }  dt$ = $\sqrt{\int_{a}^{b}1+(1- 3t^2/200)^2 }  dt$  which is easily expanded to $\sqrt{\int_{a}^{b}(2-3t^2/100 + 9t^4/40,000)} dt $ and integrated as a polynomial to $\sqrt{2t - t^3/100 + 9t^5/(5*40,000) +C  }$ between a and b?
This is my first use of Latex, so bear with me!


text:
Q: On iOS, a button Action is not invoked if the main view has a UITapGestureRecognizer. How to make it work? In a brand new iOS project using Xcode 4.3.2, if a button has an Action created using the Interface Builder, and it prints out "button is tapped on", then all works fine.
However, when the main view is added a UITapGestureRecognizer for a single tap, then even if the button is tapped on, the main view is thought to be tapped on but the button Action won't be called.
Is there a way to make this work?   (is it recommended to not use Button Action but use a UITapGestureRecognizer for the button?  But if it was a slider, then we do need the Action)

A: Exclude the button in [UIGestureRecognizer delegate] or set cancelsTouchesInView to NO.


text:
Q: What is the CGI show I'm thinking of that seems eerily similar to the Voltron episode of Rick and Morty? Recently, I remembered that as a child in the 90s, I watched a CGI show that revolved around a team of pilots that controlled some kind of animal robots. This show would have aired on YTV in Canada in the late 90s - maybe licensed from Cartoon Network/Toonami?
In the show, they had some underground base that they used to activate these vehicles and go fight evil. A major plot point of this series was that at one point, either the base or robots were destroyed and the pilots were no longer able to fight evil. As a kid, I remember this being traumatizing - I was invested in this series and I was watching the heroes getting systematically dismantled by the bad guys. This might have been some kind of finale as I don't remember watching the show again after that.
I did some minor googling based off of what I remembered but couldn't come up with any results. It left my mind until I watched the Rick and Morty episode Gotron Jerrysis Rickvangelion.
The entire Rick and Morty episode seems to mirror this show exactly as I remember it - animal robots stored in an underground lair. Specifically, the "robot suit up scene" at approximately 3:20 seems to be exactly what I remember. I'm almost positive that this CGI series I'm trying to remember also had one of the animals inside a volcano. The bright primary colors also seem very familiar.
I've since learned that this Rick and Morty show is parodying the anime series Voltron. However, I definitely didn't watch this anime show growing up, and I distinctly remember these robots being terrible CGI animations.
Watching the Rick and Morty episode makes me certain that this CGI show exists and helped inspire the visualizations, or that the CGI show entirely ripped off the imagery from Voltron. What is the CGI Voltron-like show I'm thinking of?

A: After doing some more research, I'm certain that this is Voltron: The Third Dimension. I found a trailer for the show which demonstrates the CGI animations and showcases a "robot suit up scene" where the pilots control lion robots. One of them is, in fact, inside a volcano!
Reading through TV Tropes for the series, it seems like the first season ends with the cliffhanger I remember of the robots being destroyed:

Cliffhanger: Season 1 ends with Zarkon achieving his takeover of the Galactic Alliance, the Lions still destroyed, Arus under threat from Lotor, and the rest of the Voltron Force on the run.


text:
Q: Install imdb-api and use it in Angular2 Webpack I am trying to use the imdb-api repo (https://github.com/worr/node-imdb-api) in my angular2 project, but can't seem to get it working.
I'm working on the newest angular2 webpack (Angular2 Webpack Starter). I usually know how to get libs working, but this one is just not working :(
Have cloned the Angular2 Webpack starter, and made the Npm install and npm start.. everything works great.
Then I have installed version 2.0.0 of imdb-api like this:
npm install --save imdb-api

It installed with no problems.
In a component, (lets say the about component) , I have imported the module like:
import * as imdb from 'imdb-api';

In the constructor, I am trying to console.log(imdb) to see if it's available.
constructor(public route: ActivatedRoute) {
    // var imdb = require('imdb-api');
    console.log(imdb);
}

As you see, I also tried using the var imdb = require ...
The problem is all this gives me errors I just can't seem to solve. I am getting the following errors:
ERROR in ./~/request/lib/har.js
Module not found: Error: Can't resolve 'fs' in 'C:\Users\Mikkel\Documents\Programmering\angular2-webpack-starter\node_modules\request\lib'

ERROR in ./~/forever-agent/index.js
Module not found: Error: Can't resolve 'net' in 'C:\Users\Mikkel\Documents\Programmering\angular2-webpack-starter\node_modules\forever-agent'

ERROR in ./~/forever-agent/index.js
Module not found: Error: Can't resolve 'tls' in 'C:\Users\Mikkel\Documents\Programmering\angular2-webpack-starter\node_modules\forever-agent'

ERROR in ./~/tough-cookie/lib/cookie.js
Module not found: Error: Can't resolve 'net' in 'C:\Users\Mikkel\Documents\Programmering\angular2-webpack-starter\node_modules\tough-cookie\lib'

ERROR in ./~/tunnel-agent/index.js
Module not found: Error: Can't resolve 'net' in 'C:\Users\Mikkel\Documents\Programmering\angular2-webpack-starter\node_modules\tunnel-agent'

ERROR in ./~/tunnel-agent/index.js
Module not found: Error: Can't resolve 'tls' in 'C:\Users\Mikkel\Documents\Programmering\angular2-webpack-starter\node_modules\tunnel-agent'

I have found a post about the request problem. The imdb-api is using the request-promise, thats why I'm getting the error.
The post you find here: https://github.com/request/request/issues/1529
The suggested to add the following:
console: 'empty',
fs: 'empty',
net: 'empty',
tls: 'empty'

to the node object in the webpack.config.js file. Have added it to the webpack dev config, but now I don't see any errors at all, but the application wont load.


text:
Q: create files through terminal and joining two files in script python3 I have a recursive directory called 'dir'. I am writing to list of files from all subdirectories to a CSV file with the following command in linux on the terminal.
dir$ find . -type f -printf '%f\n' > old_names.csv

I am using a detox code to change filenames. And I am making a new list using
dir $ find . -type f -printf '%f\n' > new_names.csv

I would like to join this to lists together and make a new list with two columns something like this;

To do that I read both csv files into pandas data frame and join them on index as follows in python3 script
 import pandas as pd
 import csv

 df_old=pd.read_csv(os.path.join(somepath,'old_names.csv')
 df_new=pd.read_csv(os.path.join(somepath,'new_names.csv')
 df_names=df_new.join(df_old)

The problem is I am getting something like this, wrong file pairs;

When I open the new_names.csv I see that file list is written in a different order than old_names list so joining on index resulting in wrong pairs. How can I solve this problem?

A: To isolate the problem, it's best to check old_names.csv and new_names.csv first to see if they are indeed in the same order. If that's indeed the problem, it's better to map filename to actual content of the file, e.g. checksum or something similar. There are 2 ways:
Method 1
Replace the find command with script below.

*

*Save the script below somewhere easy to find, maybe a level outside of your dir so it doesn't get detoxed. Let's call it 'get_sha_name_csv.py'.

import glob
import hashlib
import pandas
import sys

def get_df():
    '''

    :param dir_address:
    :return:
    '''
    files = glob.glob('*.*')
    hash_dict = []
    for file in files:
        with open(file, 'rb') as f:
            data = f.read()
        hash_dict.append({'sha256': hashlib.sha256(data).hexdigest(), 'filename':file})
    return pandas.DataFrame(hash_dict)

output_name = sys.argv[1]
get_df().to_csv(output_name)

*Call it from terminal:

dir$ python ../get_sha_name_csv.py ../old_names.csv

The second argument is the name of your output csv file.

*do detox stuff

*call

dir$ python ../get_sha_name_csv.py ../new_names.csv

*merge them with

import pandas as pd
import csv

df_old=pd.read_csv(os.path.join(somepath,'old_names.csv')
df_new=pd.read_csv(os.path.join(somepath,'new_names.csv')
pd.merge(df_new, df_old, on='sha256', how='outer')

Method 2
Do everything in python
import glob
import hashlib
import pandas
import os

def get_df(dir_address):
    # this function gives you the dataframe with sha256-to-filename mapping

    files = glob.glob(os.path.join(dir_address,'*.*'))
    hash_dict = []
    for file in files:
        with open(file, 'rb') as f:
            data = f.read()
        hash_dict.append({'sha256': hashlib.sha256(data).hexdigest(), 'filename':file}) # can replace with other hashfunctions
    return pandas.DataFrame(hash_dict)

def main(dir_address):
    # get old sha256-to-filename df
    df = get_df(dir_address)

    # run your detox code here, possibly with subprocess module (this part is untested)
    subprocess.run(['detox'], cwd=dir_address)

    # get new sha256-to-filename df and merge on sha256 values
    new_df = get_df(dir_address)
    output = pandas.merge(df, new_df, on='sha256', how='outer')
    print(output)

if __name__=='__main__':
    main(PUT_YOUR_DIRECTORY_LOCATION_HERE)


text:
Q: Ground states being superposition states in adiabatic quantum computation In Adiabatic Quantum Computing, a Hamiltonian $H$ is evolved for time $T$ according to $$H(t) = (1-t/T)H_{0} + (t/T)H_{P} $$ where $H_{0}$ is an initial Hamiltonian, and the ground state of $H_{P}$ encodes the solution to a problem of interest.
If this Hamiltonian is evolved slowly enough, the adiabatic theorem claims the system will always be in the lowest energy state (i.e. for each $t$ with $0 \leq t \leq T$, the qubits will be in the state which minimises $H(t)$). When the ground state is not a superposition state (is a basis state), calculating the energy should be easy.
But when in superposition, the system will have no objective energy; its energy state will be something of the form: $$ \sum_{s \in S} \alpha_{s}E_{s}$$ where $S$ denotes the set of all basis states (that we can find the qubits in when measured), $|\alpha_{s}|^{2}$ denotes the probability we measure the system in basis state $s$, while $E_{s}$ denotes the energy of the system when in basis state $s$.
But how do you determine which one of these (superposition) energy states is the ground state; I mean, how do you say that the energy of superposition state $A$ is less than the energy of superposition state $B$ if these energies are not scalars?
I am a computer scientist learning about Quantum Computing btw, so I apologize if there are errors in my argument.

A: The energy is always a scalar, I am not sure why you think that's not the case. We can compare the energies of any two stationary states since they are both positive numbers.
The other issue I think you're having here is a misconception about the structure of vector spaces. A basis in which the Hamiltonian is diagonal is always available and the ground state is always the basis vector in that set with the lowest eigenvalue for $H$. It is true that sometimes there are ground state degeneracies, but that is not really relevant to this discussion.


text:
Q: Example to illustrate difference between support and domain Assume that X is a discrete random variable, I understand that the domain of X is the set of values it can take and the support of X is the set of values it takes with non-zero probability.
Can someone give me an example of where
1) $S \subset D$
2) $S = D$

A: Let $X$ be the random variable that takes on the value 1 when you are right, and 0 when you are wrong. Then domain equals support, since sometimes you are right, and sometimes you are wrong.
Let $Y$ be the random variable that takes on the value 1 when I am right, and 0 when I am wrong. Then the support is strictly contained in the domain, since I am never wrong.


text:
Q: Load my combobox with the column names of my database table I am using the following method to load data from a database and fill into my combo box. For example if my database table is as follows:
Table Name: PERSONS
Person_Id Person_Name
1         Jason
2         Carl

The names Jason and Carl will be loaded into the combo box. This works fine. I am now looking to load my combo box only with the column names as in Person_ID, Person_Name. Is there a way I could modify my current method to do that? Please advice.
private void fillCombo(string query, string name, ComboBox c)
{
    MySqlCommand cmdReader;
    MySqlDataReader myReader;

    try
    {
        cmdReader = new MySqlCommand(query, conn);
        myReader = cmdReader.ExecuteReader();

        while (myReader.Read())
        {
            string temp;
            if (name != null)
            {
                temp = myReader.GetString(name);
                if (!c.Items.Contains(temp))
                {
                    c.Items.Add(temp);
                }
            }
        }
        myReader.Close();
    }
    catch (Exception e) { Console.WriteLine("Unable to load data from database"); }
}

public MainWindow()
{
    InitializeComponent();
    fillCombo("SELECT * FROM PERSONS;", "Person_Name", comboBox1);
}

A: You can get column names like this:
cmdReader = new MySqlCommand(query, conn);
myReader = cmdReader.ExecuteReader();

for(int index=0; index < reader.FieldCount; index++)
{
   c.Items.Add(myReader.GetName(index));
}

A: You could use the GetSchemaTable() method on the MySqlDataReader:
private void fillCombo(string query, string name, ComboBox c)
{
    MySqlCommand cmdReader;
    MySqlDataReader myReader;

    try
    {
        cmdReader = new MySqlCommand(query, conn);
        myReader = cmdReader.ExecuteReader();

        var table = myReader.GetSchemaTable();

        foreach (DataColumn column in Table.Columns)
        {
            string s = column.ColumnName;

            if (!c.Items.Contains(s))
            {
                c.Items.Add(s);
            }
        }

        myReader.Close();
    }
    catch (Exception e) { Console.WriteLine("Unable to load data from database"); }
}


text:
Q: time duration simualtion and assesment with gtest im using gtest unit testing framework in c++.
Normal flow is to set stimulation signals, invoke the function to test and then asses the output signals.
My unit to test has internal states, like running timers, and I want to check them continuously over a long period. I could of write asessments for every time increment. But are there some solutions that help me to specify a signal at a specific point in time and asses outputs over a duration of time? thank you


text:
Q: error CS0234: The type or namespace name 'Azure' does not exist in the namespace 'Microsoft' (are you missing an assembly reference?) I have installed Microsoft.azure.data nuget package in  visual studio but I m getting below error-
Program.cs(1,17): error CS0234: The type or namespace name 'Azure' does not exist in the namespace 'Microsoft' (are you missing an assembly reference?) below is my program code -
using Microsoft.Azure.Kusto.Data;
using System;
namespace LensDashboradOptimization
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");
            //var clusterUrl = "https://mykusto.kusto.windows.net";

            // replace 'WithAadUserPromptAuthentication' with your preferred method of authentication
            //var kcsb = new Kusto.Data.KustoConnectionStringBuilder(clusterUrl);

            //Console.WriteLine(kcsb);
            // Read the first row from reader -- it's 0'th column is the count of records in MyTable
            // Don't forget to dispose of reader when done.

            var client = Kusto.Data.Net.Client.KustoClientFactory.CreateCslQueryProvider("https://help.kusto.windows.net/Samples;Fed=true");
            var reader = client.ExecuteQuery("StormEvents | count");
            Console.WriteLine(reader);
        }
    }
}

A: Install Microsoft.Azure.Kusto.Data nuget. then it compiles for me. It does give me authentication errors but not assembly reference errors.

using Kusto.Data.Net.Client;

namespace ConsoleApp2
{
    class Program
    {

        static void Main(string[] args)
        {

            var client = KustoClientFactory.CreateCslQueryProvider("https://help.kusto.windows.net/Samples");
            var reader = client.ExecuteQuery("StormEvents | count");
        }
    }
}


text:
Q: Heroku push rejected: can't find jquery-rails-2.0.0 in sources I'm trying to push an Enki gem blog to Heroku and I'm getting an error
Could not find jquery-rails-2.0.0 in any of the sources

However, in the Gemfile I had
`gem 'jquery-rails'`

and I've never had a problem pushing an Enki blog with this setup before. Here's the full error message
 Running: bundle install --without development:test --path vendor/bundle --binstubs bin/ --deployment
           Fetching gem metadata from https://rubygems.org/.......
           Could not find jquery-rails-2.0.0 in any of the sources
     !
     !     Failed to install gems via Bundler.
     !
     !     Heroku push rejected, failed to compile Ruby/rails app

After I got the error message I added this to the gemfile
gem 'jquery-rails-2.0.0'

I got this error message
Could not find gem 'jquery-rails-2.0.0 (>= 0) java' in the gems available on this machine.

I then tried to do
gem install jquery-rails

It gave me
  Successfully installed jquery-rails-2.0.2
1 gem installed
Installing ri documentation for jquery-rails-2.0.2...
Installing RDoc documentation for jquery-rails-2.0.2...

But the push didn't work, same error
   -----> Heroku receiving push
-----> Ruby/Rails app detected
-----> Installing dependencies using Bundler version 1.2.0.rc
       Running: bundle install --without development:test --path vendor/bundle --binstubs bin/ --deployment
       Fetching gem metadata from https://rubygems.org/.......
       Could not find jquery-rails-2.0.0 in any of the sources
 !
 !     Failed to install gems via Bundler.
 !
 !     Heroku push rejected, failed to compile Ruby/rails app

this is the gemfile
source 'https://rubygems.org'

gem 'rails', '3.2.6'
gem 'heroku'

# Bundle edge Rails instead:
# gem 'rails', :git => 'git://github.com/rails/rails.git'

# Gems used only for assets and not required
# in production environments by default.
group :assets do
  gem 'sass-rails',   '~> 3.2.3'
  gem 'coffee-rails', '~> 3.2.1'

  gem 'uglifier', '>= 1.0.3'
end

group :development, :test do
  gem 'sqlite3'
end
group :production do
  gem 'pg'
end

group :production do
  gem 'thin'
end
platforms :jruby do
  gem 'activerecord-jdbcsqlite3-adapter'
  gem 'trinidad'
  gem 'jruby-openssl'
end

gem 'jquery-rails'
#gem 'jquery-rails-2.0.0'

# Use unicorn as the web server
# gem 'unicorn'

# Deploy with Capistrano
# gem 'capistrano'

# To use debugger
# gem 'ruby-debug'

# Bundle the extra gems:
gem 'RedCloth', '~> 4.2.9', :require => 'redcloth'
gem 'ruby-openid', :require => 'openid'
gem 'rack-openid', :require => 'rack/openid'
gem 'aaronh-chronic', :require => 'chronic' # Fixes for 1.9.2
gem 'coderay'
gem 'lesstile'
gem 'formtastic'
gem 'will_paginate', '~> 3.0.2'
gem 'exception_notification', '~> 2.5.2'
gem 'open_id_authentication'

# Bundle gems for the local environment. Make sure to
# put test-only gems in this group so their generators
# and rake tasks are available in development mode:
group :test do
  gem 'database_cleaner'
  gem 'cucumber-rails',    :require => false
  gem 'cucumber-websteps', :require => false
  gem 'factory_girl'
  gem 'rspec'
  gem 'nokogiri', '~> 1.5.0'
  gem 'webrat'
end

group :development, :test do
  gem 'rspec-rails'
end

A: I was getting this same error and fixed it using:

bundle update jquery-rails

In looking into it, it appears that jquery-rails 2.0.0 was yanked from rubygems: http://d.pr/i/cLms/1ReBI4U8 for whatever reason. So you (and I) likely happened to install jquery-rails when that gem was the most current version.
It's also wise to note that deleting your Gemfile.lock can be dangerous and not recommended in most cases. This causes all the latest versions of every gem without a version number in your Gemfile to be downloaded. If gems have been updated with API-breaking changes (happens more often than you might think), your app could break. But it also might not. Just be careful, run test cases if you have them. This has caused me more than one headache.
You can read a bit more about how bundler, Gemfile, and Gemfile.lock work (as well as guidance on how to properly upgrade certain gems) here: http://viget.com/extend/bundler-best-practices

A: Update:
I am going through mhartl's Rails Tutorials and had to update jquery-rails, '2.0.1' in the Gemfile, to get the bundle update jquery-rails going.
Thanks,
Jatin

A: Worked for me:

*

*delete the Gemfile.lock

*removed the rails version from the line => gem 'rails' (jquery was already without a v number)

*run the command "bundle install"

*run also "bundle update jquery-rails" to make sure everything is updated

*IMPORTANT, commit the new .lock file => run the "git add ." and "git commit ..."

*push everything

A: i had similar issue by changing in Gemfile jquery-rails-2.0.0 to 2.0.1 will solved my problem.

A: Michael,
I had to remove the version number from my jquery gem from 2.0.0 and let it pull the latest for this to work. I am on rails 3.2.8.rc2 and running on the cedar stack of heroku. Best of luck!
Mark


text:
Q: When using iFrame, how to enable web scraping (e.g., facebook) on the IFrame with meta data? Given a setup with two websites A=http://www.i.am.content and B=http://www.i.am.an.envelop.
A is internationalized, that is, the user can choose between different languages:
http://www.i.am.content&lang=en or http://www.i.am.content&lang=sw
Also, A is included in B via iFrame:
Now, users should be able to share B via social media (google+, fb, twitter ...). Importantly, the web crawler of the respective social media site should take image&text for the social media stream from A.
However, at least the fb crawler would not look for meta data tags (in the facebook case: Open Graph) in A, unless we also specify in B: <meta property="og:url" content=A />
This means, the link to A is hardcoded in B's html.
Our challenge is: How can we transfer meta data, such as the language code chosen by the user, to the link specified in og:url? In other words, how to make sure that the social media stream that is automagically created by the web crawlers of the social media providers, receives the link to A in the right language/meta settings?
Thanks a lot for any help on this one :)
Also, any help on the analogous problems with Google+ & Schema.org or Twitter cards would be great!

A: Why don't you do the following:

*

*B gets an extra parameter A_lang=xy (if it does not have a fixed language or can convert its own language parameter).

*Change the code of B (if that is possible) to include A via  and the meta tag becomes <meta property="og:url" content="A?lang=xy" />.

*A can then set the link in the share button to B?A_lang=xy. The link to B should be in the HTTP Referrer Header, and if that does not work you can always pass it to A as an extra parameter in the iframe and meta tags.

What this requires is of course that you need to modify the page B to properly do the language handling for A. But in most contexts that should be easy to achieve.


text:
Q: How to make a class/object that can be referenced at multiple levels I have read many, many ways of making makeshift classes in javascript. I'm trying to create a giant list of items, each with a variety of variables. I need to be able to call a certain object's properties from this list.
The following code compiles, but when line 9 tries to access items.yspeed1.name, it creates the button with the name "undefined". I have no clue how to access a function's variables in javascript like this.
var itemslist = function(){
    this.yspeed1 = function(){
        this.name = 'Yellow Upgrade';
        this.price = 50;
    }
    this.yspeed2 = function(){
        this.name = 'Blue Upgrade';
        this.price = 25;
    }
}

var newitem = document.createElement('button');
newitem.innerHTML = items.yspeed1.name;
shop.appendChild(newitem);

A: Well, for a starters yspeed1 is a function so you have to call it anyway, I think this might be the sort of thing you're looking for.
var itemslist = function(){
    this.yspeed1 = {
        name: 'Yellow Upgrade',
        price: 50
    }
}

This is just one way. other than that you'll have to create a
new items.yspeed1();

A: You use a class in JS when you are defining a reusable structure with state, i.e. you might have multiple copies (instances) of a class.
What you have is just a definition of a single object (single instance) with properties.  So use that Javascript construct instead:
var itemslist = {
    yspeed1: {
        name: 'Yellow Upgrade'
        , price: 50
    }
    , yspeed2: {
        name: 'Blue Upgrade'
        , price:  25
    }
}

Now you have a single object with two properties -- yspeed1 and yspeed2.  And those each have their own properties of name and price.
If you want to expand that object, just add to it, e.g. itemslist.yspeed3 = { hello: 'world' };

A: There are situations where "classes" are useful, but I think you can get away with a simple object here.
var items = {}
items.yspeed1 = {}
items.yspeed1.name = 'Yellow Upgrade';
items.yspeed1.price = 50;
items.yspeed2 = {};
items.yspeed2.name = 'Blue Upgrade';
items.yspeed2.price = 25;

var newitem = document.createElement('button');
newitem.innerHTML = items.yspeed1.name;
shop.appendChild(newitem);

A: if your looking to use a class based approach here's one using prototypes
Item Class:
function YSpeedItem(name, price)
{
  this.name = name;
  this.price = price;
}

YSpeedItem.prototype.getName = function()
{
  return this.name;
}

YSpeedItem.prototype.getPrice = function()
{
  return this.price;
}`

main code
var yspeed1 = new YSpeedItem("Yellow Upgrade", 50);
var yspeed2 = new YSpeedItem("Blue Upgrade", 25);
itemsList = [];
itemsList.push(yspeed1);
itemsList.push(yspeed2);

var newitem = document.createElement('button');
newitem.innerHTML = items[0].getName;
shop.appendChild(newitem);

more info here http://www.phpied.com/3-ways-to-define-a-javascript-class/


text:
Q: Run Content Script From Toolbar I want to have a Chrome Extension that will replace text on a page. I've got all the code working on the Javascript side of things, and it runs perfectly when a page loads, the problem is I only want it to replace the text on the page when you click a button on the toolbar.
I setup a button on the toolbar but the replacement Javascript still just runs when the page loads, rather than when you click the button. Additionally at the moment when you click the toolbar button, despite it not doing anything, it still shows a flash of a popup window. All I want it to do is run the text replacement code when you click the toolbar button, without showing a popup.html box.
The code currently is as follows,
Manifest.json
{
  "name": "Browser Action",
  "version": "0.0.1",
    "manifest_version": 2,
  "description": "Show how options page works",
  // Needed to retrieve options from content script
  "background": "background.html",

  // This is how you load Browser Action. Nearly equal to Page one.
  "browser_action": {
      "default_icon": "icon.png",
      "popup": "popup.html"
  },
  "content_scripts": [
    {
      "matches": ["http://*/*", "https://*/*"],
      "js" : ["popup.js"]
    }
  ]
}

popup.js
function htmlreplace(a, b, element) {
    if (!element) element = document.body;
    var nodes = element.childNodes;
    for (var n=0; n<nodes.length; n++) {
        if (nodes[n].nodeType == Node.TEXT_NODE) {
            var r = new RegExp(a, 'gi');
            nodes[n].textContent = nodes[n].textContent.replace(r, b);
        } else {
            htmlreplace(a, b, nodes[n]);
        }
    }
}

htmlreplace('a', 'IT WORKS!!!');

popup.html - Blank
background.html
chrome.browserAction.onClicked.addListener(function(tab) {
  chrome.tabs.executeScript(null, {file: "popup.js"});
});

A: You just need to do the following changes to your manifest:

*

*Remove the content_scripts section.

*Remove the browser_action.popup entry.

*Add a section: "permissions": ["activeTab"]

*Change your background section to read: "background": { "scripts": ["background.js"] } and rename your file background.html to background.js

A: There are a few changes you must make (most of them mentioned by rsanchez - but not all) and a couple more changes that could/should be made.
So, instead of listing things that could/should/must be changed, I will demonstrate a sample extension that does what you want.

First things first - More info on a few key concepts, related to your question/problem:

*

*Manifest File Format

*Permissions

*Background pages, Event pages

*Content scripts

*Browser actions

Extension directory structure:
          extension-root-directory/
           |_____manifest.json
           |_____background.js
           |_____content.js

manifest.json:
{
    "manifest_version": 2,
    "name":    "Test Extension",
    "version": "0.0",
    "offline_enabled": true,

    "background": {
        "persistent": false,
        "scripts": ["./bg/background.js"]
    },

    "browser_action": {
        "default_title": "Test Extension"
        //"default_icon": {
        //    "19": "img/icon19.png",
        //    "38": "img/icon38.png"
        //},
    },

    "permissions": [
        "activeTab"
    ]
}

background.js:
chrome.browserAction.onClicked.addListener(function(tab) {
    chrome.tabs.executeScript(tab.id, { file: "content.js" });
});

content.js:
function htmlReplace(a, b, element) {
    if (!element) {
        element = document.body;
    }

    var r = new RegExp(a, "gi");
    var nodes = element.childNodes;
    for (var n = 0; n < nodes.length; n++) {
        if (nodes[n].nodeType == Node.TEXT_NODE) {
            nodes[n].textContent = nodes[n].textContent.replace(r, b);
        } else {
            htmlReplace(a, b, nodes[n]);
        }
    }
}
htmlReplace("a", "IT WORKS !!!");


text:
Q: why Hyperledger composer supports only Hyperledger Fabric? Hyperledger Composer supports the existing Hyperledger Fabric blockchain infrastructure and runtime, which supports pluggable blockchain consensus protocols.
But why Hyperledger Composer supports only Hyperledger Fabric and not others like Hyperledger Burrow or sawtooth?

A: Basically Hyperledger Composer is a wrapped version of Hyperledger Fabric. Composer is tool for FABRIC and it provides us with easy way of writing a business logics (aka Business network or smart contract).
It uses the backend Fabric to accomplish the features of the Hyperledger Fabric BlockChain Network like Consensus like Traceability, Finality, Provenance, etc.
Composer is aiming to develop its interoperability with other BlockChain Platforms in future.
Also I would compare Composer and Fabric with Wordpress and Core PHP respectively.  Wordpress or anyother CMS written on top of PHP will only work with PHP on not with other technologies such as Ruby or Pearl.
Hope this clarifies.

A: As you correctly summize, Hyperledger Composer is pluggable and was designed to sit on top of different DLT technologies. In order for Hyperledger Composer to work with different DLT technologies assistance is needed from the community especially experts in these different DLT techologies to work with us and provide the appropriate plugins to work with other DLT technologies.
Hyperledger Fabric was the first DLT chosen as this was the DLT we had expertise in.


text:
Q: My .net application works on local machine but fails when used from a network location I have an C# application that needs to list a directory ( Directory.GetFiles() ) and also to access one of the files returned. If I run the application locally it doesnt have problem access the network location or the local locations, if I run it from a network share then I get a security exception thrown when accessing the shares.
I found out why this is happening:
http://blogs.msdn.com/shawnfa/archive/2003/06/20/57023.aspx
However the solutions seem... impractical unless I am misunderstanding it.
1) I can not use the code ( hardly an option )
2) Sign the assemblies and then have whoever is going to use it configure .NET policies to allow it? ( This relies on the person whos going to use it to change one of their policies which I have no say in ??)
3) Change the policy to allow full trust for everything on localintranet ( Not recommended or even possible in my case )
Am I missing something here, none of those choices seem optimal for a stand alone application being pushed onto a network I have no say in. I would have thought doing something as relatively simple as running an application from a network share to list files in a directory wouldnt have required such crazy hoops to jump through to make it work.
Anyone have any thoughts on what I could do in this situation?

A: These threads will answer you question, I think:

*

*Why does my .NET application crash when run from a network drive?

*Running a C# exe file
This behaviour is changed in .NET Framework 3.5 SP1, where it defaults to allowing programs running off network shares.
And yes, it does not feel very practical, but there is unfortunately not much to do about that...

A: I would deploy it as a ClickOnce app ("Publish" in VS2008 etc). ClickOnce can be located on a network share - you just run the .application instead of the .exe; this then works with none of the security issues with running it directly, and it'll work all the way back to .NET 2.0.

A: This problem should no longer exists when you require your users to upgrade to .NET Framework 3.5 SP1. See the following blog article on that topic:

.NET Framework 3.5 SP1 Allows managed code to be launched from a network share!


text:
Q: Shiny: Export dynamic plot to image? I am using shiny and I would like to create a download button which stores the current plot as image. this works:
  output$downloadPlot <- downloadHandler(
    filename <- function() {
      paste(input$group,'-top6_plot', Sys.Date(),'.png',sep='') },
    content <- function(file) {
      png(file, width = 980, height = 400, units = "px", pointsize = 12,
          bg = "white", res = NA)

      plot(sin, -pi, 2*pi)

      dev.off()},
    contentType = 'image/png'
  )

But I am using dygraphs for dyanmic plots and this creates an empty white image:
  output$downloadPlot <- downloadHandler(
    filename <- function() {
      paste(input$group,'-top6_plot', Sys.Date(),'.png',sep='') },
    content <- function(file) {
      png(file, width = 980, height = 400, units = "px", pointsize = 12,
          bg = "white", res = NA)

      ReshapedVariables<-variablesForPlot()

      if(input$timeframe == 1){
        Title ="Timeframe: 1 Month"
      } else if(input$timeframe==2){
        Title ="Timeframe: 3 Months"
      } else if(input$timeframe==3){
        Title ="Timeframe: 6 Months"
      } else if(input$timeframe==4){
        Title ="Timeframe: Year to date"
      } else if(input$timeframe==5){
        Title ="Timeframe: 3 Years"
      } else if(input$timeframe==6){
        Title ="Timeframe: All"
      } else {
        Title ="Timeframe: Year to date"
      }

      dygraph(ReshapedVariables, main=Title) %>%
        #dyLegend(width = 200, labelsSeparateLines = TRUE, labelsDiv="VariablePlotLegend", show="always")  %>%
        dyLegend(labelsSeparateLines = FALSE, labelsDiv="VariablePlotLegend", show="always") %>%
        dyOptions(strokeWidth=2, axisLineColor=GRAPH_BLUE, axisLabelColor=GRAPH_BLUE, gridLineWidth=0.1)

      dev.off()},
    contentType = 'image/png'
  )

But the plot code for dygraphs works in general...because in the web shiny app it shows the plot correctly.

A: This question is rather old, but perhaps this answer may still be useful to you or somebody else. This question is directly related to this question: How to save Leaflet in R map as png or jpg file?. I was having the same problem you are and here is how I solved it for my case:
You'll need to install the packages "htmlwidgets" and "webshot". Then,
library(htmlwidgets)
library(webshot)

You will also need to install PhantomJS. Then,
Save your plot as a separate object on the server side with a generic function call. You'll need to create your variable ReshapedVariables within a separate reactive environment, so it will now be treated as a function:
dyplot <- function(){
dygraph(ReshapedVariables(), main=Title) %>%
labelsDiv="VariablePlotLegend", show="always")  %>%
dyLegend(labelsSeparateLines = FALSE,  labelsDiv="VariablePlotLegend",show="always") %>%
dyOptions(strokeWidth=2, axisLineColor=GRAPH_BLUE, axisLabelColor=GRAPH_BLUE, gridLineWidth=0.1)}

and then the download:
output$downloadData <- downloadHandler(
filename = function () {paste(input$group,'-top6_plot', Sys.Date(),'.png',sep='') },
content = function(file) {
  saveWidget(dyplot(), "temp.html", selfcontained = FALSE)
  webshot("temp.html", file = file)
}
 )


text:
Q: ¿Cuál es la diferencia entre hacer "extends Comparable" y "implements Comparable" en Java? Estoy viendo en varios programas la implementación de la clase Comparable, pero en algunos la he visto usarse como interfaz
public class Class implements Comparable<E> ...

y en otros como una clase padre
static <E extends Comparable<E>> boolean estaOrdenada (PositionList<E> list);

¿Hay alguna diferencia?

A: Si hay diferencia.
En el primer caso se usa implements porque es la palabra clave que se utiliza para indicar que una clase implementa los métodos abstractos de una interfaz (en este caso la interfaz Comparable). Una interfaz es muy parecida a una clase abstracta (no se pueden crear objetos nuevos de esta clase, hay que heredar de ella para poder instanciarla) en la que todos sus métodos son abstractos (ningún método tiene implementación por lo que el la clase que hereda de esa interfaz debe implementar o hacer abstractos todos los métodos de su clase padre).
Nota: A partir de Java 8 hay un tipo de interfaz funcional que puede implementar algunos métodos también con alguna limitación.
Nota2: Como nos menciona además @E. Betanzos:

Las interfaces en java pueden tener todo tipo de métodos: abstractos
  (los de toda la vida), estáticos y por defecto (desde java 8); y
  privados (desde java 9). Aunque se parezcan cada vez más una clase
  abstracta, lo cierto es que no lo son. Estos nuevos tipos de métodos
  en las interfaces están ideados para usarse, sobre todo, en interfaces
  funcionales.

Esto es un mecanismo que utiliza Java para poder realizar una herencia múltiple con algunas limitaciones. También puedes heredar de otra clase con la palabra clave extends, pero siempre se heredeando de una clase en vez de una interfaz, y solamente se puede heredar de una clase (mientras que se pueden implementar múltiples interfaces).
En el segundo caso lo que se indica es que la función estaOrdenada devuelve un objeto de una clase E. No se especifica que clase es E, pero tiene que cumplir que herede de alguna forma (mediante extends o mediante implements) de una clase o interfaz que sea Comparable. En este caso no se pone nunca > aunque comparable sea una interfaz.
Con ejemplos un poco menos abstractos, imagínate que tienes estas clases
public class Ave {}
public class Mamifero {}

public interface PuedeVolar {}
public interface PuedeNadar {}

public class Aguila extends Ave implements PuedeVolar {}
public class Pato extends Ave implements PuedeVolar, PuedeNadar {}
public class Murcielago extends Mamifero implements PuedeVolar {}

En estos ejemplo tienes ejemplos de pseudo-herencia múltiple con la palabra clave implements.
Si tuviesemos una función así:
public <T extends PuedeVolar> T funcion1();

Esa función podría devolver tanto como un Aguila, como un Pato como un Murcielago (fijate que aquí uso extends pese a que PuedeVolar es un interfaz)
Esta función solo podría devolver un Pato:
public <T extends PuedeNadar> T funcion2();

Y esta función solo podría devolver un Pato o un Aguila:
public <T extends Ave> T funcion3();

Volviendo al caso que comentas con la función estaOrdenada, el motivo por el que E tiene que heredar de alguna forma de la interfaz Comparable es porque seguramente dicha función va a llamar en algún momento al método compareTo sobre cada elemento de esa lista.
Por último añadir, que cuando una interfaz hereda de otra interfaz, se utiliza extends en lugar de implements

A: Ésta es una de las (pocas) inconsistencias en la sintaxis de Java: Cuando se definieron los genéricos, se obvió la palabra implements, usando siempre extends. Creo que es más sencillo verlo con ejemplos:
Supongamos una interfaz InterfaceA:
interface InterfaceA { ... }

Podemos crear una nueva interfaz que extiende a InterfaceA:
interface InterfaceB extends InterfaceA { ... }

O podemos crear una clase que la implementa:
class ClassA implements InterfaceA { ... }

Pero cuando trabajamos con genéricos, no sabemos si el genérico declarado E es una clase o una interfaz, así que se decidió usar siempre extends para indicar que E cumple una condición:
void <E extends InterfaceA>hagoAlgo(E param);

Donde E podría ser ClassA o InterfaceB


text:
Q: Enable cookies with HTTPClient I am trying to implement a Java Code that fetch urls like this one:
http://trendistic.indextank.com/_trending-topics-archive/2011-12-25
The code I wrote is based in HTTPClient as follow:
    HttpClient httpclient = new DefaultHttpClient();
    // Create a local instance of cookie store
    CookieStore cookieStore = new BasicCookieStore();
    // Create local HTTP context
    HttpContext localContext = new BasicHttpContext();
    // Bind custom cookie store to the local context
    localContext.setAttribute(ClientContext.COOKIE_STORE, cookieStore);

    HttpGet httpget = new HttpGet(urls);

    try {
        System.out.println("executing request " + httpget.getURI());
        HttpResponse response = httpclient.execute(httpget, localContext);
        String line = "";
        StringBuilder total = new StringBuilder();
        BufferedReader rd = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
        while ((line = rd.readLine()) != null) {
            total.append(line+"\n");
        }
        System.out.println(total);

        return (total.toString());

    } catch (Exception e) {
        e.printStackTrace();
        return(e.getMessage());
    }
}

Nevertheless, the response I got is:
if (tz != tzless.readCookie('local_tz')) {
    // no cookies!
    document.write("
Cookies are not enabled for this site
");
    document.write("
In order for Trendistic to work in Internet Explorer you need to enable cookies.
");
    document.write("

Please enable cookies for this site and refresh this page

Or try Trendistic in a different browser such as Safari, Firefox or Chrome.

");
} else {
    self.location.reload();
}

How can I enable cookies for fetching the HTML with the dynamical results.


text:
Q: Find if string / object is present in array of objects I have an object list that retrieves multiple values from a database, like so:
List<Object> listRequest = daoManager.getLaptopsForRequest(BigInteger.valueOf(itemTransItem.getAssetType().getId()), BigInteger.valueOf(approverId));

The result of which looks like this (printed out on the console, via for each):
{asset_type_id=1, inventory_id=1, from_dt=2015-09-18 18:04:55.77, id=1, asset_id=1, status=1, thru_dt=null}
{asset_type_id=1, inventory_id=1, from_dt=2015-09-18 18:04:55.77, id=2, asset_id=2, status=1, thru_dt=null}
{asset_type_id=1, inventory_id=1, from_dt=2015-09-18 18:04:55.77, id=3, asset_id=3, status=1, thru_dt=null}

What's the quickest and/or most efficient way to get only the object where asset_id = 2, or an array of asset_id (1 and 2), and putting the results in another array?
I contemplated casting each object as a string, and then turning each string into an array (split by the comma), and then turning each item of the array into a further array (or a hashmap) by using the =, but that seems like a long, long, complex way of nested for loops that might fail (see comparing array of assets).
Perhaps there's another quicker / less complex way to do this that I'm missing? Any suggestions? Thanks.
EDIT: For reference, here's the getLaptopsForRequest function:
public List getLaptopsForRequest(BigInteger asset_type_id, BigInteger party_id){
    SQLQuery query = sessionFactory.getCurrentSession().createSQLQuery(laptopsForRequestSql);
    query.setResultTransformer(Criteria.ALIAS_TO_ENTITY_MAP);
    List forRequest = query.setBigInteger(0, asset_type_id).setBigInteger(1, party_id).list();
    return forRequest;
}

It returns a list of the results of the query. As this code has been in place, I'm not allowed to edit it.

A: What you are trying to do basically is to filter a list of objects. You could implement the Filter Pattern writing your own Iterator for the list.
Just extends this class to implement your own filter.
public abstract class Filter<T> {
  public abstract boolean passes(T object);

  public Iterator<T> filter(Iterator<T> iterator) {
    return new FilterIterator(iterator);
  }

public Iterable<T> filter(Iterable<T> iterable) {
    return new Iterable<T>() {
        public Iterator<T> iterator() {
            return filter(iterable.iterator());
        }
    };
}

private class FilterIterator implements Iterator<T> {
    private Iterator<T> iterator;
    private T next;

    private FilterIterator(Iterator<T> iterator) {
        this.iterator = iterator;
        toNext();
    }

    public boolean hasNext() {
        return next != null;
    }

    public T next() {
        if (next == null)
            throw new NoSuchElementException();
        T returnValue = next;
        toNext();
        return returnValue;
    }

    public void remove() {
        throw new UnsupportedOperationException();
    }

    private void toNext() {
        next = null;
        while (iterator.hasNext()) {
            T item = iterator.next();
            if (item != null && passes(item)) {
                next = item;
                break;
            }
        }
    }
}
}

and then use it in this way:
List<MyObject> newList = new ArrayList<MyObject>();
for(MyObject obj : filter.filter(listObjs) ){
      newList.add(obj);
 }

A: Assuming your objects have getter et setter methods.
Only the object where asset_id = "2", asset_id here being a string
 listRequest.stream().filter(e -> e.getAssetId() == "2" ).toArray();

A: A quick and dirty solution would be to match each item against regex ^.*asset_id=([0-9]+).*$.
If what you're getting from that method is indeed a list of Strings containing those JSONs, you could create a model class and use a JSON serializer like GSON or Jackson to read the strings into Java objects, and then you could work with them.


text:
Q: Why isn't javascript executing for one of my webpack entry points? Summary
I'm developing a front end with multiple webpack entry points using vanilla js and bootstrap 5. All of the entry points I've declared bar one are working and I can't understand why the remaining one is not. I'm using dev server and trying to console log javascript when the browser hits the relevant page but nothing is showing up. The relevant console log function does, however, show up in the output from the dist directory when I build a production version of the project.
What I've tried
I've read widely on stack overflow and through the webpack documentation and can't locate a solution or explanation about this specific behaviour. I additionally can instantiate other entry points with different names and webpack picks these up and maps them correctly. After many hours of reading documentation and adjusting settings in webpack, I tried getting around the issue by just rebuilding the relevant file with a different name, and associating a new entry point with it, which did work initially. However, I refactored the code within the relevant html file so that it is similar to another in the project and webpack is, bizarrely, no longer picking up the entry point. Hot module replacement also was previously monitoring this file and is now not.
I am a novice developer so could just be missing something obvious. Also, I don't really have the vocabulary to describe the mechanics of this but it feels like webpack has somehow 'cached' some code for two entry points together and is not picking up that they are meant to be different. I'm in the process of rebuilding and refactoring this project from a previous one so there's stuff everywhere - excuse the various similar file names. Grateful for any assistance.
Code
The problematic entry point is 'signIn2'. All entry points are below:
module.exports = {
  entry: {
    main: './src/client/js/main/main.js',
    login: './src/client/js/login/login.js',
    signInSelect: './src/client/js/signInSelect/signInSelect.js',
    signInDJ: './src/client/js/signInDJ/signInDJ.js',
    signInPatron: './src/client/js/signInPatron/signInPatron.js',
    demoUpload: './src/client/js/fileUpload/fileUpload.js',
    signIn2: './src/client/js/signIn2/signIn2.js'
  },

The relevant HtmlWebpackPlugin instance:
new HtmlWebpackPlugin({
  filename: 'html/signIn2.html',
  template: 'src/client/html/signIn2.html',
  inject: true,
  chunks: ['signIn2']
}),

Optimization settings:
  optimization: {
    splitChunks: {
      chunks: 'all'
    }
  }

The javascript entry point file:
// note - css is not hitting the page and it was previously
import '../../css/signIn.css';
import 'regenerator-runtime/runtime.js';
import { createNewUser } from './createNewUser';
import { uploadUserName } from './uploadUserName';
import { modal } from './modal';

// The below should log to the console but doesn't
console.log('This is signIn2');

const btnSignUp = document.getElementById('submitBtn');

// Add signup event
btnSignUp.addEventListener('click', async e => {
  e.preventDefault();
  // validation goes here
  createNewUser();

});

An excerpt from the signIn2 bundle output in dist:
e()(n.Z, { insert: 'head', singleton: !1 }),
        n.Z.locals,
        r(666),
        console.log('This is signIn2'), // <= note console.log is present
        document.getElementById('submitBtn').addEventListener(
          'click',

Apologies in advance if I've omitted useful details or code - I will happily provide more if appropriate. Many thanks for any assistance.


text:
Q: Hausdorff dimension of $\lim_{n\to\infty}\sin(2^nx)$
Calculate the Hausdorff dimension,$\dim_H$ of $$S=\{x\in(0,1):\lim_{n\to \infty}\sin2^nx=0\}$$

By definition We need to find the minimal $\alpha$ s.t $\sum_{i\in I}|U_i|^\alpha$ is minimal where $U_i$ is an open cover for the set.
On the other hand, I'm not sure it exists since the function diverges when $n\to\infty$. How can I find the dimension or prove that it doesn't exist?

A: Follow the hint by Daniel Fischer:
$$
\lim_{n\to\infty} \sin 2^n x = 0 \iff \exists n\  \sin 2^n x=0  \tag{1}
$$
The set of $x$ that satisfy the condition on the right is countable.
To prove (1), observe that if $|\sin y|\le 0.1$ then $|\cos y|\ge0.9$, so $|\sin 2y|\ge 1.8|\sin y|$. Thus, if for some $n$ the value of $|\sin 2^n x|$ is small but not zero, it will grow for a while and will not be that small.


text:
Q: Wondering about differences between Docker vs Supervisor They seem to accomplish the same thing of managing processes. What's the difference between Docker and Supervisor?

A: You can use supervisor in a docker container actually: when you can to make sure that exiting your container will kill all your processes.
A Container isolate one main process: as long as that process runs, the container runs.
But if your container needs to run several processes, you need a supervisor to manage the propagation of signals, especially the one indicating a process needs to be terminated.
See more at "Use of Supervisor in docker" to avoid the PID 1 zombie reaping problem. (zombie processes are processes which are never stopped, and remains "zombie", without any parent process)
Since Docker 1.12 (Q3 2016), you don't need supervisor anymore if you have multiple processes:
docker run --init

See PR 26061


text:
Q: How to loop through many columns I have about 88 columns in a pandas dataframe. I'm trying to apply a formula that calculates a single value for each column. How do I switch out the name of each column and then build a new single-row dataframe from the equation?
Below is the equation (linear mixed model) which results in a single value for each column.
B1 = (((gdf.groupby(['Benthic_Mo'])['SHAPE_Area'].sum())/Area_sum) *
  (gdf.groupby(['Benthic_Mo'])['W8_629044'].mean())).sum()

Below is a sample of the names of the columns

['OBJECTID', 'Benthic_Mo', 'SHAPE_Leng', 'SHAPE_Area', 'geometry', 'tmp', 'Species','W8_629044', 'W8_642938', 'W8_656877', 'W8_670861', 'W8_684891', 'W8_698965', 'W8_713086', 'W8_72726',...]

The columns with W8_## need to be switched out in the formula, but about 80 of them are there. The output I need is a new dataframe with a single row. I also would like to calculate the variance or Standard deviation from the data calculated with the formal.
thank you!

A: You can loop through the dataframe columns. I think the below code should work.
collist = list(orignal_dataframe.columns)
emptylist = []
emptydict = {}
for i in collist[7:]:
    B1 = (((gdf.groupby(['Benthic_Mo'])['SHAPE_Area'].sum())/Area_sum) *  (gdf.groupby(['Benthic_Mo'])[i].mean())).sum()
    emptydict[i]  = B1
emptylist.append(emptydict)
resdf = pd.DataFrame(emptylist)

A: to create new df with the results in each new col (one row), you can use similar as below:
W8_cols = [col for col in df.columns if 'W8_' in col]

df_out = pd.DataFrame()
for col in W8_cols:
    B1 = (((gdf.groupby(['Benthic_Mo'])['SHAPE_Area'].sum()) / Area_sum) *
          (gdf.groupby(['Benthic_Mo'])[col].mean())).sum()
    t_data = [{col: B1}]
    df_temp = pd.DataFrame(t_data)
    data = [df_out, df_temp]
    df_out = pd.concat(data, axis=1)


text:
Q: Fortran & Matlab linking -- undefined symbols I have inherited this mex code written in fortran 90 that I can't manage to properly build. All the object files compile nicely, but the linking fails.
Fortunately, I have several leads to go on to figure out the problem.
The only complaint from the linker is
Undefined symbols for architecture x86_64:
  "_mxgetstring_", referenced from:
      _mexfunction_ in qgstep_mex.o
ld: symbol(s) not found for architecture x86_64

Now mxGetStringis only called in one place in qgstep_mex.f90
status = mxGetString(prhs(3), prmfname, STRLEN)

So if I change this to
status = 0

and hardcode prmfname, the package builds just fine. But of course I don't want to hardcode it.
I have, however, managed to build another program that uses mxGetString(), namely the Matlab-supplied example file revord.f
Both of these programs are linked by the same command made by mex
gcc -O -Wl,-twolevel_namespace -undefined error -arch x86_64 -Wl,-syslibroot,/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.8.sdk/ -mmacosx-version-min=10.5 -bundle -Wl,-exported_symbols_list,/Applications/MATLAB_R2012a.app/extern/lib/maci64/fexport.map  -o  "revord.mexmaci64"  revord.o  -L/Applications/MATLAB_R2012a.app/bin/maci64 -lmx -lmex -lmat -L/opt/local/lib/gcc47/gcc/x86_64-apple-darwin12/4.7.3/../../.. -lgfortran -L/opt/local/lib/gcc47/gcc/x86_64-apple-darwin12/4.7.3 -lgfortranbegin

except that revord.F is substituted by qgstep_mex.f90 and similarly for the output name.
There is an include statement in revord.F
#include "fintrf.h"

which is pointed to during the compilation by the flag
-I/Applications/MATLAB_R2012a.app/extern/include

However, if I try to put this in qgstep_mex.f90, the linker just complains with
Warning: qgstep_mex.f90:1: Illegal preprocessor directive.

So, does anyone know how to get this working?
Update (in response to M.S.B.'s answer)
Changing the case of the extension to .F90 had no effect, but the -cpp flag seems to have done the trick. However, now it gives an error (during compilation, not linking) that I do not quite understand (I'm not very good with Fortran)
$ gfortran-mp-4.7 -c -I/Applications/MATLAB_R2012a.app/extern/include -I/Applications/MATLAB_R2012a.app/simulink/include -fexceptions -m64 -fbackslash -DMX_COMPAT_32 -O -cpp "qgstep_mex.f90"
qgstep_mex.f90:102.11:

  status = mxGetString700(prhs(3), prmfname, STRLEN)
           1
Error: Function 'mxgetstring700' at (1) has no IMPLICIT type

The relevant lines from the include file seems to be
#if defined(MX_COMPAT_32)
.
.
.
#define mxGetString mxGetString700

Update in response to M.S.B.'s update
Aha. It seems I'm not supposed to include fintrf.h after all. There's another file in the project directory, mexf90.f90, containing
module mexf90_mod
  interface
     function mxGetString(p, string, STRLEN)
       integer(8) :: mxGetString
       integer(8) :: p
       character*(*) :: string
       integer(4) :: STRLEN
     end function mxGetString

     function mxGetPr(pm)
       integer(8), pointer :: mxGetPr
       integer(8) :: pm
     end function mxGetPr
.
.

The strange thing is that mxGetPr is called just fine in qgstep_mex.f90, before mxGetString, but calling mxGetString fails, with the error message as noted originally above. Here's the linking command I use (linebreaks inserted for clarity)
gfortran-mp-4.7 -O -Wl,-twolevel_namespace -undefined error -arch x86_64
-Wl,-syslibroot,/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX10.8.sdk/
-mmacosx-version-min=10.5 -bundle -Wl,-exported_symbols_list,/Applications/MATLAB_R2012a.app/extern/lib/maci64/fexport.map
-o "QG_step_f.mexmaci64" utils.o parameters.o helmholtz.o calc.o qgflux.o qgstep.o mexf90.o qgstep_mex.o
-L/Applications/MATLAB_R2012a.app/bin/maci64 -lmx -lmex -lmat -L/opt/local/lib/gcc47/gcc/x86_64-apple-darwin12/4.7.3/../../..
-lgfortran -L/opt/local/lib/gcc47/gcc/x86_64-apple-darwin12/4.7.3 -lgfortranbegin

As can be seen, the object files do seem to be in the right order as well.
Update
The package builds just fine on a linux system. Hence I guess it must be some difference between the compilers. Here's the linking code used on the linux system:
gfortran -O  -pthread -shared -Wl,--version-script,/ufs/local/matlab-2012a/extern/lib/glnxa64/fexport.map -Wl,--no-undefined
-o  "QG_step_f.mexa64"  utils.o parameters.o helmholtz.o calc.o qgflux.o qgstep.o mexf90.o qgstep_mex.o
-Wl,-rpath-link,/ufs/local/matlab-2012a/bin/glnxa64 -L/ufs/local/matlab-2012a/bin/glnxa64 -lmx -lmex -lmat -lm

A: Try changing the filename qgstep_mex.f90 to qgstep_mex.F90.  That will cause gfortran to run the C preprocessor.  There is also a compiler option to cause that.
EDIT in response to the question update:
The compiler wants the function mxGetString7001 to be typed.  There are several ways that you can do this.  The ideal approach is to have the source code of the function in a module.  Then when the caller uses that module, the return type of the function and the types of its arguments are known to the compiler.  Perhaps this exists and you need to add the source code file to your compile statement ... before the file that uses this function.   If not, you could write an interface block providing this information.  Or you could declare the function and use an external statement, but this is really a work around, using FORTRAN 77 methods.

A: The include statement in fortran does not have a #
include "fintrf.h"

When building, why not use gfortran instead of gcc.  Saves the compiler having to figure out what you are compiling.


text:
Q: Curious to Know what Eclipse 'Show Heap Status' does In Eclipse (I am using 3.4 Ganymede) there is an option under
Preferences>General>Show Heap Status

which when checked shows near bottom of IDE like 46M of 98M and if we move the mouse over 'Recycle Bin' it says 'Run Garbage Collector'.
I am curoius to know how this works.What will happen when 'Run Garbage Collector' is clicked.
My enivroment set up is something like jdk6 is insatlled and IDE used for development and run in Tomcat server. So my understanding is all the objects which are run through Tomcat should be garbage collected. Is this correct.
Is there a way to see what objects Eclipse identified as Garbage
Cheers

A: As mention my previous answer, this is just a call to the JVM System.gc() function. (The JVM in which Eclipse runs: if your Tomcat spaw a new JVM session to execute itself, it wouldn't be impacted by this gc)
But with a plugin like Eclipse MAT, you can also check for unreachable objects, e.g. objects which should be garbage collected but stay around for various reasons, which can be more interesting.


text:
Q: How To Ignore Insets In SwiftUI Form I'm trying to ignore the automatic insets on a SwiftUI form in order to have an image fill the entire width of the screen. I've managed to do so by creating a fake section and adding negative padding, but this seems like a hack. Does anyone have a better suggestion?

struct ContentView: View {
    var body: some View {
        NavigationView{
            Form{
                Section(header:
                            Image("stockPhoto1")
                            .resizable()
                            .frame(height: 200)
                            .padding(.horizontal, -20)
                            .listRowInsets(.init())
                ){}

                ForEach(0..<5){ section in
                    Section(header: Text("Section \(section)")){
                        ForEach(1..<Int.random(in: 3...8)){ row in
                            Text("Row \(row)")
                        }
                    }
                }
            }
            .navigationBarTitleDisplayMode(.inline)
            .navigationTitle("Form")
        }
    }
}


text:
Q: `java.lang.UnsatisfiedLinkError: Native method not found: ` when button pressed I'm having an error when im clicking a button to print. this is the error that logged:
    java.lang.UnsatisfiedLinkError: Native method not found: com.jti.ph.pos_app.Interface.PrinterInterface.open:()
I have put the *.so to jniLibs folder manually and I noticed the *.so file has turned red.
I also add an code on build.gradle(Module:app)
sourceSets {
    main {
        jniLibs.srcDirs = ['jniLibs']
        aidl.srcDirs = ['src/main/aidl']
    }
}

this is the image:

This is the detailed logs:

need your help on this.

A: In a nutshell your libraries are not loading
you may try on of the following :

*

*Copy the *.so files to jniLibs.

*add the libraries to the build path.

*If you are running in simulator, then make sure that you have specified the correct architecture.

Run -> Run Configurations -> Target (you may need to add the required simulator using Window -> Android Virtual Device Manager).