text:
Q: Split single line into multiple lines using delimiter as ; I have a requirement of breaking single line output into multiple lines using ; as the delimiter. The input is generated by a shell script and looks like this:
REVOKE ALL ON XXXXXX_ABC_AAA FROM PUBLIC ; REVOKE ALL ON XBJE_XXXXX_ABC_AAA FROM PUBLIC ; REVOKE ALL ON XBJE_XXADTXXX_ABC_AAA FROM PUBLIC ; REVOKE ALL ON XBJE_XXVXXX_ABECC_AAA FROM PUBLIC ;

I need to split this to multiple lines like this:
REVOKE ALL ON XXXXXX_ABC_AAA FROM PUBLIC ;
REVOKE ALL ON XBJE_XXXXX_ABC_AAA FROM PUBLIC ;
REVOKE ALL ON XBJE_XXADTXXX_ABC_AAA FROM PUBLIC ;
REVOKE ALL ON XBJE_XXVXXX_ABECC_AAA FROM PUBLIC ;

How can I do this?

A: You can simply use sed to convert ; to ;\n:
$ line="REVOKE ALL ON XXXXXX_ABC_AAA FROM PUBLIC ; REVOKE ALL ON XBJE_XXXXX_ABC_AAA FROM PUBLIC ; REVOKE ALL ON XBJE_XXADTXXX_ABC_AAA FROM PUBLIC ; REVOKE ALL ON XBJE_XXVXXX_ABECC_AAA FROM PUBLIC ;"

$ sed 's/; */;\n/g' <<< "$line"
REVOKE ALL ON XXXXXX_ABC_AAA FROM PUBLIC ;
REVOKE ALL ON XBJE_XXXXX_ABC_AAA FROM PUBLIC ;
REVOKE ALL ON XBJE_XXADTXXX_ABC_AAA FROM PUBLIC ;
REVOKE ALL ON XBJE_XXVXXX_ABECC_AAA FROM PUBLIC ;

So if your script is called foo.sh, you would do:
foo.sh | sed 's/;/;\n/g'

A: Using tr and standard sed:
$ tr -s ';' '\n' <file | sed -e 's/^[[:blank:]]*//' -e 's/$/;/'
REVOKE ALL ON XXXXXX_ABC_AAA FROM PUBLIC ;
REVOKE ALL ON XBJE_XXXXX_ABC_AAA FROM PUBLIC ;
REVOKE ALL ON XBJE_XXADTXXX_ABC_AAA FROM PUBLIC ;
REVOKE ALL ON XBJE_XXVXXX_ABECC_AAA FROM PUBLIC ;

This will first replace all semi-colons with newlines, then trims any blanks off from the start of each generated line and adds a semi-colon to the end.
If your input is stored in a bash or zsh shell variable, use
printf '%s;\n' "${var//;/;$'\n'}" | sed 's/^[[:blank:]]*//'

This will first replace all ; with the same character, followed by a literal newline. It then trims the spaces off from the start of each generated line.


text:
Q: Is it possible to renew the Spotify access token automatically? I have searched a lot but I can't find the right answer.
I'm working with the Spotify Web API. The access token is only valid for 1 hour. I want to know if it's possible to renew the Spotify access token automatically? And if the answer is yes, how can I do that?
Thanks

A: Better solution what was find is: Login use Authorization Code Flow
you will receive access_token and refresh_token - and when access_token expired  you can get new use refresh_token as describe in '7. Requesting access token from refresh token'

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to refresh a page (after x seconds) opened in an iframe? I have a page opened in iFrame. I want to refresh the page after x seconds (x could be any digit I get greater than 5). How I can do this?
here is my code;

I have checked there are some questions on StackOverflow where guys reloaded the page by updating the scope. I do not want to update the scope as my URL value in scope variable remains the same. Is there anything in JavaScript or AngularJs which can help to refresh the page in an iframe.
Update-1
The solution suggested by @sarvon ks works for my own pages which are hosted within my project but it complains when I try to refresh any external/ third-party page. In my page, I have a loop over an iFrame which opens the mutiple page. Most of them are external pages. For the external pages, I get Uncaught SecurityError exception.
-- Uncaught SecurityError: Blocked a frame with origin "http://localhost:63342" from accessing a cross-origin frame.

This error is already well discussed in an existing question. Is there any other workaround to refresh page opened in iFrame?

A: check this code it will work

    var duration = 100;
    function reloadIframe() {
          var iframeDome = document.getElementsByTagName("iframe");
            iframeDome[0].contentWindow.location.reload();
    }

    setInterval(reloadIframe,duration);


text:
Q: Is there a guarantee that nonzero/nontrivial vector space will have a subspace that is not the zero vector space or itself? I know that the trivial vector space and the vector space itself are subspaces of any vector space. But, what I do not understand is that, given that the vector space is nonzero, how do we know that there is a subspace that is not the trivial vector space or itself?

A: You don't know that. If you see $\Bbb R$ as a real vector space, then its only vector subspaces are $\Bbb R$ and $\{0\}$. This works over any field.
More generally, if $V$ is a vector space over some field $k$, then the assertion "there is a subspace of $V$ that is not the trivial vector space or $V$ itself" is equivalent to the assertion that $\dim V>1$.


text:
Q: Can someone help me fix this program I have to create the program so that I can input 3 letters plus a year like "jan1999" and display the calendar.
The program must:

*

*Prompt the user for a specific month with a meaningful message.

*If the input value is a valid date (i.e. 3 characters designating the desired month (i.e. JAN, FEB, ..., in any combination of lower and
  upper case letters, followed by a space and an integer between 1900
  and 2099), then the calendar for the given date must be displayed

*(or 2BIS) If the input value is not a valid date, the user must be informed that date was not acceptable, and then be prompted again for
  another date. If more than three consecutive erroneous dates are
  given, the program must be terminated with an appropriate error
  message.

package assignment.pkg2;

import java.util.Scanner;

public class Assignment2 {
    public static int getMonthNumber(String s) {
        if (s.equalsIgnoreCase("jan")) {
            return 1;
        }
        if (s.equalsIgnoreCase("feb")) {
            return 2;
        }
        if (s.equalsIgnoreCase("mar")) {
            return 3;
        }
        if (s.equalsIgnoreCase("apr")) {
            return 4;
        }
        if (s.equalsIgnoreCase("may")) {
            return 5;
        }
        if (s.equalsIgnoreCase("jun")) {
            return 6;
        }
        if (s.equalsIgnoreCase("jul")) {
            return 7;
        }
        if (s.equalsIgnoreCase("aug")) {
            return 8;
        }
        if (s.equalsIgnoreCase("sep")) {
            return 9;
        }
        if (s.equalsIgnoreCase("oct")) {
            return 10;
        }
        if (s.equalsIgnoreCase("nov")) {
            return 11;
        }
        if (s.equalsIgnoreCase("dec")) {
            return 12;
        } else {
            System.out.println("Not valid month!");
        }
        return 0;
    }

    public static boolean isLeapYear(int year) {
        int month = 0;
        int s = getDaysIn(month, year);
        return year % 4 == 0 && (year % 100 != 0) || (year % 400 == 0);
    }

    public static int getDaysIn(int month, int year) {
        switch (month) {
            case 1:
                return 31;
            case 2:
                if (isLeapYear(month)) {
                    return 29;
                } else {
                    return 28;
                }
            case 3:
                return 31;
            case 4:
                return 30;
            case 5:
                return 31;
            case 6:
                return 30;
            case 7:
                return 31;
            case 8:
                return 31;
            case 9:
                return 30;
            case 10:
                return 31;
            case 11:
                return 30;
            case 12:
                return 31;
            default:
                return -1;
        }
    }

    public static String getMonthName(int month) {
        switch (month) {
            case 1:
                return "January";
            case 2:
                return "February";
            case 3:
                return "March";
            case 4:
                return "April";
            case 5:
                return "May";
            case 6:
                return "June";
            case 7:
                return "July";
            case 8:
                return "August";
            case 9:
                return "September";
            case 10:
                return "October";
            case 11:
                return "November";
            case 12:
                return "December";
            default:
                return "Invalid month.";
        }
    }

    public static int getStartDay(int month, int year) {
        int days = 0;
        for (int i = 1900; i < year; i++) {
            days = days + 365;
            if (isLeapYear(i)) {
                days = days + 1;
            }
        }
        for (int i = 1; i < month; i++) {
            days = days + getDaysIn(month, year);
        }
        int startday = (days + 1) % 7 + 1;
        return startday;
    }

    public static void displayCalendar(int month, int year) {
        String monthName = getMonthName(month);
        int startDay = getStartDay(month, year);
        int monthDays = getDaysIn(month, year);

        System.out.println("   Sun   Mon   Tue   Wed   Thu   Fri   Sat");
        int weekDay = startDay - 1;
        for (int i = 1; i <= startDay; i = i + 1) {
            System.out.print("    ");
        }
        for (int x = 1; x <= monthDays; x++) {
            weekDay = weekDay + 1;
            if (weekDay > 7) {
                System.out.println();
                weekDay = 1;
            }
            System.out.format("   %3d", x);
        }
        if (weekDay > 7) {
            System.out.println();
        }
    }

    public static void main(String[] args) {
        Scanner c = new Scanner(System.in);
        System.out.print("Give the first three letters of a month and enter the year: ");
        String month, year;
        month = c.next();
        year = c.next();
        int yearno = Integer.parseInt(year);
        int monthno = getMonthNumber(month);
        displayCalendar(monthno, yearno);
        System.out.println();
        System.out.println("Do you want to continue? y/n ");
    }
}

A: Most of the code is easy, the trick is in validating the input as a valid date in the specified format. You can do that with the YearMonth class. Then you can create a Calendar class from that.
If you're using Java 8, try this:
    String myInputString = null;

    try
    {
       BufferedReader bufferRead = new BufferedReader(new InputStreamReader(System.in));
       myInputString = bufferRead.readLine();
    }
    catch(Exception e)
    {
        System.out.print(e);
    }

    YearMonth myYM = null;
    Calendar calendar = null;

    try
    {
      DateTimeFormatterBuilder fmb = new DateTimeFormatterBuilder();
      fmb.parseCaseInsensitive();
      fmb.append(DateTimeFormatter.ofPattern("MMM yyyy"));

      DateTimeFormatter formatter = fmb.toFormatter();

      myYM = YearMonth.parse(myInputString.trim(), formatter);
      calendar = new GregorianCalendar();
      calendar.clear();
      calendar.set(myYM.getYear(), myYM.getMonthValue(), 1);
    }
    catch(DateTimeParseException e)
    {
        // Invalid date format
        System.out.println(e);
    }
}

A: You can use java Calendar.
public void display(int year, int month){
    Calendar car = Calendar.getInstance();
    car.set(Calendar.YEAR, year);
    car.set(Calendar.MONTH, month);
    car.set(Calendar.DAY_OF_MONTH, 1);
    print(String.format("%" + 23 + "s", new SimpleDateFormat("MMM/yyyy").format(car.getTime()))+"\n");
    print(String.format("%" + 5 + "s", "Su"));
    print(String.format("%" + 5 + "s", "Mo"));
    print(String.format("%" + 5 + "s", "Tu"));
    print(String.format("%" + 5 + "s", "We"));
    print(String.format("%" + 5 + "s", "Th"));
    print(String.format("%" + 5 + "s", "Fr"));
    print(String.format("%" + 6 + "s", "Sa\n"));
    for(int i=1;i<car.get(Calendar.DAY_OF_WEEK);i++){
        print(String.format("%" + 5 + "s", ""));
    }
    for(int i = 1;i<=LastDayOfMonth(month, year);i++){
        if(car.get(Calendar.DAY_OF_WEEK)==7){
            print(String.format("%" + 6 + "s", i+"\n"));
        }else{
            print(String.format("%" + 5 + "s", i));
        }
        car.set(Calendar.DAY_OF_YEAR, car.get(Calendar.DAY_OF_YEAR)+1);
    }
}

public void print(String s){
    System.out.print(s);
}
public boolean isLeapYear(int year){
    return ((year % 4 == 0) && (year % 100 != 0) || (year % 400 == 0));
}
public int LastDayOfMonth(int month, int year){
    if(month == 1){//February
        if(this.isLeapYear(year))return 29;
        else return 28;
    }else if(month==0||month==2||month==4||month==6||month==7||month==9||month==11){
        return 31;
    }else{
        return 30;
    }
}</p>

Note: The first month of the year in the java calendars is JANUARY which is 0.
E.g Calendar of January 2015 display(2015, 0)
If you want to validate the date, you can do it before calling the display function.


text:
Q: How to use FFI:def-call-in in clisp I have figured out how to make use of shared objects created from C code into Clisp using FFI:def-call-out but I am not able to figure out how to use FFI:Def-call-in.
I don't know the process and actually I am confused if clisp will also create some .so file that some C function can use or something else.
Can someone please explain a minimal working example for writing such callback functions ?

A: Example 32.7. Calling Lisp from C:
To sort an array of double-floats using the Lisp function SORT instead of the C library function qsort, one can use the following interface code sort1.c. The main problem is to pass a variable-sized array.
extern void lispsort_begin (int);
void* lispsort_function;
void lispsort_double (int n, double * array) {
  double * sorted_array;
  int i;
  lispsort_begin(n); /* store #'sort2 in lispsort_function */
  sorted_array = ((double * (*) (double *)) lispsort_function) (array);
  for (i = 0; i < n; i++) array[i] = sorted_array[i];
  free(sorted_array);
}

This is accompanied by sort2.lisp:
(DEFPACKAGE "FFI-TEST" (:use "COMMON-LISP" "FFI"))
(IN-PACKAGE "FFI-TEST")
(EVAL-WHEN (compile) (setq FFI:*OUTPUT-C-FUNCTIONS* t))
(FFI:DEF-CALL-IN lispsort_begin (:ARGUMENTS (n int))
  (:RETURN-TYPE nil)
  (:LANGUAGE :stdc))
(FFI:DEF-C-VAR lispsort_function (:type c-pointer))
(defun lispsort_begin (n)
  (setf (cast lispsort_function
              `(c-function
                 (:ARGUMENTS (v (c-ptr (c-array double-float ,n))))
                 (:RETURN-TYPE (c-ptr (c-array double-float ,n))
                               :malloc-free)))
        #'sort2))
(defun sort2 (v)
  (declare (type vector v))
  (sort v #'<))

To test this, use the following test file sorttest.lisp:
(EVAL-WHEN (compile) (setq FFI:*OUTPUT-C-FUNCTIONS* t))
(FFI:DEF-CALL-OUT sort10
  (:name "lispsort_double")
  (:LANGUAGE :stdc)
  (:ARGUMENTS (n int)
              (array (c-ptr (c-array double-float 10)) :in-out)))

Now try
$ clisp-link create sort sort2.c sorttest.c
$ cc -O -c sort1.c
$ cd sort
$ ln -s ../sort1.o sort1.o

Add sort1.o to NEW_LIBS and NEW_FILES in link.sh. Create a file package.lisp containing the form
(MAKE-PACKAGE "FFI-TEST" :use '("COMMON-LISP" "FFI"))

and add package.lisp to TO_PRELOAD in link.sh. Proceed:
$ cd ..
$ base/lisp.run -M base/lispinit.mem -c sort2.lisp sorttest.lisp
$ clisp-link add base base+sort sort
$ base+sort/lisp.run -M base+sort/lispinit.mem -i sort2 sorttest
> (sort10 10 '#(0.501d0 0.528d0 0.615d0 0.550d0 0.711d0
                0.523d0 0.585d0 0.670d0 0.271d0 0.063d0))
#(0.063d0 0.271d0 0.501d0 0.523d0 0.528d0 0.55d0 0.585d0 0.615d0 0.67d0 0.711d0)
$ rm -r base+sort


text:
Q: How to Get All the Min Values from a Hash Map in Java I have a Hash Map with Keys objects of type Request and Values of type Integer. I use the following code to iterate through the map and get ALL the minimum values and then add their keys to a list. I emphasize to ALL because the keys are unique but the values can be duplicate, therefore there may be more than one map elements with the minimum value.
However, this code gives me only a single such element, that is, the first that it finds through the iteration, even though I know there are more. For example, let us say that the map has the following requests - i.e. keys (I give the request IDs): 3 | 5 | 2 and their respective values are: 8 | 4 | 4. Thus, at this example we have two minimum elements, that is, two elements that share the minimum value, ID 5 and ID 2, both with value 4. The code will add to my list only the element with ID 5, that is, the first one of them.
I have to note that there is a similar thread (Key for maximum value in Hashtable) but the provided solution does not work in my case.
Here is the code:
 Entry<Request, Integer> min = null;

 List<Request> minKeyList = new ArrayList<Request>();

 for(Entry<Request, Integer> entry : this.map.entrySet()) {

      if (min == null || min.getValue() > map.getValue()) {

           min = entry;
           minKeyList.add(entry.getKey());

      }

Any suggestion or explanation why this is happenning would be appreciated.
EDIT: New approach
Well, I found a solution. It is not elegant, but it works. Here is the code.
    // list for finding the min value
    List<Integer> minValList = new ArrayList<Integer>();

    // List for keeping the keys of the elements with the min value
    List<Request> minKeyList = new ArrayList<Request>();

    // scan the map and put the values to the value list
    for(Entry<Request, Integer> entry : this.map.entrySet()) {

        minValList.add(entry.getValue());

    }

    // scan the map
    for(Entry<Request, Integer> entry: this.map.entrySet()) {

        // find the min value
        if(entry.getValue() == Collections.min(minValList)) {

            // add the keys of the elements with the min value at the keyList
            minKeyList.add(entry.getKey());

       }

    }

A: I suggest you a two-step process:

*

*Find the minimum, store in min

*Find all elements with a value equal to min
Here is a code sample:
// find minimum first
int min = Integer.MIN_VALUE;
for(Entry<Request, Integer> entry : this.map.entrySet()) {
    min = Math.min(min, map.getValue())
}

// add all elements that have a value equal to min
List<Request> minKeyList = new ArrayList<Request>();
for(Entry<Request, Integer> entry : this.map.entrySet()) {
    if(min.getValue() == min) {
        minKeyList.add(entry.getKey());
    }
}

A: As Matthias Meid said, you have to use a >= instead of a > .
Also, if think you should had something like this or you minKeyList will contain all the value min has had.
if(min == null || min.getValue() >= map.getValue()) {
    if(min == null || min.getValue() > map.getValue()){
        min = entry;
        minKeyList.clear();
    }
    minKeyList.add(entry.getKey());
}

Edit : Tested code
I tested this method with some sample code and it seems to work correctly.
Here is the code I used to test it :
public static void main(String[] args) {

    HashMap<Integer, Integer> map = new HashMap<>();
    map.put(7, 12);
    map.put(3, 3);
    map.put(1, 10);
    map.put(4, 12);
    map.put(6, 3);
    map.put(8, 3);
    map.put(9, 13);
    Entry<Integer, Integer> min = null;
    List<Integer> minKeyList = new ArrayList<Integer>();

    for(Entry<Integer, Integer> entry : map.entrySet()) {

        if (min == null || min.getValue() >= entry.getValue()) {
            if(min == null || min.getValue() > entry.getValue()){
                min = entry;
                minKeyList.clear();
            }
            minKeyList.add(entry.getKey());
        }
    }

    for (Integer integer : minKeyList) {
        System.out.println(integer);
    }
}

To ease my test, keys and values are both integers but it shouldn't change anything.
No here is my output :
3
6
8

It seems right to me.
If this doesn't help, try posting a little bit more of your code.

A: You can avoid multiple loops by using 2 lists/sets e.g.
Before loop starts
    Set setExisting = new HashSet();
    Map keyMap = new HashMap();
    // find minimum first
    int min = Integer.MIN_VALUE;`enter code here`
    for(Entry<Request, Integer> entry : this.map.entrySet()) {
    Set newSet= new HashSet<String>();
        min = Math.min(min, map.getValue());
        newSet.add(map.getValue(min));
        keyMap.put(min,newSet);
        if (min==map.getValue()){
           setExisting = (Set) keyMap.get(newSet);
           setExisting.add(map.getValue(min));
           keyMap.put(min,setExisting);
         }
  }

  // We will NOT need the below loop in that case
  // add all elements that have a value equal to min
  List<Request> minKeyList = new ArrayList<Request>();
  for(Entry<Request, Integer> entry : this.map.entrySet()) {
    if(min.getValue() == min) {
        minKeyList.add(entry.getKey());
    }
}


text:
Q: How to handle two parameters in laravel when passing from a route to a page I'm passing the below two routes
Route::get('library/course/{id}', function($id){
    return View::make('course')->with('id',$id);
});

Route::get('library/course/{id}/{video}', function($id, $video){
    $array = array('id' => '$id', 'video' => '$video');
    return View::make('course')->withvideos($array);
});

Both the routes are working properly but just one by one to the course.blade.php page. If i remove the content of first route then the 2nd route works otherwise it gives me an error. How can i handle these both routes on the page?
******UPDATED
The code of my course page is the following.
Note only I'm using the first route in this page. I'm unable to use the second as it gives an error.
@extends('layouts.master')

@section('content')

            <?php $coursesName = DB::table('topics')->select('title')->get(); ?>

                @foreach($coursesName as $courseName)

{{ $courseName->title }}

                @endforeach

            <?php $courseViews = DB::table('courses')->whereid($id)->get();  ?>

            @foreach($courseViews as $courseView)

                <?php $requiredId = $courseView->id; ?>

                <?php  $courseVideos = DB::table('videos')->whereid($requiredId)->get(); ?>

                @foreach($courseVideos as $courseVideo)

                    id }}/{{ $courseVideo->id }}">{{ $courseVideo->name }}
                @endforeach

            @endforeach

@stop

A: If think that your error is here: $array = array('id' => '$id', 'video' => '$video');
When you write '$id' it will assigned a string and not use the content of the variable.
Try te change this line by $array = array('id' => $id, 'video' => $video);
Note: You can use []instead of array() if you use PHP 5.4+

A: As @Romain Lanz also I like to mention if you write your route like this
Route::get('library/course/{id}', function($id){
    return View::make('course')->with('id',$id);
});

Route::get('library/course/{id}/{video}', function($id, $video){
    $array = array('id' => '$id', 'video' => '$video');
    return View::make('course')->withvideos($array);
});

It will always match 'library/course/{id}' rather
  'library/course/{id}/{video}'

You should write your route like this
Route::get('library/course/{id}/{video}', function($id, $video){
    $array = array('id' => $id, 'video' => $video);//Also change your array value
    return View::make('course')->withvideos($array);
});

Route::get('library/course/{id}', function($id){
    return View::make('course')->with('id',$id);
});


text:
Q: Trying to retain only non missing values (if any) for a particular variable(condition) my data is something like this
testA       testB       testC
XYZ          1
XYZ          2           ABC
XYZ          3
XYZ          4           BCA
XYZ          5
ZYX          2
ZYX          3           LMN
ZYX          4
ZYX          5
YZX          1
YZX          2

For every unique value(first.testA) I would like to pick up a non missing value of test C with the smallest value of testB.But if there are no non missing values.I just want it to have the first line for that combination.In other words I want my end result to look like this
XYZ          2           ABC
ZYX          3           LMN
YZX          1

I did get what I want using datastep and macro programming but its very convuluted and tedious since I have numerous variables for which I want to do this.I would like to know if there is an easier way
dataset test001;

 proc sort data=test001;    by testA testB testC;    run;
 proc sort data=test001 nodupkey ;  by testA;  run;

data test002;
set test001;
if missing(testC) then output missing001;
run;

data test003;
merge test001
  missing001;
by testA;
run;

proc sort data=test001;  by testA testB testC;  run;
proc sort data=test001 nodupkey ;  by testA;  run;

A: Here, what you need is effectively two passes through the data: one to identify id-groups (testA groups) that have a testC row that's useful, and one to grab the first row of those that don't.
Two ways immediately present themselves to me, in the data step.  PROC SQL could also pretty easily achieve this if you are more comfortable in that.
The simplest method is simply to create a dataset of those records who never have a testC record, and merge that back to the main dataset.  This seems close to what you were doing, but a bit faster this way.
proc sort data=have;
  by testa testb;
run;

data have_notestC;
  set have;
  by testA;
  if first.testA then testCcount = 0;        *for each testA group reinitialize the counter;
  if not missing(testC) then testCcount+1;   *if you see a testC then update counter;
  if last.testA and testCcount=0 then output;*if counter=0 then you never hit testC;
run;

data want;
  merge have have_notestC(in=_ntc);
  by testA;
  if first.testA then testCcount=0;            *reinitialize counter;
  if _ntc and first.testA then output;         *if it was a _ntc record then it has no testC;
  else if _ntc then delete;                    *if not first.testA and _ntc then uninteresting;
  else if testCcount = 0 and not missing(testC) then do;
    testCcount+1;                              *if testCcount=0 and testC is present then you want it;
    output;
  end;
                                               *otherwise ignore;
run;

A more efficient but more difficult method is the double DoW loop.  It mirrors the merge solution but does it inside one datastep.  It's more efficient because the two passes through the data are done in one read from disk, assuming your BY group size is small enough - and it can be done without sorting, if the values are all 'together' but not necessarily in alphabetic order (like your data is above - YZX is after ZYX, but all of the rows for each testA value are consecutive.)
data want;
  testCcount=0;
  hasOutput=0;
  do _n_ = 1 by 1 until (last.testA);
    set have;
    by testA notsorted;
    if not missing(testC) then testCcount=1;
  end;
  do _n_= 1 by 1 until (last.testA);
    set have;
    by testA notsorted;
    if first.testA and testCcount=0 then output;
    else if testCcount=0 then delete;
    else if hasOutput=0 and not missing(testC) then do;
      output;
      hasOutput=1;
    end;
  end;
run;

Neither of these necessarily make it super easy to deal with things if you have many variables that you're working with, although the DoW loop version could be run for multiple variables (but not easily as a macro, because you need to change things in multiple places for each variable you're adding).  It's not totally clear to me how you would do this for 'numerous variables' anyway (since output is a row-based thing) but it could be adapted certainly depending on the details.


text:
Q: Remove unused functions from c# source code Is it possible to remove unused functions from c# source code? For example, in this code:
  internal class Program
  {
    public static void Main(string[] args){

    #if !INIT
      Console.WriteLine("init");
    #elif DETAILS
      Console.WriteLine("details");
      DontAddMePleaseFunction();
    #endif
    #if FINAL
      Console.WriteLine("final");
    #endif
    }

    public static void DontAddMePleaseFunction(){
      Console.WriteLine("lalala");
    }
  }

DontAddMePleaseFunction is never called, but still added to the source code. Now, I can wrap it in #IF INIT #ENDIF (given that INIT is defined) and it will be removed, but I wonder if there is an automatic way of omitting unused functions from c# source code?


text:
Q: dynamic meta tags with react-helmet and gatsby not working So I am using react-helmet to create an SEO object in gatsby, the updated meta tags can be seen in the developer tools however when using a web crawler there are none of the dynamic meta tags, does anyone know how to fix this?

A: Just use gatsby-plugin-react-helmet along with react-helmet.
In your gatsby-config.js
plugins: [`gatsby-plugin-react-helmet`]

This is because you need to serve static properties instead of dynamic ones, so you need to add the drop-in support for the SSR (Server-Side Rendering).


text:
Q: Programmatically register Appium server node with Selenium Hub I'm trying to setup android parallel execution with help of multiple emulators and Selenium Grid.
For this I need to register Appium server node ( one for each of the emulators ) with Selenium Grid.
How to do this in Java?
I have did it through command line, now would like to automate end to end flow.
I could achieve appium server stand alone starting and stopping with below code
 private final static AppiumDriverLocalService service;

static {
System.out.println(APPIUM_HOST +"    "+ APPIUM_PORT + "     " + APPIUM_LOG_LEVEL + "     " + GeneralServerFlag.LOG_LEVEL );

    service = buildService(new AppiumServiceBuilder().
                                             withIPAddress("127.0.0.1").
                                             usingPort(Integer.parseInt("4723"))
               .withAppiumJS(new File("/usr/local/lib/node_modules/appium/build/lib/main.js"))
                   .withArgument(GeneralServerFlag.LOG_LEVEL, "info"));
}

public static void startAppiumServer() {
try{
             service.start();
}catch(Exception e){
    e.printStackTrace();
}
}

public static void stopAppiumServer() {
    try{
                if (service.isRunning()) {
                     service.stop();
                }
    }catch(Exception e){
            e.printStackTrace();
    }
}

I'm not getting how to pass other parameters needed to register node

A: I could get it working, please refer to https://discuss.appium.io/t/unable-to-start-appium-service-by-appiumdriverlocalserivce/6324/25
but couple of questions still open for me

*

*it didn't work with usingAnyFreePort(), I had to explicitly mention port number.

*I could register android emulator node, even when it was not in open state, not sure if this is valid ?


text:
Q: Windows 10 high memory usage (unknown reason) A few days ago I updated my PC to Windows 10. However, after some use my PC started to slow down until it was impossible to use – it was due to high memory usage. After a restart, everything came back to normal (total usage around 25% of 8GB of RAM). However, during a few hours of usage the memory builds up again to 70%, and if not restarted it further goes to 100%, and later on even freezes. Task manager does not help very much as it does not show all the processes (added screenshots below). Also tried RAMMap but it gives an error: "error refreshing database". I tried Googling this question, yet without much success.
I do not know much about PCs, but maybe some of you know this issue, or could help to find out what is using my RAM.

A: this guy might have a Killer Networking (previously Bigfoot networking) brand network card.
Was going crazy trying to figure out why I had a massive memory leak and even did a completely clean install and immediately after installing I had a memory leak.  Of course I installed my network drivers and video card drivers but that was it.
I searched Google... Found this thread saying it was his network driver then googled "killer memory leak" and saw hits for that and found it was the killer app itself and not just in windows 10.
Now I'm golden...
So if anyone else has this issue and they have one of the many gaming boards or laptops that have a killer NIC you can probably just disable the killer app from starting.   But what I did was completely uninstall the ASROCK provided driver and then installed the latest driver only package from the official killer networking site.  It's the smaller ~30mb download.  If your download is closer to or more than 100mb then you got the wrong one.
You'll loose everything that makes the killer stand out (it's QoS software) but that's what a good router is for in the first place... Especially since the killer app only handles the QoS of applications running on your PC and does nothing for your network as a whole.

A: The accepted answer by magicandre1981 is the correct answer to this problem, if the RAM usage continues to climb to 100% then there's most likely a memory leak.
However, if you've come to this page because Windows 10's memory usage is high but remaining steady (like in the 60%-90% range), you probably don't have a problem. Windows 10 uses RAM more effectively than past versions.  This is because unused RAM is wasted RAM.
Modern operating systems have long swapped infrequently used memory data to a pagefile on the hard drive in order to free up RAM for more frequently needed memory data. (My Win 10 system has 8GB RAM and a 12GB pagefile.)  However, it is slow to retrieve this data back from the drive, and Windows 10 will compress infrequently accessed memory and store it in the system process (in the RAM). It's faster to uncompress this data than it is to retrieve it from the hard drive (even an SSD). Just because your RAM is mostly full, does not mean you won't be able to run more things, if more RAM is needed then Win 10 will move some of this compressed memory to the pagefile to free up RAM for new applications.
If you constantly find your system process is using more than 1GB RAM (like I do) than you probably have too many browser tabs open (like I do). An extension like OneTab can help.

A: You have a memory leak caused by a driver. Look at the high value of nonpaged kernel memory. In your case this is over 3.7 GB. You can use poolmon to see which driver is causing the high usage.
Install the Windows WDK, run poolmon, sort it via P after pool type so that non paged is on top and via B after bytes to see the tag which uses most memory. Run poolmon by going to the folder where WDK is installed, go to Tools (or C:\Program Files (x86)\Windows Kits\10\Tools\x64) and click poolmon.exe.
Now see which pooltag uses most memory as shown here:

Now open a cmd prompt and run the findstr command. To do this, open cmd prompt and type cd C:\Windows\System32\drivers. Then type findstr /s __ *.*, where __ is the tag (left-most name in poolmon).
Do this to see which driver uses this tag:

Now, go to the drivers folder (C:\Windows\System32\drivers) and right-click the driver in question (intmsd.sys in the above image example). Click Properties, go to the details tab to find the Product Name. Look for an update for that product.
If the pooltag only shows Windows drivers or is listed in the pooltag.txt ("C:\Program Files (x86)\Windows Kits\10\Debuggers\x64\triage\pooltag.txt")
you have use xperf to trace what causes the usage. Install the WPT from the Windows SDK, open a cmd.exe as admin and run this:

xperf -on PROC_THREAD+LOADER+POOL -stackwalk
PoolAlloc+PoolFree+PoolAllocSession+PoolFreeSession -BufferSize 2048
-MaxFile 1024 -FileMode Circular && timeout -1 && xperf -d C:\pool.etl

capture 30 -60s of the grow. Open the ETL with WPA.exe, add the Pool graphs to the analysis pane.
Put the pooltag column at first place and add the stack column. Now load the symbols inside WPA.exe and expand the stack of the tag that you saw in poolmon.

Now find other 3rd party drivers which you can see in the stack. Here the Thre tag (Thread) is used by AVKCl.exe from G-Data. Look for driver/program updates to fix it.

The user Hristo Hristov provided a trace with a high FMfn usage during unzipping files:

The tag is used by the driver WiseFs64.sys which is part of the "Wise Folder Hider" program. Removing it fixes the leak.

The user Samuil Dichev provided a trace with a high FMic and Irp usage

The tags are used by the program Razor Cortex.
In the sample of the user chr0n0ss the FMic and Irp usage is caused by  F-Secure Antivirus Suite:

Removing it and using Windows Defender fixed the issue for him.

A: Received this answer out of band from "coolie91", posting it here, basically "it could be adware":
Today, I was able to fix it for good by following the instructions in this link:
https://www.bleepingcomputer.com/virus-removal/how-to-remove-adware-on-a-pc
The fix: Basically, a whole bunch of malware and extensions had hijacked common programs and riding on them, buried deep inside rootkits and all. They were almost impossible to detect and remove.
This seems to have worked for me as my memory still is ~ 41% after running for almost 2 hours (Phew!!!) Before, I had to reboot every 45 minutes.


text:
Q: Multithreaded access to file We have a multi threaded java program. Multiple-threads will write to a file, and one thread will read from that file. I am looking for some design ideas. Is synchronization necessary?

A: FileChannel is in theory thread safe. From the javadoc:

File channels are safe for use by multiple concurrent threads. The
  close method may be invoked at any time, as specified by the Channel
  interface. Only one operation that involves the channel's position or
  can change its file's size may be in progress at any given time;
  attempts to initiate a second such operation while the first is still
  in progress will block until the first operation completes. Other
  operations, in particular those that take an explicit position, may
  proceed concurrently; whether they in fact do so is dependent upon the
  underlying implementation and is therefore unspecified.

If you can use these, then you can use the built-in synchronization, rather than having to write your own.

A: I would consider synchronization in this case. Imagine that 2 threads (t1 and t2) open the file at the same time and start writing to it. The changes performed by the first thread are overwrited by the second thread because the second thread is the last to save the changes to the file. When a thread t1 is writing to the file, t2 must wait until t1 finishes it's task before it can open it.
Also, if you care about the latest possible update of the file, you should synchronize the writing threads with the thread that reads the file so that if there's any thread writing the the file, the reading thread should wait.

A: If being synchronous isn't important, you could have your writer running in its own thread, and allow other threads to queue up writes to the file. Although I think the first thing to consider is whether writing to a file is really what you want to do. Especially in high-traffic situations, having a lot of disk I/O may not be very efficient.

A: If you wanted multiple readers and one writer, you would be looking for a Read Write Lock or a Read Write Mutex.
But you want multiple writers and one reader.  How do you know these writers won't overwrite each others data?  Are they somehow segregated?

A: Once multiple Threads access shared data then Synchronization is necessary. If multiple threads write to the same file without some form of locking, then potentially you will end up with a lost update problem.
Reading is not as big an issue in all circumstances so you need to consider...if a thread is reading the file and at the same time another thread updates the file, does the reading thread need to know about the change? If so you need to lock the file for the reading thread also.

A: You need synchronization (locking) if you have a mix of readers and writers or writers and writers. If you only have readers, you don't need any synchronization.
You don't want two processes writing to the same file or one process writing a file that another is reading.

A: Synchronization is necessary in this case. FileChannel is useful for preventing files being modified by processes outside the JVM: not so for applications which include multiple threads writing to a single file.
From (further down in) the JavaDoc for FileChannel:

File locks are held on behalf of the
  entire Java virtual machine. They are
  not suitable for controlling access to
  a file by multiple threads within the
  same virtual machine.

See this post for a brief discussion of strategies to share file writing between threads.


text:
Q: Equivalent of preg_match, that returns pretty (multidimensional) array is there some PHP function or library, which returns result of regex as pretty multidimensional array according to brackets in regular expression? This is, what I mean:
preg_match('/(n(e?)c)(o)/', 'neco', $vysl);
var_dump($vysl);

returns this:
array(4) {
  [0]=>
  string(4) "neco"
  [1]=>
  string(3) "nec"
  [2]=>
  string(1) "e"
  [3]=>
  string(1) "o"
}

I would like to have output like this:
array(3) {
  [0]=>
  string(4) "neco"
  [1]=>
  array(2) {
    [0]=>
    string(3) "nec"
    [1]=>
    string(1) "e"
  }
  [2]=>
  string(1) "o"
}

Every subexpression result is in expected (wanted) depth in this array.

A: Interesting question! There's no such thing built-in, you'll have to capture offsets of matches and for each match check if its offset is within some other's bounds: something that reminds me of the nested sets model:
function match_tree($re, $subject) {
    preg_match($re, $subject, $ms, PREG_OFFSET_CAPTURE);

    $p = [(object)[]];

    foreach($ms as $m) {
        $m = (object) [
            'le'  => $m[1],
            'ri'  => $m[1] + strlen($m[0]) - 1,
            'str' => $m[0]];

        for($i = count($p) - 1; $i >= 0; $i--) {
            if(!$i || ($m->le >= $p[$i]->le && $m->le <= $p[$i]->ri)) {
                $p []= $m;
                $p[$i]->sub []= $m;
                break;
            }
        }
    }

    return $p[0];
}

For example,
print_r(match_tree('/(n(e?)c)(o)(f(o(abc)))/', 'XnecofoabcY'));

returns
stdClass Object
(
    [sub] => Array
        (
            [0] => stdClass Object
                (
                    [le] => 1
                    [ri] => 9
                    [str] => necofoabc
                    [sub] => Array
                        (
                            [0] => stdClass Object
                                (
                                    [le] => 1
                                    [ri] => 3
                                    [str] => nec
                                    [sub] => Array
                                        (
                                            [0] => stdClass Object
                                                (
                                                    [le] => 2
                                                    [ri] => 2
                                                    [str] => e
                                                )

                                        )

                                )

                            [1] => stdClass Object
                                (
                                    [le] => 4
                                    [ri] => 4
                                    [str] => o
                                )

                            [2] => stdClass Object
                                (
                                    [le] => 5
                                    [ri] => 9
                                    [str] => foabc
                                    [sub] => Array
                                        (
                                            [0] => stdClass Object
                                                (
                                                    [le] => 6
                                                    [ri] => 9
                                                    [str] => oabc
                                                    [sub] => Array
                                                        (
                                                            [0] => stdClass Object
                                                                (
                                                                    [le] => 7
                                                                    [ri] => 9
                                                                    [str] => abc
                                                                )

                                                        )

                                                )

                                        )

                                )

                        )

                )

        )

)


text:
Q: Increment per group but reset per criteria I'm using SQL Server and say I have this sample
CREATE TABLE TableName
    (acct int, seq int,chk int)
;

INSERT INTO TableName
    (acct, seq,chk)
VALUES
    (123,1,1),
    (123,2,1),
    (123,3,1),
    (123,4,0),
    (123,5,1),
    (123,6,1),
    (124,1,0),
    (124,2,1),
    (124,3,1),
    (124,4,0),
    (124,5,1),
    (124,6,1)
;

I want to produce a counter per acct based on when chk=1 and then resets when chk is 0. The seq is just order I want it to be in .
Is there a way to just do it in the select? If not then a loop is fine just looking a different methods like dense_rank() and row_number() but I can't get it to how I want.
This is how I want it(Counter being the column I want to create):
acct seq chk counter
123  1   1   1
123  2   1   2
123  3   1   3
123  4   0   0
123  5   1   1
123  6   1   2
124  1   0   0
124  2   1   1
124  3   1   2
124  4   0   0
124  5   1   1
124  6   1   2

I tried this and then nested one but I can't figure it out:
SELECT  acct,
        seq,
        chk,
        dense_rank() OVER (partition by acct, chk oRDER BY seq)  as counter1,
        row_number() OVER (partition by acct, chk oRDER BY seq)  as counter2
FROM    tableName
order by acct,seq

A: Use a cumulative sum to define the groups and then row_number():
select t.*,
       (case when chk = 1
             then row_number() over (partition by acct, grp, chk order by seq)
             else 0
        end) as counter
from (select t.*,
             sum(1 - chk) over (partition by acct order by seq) as grp
      from tablename t
     ) t
order by acct, seq

Here is a db<>fiddle.

A: The following produces your desired results with the logic in comments.
with cte as (
  select *
    -- Step 1 - detect changes in the chk value
    , case when lag(chk,1,0) over (order by acct, seq) <> chk and chk = 0 then 1 else 0 end lagged
  from #TableName
)
select acct, seq, chk
  -- Step 3 - get the row number using the chk partitioning
  , case when chk = 1 then row_number() over (partition by acct, chk, sumlagged order by seq) else 0 end [counter]
from (
  select *
    -- Step 2 - sum change in chk so they provide a distinct value for partitioning
    , sum(lagged) over (order by acct, seq) sumlagged
  from cte
) x
order by acct, seq;

A: It seems the output could be created using a single windowing function.  Something like this
select *, seq-max(case when chk>0 then 0 else seq end)
                over (partition by acct order by seq) as [counter]
from #TableName
order by acct, seq;

Output
acct    seq chk counter
123     1   1   1
123     2   1   2
123     3   1   3
123     4   0   0
123     5   1   1
123     6   1   2
124     1   0   0
124     2   1   1
124     3   1   2
124     4   0   0
124     5   1   1
124     6   1   2


text:
Q: Configure correctly CORS with wai-cors I am struggling with Servant and the CORS configuration: I am exposing and API through Servant and I have the following configuration:
-- Wai application initialization logic
initializeApplication :: IO Application
initializeApplication = do
  let frontCors = simpleCorsResourcePolicy { corsOrigins = Just ([pack "https://xxxx.cloudfront.net"],  True)
                                           , corsMethods = ["OPTIONS", "GET", "PUT", "POST"]
                                           , corsRequestHeaders = simpleHeaders }
  return
    $ cors (const $ Just $ frontCors)
    $ serve (Proxy @API)
    $ hoistServer (Proxy @API) toHandler server

When I perform a query like this through Chromium (by copying and pasting):
curl 'https://api.xxx/' \
  -H 'Accept: application/json, text/plain, */*' \
  -H 'Referer: https://xxx.cloudfront.net' \
  -H 'User-Agent: Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.111 Safari/537.36' \
  -H 'Authorization: Bearer XXX==' \
  --compressed

It works but if I copy-paste the fetch query in the dev console:
fetch("https://api.xxx", {
  "headers": {
    "accept": "application/json, text/plain, */*",
    "authorization": "Bearer XXX=="
  },
  "referrer": "https://xxx.cloudfront.net/",
  "referrerPolicy": "no-referrer-when-downgrade",
  "body": null,
  "method": "GET",
  "mode": "cors",
  "credentials": "include"
});

I get:
> Access to fetch at 'https://api.xxx' from origin 'https://xxx.cloudfront.net' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
polyfills-es2015.3eb4283ca820c86b1337.js:1 GET https://api.xxx net::ERR_FAILED
e.fetch @ polyfills-es2015.3eb4283ca820c86b1337.js:1
>  (anonymous) @ VM20:1
> x:1 Uncaught (in promise) TypeError: Failed to fetch

Any hints regarding that? Especially why it works in cUrl and not in Chromium?
Thanks in advance.

A: It was a basic CORS issue, in fact, sending Authorization without having it in the corsRequestHeaders makes the request rejected.
I should have written:
, corsRequestHeaders = ["Authorization", "Content-Type"]


text:
Q: Language Books/Tutorials for Groovy I am a complete newbie in groovy . I have basic knowledge of Java, C#, .NET and now i want to learn groovy beacause of some reasons like this .
I have currently started it from here but trying to find something more on groovy like some tutorial,books,any interactive learning aid for beginners of groovy .
Thanks

A: Shameless plug: I'm one of the co-authors1 of Groovy in Action, which is pretty well regarded in Groovy circles, as far as I'm aware.
There's a second edition in progress - if you order that now, you get early access to the second edition ebook as it's written, and a full copy of the first edition ebook to be going on with.
That said, of course there are plenty of other books around Groovy - with some particularly focusing on one area, such as Grails.

1 Actually I'm more like a glorified editor. While I've touched large portions of the text, I've written very few complete paragraphs, if you see what I mean.

A: Here's the obligatory Project Euler link, which is a petty universal means of familiarizing oneself with a new language.  The problems are not ideal for learning the more macro aspects of programming ( OOP, Design Patterns, etc), but it will give you a good feel for Groovy's syntax and basic features.  I've ground through just shy of 100 of them, with definite results. - Plus, it was fun.
I'd also recommend the Groovy Web Console. You can use it to run your scripts online, but perhaps more importantly, you can browse the scripts of others - I've found this to be rather invaluable, particularly while getting acquainted with Groovy's DSL capabilities.

A: If you're looking for online tutorials, I recommend reading the Practically Groovy series by Andrew Glover and Scott Davis, as well as the Groovy Goodness snippets by mrhaki which all provide plain, helpful and mostly up-to-date information about the important and pleasant language features.


text:
Q: JQUERY $j(this) in magento I am using $j(this) in my jquery change function. But the $j(this) locate the windows, instead of the changing function.
Jquery:
$j('#id').on("change", function () {
    var $this = $j(this);
    console.log($this);
});

what i get is,
[Window]

But its wrong. It should console #id's functions. why this error occurring. Is $j(this) correct or not? Please help me.. I am totally stuck at this.

A: You should use only "this" inside the on event that refers to the element.


text:
Q: SqlConnection.ClearPool() impact on webserver(IIS) performance I recently monitored my sql database activity I found about 400 processes in activity monitoring.Later I figured that the problem is with my connection string object which would not be cleared physically even though I completely closed and disposed it, so once I suspend my IIS all the processes from activity monitoring would disappear.
after a little searching I found that I can clean all of my connections from application pool so that all the useless processes from SMSS would be killed but
I'm really concerned about it's impact on webserver. It's true that this approach would clear useless tasks from SMSS but for every request a new connection should really be created is it worth it???
considering my application is kind of enterprise app which is supposed to handle to many requests, I'm so afraid of making IIS server down by using this approach.
Do notice that my connection string value is not completely fixed for all the requeests, I made it variable by changing only "Application Name" section of it in every request according to the request parameters for the purpose of getting requestors information in sql activity monitoring and sql profiler.
is it worth to do so considering my business scope or it's better I fix the connection string value in other word is performance lag on this approach is so severe that I have to change my logging strategy or it's just a little slower???

A:
Do notice that my connection string value is not completely fixed for all the requeests, I made it variable by changing only "Application Name" section of it in every request according to the request parameters for the purpose of getting requestors information in sql activity monitoring and sql profiler.

This is really bad because it kills pooling. You might as well disable pooling but that comes with a heavy performance penalty (which you are paying right now already).
Don't do that. Obtain monitoring information in a different way.
Besides that, neither SQL Server nor .NET have a problem with 400 connections. That's unusually high but will not cause problems.
If you run multiple instances of the app (e.g. for HA) this will multiply. The limit is 30k. I'm not aware of any reasons why this would cause a slowdown for the app, but it might cause problems for your monitoring tools.


text:
Q: Mapping a table's components as arraylist in another table as onetomany I'm using JPA with hibernate persistence manager.
I have two classes, LibraryLoanSystem.java and User.java.
LibraryLoanSystem.java
 @Entity
    public class LibraryLoanSystem {

        @Id
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        private Integer idOfLLS;

        @Transient
        private ArrayList<Loan> loans = new ArrayList<Loan>();

        @Transient
        private ArrayList<Loanable> loanables = new ArrayList<Loanable>();

        @OneToMany
        @JoinTable(name = "USER" , joinColumns = @JoinColumn(name = "studentId"))
        private ArrayList<User> users = new ArrayList<User>();

        @Transient
        private ObservableList<Material> materialData = FXCollections.observableArrayList();

        public LibraryLoanSystem() {

            populateUsers();
            populateMaterials();
        } //getters,setters and methods

User.java
@Entity
@Table(name = "User")
public class User {

    /* Name of the User */
    @Column(name = "name", nullable = false)
    private String name;

    /* Date of Birth for the User */
    @Column(name = "dateOfBirth",nullable = false)
    private LocalDate dateOfBirth;

    /* Student ID of the User */
    @Id
    @Column(name = "studentId", updatable = false, nullable = false)
    private String studentId;
//constructor,getters & setters

Basically, ArrayList users in libraryloansystem is the list of all users in the system, aka. all of the user records in the user table rows. These two java classes have an aggregation relationship between them, onetomany, with libraryloansystem having multiple users but the user having only one system. I'm unsure on how to map them, and I get

Illegal attempt to map a non collection as a @OneToMany, @ManyToMany
  or @CollectionOfElements: controller.LibraryLoanSystem.users

On my attempts. How can I map this arraylist correctly?Thanks

A: Instead of:
private ArrayList<User> users = new ArrayList<User>();
use: private List<User> users = new ArrayList<>();
As the documentation states (link):

Hibernate requires that persistent collection-valued fields be declared as an interface type. The actual interface might be java.util.Set, java.util.Collection, java.util.List, java.util.Map, java.util.SortedSet, java.util.SortedMap or anything you like ("anything you like" means you will have to write an implementation of org.hibernate.usertype.UserCollectionType.)


text:
Q: Read the data from file in C++ void Admin::searchFlight(string destination)
{

    int day, month, year, min, hour,flightID;
    string departure;
    double price;
    Flight sFlight;
    string read;
    Date dateOfFlight(day,month,year);
    Time timeOfFlight(min,hour);
    ifstream inFlight("Flight.txt");
    while(!inFlight.eof())
    {
        inFlight.getline(read,departure);
}
    int counter = 0;
    for(int i = 0; i<flightList.size();i++)
    {
        if(destination.compare(flightList[i].getDestination()))
        {
            //counter++;
            flightList[i].displayFlightSchedule();
        }
}
}

There is an error between inFlight.getline(read,departure);. Since my file got this type of details
(Flight ID: 1   Departure Place: Malaysia   Destination Place: UK   Price of this Flight: RM20000   Date Of Flight: 24/12/1993  Time of Flight: 12:12)
I want to read them out when I do this code admin.searchFlight("UK");

A: You (incorrectly) read the lines in the file but you don't do anything with them. Your code should probably be structured along the lines of
for (std::string departure; std::getline(inFlight, departure); ) {
    do_some_thing_with(departure);
}


text:
Q: timer on thread? Can i create successfully a timer clock on a thread? i'm creating one but it doesn't seem to work that well. My app is a multi-thread app that has to start a timer on a thread when ever a certain event happens. The timer is placed in every client connection. The clock doesn't work until i close my winform(i don't know why) . Is there anything in particular that i should know about timers in threads ?
Here is my timer code :
timer1.Interval = 1000;
timer1.Tick += new EventHandler(timer_Tick);
timer1.Enabled = true;
timer1.Start();

A: You might try to use System.Threading.Timer, which is basically a timer that's in a separate thread. You might also consider using a WaitHandle that's never fired and then using WaitOne(1000, false) to wait for a second.

A: Try this:
public void EnableTimer()
        {
            if (this.InvokeRequired)
                this.Invoke(new Action(EnableTimer));
            else
                this.timer1.Enabled = true;
        }


text:
Q: mutt weird action I wrote a little script to send multiple mails from a list with differents subjects.
 #!/bin/bash

 while read -a line
 do
 mailadd=${line[0]}
 subject=${line[1]}

 mutt -s `echo $subject` `echo $mailadd` < /home/emanuele/testomail.txt

 done < prova.txt

The scripts works fine and sends the mails, but mutt tell me that he needs a -s option.
mutt: option requires an argument -- 's'
Mutt 1.5.21 (2010-09-15)

I don't understand why the script works fine but mutt exit with an error. How can I fix it?

A: First, `echo $subject` is a convoluted way of writing $subject (except that it mangles the value a bit more if it contains whitespace or \[*?, because $subject outside quotes is treated as a whitespace-separated list of wildcard patterns, and then the result of the whole command substitution is again treated as a whitespace-separated list of wildcard patterns).
The only way for your command to result in this error is if `echo $subject` `echo $mailadd` is empty. This happens only when both `echo $subject` and `echo $mailadd` consist only of whitespace, which in turns happens only if both variables subject and mailadd are empty (plus a few oddball cases, such as subject being the character ? and the current directory containing a file whose name is a single space). So most likely you have some blank lines in your input file.
You should always put double quotes around variable substitutions and command substitutions ("$somevar", "$(somecommand)") unless you really mean the values of the variables to be interpreted as whitespace-separated lists of file wildcard patterns.
mutt -s "$subject" "$mailaddr" <~/testeomail.txt

If there's a blank line in the input file, skip it.
while read -a line; do
  mailadd=${line[0]}
  subject=${line[1]}
  if [ -z "$subject" ]; then continue; fi
  mutt -s "$subject" "$mailadd" < /home/emanuele/testomail.txt
done < prova.txt


text:
Q: Determinant of a symmetric matrix where the diagonal is the (negative) sum of all rows/columns, where one or two rows/columns are removed. Since I have absolutely no idea how to research this, I guess I will ask it here to see if someone has a bright idea.
The problem background is calculating the resistance of a resistive network. Per this question, we have that;
$$
R_{kl} = \frac{\det(A_{kl})}{\det(A_l)}
$$
Here $R_{kl}$ is the effective resistance between node k and l. Here A is a matrix with the following properties:
$$A_{ij} = \begin{cases} \sum_{k \neq i} C_{ik} & i = j \\ -C_{ij} & i \neq j \end{cases}$$
Here $C_{ij}$ is the conductivity between node i and j, where C is defined as $R = \frac{1}{C}$.
Some observations:

*

*$A$ is a symmetric matrix

*The diagonal elements of the matrix are the (negative) sum of the rows/columns

*The determinant of A itself appears to be zero (I cannot prove this)

*When removing one row/column, we go back in "one dimension" of calculating the volume of a hypervolume.

I am using this on huge resistor networks. It would be nice to come up with some kind of trick to make calculating it easier. If any of you know a good approximation technique, or another good technique to calculate this determinant, that is also fine. I am currently creating a lower triangular matrix and then calculating the determinant by multiplying the diagonal elements.


text:
Q: Get date from calendar control asp.net How can i get the current date, day, month from the calendar individually on page load function in C# like the following:
day :Friday
date: 13 // just the d, i don't the full format
month: August

A: Generally if you are using a Calendar control, you should be able to access a property like SelectedDate that would give you a proper DateTime object, which you could use to pull the properties that you need :
// Get the selected date
var date = YourCalendar.SelectedDate;

// Get the day of week (e.g. Friday)
var dayOfWeek = date.ToString("dddd");
// Get the day of the month (e.g. 19); Use date.ToString("d") if you need a string
var day = date.Day;
// Get the full month name (e.g. August)
var month = date.ToString("MMMM");


text:
Q: How to display header in a Series of pandas? data is a  instance of pandas.core.series.Series.
 >>> type(data)
<class 'pandas.core.series.Series'>
>>> data
1    002728
2    002142
3    002284
Name: scode, dtype: object

How to display it as follows ?
>>> data
     scode
1    002728
2    002142
3    002284
Name: scode, dtype: object

A: You can convert it to a dataframe. Two options on how to do so:
import pandas as pd
data = pd.Series(['002728','002142','002284'], name = 'scode')
data = data.to_frame()
print(data)
   scode
0  002728
1  002142
2  002284

or
import pandas as pd
data = pd.Series(['002728','002142','002284'], name = 'scode')
data = pd.DataFrame(data)
print(data)
 scode
0  002728
1  002142
2  002284

The only practical difference between a single column dataframe and a series that I can think of off the top of my head is indexing. If you want to select the first element of a series... you can do it as follows:
data = pd.Series(['002728','002142','002284'], name = 'scode')
data[0]
# 002728

But for a one column dataframe, data[0] wouldn't work. Here's what you'd need to do to get the value in the first row:
data = pd.Series(['002728','002142','002284'], name = 'scode')
data = data.to_frame()
data.iloc[0,0]
# 002728

And to get the value in the ith row
data = pd.Series(['002728','002142','002284'], name = 'scode')
data = data.to_frame()
print(data.iloc[i,0])

You could use
data = pd.Series(['002728','002142','002284'], name = 'scode')
data = data.to_frame()
data.iloc[i]

but that would give you a series containing just the value in the ith row.
print(type(data.iloc[0,0]))
#<class 'str'>
print(type(data.iloc[0]))
#pandas.core.series.Series

If your series consisted of numerical values...here's how a vectorized method such as multiplication would work:
numbers = pd.Series([1,3,5,7], name = 'numbers')
print(numbers)
# 0  1
1    3
2    5
3    7
Name: numbers, dtype: int64

print(numbers*3)
#0    3
1     9
2    15
3    21
Name: numbers, dtype: int64

For a single column dataframe with the same numerical values as the series above:
numbers = pd.Series([1,3,5,7], name = 'numbers')
numbers = numbers.to_frame()
print(numbers)
#   numbers
0        1
1        3
2        5
3        7

print(numbers*3)

#   numbers
0        3
1        9
2        15
3        21


text:
Q: Resize canvas to viewport without loosing quality I am trying to have a canvas fill the entire viewport and resize, whenever the user resizes the browser window.
However, when I try to use a size of 100%, it looses quality.
I am kind of a newb in JavaScript programming.
Can someone please help me?

A: I figured out a way:
I calculate a scaling factor, by which I scale the size, but not the position of each element drawn.
I do not want to scale the position, because then some elements might be off screen.
Thus I can not use setTransform, as suggested in the comments.
Here is the code I used for calculating the scaling factor.
If someone has improvements, please share them in the comments below!
if (window.screen.width > window.screen.height)
    scalingFactor = window.screen.width * window.devicePixelRatio / 1280;
else
    scalingFactor = window.screen.height * window.devicePixelRatio / 720;

A: The easiest way to resize a canvas with losing the data currently on it is to store the data, then resize the canvas (which clears it), then redraw the data into the canvas. That would look something like this:
const data = ctx.getImageData( 0, 0, canvas.width, canvas.height );
canvas.width = innerWidth;
canvas.height = innerHeight;
ctx.putImageData( data, 0, 0 );

In its purest, simplest example it would look something like this:

/* This method does the resize by storing the data and redrawing it. It loses any data outside of the screen, though. */
function onResize( event ){

  const data = ctx.getImageData( 0, 0, canvas.width, canvas.height );

  canvas.width = innerWidth;
  canvas.height = innerHeight;

  ctx.putImageData( data, 0, 0 );

}

/* This method is for drawing some content to help visualisation. */
function onRedraw(){

  const r = v => Math.floor(Math.random() * v);

  canvas.width = innerWidth;
  canvas.height = innerHeight;

  ctx.fillStyle = `rgb(${r(255)},${r(255)},${r(255)})`;
  ctx.fillRect( 0, 0, innerWidth, innerHeight );
  ctx.fillStyle = `rgb(${r(255)},${r(255)},${r(255)})`;
  ctx.fillRect( 0, 0, innerWidth / 2, innerHeight / 2 );
  ctx.fillRect( innerWidth / 2, innerHeight / 2, innerWidth / 2, innerHeight / 2 );

}

window.addEventListener( 'resize', onResize );

const canvas = document.createElement( 'canvas' );
const ctx = canvas.getContext( '2d' );
const reset = document.getElementById( 'reset' );

document.body.appendChild( canvas );

onRedraw();

redraw.addEventListener( 'click', onRedraw );
body { padding: 0; margin: 0; overflow: hidden; }
button { position: fixed; top: 20px; left: 20px; z-index: 1; }
<button id="redraw">Redraw</button>

However, you lose data drawn outside the canvas when your window grows and shrinks, as the data is never saved. We could hold a buffer with our graphics, which could simplify things a bit but makes the code slightly more complicated. In this case, we can use a second canvas that holds all our previously drawn maximum sized screen data, just for reference:

/* This method does the resize by storing the data and redrawing it. It retains data outside the screen in a buffer that holds the maximum size ever drawn. */
function onResize( event ){

  const data = bufferCtx.getImageData( 0, 0, bufferCanvas.width, bufferCanvas.height );

  bufferCanvas.width = Math.max( bufferCanvas.width, innerWidth );
  bufferCanvas.height = Math.max( bufferCanvas.height, innerHeight );

  bufferCtx.putImageData( data, 0, 0 );
  bufferCtx.drawImage( canvas, 0, 0 );

  canvas.width = innerWidth;
  canvas.height = innerHeight;

  ctx.drawImage( bufferCanvas, 0, 0 );

}

/* This method is for drawing some content to help visualisation. */
function onRedraw(){

  const r = v => Math.floor(Math.random() * v);

  canvas.width = innerWidth;
  canvas.height = innerHeight;

  ctx.fillStyle = `rgb(${r(255)},${r(255)},${r(255)})`;
  ctx.fillRect( 0, 0, innerWidth, innerHeight );
  ctx.fillStyle = `rgb(${r(255)},${r(255)},${r(255)})`;
  ctx.fillRect( 0, 0, innerWidth / 2, innerHeight / 2 );
  ctx.fillRect( innerWidth / 2, innerHeight / 2, innerWidth / 2, innerHeight / 2 );

}

window.addEventListener( 'resize', onResize );

const canvas = document.createElement( 'canvas' );
const ctx = canvas.getContext( '2d' );
const bufferCanvas = document.createElement( 'canvas' );
const bufferCtx = bufferCanvas.getContext( '2d' );
const reset = document.getElementById( 'reset' );

document.body.appendChild( canvas );

onRedraw();

redraw.addEventListener( 'click', onRedraw );
body { padding: 0; margin: 0; overflow: hidden; }
button { position: fixed; top: 20px; left: 20px; z-index: 1; }
<button id="redraw">Redraw</button>

If you'de rather use lose no data at all and 'rescale' the canvas the best it can, perhaps best to use something like this:

/* This method does the resize by just redrawing the canvas from a buffer: */
function onResize( event ){

  bufferCanvas.width = canvas.width;
  bufferCanvas.height = canvas.height;
  bufferCtx.drawImage( canvas, 0, 0 );

  canvas.width = innerWidth;
  canvas.height = innerHeight;

  ctx.drawImage( bufferCanvas, 0, 0, canvas.width, canvas.height );

}

/* This method is for drawing some content to help visualisation. */
function onRedraw(){

  const r = v => Math.floor(Math.random() * v);

  canvas.width = innerWidth;
  canvas.height = innerHeight;

  ctx.fillStyle = `rgb(${r(255)},${r(255)},${r(255)})`;
  ctx.fillRect( 0, 0, innerWidth, innerHeight );
  ctx.fillStyle = `rgb(${r(255)},${r(255)},${r(255)})`;
  ctx.fillRect( 0, 0, innerWidth / 2, innerHeight / 2 );
  ctx.fillRect( innerWidth / 2, innerHeight / 2, innerWidth / 2, innerHeight / 2 );

}

window.addEventListener( 'resize', onResize );

const canvas = document.createElement( 'canvas' );
const ctx = canvas.getContext( '2d' );
const bufferCanvas = document.createElement( 'canvas' );
const bufferCtx = bufferCanvas.getContext( '2d' );
const reset = document.getElementById( 'reset' );

document.body.appendChild( canvas );

onRedraw();

redraw.addEventListener( 'click', onRedraw );
body { padding: 0; margin: 0; overflow: hidden; }
button { position: fixed; top: 20px; left: 20px; z-index: 1; }
<button id="redraw">Redraw</button>


text:
Q: 'ng4geo-autocomplete' is not a known element: 'ng4geo-autocomplete' is not a known element:

This is in the header.component.html:

    <ng4geo-autocomplete (componentCallback)="autoCompleteCallback2($event)"></ng4geo-autocomplete>

This is header.component.ts:
import { Component, OnInit } from '@angular/core';
import {  ViewEncapsulation } from '@angular/core';
//import { Ng4GeoautocompleteModule } from '';

import {
    Ng4GeoautocompleteModule
} from 'ng4-geoautocomplete';

//@Component({
//        selector: 'layout-header',
//        templateUrl: 'app/Components/header.component.html'
//    })
@Component({
    selector: 'any-component-name',
    encapsulation: ViewEncapsulation.None,
    template: '
<ng4geo-autocomplete (componentCallback)="autoCompleteCallback1($event)"></ng4geo-autocomplete>
',

})
export class HeaderComponent {
}

I am installing npm install --save ng4-geoautocomplete on angular4 project.
Can anyone tell me what the problem is?
Here is the total error:
"Uncaught (in promise): Error: Template parse errors:
'ng4geo-autocomplete' is not a known element:
1. If 'ng4geo-autocomplete' is an Angular component, then verify that it is part of this module.
2. If 'ng4geo-autocomplete' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message. ("

                                        [ERROR ->]<ng4geo-autocomplete  (componentCallback)="autoCompleteCallback2($event)"></ng4geo-autocomplete>
   "): ng:///app/Components/header.component.html@195:40
Error: Template parse errors:
'ng4geo-autocomplete' is not a known element:
1. If 'ng4geo-autocomplete' is an Angular component, then verify that it is part of this module.
2. If 'ng4geo-autocomplete' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message. ("

                                        [ERROR ->]<ng4geo-autocomplete  (componentCallback)="autoCompleteCallback2($event)"></ng4geo-autocomplete>
   "): ng:///app/Components/header.component.html@195:40
    at Error.ZoneAwareError (http://localhost:13244/node_modules/zone.js/dist/zone.js:992:33)
    at ZoneAwareError (http://localhost:13244/node_modules/zone.js/dist/zone.js:989:35)
    at syntaxError (http://localhost:13244/node_modules/@angular/compiler/bundles/compiler.umd.js:1513:34)
    at TemplateParser.parse (http://localhost:13244/node_modules/@angular/compiler/bundles/compiler.umd.js:11522:19)
    at JitCompiler._compileTemplate (http://localhost:13244/node_modules/@angular/compiler/bundles/compiler.umd.js:25296:39)
    at eval (http://localhost:13244/node_modules/@angular/compiler/bundles/compiler.umd.js:25220:62)
    at Set.forEach (<anonymous>)
    at JitCompiler._compileComponents (http://localhost:13244/node_modules/@angular/compiler/bundles/compiler.umd.js:25220:19)
    at createResult (http://localhost:13244/node_modules/@angular/compiler/bundles/compiler.umd.js:25105:19)
    at ZoneDelegate.invoke (http://localhost:13244/node_modules/zone.js/dist/zone.js:334:26)
    at Zone.run (http://localhost:13244/node_modules/zone.js/dist/zone.js:126:43)
    at http://localhost:13244/node_modules/zone.js/dist/zone.js:713:57
    at ZoneDelegate.invokeTask (http://localhost:13244/node_modules/zone.js/dist/zone.js:367:31)
    at Zone.runTask (http://localhost:13244/node_modules/zone.js/dist/zone.js:166:47)
    at drainMicroTaskQueue (http://localhost:13244/node_modules/zone.js/dist/zone.js:546:35)"

A: The example on the projects github site is a little bit odd. Before you can use the library you have to import the module in your app.module.ts file.
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';

import { Ng4GeoautocompleteModule } from 'ng4-geoautocomplete';

@NgModule({
  declarations: [ your declarations ],
  imports: [
    BrowserModule,
    Ng4GeoautocompleteModule
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

From there on you should be able to use the libraries components.


text:
Q: How to resolve duplicate assigned IPs local network setup:
I have six linux embedded software-defined radios (SDR) all connected to a wireless local network. The only way to log into one of these SDRs is to SSH into it through a remote computer. IPv4 set to Automatic (DHCP). Remote device is an ubuntu 16.04.
The problem is, IP addresses are being assigned to 2 or possibly more SDRs and because of that, when I try to sign in using ssh root@foo, it will sign me into another SDR on the network (say root@bar). Or it just won't let me sign in at all. What's even more odd is when I use nmap to check how many devices are on my network, it gives me inconsistent results (sometimes 3, sometimes 4 devices connected out of the six).
I'm thinking something is going on with SSH keys or something with DHCP.
Edit: When trying to ssh into an SDR using it's appropriate hostname, I get:
      ssh: could not resolve hostname [hostname]: Name or service not known
      even though I've been able to connect to it before.


text:
Q: Singular Jonsson cardinals Is the following consistent?

$(*)$: There exists a singular cardinal $\kappa$ such that :
(1) $\kappa$ is a Jonsson cardinal,
(2) $\kappa$ is not a fixed point of the $\aleph-$function, i.e., $\kappa < \aleph_\kappa.$

If we remove the second assumption, then the answer is positive and easy:
(A):  Prikry forcing over a measurable cardinal $\kappa,$ turns $\kappa$ into a singular Jonsson cardinal, but $\kappa=\aleph_\kappa$ in such a model.
(B): If $κ$ is a singular limit of measurable cardinals, then $κ$ is
Jonsson, but again $\kappa=\aleph_\kappa$ .


text:
Q: Cypher virtual nodes to aggregate many to many relationships I have 8000 Authors nodes and 2000 book nodes. Each author has a country property and each book can be co-authored by many authors.
I am trying to show which countries have collaborated on books by grouping all authors from a country into a single virtualNode called Country. Then I would need to create a virtual relationship between countries based on the number of times each author in CountryA has published something with an Author from CountryB.
I have a few queries that are doing stuff, but can't get it quite to what I want. Here is what I have tried and the outcome:
MATCH (a1:Author)-->(p:Paper)<--(a2:Author)
WHERE a1.country <> a2.country
WITH apoc.create.vNode(['Country'], {name: a1.country}) as Country1,  apoc.create.vNode(['Country'], {name: a2.country}) as Country2, count(p) as numCollabs
RETURN DISTINCT Country1, Country2, apoc.create.vRelationship(Country1, 'COLLABORATED_WITH', {numCollabs: numCollabs}, Country2) LIMIT 25

This shows many duplicate countries ( I assume 1 for each author rather than aggregating authors ) and the numCollabs on each relationship is always 1.
I also tried this one:
MATCH (a: Author)
WITH a.country as country, count(*) as count
RETURN apoc.create.vNode(['Country'], {name: country, authors: count}) as countries

This gives me the proper number of countries and shows the number of authors in that country... however, I cannot figure out how to then create the vRelationship which will show how many times each country has worked with each other country.

A: Try this. I tried to adapt the example here to your data.
MATCH (a:Author)
WITH collect(distinct a.country) as countries
WITH [cName in countries | apoc.create.vNode(['Country'],{name:cName})] as countryNodes
WITH apoc.map.groupBy(countryNodes,'name') as countries
MATCH (a1:Author)-->(p:Paper)<--(a2:Author)
WHERE a1.country < a2.country
WITH a1.country AS countryName1,
a2.country as countryName2,
count(distinct p) as numCollabs, countries
RETURN countries[countryName1] as country1,
countries[countryName2] as country2,
apoc.create.vRelationship(countries[countryName1], 'COLLABORATED_WITH', {numCollabs: numCollabs}, countries[countryName2]) LIMIT 25


text:
Q: Pasar datos de una vista a layout - plantilla laravel Hola estoy trabajando en un proyecto en laravel5.6, soy muy nuevo haciéndolo, tengo ya la ruta y el controlador funcionando en una vista:

@extends('layouts.app')
@section('content')
 @foreach($grupos as $grupo)

{{ $grupo-> name }}

 @endforeach
@endsection

el controlador es:

Public function grupos(){
     $grupos = Grupo::orderBy('id','DESC')->where('status','PUBLISHED')->paginate();
        return view('grupo.inicio', compact('grupos'));
    }

el modelo App\Grupo es el siguiente:

<?php

namespace App;

use Illuminate\Database\Eloquent\Model;

class Grupo extends Model
{
    protected $fillable=[
  'user_id','name','slug','address','body','file','claveMapaGoogle','status'
 ];

 public function user(){
  return $this->belongsTo(User::class);
 }
}

quiero hacer que {{ $grupo-> name }} funcione en una de mis plantillas que se llama 'layouts.base'
buscando información  me sugirieron lo siguiente:
en AppServiceProvider:

   <?php

namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use App\Grupo;

class AppServiceProvider extends ServiceProvider
{
/**
 * Bootstrap any application services.
 *
 * @return void
 */
public function boot()
{
    view()->composer(['layouts.base'], function ($view) {
        $view->with('grupos', Grupo::count());
    });
}

/**
 * Register any application services.
 *
 * @return void
 */
public function register()
{
    //
}
}

pero me sale el siguiente error:

Class 'App\Providers\Grupo' not found (View: C:\xampp\htdocs\blog-radio\resources\views\web\inicio.blade.php)

Gracias de antemano. Saludos

A: El modelo Grupo existe dentro del namespace de App, por lo tanto debes invocarlo a través de su namespace para que funcione:
Agrégalo justo después de la llamada a la clase ServiceProvider
namespace App\Providers;

use Illuminate\Support\ServiceProvider;
use App\Grupo;


text:
Q: Restore Database or Restore Files? I am copying a database from a live environment to test environment.
I've made a .bak file from the live database and copied the file to the test server.
Question is, should I use "Restore Database" to add it to the test server or "Restore Files and Filegroups"?
(sometimes the database will already exist, sometimes it won't.  In either case I want to just have a clone of the original and don't care about overwriting)
After a bit of playing around it appears both achieve what I want - so what is the real difference, and does it matter which method I use for my situation?

A: Short answer - unless it's a huge SQL database and you're doing clever things with it then just ignore the filegroup backup, and stick with the database backup.
Long answer - With SQL server you have databases and filegroups, a database contains all of the data within that database and is nice and straight forward. A filegroup on the other hand contains either all or some of the data within the database. Filegroups hold the physical files (eg the mdf files) which make up the database, and in most cases there will only be one of them, normally called Primary, which will contain the one mdf used.
Now in a large installation you might find that your database mdf files are too large to fit onto one disk, so you might want to split the database across multiple mdf files, and at this point filegroups come into play. If you split all the tables which are regularly used and updated into one mdf on a fast HDD and put it in the Primary filegroup, and then put the less used tables used more for reference onto a slower HDD in a secondary filegroup, you could make best use of the system, however you might not want to bother backing up the secondary mdf, since the data within that file very rarely gets changed. You can therefore choose to do a filegroup backup instead of a complete database backup, and only backup the Primary filegroup, therefore reducing the amount of storage space required for your backup.

A: Use Restore Database if you do not need to change the file location or add other files like changing the specific location of the log files.
For what you are doing most likely a simple restore database would do the trick.


text:
Q: Error removing element from JList with DefaultListModel I have a standard JList that will be changed while the program is running. In order to make life easier I have created a DefaultListModel and assigned it to the JList:
JList CharList = new JList();
DefaultListModel CharListModel = new DefaultListModel();

CharList.setModel(CharListModel);

I am able to load a file into the list, and later I can add items to the list like this:
File ChFile = new File (CharListFile);
FileReader freeder = new FileReader (ChFile);
BufferedReader breeder = new BufferedReader(freeder);
String line;
while((line=breeder.readLine())!=null)
{
int pos = CharList.getModel().getSize();
CharListModel.add(pos, line);
}
...
...
//and to add items..
int pos = CharList.getModel().getSize();
CharListModel.add(pos, NewCharName);

However, I need to be able to remove items from the list, and this is giving me some considerable trouble!
I have tried the most obvious way (Yes an item is selected, and I have already retrieved both the index and the string at that index):
CharListModel.removeElement(CharList.getSelectedValue());

However, this gives me a 'java.lang.ArrayIndexOutOfBoundsException: -1' error.
I have tried all of the permutations that you can see in the code below (Some are commented out but you get the idea):
DefaultListModel model = (DefaultListModel) CharList.getModel();//CharListModel;
int selectedIndex = CharList.getSelectedIndex();
if (selectedIndex != -1) {
    //model.remove(selectedIndex);
    //model.removeElement(CharList.getSelectedValue());
    //model.removeElementAt(selectedIndex);
}

as well as a few other permutations as well:
CharListModel.removeElementAt(CharList.getSelectedIndex());
//or
CharListModel.remove(CharList.getSelectedIndex());
//or
CharList.remove(SelItemIndex);

In each case I get the same 'ArrayIndexOutOfBoundsException' error, even though the selected index is previously found with no trouble. And yes, I know I just said 'previously' so something could have changed things, but here is the code that runs directly before I try to remove the element:
int SelItemIndex = CharList.getSelectedIndex();
if(SelItemIndex == -1)
{
    JOptionPane.showMessageDialog(null, "You have to select something!");
    return;
}
String SelItem = CharList.getModel().getElementAt(SelItemIndex).toString();
//Create warning
final JComponent[] inputs = new JComponent[]
{
    new JLabel("<html>Bla Bla " + SelItem + " Are you sure?</html>")
};
int n = JOptionPane.showConfirmDialog( null, inputs,"Deletion Confirmation Warning", JOptionPane.YES_NO_OPTION);
if( n == 1)
{
    //Do not delete
    return;
}

That is all there is before trying to remove the selected element.
For the life of me I don't know why this is not working! Am I missing something really silly here?
A confusing update
In the ActionPerformed event of a JButton I have used this code - The comments in the code explain why this is so confusing!:
DefaultListModel CharListModel = (DefaultListModel)CharList.getModel();
if( CharListModel.contains(CharList.getSelectedValue()) == true)
{
    //Selected item is found
    int selItemIndex = CharListModel.indexOf(CharList.getSelectedValue());
    if(selItemIndex != -1)
    {
        //Selected item index is NOT -1 and is correct
        CharListModel.remove(selItemIndex);
        //Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: -1
    }
    else
    {
        //NEVER reached
        JOptionPane.showMessageDialog(null, "OUCH!");
    }
}

As you can see, the index of the selected item is correct right up to the point of removing it, whereupon I once again get the out of bounds exception. I also tried this in the same place but with the same results:
CharListModel.removeElement(CharList.getSelectedValue());

Even more confusion
In an attempt to work out what is going on I have created a new DefaultListModel, enumerated the old one, and put each name into the new model, except the one that I want to remove (Remember I can get the index, the object and the text, I just cant delete it).
This has worked and I now have a DefaultListModel with the correct items in it, however, the moment that I try to CharList.setModel(NewModel); I once again get the out of bounds exception.
This has got me pulling out hair! Can anyone offer any ideas to try?
A Resolution of sorts
Not really a resolution at all, but to work around this maddening problem I am using the method laid out above, where I create a copy of the list model, minus the item that I want to delete and then simply catch the exception when using setModel, since the updated list model is added to the list just fine, and subsequent actions such as adding items etc. work okay, right up until I try to delete an item again anyway!
Thanks if you tried to help - and if you have any ideas about how to hunt down this problem, by all means post away!
regards
Max

A: For reference, I added the code below to this example. If it's not helpful, it may be a useful sscce for updating your question.
panel.add(new JButton(new AbstractAction("Remove") {

    @Override
    public void actionPerformed(ActionEvent e) {
        int index = list.getSelectedIndex();
        if (index != -1) {
            model.remove(index);
        }
    }
}));

A: I had a similar problem. It turned out the error stemmed not from removing the element, but rather displaying the list. When implementing the
public void valueChanged(ListSelectionEvent e)

method, which updates the list on the screen, make sure to check if the model is null before you set the values. This is what caused the exceptions in my case.
Creating a list, removing from there, and then updating the model with the list is also a usable workaround.

A: I have faced the same issue. It seems when the item is removed from the model, it gets removed from the array as well. Hence is messes up the array index.
As a work around, I moved the array contents into a List and remove the List contents from the model. Now it works fine for me.

A: I have the same problem, i fix this doing that:
Button Action
int index = mylist.getSelectedIndex();
MyObject = (MyObject) mylist.getSelectedValue();
int Size = mylistmodel.getSize();
if (index >= 0 && MyObject != null && Size > 0) {
    modeloLista.removeElementAt(indice);
}

And.
listValueChanged
if (list.getSelectedValue() != null) {
    your code..
}


text:
Q: Django query count wrong I have a model (called MyModel here) where I do
MyModel.objects.filter(value__exact='').delete()

to delete all objects with a blank value (value is a TextField with blank=True).
However there seem to disappear more objects when I do this, than the count I get before deleting with
MyModel.objects.filter(value__exact='').count()

If I count blank valued MyOModel objects with a loop, using
count = 0
for obj in MyModel.objects.iterator():
    if not obj.value or obj.value.strip() == '':
        count += 1

I only get very few extra objects, compared tothe above count.
What can cause this?
I have checked related models that are referencing MyModel if they could cascade and somehow delete instances of MyModel without blank values. This is not the case.
I'm on Django 1.8.7.
UPDATE
To add to the mysticism I have now tried to delete in a for loop:
count = 0
for attribute_value in AttributeValue.objects.filter(value__exact=''):
    attribute_value.delete()
    count += 1

The count variable comes out with the expected number of deleted MyModel objects, but still
MyModel.objects.filter(value__exact='').count()

comes out with a lower number than expected. In fact it seems like there was deleted more than three times the number of objects expected.
I have also tried the following for the count (see comments)
MyModel.objects.filter(value='').count()
MyModel.objects.filter(value=u'').count()

with same results for counts.

A: This will sort your problem
from django.db.models.functions import Length

To get all the value fields which contain something
MyModel.objects.annotate(value_length=Length('value')).filter(value_length=0)

To get all the values which are not null
MyModel.objects.annotate(value_length=Length('value')).filter(value_length__gt=0)
You can also do this way
MyModel.objects.filter(value='',value__isnull=True)

A: I found the culprit in another model with an unnoticed foreign to MyModel. The reason why I didn't look there was that this model in my setup is references by MyModel too, and PyCharm somehow missed the relation (or I did in the PyCharm GUI). The new version of PyCharm which just came now fixed it for me.
Sorry for the confusion.


text:
Q: handle listview with button i have a listview and button on the list how can i use both button.setonclicklistener and onListItemClick in listview

A: I had the same issue.But while adding button's onClick event to adapter,it was not able to listen to the list item's click event.so I used image instead of a button and then registered its click event in adapter,and that was working nicely.

A: Set the button.setOnCLickListener in your getView() method of the adapter.


text:
Q: Regular expression should not match a specific word with all possibilities My expression should not match a specific word which is "COUNTY" and gives you an error. I have a regular expression as
*[^\s].*[^(!?.*!?county|!?County|!?COUNTY)$.*]

which doesn't work properly.
This is my regular expression
*[^\s].*[^(!?.*!?county|!?County|!?COUNTY)$.*]

but it gives me an error when the string is test1 county but not for county test1, test1 county test2
Valid string:

*

*LAs Vegas parkway or empty string/no data

Invalid string

*

*County Las vegas Parkway

*Las vegas county Parkway

*Las vegas parkway COUNTY

A: This will help you:
((.*)(?:COUNTY|County|county)(.*)?)

And call group $2$3
See this link: https://regex101.com/r/HgC3DG/1
OR
Use
(.*)(?:COUNTY|County|county)(.*)?

And call group $1$2
See link: https://regex101.com/r/HgC3DG/2
For XSD use this:
^((?!County)(?!COUNTY)(?!county).)*$

See link: https://regex101.com/r/gfd0DK/1


text:
Q: Listing all shared drives from Google drive I am trying to list all shared drives from googledrive using List drive java method.
this is my code.
public static void getDriveId(String folderName, String oauthToken) throws Exception {
            DriveList list ;
            String pageToken = null;
            GoogleCredential credential = new GoogleCredential();
            credential.setAccessToken(oauthToken);
            try {
                _driveService = new Drive.Builder(GoogleNetHttpTransport.newTrustedTransport(), JacksonFactory.getDefaultInstance(), credential).setApplicationName(appName).build();
            } catch (GeneralSecurityException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            list = _driveService.drives().list().setQ(folderName).setFields("nextPageToken, drives(id, name)")
                 .execute();
        System.out.println(list.toString());
        }

I am setting Q parameter in query where foldername= "salesDrive"
Its giving me error like
Caused by: com.google.api.client.googleapis.json.GoogleJsonResponseException: 400 Bad Request
{
  "code" : 400,
  "errors" : [ {
    "domain" : "global",
    "location" : "q",
    "locationType" : "parameter",
    "message" : "Invalid Value",
    "reason" : "invalid"
  } ],
  "message" : "Invalid Value"
}

How can i set this q parameter inorder to display only specific shared drive details?

A: You are missing two things:

*

*It is not enough to just provide foldername, you should specify name = 'foldername' (please keep in mind that it should the name of the shared Drive, not a folder contained in this Drive)

*As mentioned in the documentation:

To search for a specific set of shared drives, set the useDomainAdminAccess parameter to true

Missing out on any of the steps above will result in an 400 error, as the one you received.


text:
Q: Flutter retrieval of data broken when using session? This is how i view the result from php.

final String uri =
'My PHP FILE';
Future<List<Dbjobs>> dbgetdbusers() async {
var response = await http.get(uri);
if (response.statusCode == 200) {
final items = json.decode(response.body).cast<Map<String, dynamic>>();
List<Dbjobs> dbusers = items.map<Dbjobs>((json) {
return Dbjobs.fromJson(json);
}).toList();
print(dbusers);
return dbusers;
} else {
throw Exception('Failed to load data.');
}
}
@override
Widget build(BuildContext context) {
return FutureBuilder<List<Dbjobs>>(
future: dbgetdbusers(),
builder: (context, snapshot) {
if (!snapshot.hasData)
return Center(child: CircularProgressIndicator());
return ListView(
children: snapshot.data
.map((data) => Column(
children: <Widget>[
GestureDetector(
onTap: () {
Navigator.push(
context,
MaterialPageRoute(
builder: (context) => JobDetails()));
},
child: Column(
children: <Widget>[
Container(
color: Colors.grey,
child: Column(
children: <Widget>[
Align(
alignment: Alignment.topLeft,
child: Text(
data.dateCreated,
style: TextStyle(fontSize: 30.0),
),
),

My Login Php

<?php
session_start();
include 'testConz.php';
$username = $_POST['Username'];
$password =md5($_POST['Password']);
$Consult = $connect -> query("SELECT * FROM tuser_ppim WHERE LoginName = '$username' and Password = '$password' ");
$Result = array();
while ($extractData=$Consult->fetch_assoc()) {
$Result[] = $extractData;
}
$ID = $Result['0']['ID'];
$_SESSION['$Consult'] = $Result;
echo json_encode($Result);
?>
>

This php file works with flutter, there are results based on the query.
<?php
session_start();
include 'testConz.php';
$Consult1=$connect->query("
SELECT * FROM tjob WHERE AssignedTo = '6';
");
$Outcome1 = array();
while ($extractData=$Consult1->fetch_assoc()) {
$Outcome1[] = $extractData;
}
echo json_encode($Outcome1);
?>
>

This one makes my screen loads with no result. any ideas?
<?php
session_start();
include 'testConz.php';
$userDetails = $_SESSION['$Consult'];
$SesID = $userDetails['0']['ID'];
$Consult1=$connect->query("
SELECT * FROM tjob WHERE AssignedTo = ".$SesID.";
    ");
$Outcome1 = array();
while ($extractData=$Consult1->fetch_assoc()) {
$Outcome1[] = $extractData;
}
echo json_encode($Outcome1);
echo json_encode($userDetails);
?>
>

BTW both produces the number for AssignedTo is equal 6
AND
Both produces the same result when in browser. but when it is in flutter screen the other one has no result.
Thank you!


text:
Q: EC2 r3 8xlarge EBS limit We have a r3.8xlarge SQL 2014 instance. We have attached 2 EBS volumes (each of 5 TB) to this instance.
We need another 5TB volume that we plan to attach to this SQL instance.
Is there a limit on how many EBS volumes can be attached or total EBS storage limit that can be attached to an EC2 e.g. not exceeding 15 TB or some best practice?
For our scenario, we expect the instance to be running only against one EBS volume at a given time.
thanks