text:
Q: Need helping passing variables from listview item to another activity I need some type of explanation as to how I can pass any database column value I want from the database for a listview item.
I would like to be able to grab any value, and pass it through to another activity via putExtras. I know how to do that part, what I don't have a strong grasp of is how to get the value I want from the listview before sending it through the intent.
Here is my code and some more details to help you help me:
Day.java:
package com.dd.gfit;

public class Day {

    private long id;
    private long id_routine;
    private String name;
    private String day;

    public long getId() { return id; }
    public long getIdRoutine() { return id_routine; }
    public String getName() { return name; }
    public String getDay() { return day; }

    public void setId(long id) { this.id = id; }
    public void setIdRoutine(long id_routine) { this.id_routine = id_routine; }
    public void setName(String name) { this.name = name; }
    public void setDay(String day) { this.day = day; }

}

This is where the values are stored and retreived. I get that.
DaysDataSource.java:
package com.dd.gfit;

import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;
import android.database.sqlite.SQLiteDatabase;

public class DaysDataSource {

    private SQLiteDatabase database;
    private MySQLiteHelper dbHelper;
    private String[] allColumns = { MySQLiteHelper.COLUMN_ID, MySQLiteHelper.COLUMN_ID_ROUTINE, MySQLiteHelper.COLUMN_NAME, MySQLiteHelper.COLUMN_DAY };

    public DaysDataSource(Context context) {
        dbHelper = new MySQLiteHelper(context);
    }

    public void open() throws SQLException {
        database = dbHelper.getWritableDatabase();
    }

    public void close() {
        dbHelper.close();
    }

    public Cursor fetchAllDays(long id) {
        Cursor cursor = database.query(MySQLiteHelper.TABLE_DAYS, allColumns, MySQLiteHelper.COLUMN_ID_ROUTINE + " = " + id, null, null, null, null);
        if (cursor != null) { cursor.moveToFirst(); }
        return cursor;
    }

}

This is the data source where I can retrieve all the days and their column values into a cursor to be used in a simplecursoradapter to be applied to a listview. I get this too.
DaysActivity.java:
package com.dd.gfit;

import android.app.ListActivity;
import android.database.Cursor;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.widget.SimpleCursorAdapter;

public class DaysActivity extends ListActivity {

    private DaysDataSource datasource;
    private SimpleCursorAdapter dataAdapter;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_days);

        datasource = new DaysDataSource(this);
        datasource.open();

        Cursor cursor = datasource.fetchAllDays(routineDataID);
        String[] columns = new String[] { MySQLiteHelper.COLUMN_NAME, MySQLiteHelper.COLUMN_DAY };
        int[] to = new int[] { R.id.listitem_day_name, R.id.listitem_day_day };
        dataAdapter = new SimpleCursorAdapter(this, R.layout.listitem_day, cursor, columns, to, 0);
        setListAdapter(dataAdapter);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.activity_days, menu);
        return true;
    }

    @Override
    protected void onListItemClick(ListView l, View v, int position, long thisID)
    {
        Day day = (Day)getListAdapter().getItem(position);
        long id = day.getId();

        Intent startDayActivity = new Intent(this, DayActivity.class);
        startDayActivity.putExtra("routineDataID", id);
        this.startActivity(startDayActivity);
    }

}

This is the part I don't get. First of all the listview shows up perfect with what I want in it. The onListItemClick() function is causing the app to crash when it is fired (when I click a list item). id seems to be coming up null or something? It's like it was never assigned a value for the list item.
I need to know what I am missing here. I need someone to help me and tell me what I need to add to my code and where to add it so I can better understand how to do this properly in the future.
I'm assuming I need to have the values for the day applied BEFORE trying to use the getId() function? Any help would be great.
EDIT:
I have a button inside the listview, I also want to be able to grab the id when this button is clicked.
Heres the code using an array adapter that I would like to convert to a simplecursoradapter:
public void onClick(View view) {
    @SuppressWarnings("unchecked")
    ArrayAdapter<Day> adapter = (ArrayAdapter<Day>)getListAdapter();
    ListView lv = getListView();
    int position = lv.getPositionForView(view);
    Day day = (Day) getListAdapter().getItem(position);
    long id = day.getId();
}

EDIT AGAIN:
Figured it out. Heres the code:
    ListView l = getListView();
    int position = l.getPositionForView(view);

    Cursor cursor = ((SimpleCursorAdapter)l.getAdapter()).getCursor();
    cursor.moveToPosition(position);
    long id = cursor.getLong(cursor.getColumnIndex(MySQLiteHelper.COLUMN_ID));
    String name = cursor.getString(cursor.getColumnIndex(MySQLiteHelper.COLUMN_NAME));

A: Change your onListItemClick code as for getting selected value from Cursor:
@Override
    protected void onListItemClick(ListView l, View v, int position, long thisID)
    {
      Cursor cursor = ((SimpleCursorAdapter)l.getAdapter()).getCursor();
      cursor.moveToPosition(position);
      long id = cursor.getLong(cursor.getColumnIndex("YOUR_COLUMN_NAME_HERE"));

      Intent startDayActivity = new Intent(DaysActivity.this, DayActivity.class);
      startDayActivity.putExtra("routineDataID", id);
      startActivity(startDayActivity);
    }

A: Use this:
String selectedData =(String) (l.getItemAtPosition(position));


text:
Q: Finding lowest value with no overlapping dates I have a spreadsheet with criteria, a start and end date, and a value. The goal is to find the lowest value for each unique criteria and start date without overlapping dates (exclusive of end date). I made a pivot table to make it easier for myself but I know there is probably a way to highlight all valid rows that meet the above requirements with some formula or conditional formatting.
I have attached a google drive link where the spreadsheet can be found here and I have some images of the sheet as well. I know that it might be possible with conditional formatting but I just don't know how to combine everything I want it to do in a single formula.
Example below:
Row 2 is a valid entry because it has the lowest value for Item 1 starting on 03-15-2021, same with row 9.
Row 5 is valid because the start date does not fall within the date range of row 2 (exclusive of end date)
Row 7 is not valid because the start date is between the start and end date of row 6

A: You may add a bounded script to your project. Then you can call it either with a picture/drawing that has the function assigned (button-like), or adding a menu to Google Sheets.
From what you said in the question and the comments, this seems to do what you are trying. Notice that this requires the V8 runtime (which should be the default).
function validate() {
  // Get the correct sheet
  const spreadsheet = SpreadsheetApp.getActiveSpreadsheet()
  const sheet = spreadsheet.getSheetByName('Sheet1')

  // Get the data
  const length = sheet.getLastRow() - 1
  const range = sheet.getRange(2, 1, length, 4)
  const rows = range.getValues()
  const data = Array.from(rows.entries(), ([index, [item, start, end, value]]) => {
    /*
     * Row               Index
     *  1   Criteria 1
     *  2   Item 1         0
     *  3   Item 1         1
     *  4   Item 1         2
     *
     * row = index + 2
     */
    return {
      row: index + 2,
      criteria: item,
      start: start.getTime(),
      end: end.getTime(),
      value: value
    }
  })

  // Sort the data by criteria (asc), start date (asc), value (asc) and end date (asc)
  data.sort((a, b) => {
    let order = a.criteria.localeCompare(b.criteria)
    if (order !== 0) return order

    order = a.start - b.start
    if (order !== 0) return order

    order = a.value - b.value
    if (order !== 0) return order

    order = a.end - b.end
    return order
  })

  // Iterate elements and extract the valid ones
  // Notice that because we sorted them, the first one of each criteria will always be valid
  const valid = []
  let currentCriteria
  let currentValid = []

  for (let row of data) {
    if (row.criteria !== currentCriteria) {
      // First of the criteria
      valid.push(...currentValid)    // Move the valids from the old criteria to the valid list
      currentValid = [row]           // The new list of valid rows is only the current one (for now)
      currentCriteria = row.criteria // Set the criteria
    } else {
      const startDateCollision = currentValid.some(valid => {
        row.start >= valid.start && row.start < valid.end
      })
      if (!startDateCollision) {
        currentValid.push(row)
      }
    }

  }
  valid.push(...currentValid)

  // Remove any old marks
  sheet.getRange(2, 5, length).setValue('')

  // Mark the valid rows
  for (let row of valid) {
    sheet.getRange(row.row, 5).setValue('Valid')
  }
}

Algorithm rundown

*

*We get the sheet that we have the data in. In this case we do it by name (remember to change it if it's not the default Sheet1)

*We read the data and transform it in a more an array of objects, which for this case makes it easier to manage

*We sort the data. This is similar to the transpose you made but in the code. It also forces a priority order and groups it by criteria

*Iterate the rows, keeping only the valid:

*

*We keep a list of all the valid ones (valid) and one for the current criteria only (currentValid) because we only have to check data collisions with the ones in the same criteria.

*The first iteration will always enter the if block (because currentCriteria is undefined).

*When changing criteria, we dump all the rows in currentValid into valid. We do the same after the loop with the last criteria

*When changing criteria, the CurrentValid is an array with the current row as an element because the first row will always be valid (because of sorting)

*For the other rows, we check if the starting date is between the starting and ending date of any of the valid rows for that criteria. If it's not, add it to this criteria's valid rows

*We remove all the current "Valid" in the validity row and fill it out with the valids

The cornerstone of the algorithm is actually sorting the data. It allows us to not have to search for the best row, as it's always the next one. It also ensures things like that the first row of a criteria is always valid.
Learning resources

*

*Javascript tutorial (W3Schools)

*Google App Scripts

*Overview of Google Apps Script

*Extending Google Sheets

*Custom Menus in Google Workspace
Code references

*

*Class SpreadsheetApp

*Class Sheet

*Sheet.getRange (notice the 3 overloads)

*let ... of (MDN)

*Spread syntax (...) (MDN)

*Arrow function expressions (MDN)

*Array.from() (MDN)

*Array.prototype.push() (MDN)

*Array.prototype.sort() (MDN)

*Date.prototype.getTime() (MDN)

*String.prototype.localeCompare() (MDN)

redpajama_set_name: RedPajamaStackExchange


text: Q: Issues: Google maps v3 about toggleGroup clicking checkbox does not show groups marker, but it show all markers and all groups. When I search "T^T," It takes a very long time.


text:
Q: Populate a list with data using Meteor Angular2 rxjs and material2 I am starting out with BoilerPlate and so far I have had some success learning and implementing my first full stack application.  The question comes where its time to retrieve data from the mongodb and display it on the UI.
I have a "both" folder that contains models and collections.
This is my "bill" model.
export interface Bill {
    name: string;
    due: string;
    cost: string;
}

My "bill" collection
import { MongoObservable } from 'meteor-rxjs';
import { Bill } from '../models/bills.model';

export const Bills = new MongoObservable.Collection<Bill>('Bills');

I have a function that runs on server startup that populates this collection with some test data. I have verified via mongo shell.
I would like to represent this data on the UI like this...
<md-list>
  <md-list-item *ngFor="let bill of bills | async">

{{bill.name}}

{{bill.cost}}

{{bill.due}}

  </md-list-item>
</md-list>

my angular component looks like this
@Component({
    selector: 'bills',
    animations: [routerTransition('routeAnimations')],
    template
})

export class BillsComponent implements OnInit {
    bills: Observable<Bill[]>;
    public result: any;

    constructor(private dialogService: DialogService) {
        console.log('constructed bills component');
         this.bills = Bills.find({}).zone();
    }

I am essentially trying to use concepts from this Tutorial to help develop this app.
The problem is that the md-list is empty and the mongo database has 3 entries.  I have searched for the last couple of days and can't seam to figure it out. Most examples using this methodology show that I am doing it right.
 No errors and debugging this shows that "this.bills" in the component is an observable.


text:
Q: Magento 2 rewrite not working I need to override this class
Magento\CatalogSearch\Model\ResourceModel\Fulltext
Collection

in my custom module. I have created di.xml in etc/frontend folder.
and created the class and overridden the method. This my code:
di.xml

    <preference for="Magento\CatalogSearch\Model\ResourceModel\Fulltext\Collection" type="Daiva\Customsearch\Model\Resource\Fulltext\Collection"/>
</config>

Class:

namespace Daiva\Customsearch\Model\Resource\Fulltext;

/**
 * Fulltext Collection
 * @SuppressWarnings(PHPMD.CouplingBetweenObjects)
 */
class Collection extends \Magento\CatalogSearch\Model\ResourceModel\Fulltext\Collection {

    /**
     * @inheritdoc
     */
    protected function _renderFiltersBefore() {
echo "Daiva";
        exit;
        $result = parent::_renderFiltersBefore();
        $this->_totalRecords = null;
        return $result;
    }

}

But it is not working. Did i make any mistake?


text:
Q: Area between a docking object and the object of docking We have a space station, which is the object of docking (OOD), and a spaceship, which is the docking object (DO).
What's the name of the area between the DO and the OOD once the DO docks with OOD?
I thought it was "a bridge" at first but a bridge is "the raised part of a ship on which the captain and other officers stand and from where they control the movement of the ship".
I was thinking of "ramp" but no dictionary has a definition I need.
I found "docking port" at NASA but it refers only to the retractable socket that grips the docking ship.
I found "docking compartment" and "docking module" but can't understand what they refer to.
Edit: The area should be a tunnel of some kind through which an astronaut must pass in order to reach the station.
It should be something like this only in space. It should be extendable and lead to a decompression chamber of the space station. It may be rectangular or cylindrical or any other shape. It may be within another extendable object like a wrapped tunnel. Is there some unified name for it?

A: I would call the means of ingress/egress to/from the station the gangway.
P.S. We can call the means of ingress/egress to/from the station the gangway because a gangway is the name for the structure that allows people and cargo to cross from the ship over to the dock (and vice versa).  The situation in space is analogous. We even call them "space ships".
P.P.S. Gangway
An opening in the bulwark of the ship to allow passengers to board or leave the ship.  (Wikipedia Glossary of nautical terms)

A: Within reason, I think the terminology is open to debate and change, as different mechanisms appear and the physical structure changes (and people try to be creative and quirky, because space is cool again).
If, for example, you had a tunnel (extendable or permanent) then it would be entirely reasonable and understandable to call it a docking tunnel (used in some NASA documentation) or a docking sleeve if extendable.

The probe, drogue, tension tie, and a docking ring are the principal components of the docking subsystem. Each module also contains a docking pressure hatch and a tunnel through which the astronauts will transfer from one vehicle to the other.

Your dismissal of bridge might be a bit premature, as it also refers to something people can travel (float?) across, which would work in this context.
I'm not sure, as a native speaker, that ramp seems to work here. To me, it implies moving up a slope.
A docking module is a more generic term that might mean the docking mechanism, including its mating ring, or it could mean the entire structure including any tunnel.

A: If you merely want to refer to it, it would be called the dock.  It's really not important if it's a long tunnel, a zero-length portal, or an extension of both ships connected in the middle, "dock" works well and will be understood.
If you for some reason need to illustrate what the dock looks like, then you might use docking tunnel or docking station but for simple reference -- just dock.

A: My personal choices might well be docking station and docking port as a reasonably generic term for describing a place where something can dock (although probably not the bit that joins the two). A Wikipedia article on spacecraft docking and berthing appears to favour docking interface.
The bit that joins the two could be called a docking arm or transfer passage (the term used in the Wikipedia article). If it was reasonably small, it could probably be called an airlock.
I guess if you are most interested in the connector (which is I guess another word you could use), it would seem transfer passage is the most appropriate existing term, although I don't think anyone would know what you were talking about out of context.


text:
Q: WooCommerce Wordpress Yoast Hatom Rich Snippets Solutions? Rich snippets are not working inside of my Woocommerce Wordpress environment. These snippets work on a parent page except for any Woocommerce individual product pages. I have found a couple of articles that address this issue however none of them suffice.
http://www.ilmigo.com/fix-hfeed-warning-field-set-hatomentry.html
This article explains adding new class tags throughout your document, however there are several tags missing on any single Woocommerce individual page including data, author,  time, and title. Should you create these tags and hide them using CSS just for the sake of Google? What is the best solution? Are there Woocommerce plugins available for Hatom? Below is a report of an individual page taken from Google Webmasters which describes in better detail the complications I am having.
http://www.google.com/webmasters/tools/richsnippets?q=http%3A%2F%2Fcreativeind.com%2Fbullet-resistant%2Fwindows%2Fvision-window-with-aluminum-clamp-on-frame%2F

A: we solved it simply by defining a google+ author of the posts
https://support.google.com/webmasters/answer/2539557?hl=en
So on the product template page add this anywhere in the page-
Google

Then you need to define yourself as a contributor to the website from within your google+ account settings here -
http://plus.google.com/me/about/edit/co


text:
Q: How to define deduction guide with templated constructor? In order to simplify my problem, I'll be using std::unique_lock as the tool to explain.
std::unique_lock has a template argument, the mutex. However, it's constructor is also a template function unique_lock(TMutex &, const chrono::duration<_Rep, _Period>&).
When one uses this, one can write:
 auto lock = std::unique_lock(my_mutex, 5s);

So, the question: How to write out the deduction guide for this (without changing behavior), how to do so?
My best attempt upto now:
template<typename _Mutex>
template<typename _Rep, typename _Period>
unique_lock(_Mutex &, const chrono::duration<_Rep, _Period>&) -> unique_lock<_Mutex>;

Unfortunately, clang doesn't accept this:

error: extraneous template parameter list in template specialization or out-of-line template definition

A: GCC has a better error message for this:

error: too many template-parameter-lists

You can change it to a single template parameter list, like this:
template<typename _Mutex, typename _Rep, typename _Period>
unique_lock(_Mutex &, const chrono::duration<_Rep, _Period>&) -> unique_lock<_Mutex>;

And it works.
From the comments in your question, you seem to be mixing CTAD and specializations.
You're not specializing anything in unique_lock. Not a member function, not a constructor, you're just defining a deduction guide.
More specifically, from cppreference:

The syntax of a user-defined deduction guide is the syntax of a function declaration with a trailing return type [...]
  A deduction guide is not a function [...]

Notice that it has a syntax of a declaration, not a specialization. It's just different from what you expected.


text:
Q: Unable to resolve class EnableZuulProxy when starting customer-stores-ui/app.groovy using Spring Boot CLI I'm quite new to Spring Boot and Spring Cloud and was trying to start the customer-stores example. I got the microservices running but each time when I try to start the the UI with
spring run app.groovy

I get the following exception:
startup failed:
file:/C:/Workspace/git/customers-stores/customers-stores-ui/app.groovy: 1: unable to     resolve class EnableZuulProxy ,  unable to find class for annotation
@ line 1, column 1.
@EnableZuulProxy
^

1 error

OK, this seems to be a missing dependency. But I don't have any clue of how to add this dependency. I tried with:
@Grab("org.springframework.cloud:spring-cloud-netflix-core:1.0.0.BUILD-SNAPSHOT")

But that doesn't change anything. Any ideas? Thanks in advance.

A: Some discussion here tends to suggest there's a Windows platform issue with the "install" command, which is what the README tells you to use.
This workaround works for me on Windows
$ gvm use springboot 1.1.5.RELEASE
$ cat grabber.groovy
@Grab('org.springframework.cloud:spring-cloud-cli:1.0.0.M1')
class App {}
$ spring grab grabber.groovy
$ find ./repository -name \*.jar -exec cp {} ~/.gvm/springboot/1.1.5.RELEASE/lib \;

then you should have all the dependencies installed.
The @Grab version will work if you a) add the starter for Zuul, not the bare core dependency, i.e.
@Grab("org.springframework.cloud:spring-cloud-starter-zuul:1.0.0.BUILD-SNAPSHOT")

and b) explicitly add imports for all the classes you use.


text:
Q: Exclude objective c file from public access in Swift module I have a module in one of my projects that exposes a Swift interface, but in the module it needs to use an objective c class.  I don't want to expose this class publicly.  I can't figure out how to do this.  In order to use the objective c file, I have to import it into the umbrella header.  But when I do, Xcode is forcing me to make both the umbrella header and import public in order to compile...  How can I use the objective c file privately in the module without exposing it publicly?
I apologize if this has already been answered.  I've searched through about a dozen SO questions and read the Apple Docs.  I feel as though I'm missing something right in my face but damn.. I'm just not seeing it.


text:
Q: Help me transfer contacts to new phone So my mom just bought a new Iphone 7 and she wants me to transfer ONLY her contacts to her new phone but cant i just login in with the apple ID on the New phone and everything would restore on it? If not please show a easy way to do this

A: Yes, contacts are linked to your Apple ID. To import them, just to go Settings > iCloud on both the old and new phone and enable contacts.
After that, go into the contacts app on the new phone and hit the refresh button. Her contacts should appear shortly.


text:
Q: Recursive grep matching only specific line number How can I can I find files that contain a specific pattern on a specific line number ?
Let's assume I have a directory with a bunch of text files containing 3 lines, such as:
Title A
Category X
Description Y

How can I grep / filter every files that have Category X on line 2?
How can I find files that have Title A as line 1?
I looked at the grep man page, ripgrep and alternative but not sure you can limit the search of a pattern to specific line numbers.

A: You can use awk like that:
awk 'FNR == 2 && /Category X/ {print FILENAME}' *

A: Your can use find with awk in order to exit processing the rest of the file when pattern found in the 2nd line, or even also exit if it was not found that in the 2nd line.
find -type f -name 'xyz*.txt' -exec \
    awk 'NR==2{ if(/pattern/) print FILENANE; exit }' {} \;

A: grep only, for the fun of it:
PAT="Category X"
LN=2
> grep -n "$PAT" file* | grep ":$LN:$PAT$" | grep -o "^[^:]*"
file1
file2

A: To test just the files in your current directory (assuming there's no sub-dirs or unreadable files in this directory and not so many as to exceed ARGS_MAX) would be:
awk 'FNR==2{ if (/Category X/) print FILENAME; nextfile }' *

but from your comments it sounds like you want to descend a hierarchy which would be:
find . -type f -exec \
    awk 'FNR==2{ if (/Category X/) print FILENAME; nextfile }' {} +

The use of + in the find command (may require GNU find) will cause it to run awk on batches of files instead of 1 at a time, and the use of nextfile (if your awk supports it - many do, some don't) will cause awk to stop reading the current file and move on to the next one once the 2nd line is read. Since your input files are each only 3 lines long it'll be very efficient whether your awk supports nextfile or not.

A: GNU grep can be used for your use case:
$ grep -Plzr '^(?:.*\n){1}.*Category X' .

grep normally works on a per-line basis, but GNU grep has added the -z option where in it treats the whole file as a line because it separates records on a character NOT found in text files (\0).
So now we can apply the regex on the whole file. Your requirement is searching only the second line, hence we drive past one line without doing anything ^(?:.*\n){1}
The caret ^ anchors the regex to begin from the beginning. The dot can not span lines because it doesn't match a newline.
Then the .*Category X will start looking in the next line, meaning the second, but won't span lines , so it matches if the pattern is found on the second line.
If there's a match, the -l option will list out the filename to STDOUT.
The -r option will make grep run recursively (GNU feature).
The -P will enable to write Perl style regexes (GNU feature).

Here is another stab at the problem, with GNU find+sed combo:
$ find . -type f -exec sed -ns '2{/Category X/F;}' {} +

GNU find + GNU xargs feed into Perl can also do it:
find . -type f ! -size 0 -print0 |
xargs -r0 perl -lne '
  (eof||$.==2)&&do{
    print $ARGV if $.==2 && /Category X/;
    close  ARGV; undef $.;
  };
'


text:
Q: Docker throwing SyntaxError: Unexpected token ':' I've got a very simple project express app. I've dockerized the app but Im having issues running the docker run command.
I keep on seeing this error when I run docker run test -p 8080:3000
docker run test -p 8080:3000
[eval]:1
8080:3000
    ^

SyntaxError: Unexpected token ':'
    at new Script (vm.js:99:7)
    at createScript (vm.js:249:10)
    at Object.runInThisContext (vm.js:297:10)
    at Object.<anonymous> ([eval]-wrapper:10:26)
    at Module._compile (internal/modules/cjs/loader.js:1176:30)
    at evalScript (internal/process/execution.js:94:25)
    at internal/main/eval_string.js:23:3

my dockerfile looks llike this:
FROM node:alpine
RUN apk update && apk add python make g++
WORKDIR /app
COPY ./package.json ./
RUN npm install
COPY ./ ./
CMD ["npm", "run", "dev"]

If I run docker run imageName, it's fine the container starts. But because I don't have port mapping I cant make use of the app.
What am I doing wrong?

A: The issue is with the command Im running. Instead of running docker run test -p 8080:3000 it should have been docker run -p 8080:3000 test.


text:
Q: Use java 8 features (newer janino version) in pentaho data integration Pentaho Data Integration 8.0.x is using Janino 2.5.16, released in 2010 for compiling the User Defined Java Class step. There is a JIRA in pentaho for updating this to use a newer Janino version which would bring new java 8 related features in pentaho v8.2.0 GA. But there is no info on when will this be released.
Is there any other way I can use a newer janino version (janino-3.0.8.jar) with exiting pentaho for UDJC? I tried to copy updated jar in the lib and also added commons-compiler-3.0.8.jar to fulfill dependency. Now when I open Spoon, I get the following error:

Please advise on how this can be achieved. I understand that just replacing the jar may not be enough but just want if something else can be done.

A: This is not easy. Even now, since you got ClassNotFound, public api of janino is changed. Some classes are removed some are changed. What is actual needs to update it?
If you need really complicated business logic, then create custom plugin. Documentation and tutorials are available and you can look into sources of current builtin plugins (sources are available on github).
What important new version of janino has, that old doesn't (beside java8 support)? Checkout kettle engine, look into sources of UserDefinedClass step, change code to support new janino version, test and make own build of pdi kettle, and try to send push request to maintainers of repository.
Any of this quite complicated, This plugin is builtin into engine, and you have to make own build. Own build means, you have to support it by yourself. This is non trivial, project is huge and now even bigger and continue evolving, I spent several days to make my first custom build (version of 4, was in ivy) just for purpose to know better and debug complicated cases, and it used never in production.
Maintainers of repository must have good reason to include your changes into stream, it must be well tested and it is long procedure and most probably doesn't worth it. A lots of changed since 2010, I probable have seen in release notes, new version of java already have abilities to compile at runtime.
My advice is to make you own plugin.


text:
Q: How to place the elements in relative layout I have a design in relative layout which has a central element. I want another element to the left of that central element and the base of both of these should be at same level. I have tried alignBaseline but of no use.
Please help ... !!!

A: This works for me.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="#ff0" >

    <Button
        android:id="@+id/first"
        android:layout_width="50dip"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:layout_marginTop="5dip" />

    <Button
        android:id="@+id/second"
        android:layout_width="50dip"
        android:layout_height="wrap_content"
        android:layout_alignBaseline="@+id/first"
        android:layout_alignBottom="@+id/first"
        android:layout_toRightOf="@+id/first" />

</RelativeLayout>

A: You have to use the atributes of the RelativeLayout, check here for instructions and some examples.
But to sum it up you need:
android:layout_toLeftOf="@+id/center_element"
android:layout_alignBottom="@+id/center_element"


text:
Q: Cant figure out how it determine the exact click I will like to understand how it determines the exactly clicked arrow and show its remaining content. My expectation is that the loop is supposed to be complete and i is expected to be equal to the final index of the array. What exactly is happening at the time of the click event?
let answer = document.querySelectorAll(".answer");
let arrow = document.querySelectorAll(".arrow");

for (let i = 0; i < arrow.length; i++) {

 /* prompt(i); */

  arrow[i].onclick = function() {
  arrow[i].classList.toggle("active");
  answer[i].classList.toggle("active");
  }
}


text:
Q: DataType.Time Attribute on ViewModel ignored by Telerik MVC Grid Filters I have a ViewModel property decorated with the
[DataType(DataType.Time)]

The grid column is described thus:
columns.Bound(m => m.ArrivalTime).Width(130).Format("{0:hh:mm tt}");

The Telerik MVC Grid's edit mode detects the datatype as intended and provides only time values via drop-down. Good!
The bad news is that the filtering menu ignores the datatype specification and instead provides a datepicker control. Needless to say this prohibits filtering on the column.

A: Telerik mvc grid not support time only picker as we can see in method
createTypeSpecificInput

file telerik.grid.filtering.js. So you can write your own tile filter input plugin... or try this code


text:
Q: How do I quickly calculate the standard deviation of something using pandasql? I want to calculate the standard deviation of a field called QUANTITY in my data using pandasql. The problem is that pandasql does not have STD, STDEV, or anything else like that supported. I want to calculate the COV for a field in my data but I'm having a difficult time doing that. Here is my code with the SQL query:
mysql = lambda q: sqldf(q, globals())
classified_df = mysql("""with data as (
    select
        CP_REF,
        count(*) * 1.0 /
          nullif(count(case when QUANTITY > 0 then 1 end), 0) as ADI,
          stdevp(QUANTITY) / nullif(avg(QUANTITY), 0) as COV
    from df
    where parent is not null
    group by CP_REF
)
select
    CP_REF, ADI, COV,
    case
        when ADI <  1.32 and COV <  0.49 then 'Smooth'
        when ADI >= 1.32 and COV <  0.49 then 'Intermittent'
        when ADI <  1.32 and COV >= 0.49 then 'Erratic'
        when ADI >= 1.32 and COV >= 0.49 then 'Lumpy'
        else 'Smooth'
    end as DEMAND
from data;""")

The line stdevp(QUANTITY) / nullif(avg(QUANTITY), 0) as COV is what I'm looking at in particular. Please help.
It doesn't necessarily need to be in pandasql though. I just need to query a dataframe using this method (query).

A: I had the same problem as you, I calculated manually (code below). I hope it helps.
q1 = """

SELECT
sqrt(avg(QUANTITY_MEAN*QUANTITY_MEAN)) as stdd_value

from
(select x1.*,
(QUANTITY-(AVG(QUANTITY) over (partition by CP_REF))) as QUANTITY_MEAN,
FROM df x1)
GROUP BY CP_REF
"""

dfsql1 = ps.sqldf(q1)


text:
Q: How do I store "multiple pieces of information" of an item in Java I need a Data Structure that will allow me to store at least 2 pieces of data per item. I want the items to be store in the order they were inserted in.
Example:
Insert (xyz, string) ... insert (789, number)
System.out.println( dataStruct );

will print out (xyz, string) then (789,number)
If possible, please show some sample codes. Thank you!

A: The below code can be your data structure :
 List<Item> list;

    class Item {
     public String desc;
     public Integer val;
     void insert(String desc,Integer val){
     this.desc = desc;
     this.val = val;
     }
     void insert(Integer val,String desc){
     insert(desc,val);
     }
    }

A: You can use a Hashtable or a List
Example:
Hashtable<Integer,String> hTable=new Hashtable<Integer,String>();
//adding or set items in Hashtable by put method key and value pair
hTable.put(new Integer(2), "Two");
hTable.put(new Integer(1), "One");
hTable.put(new Integer(4), "Four");
hTable.put(new Integer(3), "Three");
hTable.put(new Integer(5), "Five");

Take a look at some Java structures.
EDIT
In order to keep the insertion order one can use a LinkedHashSet or LinkedHashMap

A: public class Store {
String str1;
String str2;

public Store(String string1, String string2) {
    str1 = string1;
    str2 = string2;
}

public static void main(String[] args) {

    Store[] s = new Store[10]; // size
    for (int i = 0; i < s.length; i++) {
        s[i] = new Store("A", "B");
        System.out.println(s[i].str1);
        System.out.println(s[i].str2);

    }

}
}

I think this is what you are searching for . This is  C like structure. Try this.
This will help you to insert more than 2 piece of data per item  by just doing little changes. And order will be maintained too.

A: This will somehow fill the requirement,you can also use parameters of the type in the constructors of HashMap.
HashMap map= new HashMap();
List<HashMap> virtualDs= new ArrayList<HashMap>();


text:
Q: Is `new` in `new int;` considered an operator? The expression new int; such as in int * x = new int; is a new expression. The term "new operator" seems to be used interchangeably with "new expression", for example in this question : Difference between 'new operator' and 'operator new'?
Is it correct to say that the keyword new as it is used in a new expression is an operator? Why or why not?
If not, is there another justification for calling a new expression "new operator"?
I am having trouble finding an authoritative definition for what constitutes an operator.
I already understand the distinction between operator new which allocates memory for an object and "new expression" which may eventually call an operator new.

A: This is governed by [expr.new], which clearly differentiates between a new-expression and how a new expression may obtain storage by means of calling an allocation function, which is named operator new. Particularly, from  [expr.new]/8 [emphasis mine]:

A new-expression may obtain storage for the object by calling an allocation function ([basic.stc.dynamic.allocation]). If the new-expression terminates by throwing an exception, it may release storage by calling a deallocation function. If the allocated type is a non-array type, the allocation function's name is operator new and the deallocation function's name is operator delete. If the allocated type is an array type, the allocation function's name is operator new[] and the deallocation function's name is operator delete[].

Is it correct to say that the keyword new as it is used in a new expression is an operator?

Particularly, the example, albeit non-normative, of [expr.new]/4 describe this function as an operator function;  "[...] the new operator":

[...] Instead, the explicitly parenthesized version of the new operator can be used [...]

A: No.
Well, sort of yes, in the sense that there exist people who consider new in new int to be an operator. However, this opinion is (mostly) at odds with the standard.
Firstly, [lex.operators/1] lists the operators in the language. Don't be fooled into thinking that these are just "preprocessing operators", either; no such distinction exists in the sense of lexical operators. It wouldn't make sense, either, since you cannot (for example) ++ a macro.
new is, in fact, a keyword (per [lex.key/1]).
Next, let's look at new-expression itself. This is where things get a little more wooly.  There is, for example, the following wording in [expr.new/4]:

Instead, the explicitly parenthesized version of the new operator can be used to create objects of compound types

I consider this to be an editorial error, since it is at odds with the definitions provided above, and does not occur anywhere else in that section.
Then we come to operator overloading. In its grammatical production for an operator declaration, the terminal listing things (including new) is named operator ([over.oper.general/1]). I don't think we need to worry about this. The names of terminals in the grammar have never been intended to introduce definitions of terms. After all, you have and-expression that _doesn't need to be a bitwise AND operation; it can just be an equality-expression:

and-expression:
   equality-expression
   and-expression & equality-expression

It's common to define grammars like this, and it certainly doesn't mean that every equality-expression is somehow to be considered an invocation of the bitwise AND operator.
Finally, some have claimed that the following wording (also in the operator overloading section) is proof that new is somehow now, in isolation, magically an operator:

The operators new[], delete[], (), and [] are formed from more than one token

To them I say, not only is new not even listed, but this is clearly using the term "operator" in the more broad sense of "things that can be overloaded", even though new in itself is still not an operator. It's also in a non-normative note, which should tell you all you need to know.
And, as you point out yourself, we already consider operator new to be something else.

A: While I know you're looking for a semantical answer, as far as opinion I would say it's a "keyword" (as it's clearly reserved), and I assume we both know that it's simply C++'s construct for memory allocation. That said, when I think of C++'s "operator"s, I tend to think of functions with a set input/output that can be overriden for specific types. new is the same for all types (and more confusingly it can be overridden).
Not sure how official cppreference is, but:

The new-expression allocates storage by calling the appropriate allocation function. If type is a non-array type, the name of the function is operator new. If type is an array type, the name of the function is operator new[]

https://en.cppreference.com/w/cpp/language/new
It seems to follow then that new <type> is an expression to allocate memory, while new is the operator for that expression.
Using that same logic:

*

*sizeof is an "operator" for the expression sizeof(<type>) (though sizeof is a "compile-time" operator, a bit different than what we're used to)

*+ is an operator for an expression <type> <operator> <type>

*throw is an operator for the expression throw <throwaable>

A:
Is it correct to say that the keyword new as it is used in a new-expression is an operator? Why or why not?

No. The new in a new-expression is a keyword identifying a new-expression.
A new-expression calls an operator new or operator new[] to get storage. It also initializes that storage, and de-allocates it (with operator delete or operator delete[]) if the initialization throws.
There's a clear distinction, in that operator new is only referred to as a overloadable user-replaceable function, and a new-expression does more than just call this function.
Reference: 7.6.2.8/10 [expr.new]

A new-expression may obtain storage for the object by calling an allocation function ([basic.stc.dynamic.allocation]).
If the new-expression terminates by throwing an exception, it may release storage by calling a deallocation function.
If the allocated type is a non-array type, the allocation function's name is operator new and the deallocation function's name is operator delete.
If the allocated type is an array type, the allocation function's name is operator new[] and the deallocation function's name is operator delete[].

Consider by way of counterexample, that we define both
T operator+(T, T);
void* T::operator new(std::size_t);

for some type T, then addition in either form:
T a, b;
T c = a + b;
T d = T::operator +(a, b);

is identical. The infix notation is just syntactic sugar for the operator call.
Allocation however, behaves very differently:
T *p = new T;
// does much more than
void *v = T::operator new(sizeof(T));

so it's not reasonable to call the new-expression syntactic sugar for a call to operator new. Thus, the new keyword isn't simply selecting the function to call. It can't be, or it would have to mention the operator delete function that might also be called.

A: new in new int is not considered to be an operator. It is also not considered to be not an operator.
The C++ standard is really vague, and even inconsistent, about what constitutes an 'operator'. When listing operators (as defined during lexing and preprocessing), it lists them along with "punctuators" (things like (), but never really gives any rules for punctuators in general. It lists new as both a keyword and an operator. It lists sizeof in the set of keywords but NOT in the set of operators, but later refers to it as an operator.
The takeaway here is that the C++ standards committee is not overly concerned with separating the lexical world into "operators" and "non-operators". This is because there isn't really any need to. There's no grammatical rules which apply to all operators or all non-operators. Important sets, like the set of overloadable operators, are given separately; grammatical rules for things like binary arithmetic expressions are given one at a time.
Basically, "operator" is not a category which is formally meaningful to the C++ language, so any categorical answer is going to be based on how it "feels". You can call it an operator if you like, but you can also call it a keyword (or a punctuator!) and the language standard will not disagree with you.

A: I would only call it new expression to avoid confusion with void* operator new  ( std::size_t count ) which only allocates memory as part of the process the new expression  invoices (allocation memory, starting lifetime, calling constructor).
The problem with new is that it does more than just calling the operator new. Which is a bit confusing because for x + y the + only calls operator +.


text:
Q: Which is faster: access repository directly or use hashmap with the results from it? I have a service with Hibernate. And I want to make it work as fast as possible.
Would it be better to store all my tables into hashmaps in the beginning, and then use it to access entities, or it would be the same as using repo.findById() method? I am working with data within one transaction.
I've heard that hibernate caches all the results until the end of the transaction and if so, then I assume findById() would work with the same speed. But I just want to make sure)


text:
Q: how to use JACKSON serializer for domain object used for different services? I have one domain object which is used for 2 different services as below :
public class PersonDetails {

    private String personId;
    private String personMaritalStatus;
    private String personFirstName;
    private String personLastName;

    // setters and getters ...
}

and having two different services.
First One :
public BaseResponse getClient(@QueryParam("id") @DefaultValue("-1") String id)
{
}

this service should return json as below :
{ "personId":12,
  "personMaritalStatus":"married",
  "personFirstname" :"abc",
  "personLastname":"pqr" }

Second service :
public BaseResponse getClientName(@QueryParam("id") @DefaultValue("-1") String id)
{
}

this service should return json as below :
{"personFirstname" :"abc"}

So if I used @JsonSerialize(using=PersonDetailsSerializer.class) over domain object and serializer class will be as below :
public class PersonDetailsSerializerextends JsonSerializer<PersonDetails>
{
    @Override
    public void serialize(PersonDetails personDetails,
                          JsonGenerator jsonGenerator,
                          SerializerProvider serializerProvider)
                              throws IOException, JsonProcessingException {
        jsonGenerator.writeStartObject();
        jsonGenerator.writeStringField("personFirstname", personDetails.getpersonFirstName());
        jsonGenerator.writeEndObject();
    }
}

then it impact response for getPerson service also.
So how can I used service level serialization or is anyother way to handle this, using JACKSON...

A: You can use two different ObjectMappers one with a MixIn and one without.
abstract class PersonNameMixIn {
    @JsonIgnore()
    abstract String getPersonLastName();
    @JsonIgnore()
    abstract String getPersonMaritalStatus();
}

public getClientName() {
        ObjectMapper mapper = new ObjectMapper();
        mapper.getSerializationConfig().addMixInAnnotations(PersonDetails.class, PersonNameMixIn.class);
        mapper.writeValue(writer, person);
}

public getClient() {
        ObjectMapper mapper = new ObjectMapper();
        mapper.writeValue(writer, person);
}


text: Q: What is the horn torus homeomorphic to? Is the horn torus homeomorphic to some other well known object? In particular, the standard torus can be described by a square with collapsed edges. What about the horn torus?


text:
Q: Setting up mongodb behind nginx I am trying to setup mongodb behind nginx, and below is the configuration I used. But I keep getting the following error when I reload nginx. Any help is appreciated.
nginx: [emerg] "stream" directive is not allowed here in /etc/nginx/sites-enabled/mongodb:1
stream {
    server {
        listen 27020;
        proxy_connect_timeout 5s;
        proxy_timeout 20s;
        proxy_pass    stream_mongo_backend;
    }

    upstream stream_mongo_backend {
        server 127.0.0.1:27017;
    }
}

A: Check nginx.conf where the sites-enabled files are included.
Thats probably done in the http section of the conf file, but the stream directive is only allowed in the main section as stated here: http://nginx.org/en/docs/stream/ngx_stream_core_module.html#stream
You have to move your directive in nginx.conf file itself:
user ...
...
http {
  ...
}
stream {
  ...
}

A: in /etc/nginx/nginx.conf
user www-data;
worker_processes auto;
pid /run/nginx.pid;
include /etc/nginx/modules-enabled/*.conf;

events {
    ....

}

stream {
    server {
        listen  27018;
        proxy_connect_timeout 1s;
        proxy_timeout 3s;
        proxy_pass    stream_mongo_backend;
    }

    upstream stream_mongo_backend {
        server localhost:27017;
    }
}

http {
...
}


text:
Q: Oracle apex - Place field next to breadcrumb region I want to place an item\region next to breadcrumb region, but Apex doesn't seem to allow it, any ideas?

A: Thanks to @KoenLostrie I checked the Page template and found the "Template Substitution" to which the breadcrumb belongs to. There, in the section "Display Points" need to check the "Grid Support" for this specific template Substitution.


text:
Q: Label a set of numbers with an easily comparable "reference number". I have a set of numbers (product codes).
I want to perform some calculation that returns a short easily compared "reference number" to identify this set.
Each week, I compare the records in my database with my packing slips used to ship goods.
So my database will record that a shipment with the following product codes was shipped.
32600,32600,12589,13872,14899,16990,34907,5003,42988
If everything has been performed correctly, I expect the packing slip to record the same information.
It is a very tedious task to do this sort of comparison.
Is there a function I can perform on this set that will return a simple, easy to compare number.
For instance, the set above might return 986547. A number calculated to be unique to this set. So all I would need to do is ensure the 986547 appears both in the database and on the packing slip.
As I'm sure you can tell from the style of question, I'm not great at Maths. But I know enough to ask the question here!
Any help is appreciated. Thank you.

A: You can use a cyclic redundancy check or a hash function.  Either one will take a list of numbers and return a single value, which you can compare for the two lists.  You will need to sort the numbers in the list or the output values will disagree.  You need a small version or the length of your output number may be greater that the input numbers an it won't save any work.


text:
Q: Resizing pane is not working for tmux on mac? After searching through, I figured ctrl+b ( PREFIX ) then ctrl + arrow should resize the current pane. But it is not working. Am I missing anything ?
Thanks.

A: Probably your terminal is not sending a (distinct) sequence when you hold Control and press an arrow key.
Try running cat and typing the keys into it (Control-C to quit). You will probably find that (e.g.) Up and Control-Up both generate the same sequence.
OS X Terminal application
In its default configuration the OS X Terminal application sends the sequence ^[[A (or ^[OA) whether you type Up or Control-Up (also any combination with Shift and Option, too).
However, you can reconfigure Terminal to send appropriate codes. It is a bit tedious, but you usually only have to do it once.

*

*Terminal > Preferences…

*Settings top-level tab

*pick the profile you want to modify

*Keyboard tab

*click the plus button to add a new binding

*

*pick a cursor key

*set the modifier to control

*use the Send Text: action

*type Escape (will show up as \033) followed by [1;5 and one more character:

*

*A for Up,

*B for Down,

*C for Right, or

*D for Left

*click OK to add the binding

For example, the final sequence for Control-Up should end up looking like \033[1;5A.
These sequences are the ones that XTerm generates (see the ctlseqs documentation for details).
Repeat the last step for the other arrow keys.
iTerm 2
iTerm 2 sends the expected sequence by default.

A: Open the tmux.conf file and edit it with vi:
vi ~/.tmux.conf

Insert these lines:
set -g mouse on
set -g mouse-select-window on
set -g mouse-select-pane on
set -g mouse-resize-pane on

Press "Esc" and "ZZ" to save your changes.
Now you can resize the panes using the mouse.

A: By default Mac OS has Mission Control shortcuts bound to ctrl+arrows, and they take precedence over the Tmux controls. I do not use these shortcuts on Mac anyway, so I just turned them off in keyboard settings, and now the Tmux controls work as expected:

A: You can use the meta key instead of the control key in the ctrl-↑ and ctrl-↓ combinations. In OSX Terminal the default meta key is the escape key. For example, to increase the size of a pane type ctrl-b esc-↑.
I find the escape key a pain to reach so I use the option key as the meta key instead. In Terminal.app you can change it by going to Terminal > Preferences > Profiles > Keyboard : check the "Use Option as Meta Key".
Now you can type ctrl-b option-↑ to increase the size or ctrl-b option-↓ to decrease the size and you don't have to remap the mission control keys.

A: I added the following key bindings to ~/.tmux.conf to resize with Ctrl + hjkl:
bind -n C-k resize-pane -U 5
bind -n C-j resize-pane -D 5
bind -n C-h resize-pane -L 5
bind -n C-l resize-pane -R 5

Then run tmux source-file ~/.tmux.conf to reload the config.

A: On at least Mavericks and iTerm2, you have to hold Control, then press b (instead of holding), then hold down a directional button. This sends pretty much the same sequences as holding down Control-b with a directional button so it works.
Also, make sure to head over to keyboard settings and in shortcuts tab disable any mission control and such keyboard shortcuts you may have for Control plus a directional key.


text:
Q: How do you change a UIStepper's value: Double outside of its @IBAction? Within the @IBAction you just change the value property, but what about outside of it?

A: A stepper does not have a text property. It has a value property, which is how you change it's value.
You need to set up an IBOutlet to your stepper:
@IBOutlet weak var myStepper: UIStepper!

and when you want to set its value:
myStepper.value = 6


text:
Q: Network latency caused by incorrect cable? Our team recently setup a new network and now we are experiencing network latency issues. the flow of traffic is as such:
modem -> router -> packet shaper -> cisco3750 switch
from router to packet shaper, I believe we used a cross over cable and from packet shaper to switch, a straight through.
My question is, would using a crossover cable vs straight through cause noticeable lag in the network? The client site is a few hours away and am hoping this is not the case :(
UPDATE:
Here are some speed test results

*

*speedtest.net

*connectionanalyzer.com
The latency is very noticible during VOIP calls, we have 2 sites and a T1 connecting the two. The above speed test results are from one of the sites.

A: In your question's scenario : No. It would either work (meaning that your ports have Auto MDI-X, which is built into Gigabit Ethernet, IIRC) just fine, or not work at all.
Which means the cause of your problem is elsewhere.


text:
Q: Using one activity resources from other class I have situation where I get the nearest location based on checking the distance between current lat and long
public void onLocationChanged(Location loc) {
        lat1=loc.getLatitude();
    lng1=loc.getLongitude();
           Com_Util.check_NearLoc(lat1,lng1);
    }

I update a static variable which contains the nearest place from the current location and display in a  text view showing the current location in all the activities. I am able to get the nearest place and was able to display it only during onCreate of an activity.
I need a text view showing the current location while using the app. I dont want a thread to be running all the time checking for the location change instead is there any way updating the textviews from the check_NearLoc function itself which is in a nonactivity class.


text:
Q: SpringFramework: instantiation exception I'm new to Spring Framework so I decided to buy a book ("Spring in action" 3rd edition). Currently I'm at first chapter which covers basics - Dependency Injection (DI) and Aspect oriented programming (AOP).
I managed to run this code which showed DI.
1#Interface implemented by knight
package com.springinaction.knights;

public interface Knight {
  void embarkOnQuest() throws QuestException;
}

1#Knight class
package com.springinaction.knights;

public class BraveKnight implements Knight {
  private Quest quest;

  public BraveKnight(Quest quest) {
    this.quest = quest;       //<co id="co_injectedQuest"/>
  }

  public void embarkOnQuest() throws QuestException {
    quest.embark();
  }
}

#2Quest interface
package com.springinaction.knights;

public interface Quest {
  void embark() throws QuestException;
}

#2Quest Exception
package com.springinaction.knights;

public class QuestException extends RuntimeException {
  private static final long serialVersionUID = 1L;
}

#2Quest type class implementation
package com.springinaction.knights;

public class SlayDragonQuest implements Quest {

  public void embark() throws QuestException {
    System.out.println("Slaying Dragon!");
  }

}

#3Testing brave knight DI
package com.springinaction.knights;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class KnightMain {
  public static void main(String[] args) {
    ApplicationContext context =
        new ClassPathXmlApplicationContext("knights.xml"); //<co id="co_loadKnightContext"/>

    Knight knight = (Knight) context.getBean("knight"); //<co id="co_getBeanKnight"/>

    knight.embarkOnQuest();//<co id="co_useKnight"/>
  }
}

This is XML application context which injects quest into knight
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
     http://www.springframework.org/schema/beans/spring-beans-3.2.xsd">

    <bean id="quest" class="com.springinaction.knights.SlayDragonQuest" /><!--<co
        id="co_quest_bean"/> -->

    <bean id="knight" class="com.springinaction.knights.BraveKnight">
        <constructor-arg ref="quest" /> <!--<co id="co_inject_quest_bean"/> -->
    </bean>

</beans>

To this moment everything works, but when author wants to show AOP then something is wrong in XML file. The idea is that minstrel sings (logs) before knight goes on a quest and sings (logs off) when knight comes back from a quest.
Minstrel class
package com.springinaction.knights;

public class Minstrel {
  public void singBeforeQuest() {     //<co id="co_singBefore"/>
    System.out.println("Fa la la; The knight is so brave!");
  }

  public void singAfterQuest() {     //<co id="co_singAfter"/>
    System.out.println(
            "Tee hee he; The brave knight did embark on a quest!");
  }
}

XML AOP file, I guess there is some kind of error here, but I don't know what...
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xmlns:aop="http://www.springframework.org/schema/aop"
 xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
        http://www.springframework.org/schema/aop
    http://www.springframework.org/schema/aop/spring-aop-3.2.xsd">

  <bean id="knight" class="com.springinaction.knights.BraveKnight">
    <constructor-arg ref="quest" />
  </bean>

  <bean id="quest"
        class="com.springinaction.knights.SlayDragonQuest" />

  <bean id="minstrel"
     class="com.springinaction.knights.Minstrel" /> <!--<co id="co_minstrel_bean"/>-->

  <aop:config>
    <aop:aspect ref="minstrel">

      <aop:pointcut id="embark"
          expression="execution(* *.embarkOnQuest(..))" /> <!--<co id="co_define_pointcut"/>-->

      <aop:before pointcut-ref="embark"
                  method="singBeforeQuest"/>    <!--<co id="co_minstrel_before_advice"/>-->

      <aop:after pointcut-ref="embark"
                 method="singAfterQuest"/>     <!--<co id="co_minstrel_after_advice"/>-->

    </aop:aspect>
  </aop:config>
</beans>

Testing this looks exactly like in #3 Testing BraveKnight
Exception which is verry long.
sie 20, 2013 3:06:58 PM org.springframework.context.support.AbstractApplicationContext prepareRefresh
INFO: Refreshing org.springframework.context.support.ClassPathXmlApplicationContext@14d5bc9: startup date [Tue Aug 20 15:06:58 CEST 2013]; root of context hierarchy
sie 20, 2013 3:06:58 PM org.springframework.beans.factory.xml.XmlBeanDefinitionReader loadBeanDefinitions
INFO: Loading XML bean definitions from class path resource [knights-aop.xml]
sie 20, 2013 3:06:58 PM org.springframework.beans.factory.support.DefaultListableBeanFactory preInstantiateSingletons
INFO: Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@46aa61: defining beans [knight,quest,minstrel,org.springframework.aop.config.internalAutoProxyCreator,org.springframework.aop.aspectj.AspectJPointcutAdvisor#0,org.springframework.aop.aspectj.AspectJPointcutAdvisor#1,embark]; root of factory hierarchy
sie 20, 2013 3:06:58 PM org.springframework.beans.factory.support.DefaultSingletonBeanRegistry destroySingletons
INFO: Destroying singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@46aa61: defining beans [knight,quest,minstrel,org.springframework.aop.config.internalAutoProxyCreator,org.springframework.aop.aspectj.AspectJPointcutAdvisor#0,org.springframework.aop.aspectj.AspectJPointcutAdvisor#1,embark]; root of factory hierarchy
Exception in thread "main" org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'knight' defined in class path resource [knights-aop.xml]: BeanPostProcessor before instantiation of bean failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.aop.aspectj.AspectJPointcutAdvisor#0': Cannot create inner bean '(inner bean)' of type [org.springframework.aop.aspectj.AspectJMethodBeforeAdvice] while setting constructor argument; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name '(inner bean)': Cannot resolve reference to bean 'embark' while setting constructor argument; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'embark': Instantiation of bean failed; nested exception is java.lang.NoClassDefFoundError: org/aspectj/weaver/BCException
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:454)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:295)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:223)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:292)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
    at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:626)
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:932)
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:479)
    at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:139)
    at org.springframework.context.support.ClassPathXmlApplicationContext.<init>(ClassPathXmlApplicationContext.java:83)
    at com.springinaction.knights.KnightAopMain.main(KnightAopMain.java:10)
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.aop.aspectj.AspectJPointcutAdvisor#0': Cannot create inner bean '(inner bean)' of type [org.springframework.aop.aspectj.AspectJMethodBeforeAdvice] while setting constructor argument; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name '(inner bean)': Cannot resolve reference to bean 'embark' while setting constructor argument; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'embark': Instantiation of bean failed; nested exception is java.lang.NoClassDefFoundError: org/aspectj/weaver/BCException
    at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveInnerBean(BeanDefinitionValueResolver.java:282)
    at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:126)
    at org.springframework.beans.factory.support.ConstructorResolver.resolveConstructorArguments(ConstructorResolver.java:629)
    at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:148)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1045)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:949)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:487)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:458)
    at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:295)
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:223)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:292)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:198)
    at org.springframework.aop.framework.autoproxy.BeanFactoryAdvisorRetrievalHelper.findAdvisorBeans(BeanFactoryAdvisorRetrievalHelper.java:86)
    at org.springframework.aop.framework.autoproxy.AbstractAdvisorAutoProxyCreator.findCandidateAdvisors(AbstractAdvisorAutoProxyCreator.java:101)
    at org.springframework.aop.aspectj.autoproxy.AspectJAwareAdvisorAutoProxyCreator.shouldSkip(AspectJAwareAdvisorAutoProxyCreator.java:103)
    at org.springframework.aop.framework.autoproxy.AbstractAutoProxyCreator.postProcessBeforeInstantiation(AbstractAutoProxyCreator.java:276)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyBeanPostProcessorsBeforeInstantiation(AbstractAutowireCapableBeanFactory.java:890)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.resolveBeforeInstantiation(AbstractAutowireCapableBeanFactory.java:862)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:448)
    ... 10 more
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name '(inner bean)': Cannot resolve reference to bean 'embark' while setting constructor argument; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'embark': Instantiation of bean failed; nested exception is java.lang.NoClassDefFoundError: org/aspectj/weaver/BCException
    at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:329)
    at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveValueIfNecessary(BeanDefinitionValueResolver.java:107)
    at org.springframework.beans.factory.support.ConstructorResolver.resolveConstructorArguments(ConstructorResolver.java:615)
    at org.springframework.beans.factory.support.ConstructorResolver.autowireConstructor(ConstructorResolver.java:148)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.autowireConstructor(AbstractAutowireCapableBeanFactory.java:1045)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:949)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:487)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:458)
    at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveInnerBean(BeanDefinitionValueResolver.java:271)
    ... 28 more
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'embark': Instantiation of bean failed; nested exception is java.lang.NoClassDefFoundError: org/aspectj/weaver/BCException
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:1007)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:953)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:487)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:458)
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:314)
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:194)
    at org.springframework.beans.factory.support.BeanDefinitionValueResolver.resolveReference(BeanDefinitionValueResolver.java:323)
    ... 36 more
Caused by: java.lang.NoClassDefFoundError: org/aspectj/weaver/BCException
    at java.lang.Class.getDeclaredConstructors0(Native Method)
    at java.lang.Class.privateGetDeclaredConstructors(Unknown Source)
    at java.lang.Class.getConstructor0(Unknown Source)
    at java.lang.Class.getDeclaredConstructor(Unknown Source)
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:78)
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateBean(AbstractAutowireCapableBeanFactory.java:1000)
    ... 42 more
Caused by: java.lang.ClassNotFoundException: org.aspectj.weaver.BCException
    at java.net.URLClassLoader$1.run(Unknown Source)
    at java.net.URLClassLoader$1.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    at sun.misc.Launcher$AppClassLoader.loadClass(Unknown Source)
    at java.lang.ClassLoader.loadClass(Unknown Source)
    ... 48 more

A: Download AspectJ and add aspectjrt.jar & aspectjweaver.jar to your classpath. Spring's aop config with the aop namespace is based on AspectJ, which is no more shipped bundled with org.springframework.aop jar.
Following is maven dependency in case its a maven based project
<dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aop</artifactId>
            <version>${org.springframework.version}</version>
</dependency>
<dependency>
        <groupId>org.aspectj</groupId>
        <artifactId>aspectjweaver</artifactId>
        <version>1.6.1</version>
</dependency>


text:
Q: REST URL Design for One to Many and Many to Many Relationships Your backend has two Models:
One Company to Many Employees.

You want to accomplish the following:
Get all Companies
Get a Company by ID
Get all Employees for a Company
Get all Employees
Get a Employee by ID

What is the best practice for handling the REST URLs when your models have 1:M relationships? This is what I have thought of so far:
/companies/
/companies/<company_id>/
/companies/<company_id>/employees/
/employees/
/employees/id/<employee_id>/

Now let's pretend One Company has Many Models. What is the best name to use for "Adding an employee to a Company" ? I can think of several alternatives:
Using GET:
/companies/<company_id>/add-employee/<employee_id>/
/employees/<employee_id/add-company/<company_id>/

Using POST:
/companies/add-employee/
/employees/add-company/

A: The URIs look fine to me, except maybe the last one, that does not need an additional "id" in the path. Also, I prefer singular forms of words, but that is just me perhaps:
/company/
/company/<company_id>/
/company/<company_id>/employee/
/employee/
/employee/<employee_id>/

The URIs do not matter that much actually, and can be changed at any point later in time when done properly. That is, all the URIs are linked to, instead of hardcoded into the client.
As far as adding an employee, I would perhaps use the same URIs defined above, and the PUT method:
PUT /employee/123

With some representation of an employee. I would prefer the PUT because it is idempotent. This means, if the operation seems to fail (timeout, network error occurs, whatever) the operation can be repeated without checking whether the previous one "really" failed on the server or not. The PUT requires some additional work on the server side, and some additional work to properly link to (such as forms), but offers a more robust design.
As an alternative you can use
POST /employee

With the employee representation as body. This does not offer any guarantees, but it is easier to implement.
Do not use GET to add an employee (or anything for that matter). This would go against the HTTP Specification for the GET method, which states that it should be a pure information retrieval method.


text:
Q: python netCDF4 intermittent error either ok, invalid arguement or no such file I have been successfully loading netCDF files in python for a couple of days now and today out of the blue my script is starting to fail.
I use a simple function to load netCDF variables as numpy arrays from a list of netCDF's in one of four subfolders. All four paths are the same apart from the subfolder name.
When I run an os.path.exists I get true but on some the netCDF4.Dataset(filename, 'r') will not work but on others it does as below only difference is filenames end in 2.nc and 3.nc

os.path.exists(r'//WRON/working/SAF/LUTO/data/GLUCM/climate/climate_time_series_netcdf/evap/all/19830102.nc')
True
fi=netCDF4.Dataset(r'//WRON/working/SAF/LUTO/data/GLUCM/climate/climate_time_series_netcdf/evap/all/19830102.nc', 'r')
error

Traceback (most recent call last):
  File "", line 1, in
  File "netCDF4.pyx", line 1328, in netCDF4.Dataset.init (netCDF4.c:6336)
RuntimeError: Invalid argument

os.path.exists(r'//WRON/working/SAF/LUTO/data/GLUCM/climate/climate_time_series_netcdf/evap/all/19830103.nc')
True
fi=netCDF4.Dataset(r'//WRON/working/SAF/LUTO/data/GLUCM/climate/climate_time_series_netcdf/evap/all/19830103.nc', 'r')
      `

Could I have corrupted netCDF files somehow, this was working this morning.


text:
Q: Wordpress appends RSS item with unwanted content Wordpress is adding a message to the end of each item in RSS feed that reads
"The post [post_name] appeared first on ]site_name]."
I want this message to go away. I browsed through a my feed.php files, but couldn't find the code that assembles this message. Where should I look for this?

A: This text is probably being added to your feed by the "WordPress SEO by Yoast" plugin.  In your admin panel menu, go to SEO, RSS.  Delete everything in the box labeled "Content to put after each post."

A: This text is probably being added by the Yoast SEO plugin. To remove it:

*

*Navigate to SEO > Advanced > RSS.

*Remove the text in Content to put after each post in the feed:

*Click Save changes.


text: Q: Analyzing quantitative data in WEKA Hi My dataset contains only quantitative data(numerical). It doesn't have any class attributes. The dataset contains with sales of different years. I need to analyze the data in different ways. Can I use WEKA for this analysis? I tried to use WEKA tool. But it seemed I cannot proceed with WKA unless I have class variables for the dataset. Please kindly give me a hint.


text:
Q: ScalaCheck can not cast boolean to Prop instance I have the following property:
import org.scalacheck.Prop.propBoolean

def elementsAreReversed(list: List[Int], reversed: List[Int]): Boolean =
  if (list.isEmpty) true else {
    val lastIdx = list.size - 1
    list.zipWithIndex.forall { case (element, index) =>
      element == reversed(lastIdx - index)
    }
  }

val propReversed = Prop.forAll { list: List[Int] =>
  val reversed = list.reverse

  if (list.isEmpty)
    list == reversed
  else {
    val hasSameSize    = reversed.size == list.size
    val hasAllElements = list.forall(reversed.contains)

    // It works until  I add a label here:
    hasSameSize && hasAllElements && elementsAreReversed(list, reversed)
  }

If a add a label it breaks:
    hasSameSize :| " a label which doesn't let the code compile" &&
    hasAllElements &&
    elementsAreReversed(list, reversed)

Compiler gives me the following:
Error:(47, 36) No implicit view available from Any => org.scalacheck.Prop.
val propReversed = Prop.forAll { list: List[Int] =>
Error:(47, 36) not enough arguments for method forAll:
(implicit p: Any => org.scalacheck.Prop, implicit a1: org.scalacheck.Arbitrary[List[Int]], implicit s1: org.scalacheck.Shrink[List[Int]], implicit pp1: List[Int] =>
org.scalacheck.util.Pretty) org.scalacheck.Prop. Unspecified value parameters
p, a1, s1...
val propReversed = Prop.forAll { list: List[Int] =>
I'm using ScalaCheck version 1.13.4

A: The problem is that you've got an if expression with the true side having type Boolean and the false side having type Prop. The compiler will apply the propBoolean implicit conversion to a boolean value in cases where it expects a Prop, but a conditional like this isn't one of those places—instead the compiler simply takes the least upper bound of Boolean and Prop and makes that the return type. (Maybe a little more surprisingly, this is true even if the Prop comes first and the Boolean second.)
There are several ways you could make this work, but the simplest is just to apply the conversion explicitly:
val propReversed = Prop.forAll { list: List[Int] =>
  val reversed = list.reverse

  if (list.isEmpty) Prop.propBoolean(list == reversed) else {
    val hasSameSize    = reversed.size == list.size
    val hasAllElements = list.forall(reversed.contains)

    hasSameSize :| " a label which doesn't let the code compile" &&
      hasAllElements && elementsAreReversed(list, reversed)
  }
}

For me this is just another example of the frustrations of fancy implicit conversion-supported DSLs. I like ScalaCheck and use it every day, but I don't really see the value in doing backflips to support slightly more concise usage when the tricks are just going to break down once they start interacting with other corners of Scala's (enormously complicated) syntax.


text:
Q: android: one click listener on many imageviews in layout I have the following scenario:

In a layout, I have imageviews aligned horizontally and vertically as shown in image.
First, which layout should be used for this purpose? RelativeLayout or FrameLayout? ListView inside the layout?
Also, instead of writing setOnClickListener for every imageview, how can I write just one click listener to get the clicked imageview?

A: A GridView is perfect for this. For more information on GridView, look here.
As for your onClickListener question: there is no easy way to do this, but what you can do is something like this:

*

*Have an array containing every ImageView id like so:
public static final int[] IMAGE_VIEWS = {R.id.imageView1, R.id.imageView2, R.id.imageView3 /*etc*/}; //Make sure to list from the first imageview to the last image view in correct order

*Define an onClickListener
private View.OnClickListener imageViewListener = new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        for (int i = 0; i < IMAGE_VIEWS.length; i++) {
            if (v.getId() == IMAGE_VIEWS[i]) {
                doSomethingWithImageViewClick(i); //if ImageView 4 was clicked, variable 'i' will be 3 (because arrays start at index = 0).
            }
        }
    }
}

*Set the onClickListeners for all your imageViews:
final ImageView view1 = (ImageView) view.findViewById(R.id.imageView1);
view1.setOnClickListener(imageViewListener);
//etc

A: GridView can achieve the effect. I think you can look at this Grid View.

A: Use 'GridView' in the layout and use 'setOnItemClickListener' to handle click events,
You can find more details in below link
 GridView.


text:
Q: Cancelling other running tasks queued on Prism EventAggregator I have a WPF application using Prism. When a user selects rows from the datagrid, it fires a SelectionUpdated event on the EventAggregator.
One of my other ViewModels is listening to that event and when it receives it, kicks off an asynchronous process to retrieve some remote results based on the selection. This can take up to 10 seconds. When it gets the results back, it updates the ViewModel with the results which are then bound to a results grid.
The problem I have is if user makes a second selection while the first is running, ie selects rows 2-4 then changes his mind and selects rows 2-8 instead, it seems the EventAggregator is a single thread pipe and the first received event must complete fully, including the async bit, before the second will begin.
I effectively want a way to cancel the first request if a second one is received. My code-behind for the view is where the selection event is captured, and this code-behind then publishes the SelectionUpdated event. So if the EventAggregator is single thread only, then I need some way in the code-behind to tell my viewmodel that is currently processing the SelectionUpdated event, to cancel and quit out, freeing the EventAggregator subcribe() pipe up to process the second event immediately.
Hope this makes sense. My code behind.
Grid.MouseLeftButtonUp += (sender, args) =>
{
    var selectedEntries = Grid.SelectedCells.Select(c => c.Item as EntryViewModel).Where(c => c != null).Distinct().ToArray();
    _eventAggregator.GetEvent<SelectionUpdatedEvent>().Publish(selectedEntries);
};

And the listening ViewModel (relevant lines only)
_eventAggregator.GetEvent<SelectionUpdatedEvent>().Subscribe(async x => await UpdateSelectedEntries(x));

private async Task UpdateSelectedEntries(EntryViewModel[] selectedEntries)
{
    _selectedEntries = selectedEntries;
    RaisePropertyChanged(nameof(SelectedText));
    RaisePropertyChanged(nameof(SelectedBreakdown));

    await RecalculateAll();
}

private async Task RecalculateAll()
{
    try
    {
        var entryIds = _selectedEntries.SelectMany(s => s.StatusInfo.ValidEntryIds).OrderBy(t => t).ToArray();
        ProcessingCount++;
        var results = await _resultsService.GetResults(_resultType, entryIds);
...
}

It is the final call to GetResults that I want to interrupt if my code-behind detects a new selection has been made, but I cannot figure out how to do this.
Any thoughts?

A: By default, you subscribe on the publisher thread. You want to subscribe on a threadpool thread so that your subscribtions can run in parallel.
_eventAggregator.GetEvent<SelectionUpdatedEvent>().Subscribe(async x => await UpdateSelectedEntries(x), ThreadOption.BackgroundThread);

Your subscriber will then cancel the CancellationToken used by the previous task to, replace it with his own (this part obviously has to be synchronized).


text: Q: css property nested in previous one - sass Does anyone have problem with Sass? I think I did something with Atom and the css line input is nested in the previous one. See image below. I tried return and shift+return and it just not seems to work


text:
Q: How to get right values from array thats values are in other table I have the list of records saved as array in database like below:
---
- '9'
- '10'
- '11'

These are saved in option_ids column in table.
I have another table in which they all are present like below.

What I need to do is to print the values text like speak well if its id is present in options_ids column. So, what will happen is, if options_ids contains 9,10,12 etc so we will print data from other rows table like speak well, read well, listen well.

A: Assuming your "other table" is class OtherTable and assuming your fourth column is called text then you'd want to do
options_ids.map{|option| OtherTable.find(option).text}.join(', ')

A: When using rails you should take advantage of Active Record Associations.
I guess that a user(?) can choose different options from that second table.
The association would be a has_and_belongs_to_many-relation.
A good read is this section in the rails guide: http://guides.rubyonrails.org/association_basics.html#the-has-and-belongs-to-many-association
Basically you set up a join table between users and options and tell the two models that they have a has_and_belongs_to_many-relation with each other.
Then when you fetch a user you can simple call user.options and it shows the options that are related to that user object.


text:
Q: Using a variable in the form name of DOM This appears to be something that's easy when you know it but hard to figure out.  The code should be pretty self-explanatory:
<html>
<head>
<body>

<form id='updatenotes_1139' action=index.php method=POST>
<input size=20 type='input' id='b_user' value="Default value">
<input type=submit>
</form>

<script>
var entered = 1139;
var formName = "updatenotes_"+entered;
//alert(formName);  // Displays "updatenotes_1139"
document.forms[formName]b_user.value = "Hello!";
</script>
</body>
</html>

The basic idea is to be able to tell JavaScript what form to edit via a variable.  I can't just use GetElementByID because in the full application there are many forms with the same name of input (e.g., 15 forms that each have a "b_user" input).  This is mainly so that the browser's autocomplete will function across all of them (it's just a script for me, so it doesn't have to be pretty so long as it works).
For what it's worth, the alert there works just fine.  I just have no idea how to construct the next line, as all the examples I could find online were about using a variable on the input id and not the form id.

A: document.forms[formName].b_user.value = "Hello!";
                     // ^ This is how you'd access it.

jsFiddle.

A: As already mentioned, IDs have to be unique. However, names don't have to be. Change your HTML to:
<input size=20 type='input' name='b_user' value="Default value">

(or keep the id attribute, but you need name)
Then you can do:
var form = document.getElementById(formName);
var b_user = form.getElementsByName('b_user')[0];
b_user.value = 'Hello';

A: With an id I first tried using this code to access the form via its id
document[ "formID" ]; // returned undefined

However, when I used the following code it returned the correct form
window[ "formID" ]; // returned form element

Not really sure whether this is best practice. Anyhow, here is the code I ended up with.
var entered = 1139;
var formID = "updatenotes_" + entered;
window[formID].b_user.value = "Hello!";

Fiddle here

A: DO you want something like this
<html>
<head>
<body>

<form id='updatenotes_1139' action=index.php method=POST>
<input size=20 type='input' id='b_user' value="Default value">
<input type=submit>
</form>

<script>
var entered = 1139;
var formName = "updatenotes_"+entered;
//alert(formName);  // Displays "updatenotes_1139"
var myForm = document.forms[formName];
  console.log(myForm);
  myForm.getElementsByTagName('input')[0].value = "Hello!";
</script>
</body>
</html>

Working BIN


text:
Q: Parameterize a JDBC SQL Query in SOAP UI from a Custom Property To proceed with a Database validation, I am having a need of comparing a record in the DB along with a data which is dynamically generated in the previous REST response, using SoapUI.
I have already captured the property value using a Property Transfer step and stored the required value in a custom property in Test-Case successfully i.e., using property expansion, say ${TestCase#customerId}
My intention is to use that particular value stored in the custom properties to query the result I am expecting, in the JDBC Request test step.
The query which I have drafted with the parameter is as below :
Select *
From ABC.SEC_CUST
Where ABC.SEC_CUST.CUSTOMER_ID =  ${TestCase#customerId}

The response I receive after executing is as below.

Error getting response; java.sql.SQLSyntaxErrorException : ORA-00911: Invalid character.

But, when I run the query without the parameterized value it executes perfectly. Where, I tend the conclusion as there is a syntax issue in the way I have mentioned the parameter in the query.
But, I am unable to find the correct way to mention the parameter in the query in SoapUI.
Can anyone with experience in SoapUI, please assist me on this?

A: That is not working because of the use of property expansion which is only known to SoapUI, but not for the SQL query.
In order to get it work for the same, you need to define the variables in the top for all the parameters that are going to be used in the sql query.
Here the screen shot which explains how to use the same:

A: You forgot a '#'
Select *
From ABC.SEC_CUST
Where ABC.SEC_CUST.CUSTOMER_ID =  ${#TestCase#customerId}

A: Try this.
Select * From ABC.SEC_CUST
Where ABC.SEC_CUST.CUSTOMER_ID = :customerId


text:
Q: Unable to SSH a script of bash commands via expect I'm attempting to push a single set of commands to multiple remote hosts. I can use the following on an individual basis:
ssh user@remoteHost "bash -s" <./commands.sh
I can put this into a loop, but then I'm stuck typing in the password n number of times. Disabling the password prompts in the SSH config files is not an option for me.
I've attempted to use expect within a loop, but I'm unable to get it working.
#!/bin/bash
HOSTS="host1 host2"
read -sp "Password: " PASSWORD
for HOST in $HOSTS; do
    expect -c "
    spawn /usr/bin/ssh user@$HOST "bash -s" <./commands.sh
    expect_before {
        "*yes/no*" {send "yes"\r;exp_continue}}
    expect {
        "*Password*" {send $PASSWORD\r;interact}}
    exit"
done

I get the following error:
spawn /usr/bin/ssh root@host1 bash
expect: invalid option -- 's'
usage: expect [-div] [-c cmds] [[-f] cmdfile] [args]
spawn /usr/bin/ssh root@host2 bash
expect: invalid option -- 's'
usage: expect [-div] [-c cmds] [[-f] cmdfile] [args]

Any ideas? It appears as though expect is trying to interpret the bash commands. I'm unsure how to stop this.

A: Solution:
replace
spawn /usr/bin/ssh user@$HOST "bash -s" <./commands.sh
with
spawn sh -c {ssh root@$HOST 'bash -ls' < /tmp/commands.sh}
Final Code:
#!/bin/bash

HOSTS="host1 host2"

read -sp "Password: " PASSWORD

for HOST in $HOSTS; do
        expect -c "
                spawn sh -c {ssh root@$HOST 'bash -ls' < /tmp/commands.sh}
                expect_before {
                "*yes/no*" {send "yes"\r;exp_continue}}
                expect {
                "*assword*" {send $PASSWORD\r;interact}}
                exit"
done

A: I'd suggest this:
#!/bin/bash
hosts=(host1 host2)
read -sp "Password: " password
for host in "${hosts[@]}"; do
    env h="$host" p="$password" expect <<'END_EXPECT'
        spawn sh -c "/usr/bin/ssh user@$env(h) 'bash -s' <./commands.sh"
        expect {
            "*yes/no*"   {send "yes\r"; exp_continue}
            "*Password*" {send "$env(p)\r"}
        }
        interact
END_EXPECT
done

notes

*

*uses lower case variable names: leave upper case varnames for the shell's use

*uses a quoted heredoc to contain the expect code

*

*that lets you use single and double quotes within expect without having to worry about quoting hell in the shell

*uses env to pass shell variables to expect via the environment

*simplifies your expect statement

The danger with using
expect -c " ...; expect "*Password*" ..."

is that the inner double quotes get matched with the outer quotes, and are removed by the shell. That leaves *Password* as a bare glob that the shell can expand based on the files in your current directory and the shell settings. For example, create a file named "The Password" (with a space) and you'll get an
error.


text:
Q: Line number of SyntaxError in Node.js I have some code that uses vm module and runInNewContext function and executes dynamically generated JavaScript code. Basically a safer option of eval.
The code (variable code) can possibly contain syntax errors, so I would like to catch them and print some useful information.
try {
    vm.runInNewContext(code, sandbox, filename);
}
catch (e) {
    if (e instanceof SyntaxError) { // always false
        console.log(e.toString()); // "SyntaxError: Unexpected token ||" for example
        console.log(e.line); // how to get the line number?
    }
}

I'd like to print the number of the line with the syntax error, but I have two problems:

*

*I don't know how to recognize whether the exception is SyntaxError or something else. instaceof doesn't work (update - I can use e.name === "SyntaxError").

*Even if I was able to recognize it, how could I get the line number? Is it possible?

Thanks in advance.
Update: I can get some information from e.stack - however, the topmost call in the stack trace is runInNewContext (with its line number), but I still can't find the line number inside code, which caused the exception (SyntaxError).

A: use a try/catch
store the stack in a global variable
log the sandbox
var util = require('util');
var vm = require('vm');
var sandbox = {e:null};
var src = 'try{count += 1;}catch(err) {e=err.stack}';

vm.runInNewContext(src , sandbox, 'myfile.vm');
console.log(util.inspect(sandbox));

this will log:

{ e: 'ReferenceError: count is not defined\n    at myfile.vm:1:13\n
  ...

now you can see that the error occurs at line 1, character 13 of myfile.vm
this will still require you to place some try/cathc blocks at various places
but at least you can get feedback now
EDIT:
Adding a method to detect Syntax errors from within your running code
var acorn = require('acorn');
var src = "try{\n"+
    "   {" +
    "       count += 1;\n"+
    "   }catch(err) {\n" +
    "       e=err.stack\n" +
    "}";

var result = acorn.parse(src);

doing this will result in a thrown Exception with
"SyntaxError: Unexpected token (3:4)"
eg. line 3, character 4 is the unexpected token, (the extra { that shouldnt be there)

A: 1) Use if (e.name === "SyntaxError").
2) All data associated with the error is kept in e.stack.

A: Although a bit (very) old, you can use the stackedy module, which can help you manipulate stack traces. It isn't the perfect solution though, as the line number displayed is the line number inside the function call, and not the line number in the source file.
In particular, look at the simple example:
index.js
var stackedy = require('stackedy');
var fs = require('fs');

var src = fs.readFileSync(__dirname + '/src.js');
var stack = stackedy(src, { filename : 'stax.js' }).run();

stack.on('error', function (err, c) {
    stack.stop();
    console.log('Error: ' + err);

    var cur = c.current;
    console.log('  in ' + cur.filename + ' at line ' + cur.start.line);

    c.stack.forEach(function (s) {
        console.log('  in ' + s.filename + ', '
            + s.functionName + '() at line ' + s.start.line
        );
    });
});

src.js
function f () { g() }
function g () { h() }
function h () { throw new SyntaxError('woops') }

f();

Output:
~/tmp ❯❯❯ node index.js
Error: SyntaxError: woops
  in stax.js at line 2
  in stax.js, h() at line 1
  in stax.js, g() at line 0
  in stax.js, f() at line 4

As noted in the comments, you can use err.name === 'SyntaxError' to check for the error type.

A: For *nix:
if (err) console.log(err.stack.split('\n')[1]);
It will log second line of stacktrace, the point where the error occured.
Windows or mac can require other split symbol (depends on system line endings)