Q: MongoDB - Find first and last in the embedded array for a single matching document I have a collection of websites, which each contain a list of websites and their keywords that are being tracked. I also have another collection called "rankings" which for each of the keywords in the website contains a ranking. The collection so far looks like this:
{
    "_id" : ObjectId("58503934034b512b419a6eab"),
    "website" : "https://www.google.com",
    "name" : "Google",
    "keywords" : [
        "Search",
        "Websites",
    ],
    "tracking" : [
        {
            "_id" : ObjectId("5874aa1df63258286528598d"),
            "position" : 0,
            "created_at" : ISODate("2017-01-1T09:32:13.831Z"),
            "real_url" : "https://www.google.com",
            "keyword" : "Search"
        },
        {
            "_id" : ObjectId("5874aa1ff63258286528598e"),
            "keyword" : "Search",
            "real_url" : "https://www.google.com",
            "created_at" : ISODate("2017-01-2T09:32:15.832Z"),
            "found_url" : "https://google.com/",
            "position" : 3
        },
        {
            "_id" : ObjectId("5874aa21f63258286528598f"),
            "keyword" : "Search",
            "real_url" : "https://www.foamymedia.com",
            "created_at" : ISODate("2017-01-3T09:32:17.017Z"),
            "found_url" : "https://google.com/",
            "position" : 2
        },

        {
            "_id" : ObjectId("5874aa21f63258286528532f"),
            "keyword" : "Websites",
            "real_url" : "https://www.google.com",
            "created_at" : ISODate("2017-01-1T09:32:17.017Z"),
            "found_url" : "https://google.com/",
            "position" : 1
        },

         {
            "_id" : ObjectId("5874aa21f63258286528542f"),
            "keyword" : "Websites",
            "real_url" : "https://www.google.com",
            "created_at" : ISODate("2017-01-1T09:32:17.017Z"),
            "found_url" : "https://google.com/",
            "position" : 2
        },

    ]
}

What I want to do is:
1) Group all of the keywords together by their keyword
2) Find the starting position (at the very start of the month)
3) Find the current position (as of today)
So in theory I want to be given an object like:
{
    "_id" : ObjectId("58503934034b512b419a6eab"),
    "website" : "https://www.google.com",

    "tracking" : [
       {
           "_id" : ObjectId("5874aa1df63258286528598d"),
           "keyword": "Search",
           "start_position": 0,
           "todays_position": 3,

       },

        {
           "_id" : ObjectId("5874aa1df63258286528598d"),
           "keyword": "Website",
           "start_position": 0,
           "todays_position": 2,

       },

    ]

I am confused about how to do the grouping on another field, though. I have tried the following so far:
db.getCollection('websites').aggregate([

    {
        $lookup: {
            from: "seo_tracking",
            localField: "website",
            foreignField: "real_url",
            as: "tracking"
        }
    },

    {
        $match: {
            "_id" : ObjectId("58503934034b512b419a6eab")
        }
    },

    {
        $group: {
            "_id" : "$_id",
            "keyword" : {
                $first: "$tracking.keyword",
            },
        }
    }

]);

But this is not grouping by the keyword, nor can I figure out how I would get the expected value.

A: You can try something like this. $unwind the tracking array followed by $sort on tracking.keyword and tracking.created_at. $group by tracking.keyword and $first to get starting position,  $avg to get average position and $last to get the today's position. Final $group to roll up everything back to tracking array.
db.website.aggregate([{
    $match: {
        "_id": ObjectId("58503934034b512b419a6eab")
    }
}, {
    $lookup: {
        from: "seo_tracking",
        localField: "website",
        foreignField: "real_url",
        as: "tracking"
    }
}, {
    $unwind: "$tracking"
}, {
    $sort: {
        "tracking.keyword": 1,
        "tracking.created_at": -1
    }
}, {
    $group: {
        "_id": "$tracking.keyword",
        "website": {
            $first: "$website"
        },
        "website_id": {
            $first: "$_id"
        },
        "avg_position": {
            $avg: "$tracking.position"
        },
        "start_position": {
            $first: "$tracking.position"
        },
        "todays_position": {
            $last: "$tracking.position"
        }
    }
}, {
    $group: {
        "_id": "$website_id",
        "website": {
            $first: "$website"
        },
        "tracking": {
            $push: {
                "keyword": "$_id",
                "avg_position":"$avg_position",
                "start_position": "$start_position",
                "todays_position": "$todays_position"
            }
        }
    }
}]);


Q: using react-native webview component, can the website access the camera and audio of the device? I am unable to get the web-view component in React Native to access the device camera and audio when loading a html5 website that requires camera/audio to take a video via the front-facing camera.
I have tried using the solution from https://github.com/facebook/react-native/issues/11610 however, the web-view still cannot access the camera/audio function
<View style={{flex: 1,backgroundColor:color.main_background}}>
  <NavBar navigation={this.props.navigation}>

   <WebView
      source={{uri:url }}
      javaScriptEnabled={true}
      />
 </NavBar>
</View>

A: If you can base64 serialize the data, then seems like you should be able to use this component to send data to your Webview. Not sure how performant it would be though.
https://github.com/R1ZZU/react-native-webview-messaging


Q: Linux semaphores I'm looking for help with synchronization problem in Linux. I'm newbie, and I think I don't really understand how to use semaphores to synchronize. My task is to sync two processes that access a file - one reads from fifo from another process, writes to this file, then another reads. I know that my code lacks synchronization, but i have no clue how to do this.
Code:
sem_t writer, reader;
    void readFromFifoSendToFile(void) {
         sem_init(&writer, 1, 1);
         FILE *fp;
         char buffer[100];
         FILE *file;
         file = fopen("file", "w+");
         fclose(file);

         while(1) {
                  sem_wait(&writer);
                  fp = fopen("fifo", "r");
                  fscanf(fp, "%s", buffer);
                  fclose(fp);
                  file = fopen("file", "a+");
                  fputs(buffer, file);
                  fclose(file);
                  sem_post(&writer);
         }
    }

    void readFromFileAndPrint(void) {
         sem_init(&reader, 1, 1);
         FILE *fp;
         char buffer[100];
         int counter = 0;

         while(1) {
                  sem_wait(&reader);
                  counter++;
                  if(counter == 1) {
                      sem_wait(&writer);
                  sem_post(&reader);
                  fp = fopen("file", "r");
                  fscanf(fp, "%s", buffer);
                  fclose(fp);
                  printf("%s", buffer);
                  sem_wait(&reader);
                  if(counter == 0) {
                      sem_post(&writer);
                  }
                  sem_post(&reader);
         }
    }

A: Your main problem appears to be related to the concept of how a semaphore works.  Semaphores are best viewed as a signal between a producer and consumer.   When the producer have done something they post a signal on the semaphore, and the consumer will wait on the semaphore until the producer post a signal.
So in your case, there should only be one semaphore between the consumer and the producer -- they should share this semaphore for their synchronization. Also, the semaphore should start at the value zero since nothing have been produced yet.  Every time the producer post to the semaphore the value will increase by one,  the consumer when it waits on the semaphore will sleep if the value is zero, until such a time when the producer post and the value increases and becomes one.   If the producer is much faster than the consumer the value of the semaphore can go up and be more than one which is fine, as long as the consumer is consuming the output in the same size of units as the producer produces them.
So a working example here, but without any error handling -- adding error handling is beyond the scope of this -- I have used threads but you can do the same with processes as long as you can share the semaphore between them
#include <semaphore.h>
#include <pthread.h>
#include <stdio.h>
#include <unistd.h>

sem_t thereBeData;

void* readFromFifoSendToFile(void*) {

    FILE *fp = stdin;
    char buffer[100];
    FILE *file;

    file = fopen("file", "a+");

    while(1) {
       fscanf(fp, "%s", buffer);

       fprintf(file,"%s\n",buffer);
       fflush(file);

       sem_post(&thereBeData); // signal the consumer
    }
}

void* readFromFileAndPrint(void*) {
    FILE *fp = 0;
    char buffer[100];
    int counter = 0;

    while(1) {
       sem_wait(&thereBeData); // Waiting for the producer

       if (!fp) fp = fopen("file", "r");
       fscanf(fp, "%s", buffer);

       printf("%s\n", buffer);
    }
}

int main(void)
{
    pthread_attr_t attr;
    pthread_t thread1;
    pthread_t thread2;

    sem_init(&thereBeData, 0,0);
    pthread_attr_init(&attr);
    pthread_create(&thread1, &attr, readFromFifoSendToFile, (void*)0);
    pthread_create(&thread2, &attr, readFromFileAndPrint, (void*)0);

    sleep(10);
}


Q: Getting associated models with $this->Auth in Cakephp I am using CakePHP 2.0's integrated Auth component.
I have the following tables :

*

*Users

*Groups

*Profiles

My model relations are as follows:
User belongsTo Group
User hasMany Profiles

While logged in to the site, I noticed the Auth session contains only User table information, but I need the information of Groups and Profiles tables too for the logged in user.
Is there any way to do that with the Auth component?

A: There is no way to do this with the AuthComponent because of the way it handles the session keys. You can, however, just save it to the session yourself.
The only way to do this is to add to the session when the user logs in:
function login() {
    if ($this->Auth->login($this->data)) {
        $this->User->id = $this->Auth->user('id');
        $this->User->contain(array('Profile', 'Group'));
        $this->Session->write('User', $this->User->read());
    }
}

Then in your beforeFilter() in your AppController, save a var for the controllers to get to:
function beforeFilter() {
    $this->activeUser = $this->Session->read('User');
}

// and allow the views to have access to user data
function beforeRender() {
    $this->set('activeUser', $this->activeUser);
}

Update: As of CakePHP 2.2 (announced here), the AuthComponent now accepts the 'contain' key for storing extra information in the session.

A: As far as I'm aware the Auth component only caches the data from your Users model. You can use that information to retrieve the desired data from the other models, by for example using this in your controller:
$group_data = $this->Group->findById($this->Auth->user('group_id'));

Or
$profile_data = $this->Profile->findByUserId($this->Auth->user('id'));

But I don't think you can get it from the Auth component directly, as it doesn't cache the related model data out of the box.

A: Two ways:
1) Extend the FormAuthenticate class (see /Controller/Component/Auth) or whatever you use to login and override the _findUser() method and tell the Auth component to use this authorize class. See this page how to do all of that http://book.cakephp.org/2.0/en/core-libraries/components/authentication.html
2) Simply implement a method in the model that will fetch all data you want and call it in the  login method of your controller and write the data into the session. IMO it is handy to have such a method because sometimes you need to refresh the session data anyways.
Because of your comment on the other answer:
You will have to write a method and some code in a model that will return you the data. CakePHP can't read your mind and a database without code. No matter which of both suggested ways you're going to use, you'll have to write code.


Q: "extended initializer lists only available with -std=c++11 or -std=gnu++11", I'm Getting this error #include <iostream>
#include <vector>

using namespace std;

int main(){
    vector <int> num = {2,3,4};
    return 0;
}

A: Below style of initialization is only introduced in C++ 11.
vector <int> num = {2,3,4};

This is not available in initial C++ version. That is what your gcc compiler is complaining. You need to tell the compiler to use C++11 version. Use below command.
g++ -std=c++11 myProgram.cpp


Q: How to change the color of a specific pixel of an image in Android? I'm quite new to Android and am doing my own mini-project and I want to change a specific pixel's color. searching for how to do so, I came across this question from a couple of years back. I tried myBitmap.setPixel(10, 10, Color.rgb(45, 127, 0));, but when I am actually activating it on my phone, it just crashes the second I activate this line of code. It seems to crash whenever I'm interacting with the bitmap. int x =myBitmap.getHeight(); this line also crashes the app.
Yet, the initial creation of the bitmap doesn't cause any problems:
background = (ImageView) findViewById(R.id.dangeon);
background.setDrawingCacheEnabled(true);
background.buildDrawingCache(true);
dang = background.getDrawingCache();

Do I have to install any package or activate anything to use the setPixel or getHeight functions? Alternatively, is there any other way to change a specific pixel?
logcat error when trying @jayanth suggestion:
2021-10-09 20:23:18.276 24894-24894/Aviv.Aviv E/AndroidRuntime: FATAL EXCEPTION: main
Process: Aviv.Aviv, PID: 24894
java.lang.NullPointerException: Attempt to invoke virtual method 'android.graphics.Bitmap android.graphics.Bitmap.copy(android.graphics.Bitmap$Config, boolean)' on a null object reference
at Aviv.Aviv.MainActivity.onClick(MainActivity.java:247)
at android.view.View.performClick(View.java:7339)
at android.view.View.performClickInternal(View.java:7305)
at android.view.View.access$3200(View.java:846)
at android.view.View$PerformClick.run(View.java:27787)
at android.os.Handler.handleCallback(Handler.java:873)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7089)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:494)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:965)

A: If you are trying setPixel() method on the immutable bitmap. it will throw a IllegalStateException.
first, create a mutable copy of your bitmap. and then you can change the color of the pixel in your bitmap.
Bitmap mutableBitmap = bitmap.copy(Bitmap.Config.ARGB_8888, true);
int red = 255; //replace it with your color
int green = 255; //replace it with your color
int blue = 255; //replace it with your color
int color = Color.argb(0xFF, red, green, blue);
mutableBitmap.setPixel(indexI, indexJ, color);
//now if you apply it to any image view to see change.
imageView.setImageBitmap(mutableBitmap);


Q: Model validation with viewModel don't works I use viewModels to communicate between my controller and my view.
To get model validation, i use a partial class like this :
[MetadataType(typeof(EvaluationValidation))]
public partial class Evaluation
{
    public class EvaluationValidation
    {
        [DisplayName("Title of evaluation")]
        [Required( ErrorMessage="Please give a title")]
        public string Title { get; set; }
    }
}

The Displayname is binded to view with no problem but when i try to submit the view, i get this error :

The model item passed into the
  dictionary is of type
  'FOOBAR.Models.Evaluation',
  but this dictionary requires a model
  item of type
  'FOOBAR.Areas.Evaluation.ViewModels.EvaluationFormViewModel'.

This is the code used in my controller
    [HttpPost]
    public ActionResult Create(FormCollection formValues)
    {
        Models.Evaluation data = new Models.Evaluation();
        if (TryUpdateModel(data, "evaluations"))
        {
            this.daoe.Create(data);
            return RedirectToAction("Index");
        }
        return View(data);
    }

And this is my viewModel
public class EvaluationFormViewModel
{
    public FOOBAR.Models.Evaluation evaluations;
    public SelectList selectlist_evaluationtypes { get; set; }
    public SelectList selectlist_evaluationstatus { get; set; }
}

Have you got an idea ?
Thank's by advance

A: You are passing a Models.Evaluation instance to your view, which is bound to a model of another type.
Models.Evaluation data = new Models.Evaluation();
if (TryUpdateModel(data, "evaluations"))
{
   // ...
}
return View(data);

If TryUpdateModel returns false (which happens when the form does not pass validation, for example), you are effectively passing data to the View, which is of type Models.Evaluation.
Try mapping it to type FOOBAR.Areas.Evaluation.ViewModels.EvaluationFormViewModel before passing it to the view.


Q: Difference between these 2 pieces of code for pre-flight in NodeJS Express First of all, I am a beginner with NodeJS, I am just watching some tutorials to get my feet wet: this question will probably sound very silly to anyone who has any Node experience.
In short, I am trying to allow pre-flight requests on my server, and the docs suggest I do this before my routes:
app.use(cors());

app.options('*', cors());

The tutorial I am following, on the other hand, proposes this:
app.use(cors())

app.options("*", (req, res, next) => {
  res.header("Access-Control-Allow-Origin", "*");
  res.header("Access-Control-Allow-Methods", "GET, PUT, POST, OPTIONS");
  res.header("Access-Control-Allow-Headers", "Authorization, Content-Length, X-Requested-With");
})

So, what is the difference between these 2 pieces of code?
My current hypothesis is that
app.options('*', cors());

and
res.header("Access-Control-Allow-Origin", "*");

are equivalent, but I am not sure

A: TL;DR yes, is the same
This cors() is from cors package.

CORS is a node.js package for providing a Connect/Express middleware that can be used to enable CORS with various options.

Basically is just a beautiful way to enable cors in routes with middleware.
You can check in source code to see how it works, and check documentation other usage ways

A: The second one allows you to set custom values for the allowed origin/methods/headers, but the CORS middleware actually supports this anyway - see the "Configuration Options" section on this page.
To explain a bit what's going on here:

*

*app.use(cors()) means "use the cors() middleware for all methods and all paths".

*app.options('*', cors()) means "use the cors() middleware for the OPTIONS method, for all paths (*)".

*app.options('*', (req, res, next) => { /* ... */ }) means "use the provided function as a middleware for all OPTIONS requests, for all paths (*)".


Q: What would be the fastest method? I'm building a dashboard using ASP.Net MVC, Angular.js, SQL Server and Fusion charts. All my data for charting is stored in database and I'm getting them via stored procedure. Now I need to pass the results from stored procedure to Json/XML, only formats Fusion Charts supports. What would be the best method to convert this data:
Hour Input   Output  InTarget  OutTarget
7    22314   18537    6500      4875
8    36395   29931    6500      4875
9    32661   28518    6500      4875
10   34895   29793    6500      4875
11   30300   26538    6500      4875
12   31011   26898    6500      4875
13   16363   13716    6500      4875

into this Json?
{
                "chart": {
                    "caption": "Input and Output",
                    "numberprefix": "$",
                    "plotgradientcolor": "",
                    "bgcolor": "FFFFFF",
                    "showalternatehgridcolor": "0",
                    "divlinecolor": "CCCCCC",
                    "showvalues": "0",
                    "showcanvasborder": "0",
                    "canvasborderalpha": "0",
                    "canvasbordercolor": "CCCCCC",
                    "canvasborderthickness": "1",
                    "yaxismaxvalue": "30000",
                    "captionpadding": "30",
                    "yaxisvaluespadding": "15",
                    "legendshadow": "0",
                    "legendborderalpha": "0",
                    "palettecolors": "#f8bd19,#008ee4,#33bdda,#e44a00,#6baa01,#583e78",
                    "showplotborder": "0",
                    "showborder": "0"
                },
                "categories": [
                    {
                        "category": [
                            {
                                "label": "7"
                            },
                            {
                                "label": "8"
                            },
                            {
                                "label": "9"
                            },
                            {
                                "label": "10"
                            },
                            {
                                "label": "11"
                            },
                            {
                                "label": "12"
                            },
                            {
                                "label": "13"
                            }
                        ]
                    }
                ],
                "dataset": [
                    {
                        "seriesname": "Input",
                        "data": [
                            {
                                "value": "22314"
                            },
                            {
                                "value": "36395"
                            },
                            {
                                "value": "32661"
                            },
                            {
                                "value": "34895"
                            },
                            {
                                "value": "30300"
                            },
                            {
                                "value": "31011"
                            },
                            {
                                "value": "16363"
                            }
                        ]
                    },
                    {
                        "seriesname": "Output",
                        "data": [
                            {
                                "value": "18537"
                            },
                            {
                                "value": "29931"
                            },
                            {
                                "value": "28518"
                            },
                            {
                                "value": "29793"
                            },
                            {
                                "value": "26538"
                            },
                            {
                                "value": "26898"
                            },
                            {
                                "value": "13716"
                            }
                        ]
                    },
                    {
                        "seriesname": "InTarget",
                        "renderas": "Line",
                        "data": [
                            {
                                "value": "6500"
                            },
                            {
                                "value": "6500"
                            },
                            {
                                "value": "6500"
                            },
                            {
                                "value": "6500"
                            },
                            {
                                "value": "6500"
                            },
                            {
                                "value": "6500"
                            },
                            {
                                "value": "6500"
                            }
                        ]
                    },
                    {
                        "seriesname": "OutTarget",
                        "renderas": "Line",
                        "data": [
                            {
                                "value": "4875"
                            },
                            {
                                "value": "4875"
                            },
                            {
                                "value": "4875"
                            },
                            {
                                "value": "4875"
                            },
                            {
                                "value": "4875"
                            },
                            {
                                "value": "4875"
                            },
                            {
                                "value": "4875"
                            }
                        ]
                    }
                ]
            }

What I'm thinking to do is:

*

*stored procedure into datatable

*put each column into separate array

*convert array to Json in the format below

Is this going to be the best (performance) approach?
EDIT:
        public Series[] GetGraphData(string sp)
    {
        var connection = ConfigurationManager.ConnectionStrings["EFDbContext"].ConnectionString;
        using (var da = new SqlDataAdapter("exec " + sp, connection))
        {
            var dt = new DataTable();

            da.Fill(dt);
            da.FillSchema(dt, SchemaType.Mapped);

            Series[] arrSeries = new Series[dt.Columns.Count];

            foreach(DataColumn dc in dt.Columns)
            {
                if (dc.Ordinal == 0)
                {
                  //Category here
                }
                else
                {
                    var strarr = dt.Rows.Cast<DataRow>().Select(row => row[dc.Ordinal]).ToList();

                    Series s = new Series()
                    {
                        seriesname = dc.ColumnName,
                        renderas = "Line",
                        data = strarr.Select(o => new SeriesValue { value = o.ToString() }).ToList()
                    };

                    arrSeries[dc.Ordinal] = s;
                }
            }

            return arrSeries;
        }
    }

A: I would load all the data into a datatable as you said, then have a Series object:
class Series{
  public string seriesname{get;set;}
  public string renderas{get;set;}
  public IList<SeriesValue> data{get;set;}
}

class SeriesValue{
  public string value{get;set;}
}

and return an array of Series to the frontend, serialized as JSON. Then you have the dataset array already built and you don't need to do any other processing on it.
I expect the performance bottleneck to be in loading the data from the db and sending it to the client .. the actual conversion to json shouldn't matter in the grand scheme of things.


Q: How to filter the apps that show up when sharing intent Android? I know this has been asked before and I reference one of the answers but I can't get my code to work the way it should. I have a simple note-taking app, which allows the user to share notes through external applications. The code is supposed to filter the apps so the user can only share to facebook, twitter, mms, gmail, and email (so I thought). I took it from the top answer here How to filter specific apps for ACTION_SEND intent (and set a different text for each app). When I click on the button that launches the method to share intents, I do get mms, gmail, facebook twitter, and email, but I also get google drive, android beam, evernote, twitter direct message, facebook messenger and snapchat.
The only apps that the information gets sent correctly to are mms, email and gmail. Facebook doesn't work, there's some comments below on why, and twitter I'm not sure of because I don't have an account to test it out. I don't have the code to check if the packageName contains "drive" or "googledrive", but I can still share to drive and the data from my note gets passed along. I want to be able to send the note text and the note title however (2 editText fields in my app), but I don't know how to since I don't know what the package name is.
For the apps that don't work or I want to remove from the list of choices, how can I get rid of them? Here is the code:
public void sendNote(View view) {
    Resources resources = getResources();

    Intent emailIntent = new Intent();
    emailIntent.setAction(Intent.ACTION_SEND);
    // Native email client doesn't currently support HTML, but it doesn't hurt to try in case they fix it
    emailIntent.putExtra(Intent.EXTRA_TEXT, titleEditor.getText().toString());
    emailIntent.putExtra(Intent.EXTRA_SUBJECT, noteEditor.getText().toString());
    emailIntent.setType("message/rfc822");

    PackageManager pm = getPackageManager();
    Intent sendIntent = new Intent(Intent.ACTION_SEND);
    sendIntent.setType("text/plain");

    Intent openInChooser = Intent.createChooser(emailIntent, titleEditor.getText().toString() + ": " + noteEditor.getText().toString());

    List<ResolveInfo> resInfo = pm.queryIntentActivities(sendIntent, 0);
    List<LabeledIntent> intentList = new ArrayList<LabeledIntent>();
    for (int i = 0; i < resInfo.size(); i++) {
        // Extract the label, append it, and repackage it in a LabeledIntent
        ResolveInfo ri = resInfo.get(i);
        String packageName = ri.activityInfo.packageName;
        if(packageName.contains("android.email")) {
            emailIntent.setPackage(packageName);
        } else if(packageName.contains("twitter") || packageName.contains("facebook") || packageName.contains("mms") || packageName.contains("android.gm")) {
            Intent intent = new Intent();
            intent.setComponent(new ComponentName(packageName, ri.activityInfo.name));
            intent.setAction(Intent.ACTION_SEND);
            intent.setType("text/plain");
            if(packageName.contains("twitter")) {
                intent.putExtra(Intent.EXTRA_TEXT, titleEditor.getText().toString() + ": " + noteEditor.getText().toString());
            } else if(packageName.contains("facebook")) {
                // Warning: Facebook IGNORES our text. They say "These fields are intended for users to express themselves. Pre-filling these fields erodes the authenticity of the user voice."
                // One workaround is to use the Facebook SDK to post, but that doesn't allow the user to choose how they want to share. We can also make a custom landing page, and the link
                // will show the <meta content ="..."> text from that page with our link in Facebook.
                intent.putExtra(Intent.EXTRA_TEXT, titleEditor.getText().toString() + ": " + noteEditor.getText().toString());
            } else if(packageName.contains("mms")) {
                intent.putExtra(Intent.EXTRA_TEXT, titleEditor.getText().toString() + ": " + noteEditor.getText().toString());
            } else if(packageName.contains("android.gm")) { // If Gmail shows up twice, try removing this else-if clause and the reference to "android.gm" above
                intent.putExtra(Intent.EXTRA_TEXT, noteEditor.getText().toString());
                intent.putExtra(Intent.EXTRA_SUBJECT, titleEditor.getText().toString());
                intent.setType("message/rfc822");
            }
            //else if (packageName.contains("drive")) {
                //intent.putExtra(Intent.EXTRA_TEXT, titleEditor.getText().toString() + ": " + noteEditor.getText().toString());
            //}
            else {

            }

            intentList.add(new LabeledIntent(intent, packageName, ri.loadLabel(pm), ri.icon));
        }
    }

    // convert intentList to array
    LabeledIntent[] extraIntents = intentList.toArray( new LabeledIntent[ intentList.size() ]);

    openInChooser.putExtra(Intent.EXTRA_INITIAL_INTENTS, extraIntents);
    startActivity(openInChooser);
}

I have an else if near the bottom that is commented out. That was my attempt in finding the google drive packageName and sending the intent so the user can still use that application, it didn't work. Like I said earlier, drive gets information sent to it, but it's just the note text, not the title and text like I want it to be.
So I have 2 questions.

*

*How can I filter out all of the apps that I don't want the user to be able to send information to so they don't even show up as an option, lets take twitter for example.

*If the above is not possible, how can I find the package names for these different apps? For Google Drive, I tried using the commented out else if statement to send an intent to the app there but it never executed. I've searched everywhere to get intents for google drive but I can't get the package name to get my code working.
Thanks in advance


Q: getting sum using sql with multiple conditions I m having data in columns as: -
  Process   Volume      TAT
  1            1        Pass
  1            2        Fail
  2            5        Fail
  2            5        Pass
  3            1        Pass
  4            6        Fail
  4            4        Pass

Now grouping by Process, i want the sum of volume (not taking into account whatever TAT), sum of volume where TAT  = Pass, sum of Volume where TAT = Fail.
Like this
Process     Total Volume    Volume(TAT=Pass)    Volume(TAT = Fail)
1           3               1                   2
2           10              5                   5
...
...

A: For SQL Server, you can use CASE expressions to conditionally determine the amount you need to add, then SUM them together, like this:
SELECT Process, SUM(Volume) AS TotalVolume,
    SUM(CASE WHEN TAT = 'Pass' THEN Volume ELSE 0 END) AS Pass,
    SUM(CASE WHEN TAT = 'Fail' THEN Volume ELSE 0 END) AS Fail
FROM (
     -- Dummy data here for testing
    SELECT 1 AS Process, 1 as Volume, 'Pass' AS TAT
    UNION SELECT 1, 2, 'Fail'
    UNION SELECT 2, 5, 'Fail'
    UNION SELECT 2, 5, 'Pass'
    UNION SELECT 3, 1, 'Pass'
    UNION SELECT 4, 6, 'Fail'
    UNION SELECT 4, 4, 'Pass'
) MyTable
GROUP BY Process
ORDER BY Process

For Microsoft Access, CASE isn't supported, so you can use SWITCH or IIF, like so:
SUM(IIF(TAT = 'Pass', Volume, 0)) AS Pass


Q: Deleting rows based on multiple columns conditions Given the following table have, I would like to delete the records that satisfy the conditions based on the to_delete table.
data have;
infile datalines delimiter="|";
input id :8. item :$8. datetime : datetime18.;
format datetime datetime18.;
datalines;
111|Basket|30SEP20:00:00:00
111|Basket|30SEP21:00:00:00
111|Basket|31DEC20:00:00:00
111|Backpack|31MAY22:00:00:00
222|Basket|31DEC20:00:00:00
222|Basket|30JUN20:00:00:00
;

+-----+----------+------------------+
| id  |   item   |     datetime     |
+-----+----------+------------------+
| 111 | Basket   | 30SEP20:00:00:00 |
| 111 | Basket   | 30SEP21:00:00:00 |
| 111 | Basket   | 31DEC20:00:00:00 |
| 111 | Backpack | 31MAY22:00:00:00 |
| 222 | Basket   | 31DEC20:00:00:00 |
| 222 | Basket   | 30JUN20:00:00:00 |
+-----+----------+------------------+

data to_delete;
infile datalines delimiter="|";
input id :8. item :$8. datetime : datetime18.;
format datetime datetime18.;
datalines;
111|Basket|30SEP20:00:00:00
111|Backpack|31MAY22:00:00:00
222|Basket|30JUN20:00:00:00
;

+-----+----------+------------------+
| id  |   item   |     datetime     |
+-----+----------+------------------+
| 111 | Basket   | 30SEP20:00:00:00 |
| 111 | Backpack | 31MAY22:00:00:00 |
| 222 | Basket   | 30JUN20:00:00:00 |
+-----+----------+------------------+

In the past, I used to operate with the catx() function to concatenate the conditions in a where statement, but I wonder if there is a better way of doing this
proc sql;
    delete from have
        where catx('|',id,item,datetime) in
              (select catx('|',id,item,datetime) from to_delete);
run;

+-----+--------+------------------+
| id  |  item  |     datetime     |
+-----+--------+------------------+
| 111 | Basket | 30SEP21:00:00:00 |
| 111 | Basket | 31DEC20:00:00:00 |
| 222 | Basket | 31DEC20:00:00:00 |
+-----+--------+------------------+

Please note that it should allow the have table to have more columns than the table to_delete.

A: You can use except from to compute difference set of two sets:
proc sql;
  create table want as
  select * from have except select * from to_delete
  ;
quit;


Q: how to open a url from the barcode scanner in phonegap build i'am using the Barcode Scanner for phonegap build, How would i retrieve the QR Codes URL data and display the webpage into a Iframe or div
$(document).ready(function(e) {
$("#scanner_mode").click(function() {

    cordova.plugins.barcodeScanner.scan(
      function (result) {
          alert("We got a barcode\n" +
                "Result: " + result.text + "\n" +
                "Format: " + result.format + "\n" +
                "Cancelled: " + result.cancelled);
      },
      function (error) {
          alert("Scanning failed: " + error);
      }
   );

});
});

Right i have tried this but its not working, so how would i get the src of a iframe to load result.text url
$(document).ready(function(e) {
$("#scanner_mode").click(function() {

    cordova.plugins.barcodeScanner.scan(
      function (result) {
              document.getElementById("frame").src = result.text;
      },
      function (error) {
          alert("Scanning failed: " + error);
      }

   );

});
});

A: yep so its working :)
$(document).ready(function(e) {
$("#scanner_mode").click(function() {

    cordova.plugins.barcodeScanner.scan(
      function (result) {
              document.getElementById("frame").src = result.text;
      },
      function (error) {
          alert("Scanning failed: " + error);
      }

   );

});
});

that works :)


Q: AJAX RETURN help on php/mysql dynamic drop down menu I am trying to populate one drop down menu based on the selection of the first drop down. The first drop down is a list of tables in my database, and the second drop down menu would populate from the providers within that table.
I am having trouble with the ajax script. I DO NOT KNOW how I can test ajax returns, I am fairly new to all this. But as of right now when I select the table from the first drop down menu, nothing happens(the second drop down menu is supposed to populate). I believe my issue lies within retrieving results from the ajax but that is only a guess.
Any help would be greatly appreciated.
My Javascript which sends the selction info from my specialist table to the ajax file...

My ajax file
$specialist = isset($_POST['specialist']) ? $_POST['specialist'] : 0;
if ($specialist <> 0) {
    $errorcode = 0;
    $strmsg = "";
    $sql="SELECT * from $specialist ORDER BY provider";
    $result=mysql_query($sql);
    $cont=mysql_num_rows($result);
    if(mysql_num_rows($result)){
        $chtml = '<select name="provider" id="provider"><option value="0">--Select Provider--</option>';
        while($row = mysql_fetch_array($result)){
            $chtml .= '<option value="'.$row['id'].'">'.$row['provider'].'</option>';
        }
        $chtml .= '</select>';
        echo json_encode(array("errorcode"=>$errorcode,"chtml"=>$chtml));
    }else{
        $errorcode = 1;
        $strmsg = 'No Provider available';
        echo json_encode(array("errorcode"=>$errorcode,"chtml"=>$strmsg));
    }
}

The HTML

1.Specialist

                    <select id="specialist" name="specialist" required>
                        <option value="">--Select Specialist--</option>
                        <option value="addiction_specialist">Addiction Specialist</option>
                        </select

2.Provider

A: Set up debugging on the PHP Side (XDebug works pretty well in most scenarios).  Also, for ANY AJAX/web request functionality, I run fiddler (http://www.telerik.com/fiddler) to see what is being returned to the client from the web server (it will give you a complete view of the web request).
Hope this helps!


Q: can I implement a kill switch into a .bat fork bomb? I want to show a friend how big the impact of a fork bomb can be on performance, but without needing to restart the computer afterwards.
Assuming the following fork bomb:
%0|%0

Is there a way to add a kill switch to this which, with one button press, will stop all running copies of this file, stop any new from being created and hopefully save the machine? I'm not really familiar with the command prompt syntax, so I'm not sure.

A: Two ideas:
a) limit the depth your "bomb" is going to fork:
@echo off
set args=%*
if "%args%" EQU "" (set args=0) else set /a args=%args%+1
if %args% LSS 8 start /min thisfile.bat

(this will produce 2^9 -1 command windows, but only your main window is open.)
b) kill the cmd.exe process in the main batch file
@echo off
SET args=%*
:repeat
start /min thisfile.bat.bat some_arg
if "%args%" NEQ "" goto repeat
pause
taskkill /im cmd.exe

pressing any key in the initial batch file will instamntly kill all cmd windows currently open.
These solutions were tested with some restrictions, so if they work in a "hot" forkbomb, please let me know.
hope this helps.
EDIT:
c)implement a time switch in the original bat:
(still stops even if you can't get past pause)
@echo off
set args=%*
:repeat
start /min thisfile.bat some_arg
if "%args%" NEQ "" goto repeat
timeout /T 10
taskkill /im cmd.exe

or, using the smaller "bomb":
@echo off
set args=%*
if "%args%" NEQ "" (%0 some_arg|%0 some_arg) else start /min thisfile.bat some_arg
timeout /T 10
taskkill /im cmd.exe

A: If you're out to just show your friend fork bombs why not go for a silent but deadly approach? The fork bomb is in vbs, the cleanup is in batch.
Do note, the vbs fork bomb does nothing turning your pc off/on wont fix, it just floods your session proccess's.
The fork bomb:
Do until true = false
  CreateObject("Wscript.Shell").Run Wscript.ScriptName
Loop

Source
Cleanup:
title=dontkillme
FOR /F "tokens=2 delims= " %%A IN ('TASKLIST /FI ^"WINDOWTITLE eq
dontkillme^" /NH') DO SET tid=%%A
echo %tid%
taskkill /F /IM cmd.exe /FI ^"PID ne %tid%^"

Source

A: If it runs in an accessible directory, you could try
IF EXIST kill.txt (exit /b) ELSE (%0|%0)

and make a file called kill.txt in the directory to stop the bomb.


Q: appium script starting off I have installed appium. I want to use it with android apps using Python on a win 7 machine. I do not know how to start a script off to use appium and do not know to use Python IDLE or something else? I have checked examples and discussion groups and found them not helpful. If there is better examples on how to use appium this would be appreciated as well.

A: Here are some links to get started provided from people working on Appium. Some documentation is not up to date since this is still pre Appium 1.0 but should be updated by May 1st.
http://appium.github.io/training/
https://github.com/appium/appium/tree/master/docs


Q: Lazy fetching OneToMany collection throws NPE in Collections.processReachableCollection when referenced column is null I have a problem with lazy loading when in a one to many unidirectional mapping the referenced column is null. Here is my "dummy" code example:
public class A {

    @Column(name = "id")
    private UUID id;

    @Column(name = "b_reference")
    private UUID bReference;

    @OneToMany
    @JoinColumn(name = "b_id", referencedColumnName = "b_reference", insertable = false, updatable = false)
    private List<B> bList;
}

public class B {

    @Column(name = "id")
    private UUID id;

    @Column(name = "b_id")
    private UUID bId;

}

With eager loading, everything works fine, but I have too many entries so it really affects the performance.
I am working with the latest quarkus version (2.7.1 - also tried with 2.31) and in order to test this I also wrote just a simple named query:
@NamedQuery(name = A.FIND, query = "SELECT a FROM A a").
org.hibernate.resource.transaction.backend.jta.internal.synchronization.RegisteredSynchronization@4699241e >: java.lang.NullPointerException
    at org.hibernate.engine.internal.Collections.processReachableCollection(Collections.java:149)
    at org.hibernate.event.internal.FlushVisitor.processCollection(FlushVisitor.java:53)
    at org.hibernate.event.internal.AbstractVisitor.processValue(AbstractVisitor.java:104)
    at org.hibernate.event.internal.AbstractVisitor.processValue(AbstractVisitor.java:65)
    at org.hibernate.event.internal.AbstractVisitor.processEntityPropertyValues(AbstractVisitor.java:59)
    at org.hibernate.event.internal.DefaultFlushEntityEventListener.onFlushEntity(DefaultFlushEntityEventListener.java:183)
    at org.hibernate.event.service.internal.EventListenerGroupImpl.fireEventOnEachListener(EventListenerGroupImpl.java:107)
    at org.hibernate.event.internal.AbstractFlushingEventListener.flushEntities(AbstractFlushingEventListener.java:229)
    at org.hibernate.event.internal.AbstractFlushingEventListener.flushEverythingToExecutions(AbstractFlushingEventListener.java:93)
    at org.hibernate.event.internal.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:39)
    at org.hibernate.event.service.internal.EventListenerGroupImpl.fireEventOnEachListener(EventListenerGroupImpl.java:107)
    at org.hibernate.internal.SessionImpl.doFlush(SessionImpl.java:1402)
    at org.hibernate.internal.SessionImpl.managedFlush(SessionImpl.java:493)
    at org.hibernate.internal.SessionImpl.flushBeforeTransactionCompletion(SessionImpl.java:3285)
    at org.hibernate.internal.SessionImpl.beforeTransactionCompletion(SessionImpl.java:2420)
    at org.hibernate.engine.jdbc.internal.JdbcCoordinatorImpl.beforeTransactionCompletion(JdbcCoordinatorImpl.java:449)
    at org.hibernate.resource.transaction.backend.jta.internal.JtaTransactionCoordinatorImpl.beforeCompletion(JtaTransactionCoordinatorImpl.java:356)
    at org.hibernate.resource.transaction.backend.jta.internal.synchronization.SynchronizationCallbackCoordinatorNonTrackingImpl.beforeCompletion(SynchronizationCallbackCoordinatorNonTrackingImpl.java:47)
    at org.hibernate.resource.transaction.backend.jta.internal.synchronization.RegisteredSynchronization.beforeCompletion(RegisteredSynchronization.java:37)
    at com.arjuna.ats.internal.jta.resources.arjunacore.SynchronizationImple.beforeCompletion(SynchronizationImple.java:76)
    at com.arjuna.ats.arjuna.coordinator.TwoPhaseCoordinator.beforeCompletion(TwoPhaseCoordinator.java:360)
    at com.arjuna.ats.arjuna.coordinator.TwoPhaseCoordinator.end(TwoPhaseCoordinator.java:91)
    at com.arjuna.ats.arjuna.AtomicAction.commit(AtomicAction.java:162)
    at com.arjuna.ats.internal.jta.transaction.arjunacore.TransactionImple.commitAndDisassociate(TransactionImple.java:1295)
    at com.arjuna.ats.internal.jta.transaction.arjunacore.BaseTransaction.commit(BaseTransaction.java:128)
    at io.quarkus.narayana.jta.runtime.CDIDelegatingTransactionManager.commit(CDIDelegatingTransactionManager.java:105)
    at io.quarkus.narayana.jta.runtime.CDIDelegatingTransactionManager_Subclass.commit$$superforward1(Unknown Source)
    at io.quarkus.narayana.jta.runtime.CDIDelegatingTransactionManager_Subclass$$function$$6.apply(Unknown Source)
    at io.quarkus.arc.impl.AroundInvokeInvocationContext.proceed(AroundInvokeInvocationContext.java:54)
    at io.quarkus.arc.runtime.devconsole.InvocationInterceptor.proceed(InvocationInterceptor.java:62)
    at io.quarkus.arc.runtime.devconsole.InvocationInterceptor.monitor(InvocationInterceptor.java:49)
    at io.quarkus.arc.runtime.devconsole.InvocationInterceptor_Bean.intercept(Unknown Source)
    at io.quarkus.arc.impl.InterceptorInvocation.invoke(InterceptorInvocation.java:41)
    at io.quarkus.arc.impl.AroundInvokeInvocationContext.perform(AroundInvokeInvocationContext.java:41)
    at io.quarkus.arc.impl.InvocationContexts.performAroundInvoke(InvocationContexts.java:32)
    at io.quarkus.narayana.jta.runtime.CDIDelegatingTransactionManager_Subclass.commit(Unknown Source)
    at io.quarkus.narayana.jta.runtime.interceptor.TransactionalInterceptorBase.endTransaction(TransactionalInterceptorBase.java:365)
    at io.quarkus.narayana.jta.runtime.interceptor.TransactionalInterceptorBase.invokeInOurTx(TransactionalInterceptorBase.java:165)
    at io.quarkus.narayana.jta.runtime.interceptor.TransactionalInterceptorBase.invokeInOurTx(TransactionalInterceptorBase.java:103)
    at io.quarkus.narayana.jta.runtime.interceptor.TransactionalInterceptorRequiresNew.doIntercept(TransactionalInterceptorRequiresNew.java:41)
    at io.quarkus.narayana.jta.runtime.interceptor.TransactionalInterceptorBase.intercept(TransactionalInterceptorBase.java:57)
    at io.quarkus.narayana.jta.runtime.interceptor.TransactionalInterceptorRequiresNew.intercept(TransactionalInterceptorRequiresNew.java:32)
    at io.quarkus.narayana.jta.runtime.interceptor.TransactionalInterceptorRequiresNew_Bean.intercept(Unknown Source)
    at io.quarkus.arc.impl.InterceptorInvocation.invoke(InterceptorInvocation.java:41)
    at io.quarkus.arc.impl.AroundInvokeInvocationContext.perform(AroundInvokeInvocationContext.java:41)
    at io.quarkus.arc.impl.InvocationContexts.performAroundInvoke(InvocationContexts.java:32)


Q: Using 'not' in Prolog in logic statements I'm working on a condition in Prolog but the not operator is not working as expected. I see not being used in an example here http://www.cs.trincoll.edu/~ram/cpsc352/notes/prolog/factsrules.html
I have the following statements. What i want is for is_not_immune_to to return the result, but not seems to not be working here. Without the not it works fine, and returns whether the Pokemon is immune.
weak(fire, ground).
immune(flying, ground).

is_type(charizard, fire).
is_type(charizard, flying).

is_not_immune_to(Pkmn, AtkType) :-
    is_type(Pkmn, Type), not(immune(Type, AtkType)).

I get the following error when calling is_not_immune_to with charizard and any type..:
uncaught exception: error(existence_error(procedure,not/1),is_not_immune_to/0)

What i want is for is_not_immune_to to return what it should. I want to be able to use not in logic statements. How should i do that?

A: Your code uses the old and deprecated not/1 predicate, which apparently is not supported in the Prolog system you're using, hence the existence error. Use instead the standard \+/1 predicate/prefix operator:
is_not_immune_to(Pkmn, AtkType) :-
    is_type(Pkmn, Type), \+ immune(Type, AtkType).

With this change, you get for your sample call:
| ?- is_not_immune_to(charizard, ground).

true ? ;

no


Q: Moving PictureBox with Timer I want to create a program wherein when I click a Button, the PictureBox that is of the same width and height as the form moves down but I want the Timer to stop right after the PictureBox leaves the frame/form. And when I click another Button, the PictureBox will move back up but it will stop when it's at the center of the form, basically at the same location it was before moving down. The form's size is 700, 1000 if that helps. This is my code:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    Timer1.Enabled = True
End Sub

Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
    PictureBox1.Location = New Point(PictureBox1.Location.X, PictureBox1.Location.Y + 9)
    If (PictureBox1.Location = New Point(700, 1100)) Then
    Timer1.Enabled = False
    End If

End Sub

Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
    Timer2.Enabled = True
End Sub

Private Sub Timer2_Tick(sender As Object, e As EventArgs) Handles Timer2.Tick
    PictureBox1.Location = New Point(PictureBox1.Location.X, PictureBox1.Location.Y - 9)
    If (PictureBox1.Location = New Point((Me.Width / 700) - (PictureBox1.Width / 700), (Me.Height / 1000) - (PictureBox1.Height / 1000))) Then
        Timer2.Enabled = False
    End If
End Sub

A: Let's assume your PictureBox starts in the top, left corner of the containing control (i.e. the Form, or a Panel, or whatever). This is Point(0,0).
In this event handler...
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
    PictureBox1.Location = New Point(PictureBox1.Location.X, PictureBox1.Location.Y + 9)
    If (PictureBox1.Location = New Point(700, 1100)) Then
    Timer1.Enabled = False
    End If

End Sub

...you are checking if the top left corner of PictureBox1 is at position 700,1100 instead of checking if it is at 0,1100. Also, since you're adding + 9 each timer tick, it'll never be at a Y position of exactly 1100.
And then in this event...
Private Sub Timer2_Tick(sender As Object, e As EventArgs) Handles Timer2.Tick
    PictureBox1.Location = New Point(PictureBox1.Location.X, PictureBox1.Location.Y - 9)
    If (PictureBox1.Location = New Point((Me.Width / 700) - (PictureBox1.Width / 700), (Me.Height / 1000) - (PictureBox1.Height / 1000))) Then
        Timer2.Enabled = False
    End If
End Sub

You want to check if PictureBox1.Location is now 0,0 (the starting position) instead of all of that position math you are doing.
Here is a cleaned-up version of your code. Note that it first checks the position of the PictureBox and only moves it if necessary.
Private Const INCREMENT As Integer = 9

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click

    Timer1.Enabled = True

End Sub

Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick

    If PictureBox1.Location.Y >= 1100 Then

        Timer1.Enabled = False

    Else

        PictureBox1.Location = New Point(PictureBox1.Location.X, PictureBox1.Location.Y + INCREMENT)

    End If

End Sub

Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click

    Timer2.Enabled = True

End Sub

Private Sub Timer2_Tick(sender As Object, e As EventArgs) Handles Timer2.Tick

    If PictureBox1.Location.Y <= 0 Then

        Timer2.Enabled = False

    Else

        PictureBox1.Location = New Point(PictureBox1.Location.X, PictureBox1.Location.Y - INCREMENT)

    End If

End Sub


Q: Flutter Firesbase is returning Null final db = FirebaseFirestore.instance.collection('dutyStatus');

Future<void> readOnDutyStatus() async {
//The function is being called in the authentication bloc
try {
  List status = [];
  // await db.add({'onDuty': true});
  var data = await db.doc('driver1').get();
  var temp = data.data();
  status.add(temp);
  print(
      '_______________________________________________________________________________________');
  print(status.toString());
  print(
      '_______________________________________________________________________________________');
} catch (e) {
  print(e);
}

}
The result :
I/flutter (25466): _______________________________________________________________________________________
I/flutter (25466): [null]
I/flutter (25466): _______________________________________________________________________________________
W/er_drive_mobil(25466): Accessing hidden method Lsun/misc/Unsafe;->putObject(Ljava/lang/Object;JLjava/lang/Object;)V (greylist, linking, allowed)
W/er_drive_mobil(25466): Accessing hidden method Lsun/misc/Unsafe;->putInt(Ljava/lang/Object;JI)V (greylist, linking, allowed)
Note: The same code when used on another account of firebase works as intended and I can't seem to figure out the issue.

A: Most likely driver1 doesn't exist.
Try this
var temp =  data.exists ? data.data() : "Doc does not exist";

Print list should return [Doc does not exist] instead of null.
Check if there is a white space before driver1 i.e _driver1 or after it. Otherwise there's no other explanation.


Q: Replicate Excel's IF and COUNTIF functions in pandas I am trying to replicate the ability of Excel countif and if statements in Pandas.
In Excel, I have the following table:
+---------+-------+------+--------+
| Row/Col |   A   |  B   |   C    |
+---------+-------+------+--------+
|       1 | Name  | Date | Type   |
|       2 | John  | 21/4 | New    |
|       3 | John  | 22/4 | Update |
|       4 | Jacob | 23/6 | New    |
|       5 | Mary  | 24/7 | New    |
|       6 | Jacob | 26/8 | Update |
+---------+-------+------+--------+

In order to get the Type values, I would use the following code in all of column C (for row 2):
=IF(COUNTIF($A2:A2, A2)>1, "Update", "New")

For the same data in a df, how would I implement it, so that I counts only from the first row of the column down, and does not include any row below the row it is calculating for?

A: In panda we have groupby with cumcount
df['C']=df.groupby('A').cumcount().gt(0).map({False:'New',True:'Update'})


Q: How to replace next button with mat-chip in Angular Material stepper? I am using angular material stepper, in the stepper i want to replace next button with mat-chip and act as same functionality as next button.
Here is angular stepper stackblitz example
This is what i want:

A: I you just want the button to look like a material chip (rather than actually be a material chip), you could remove 'mat-button' from the next button and add your own class, e.g. 'next_btn':
<button class="next_btn" matStepperNext>Next</button>

You can then just style the button so it looks like a chip:
button.next_btn {
    padding: 7px 12px;
    border-radius: 16px;
    min-height: 32px;
    background-color: #e0e0e0;
    color: rgba(0,0,0,.87);
    box-shadow:none;
    border:none;
    cursor: pointer;
    outline:none;
}

button.next_btn:focus
{
    outline:none;
}

Example here.

A: How about inserting the button inside the chip? and managing the look... take a look here for demo
HTML:
<mat-chip-list>
  <mat-chip><button mat-button matStepperPrevious>Back</button></mat-chip>
  <mat-chip><button mat-button matStepperNext>Next</button></mat-chip>
</mat-chip-list>

CSS:
mat-chip{padding:0;}


Q: Streaming cameras by ip with python I have a remote camera streaming through rtsp protocol and am trying to access it in OpenCV 2.13.1 using python with following code.
camera = cv2.VideoCapture("rtsp://admin:<pass>@<ip>:<port>/xyz/video.smp")

However, when I do that I get the following warning
[tcp @ 00000188ed4e9b00] Connection to tcp://ip failed: Error number -138 occurred
warning: Error opening file (/build/opencv/modules/videoio/src/cap_ffmpeg_impl.hpp:901)
warning: http://ip (/build/opencv/modules/videoio/src/cap_ffmpeg_impl.hpp:902)

I dont know how to fix that


Q: Trouble in implementing link list sorting in c# I am having trouble implementing a sort algo (merge) for singly list as defined below
My mergesort method always gives me null..I am not able to figure out what is wrong
Can you guys help me out?
Node class
public class Node
        {
           private int data;
           private  Node next;
    }

Linked List class
public class SSL
        {
            private Node head;
    }

My merge sort code
public static void MergeSort(SSL a)
        {
            SSL x = new SSL();
            SSL y = new SSL();
            if (a.Head == null || a.Head.Next == null) // base case if list has 0 or 1 element
                return;
            AlternateSplitting(a, x, y);
            MergeSort(x);
            MergeSort(y);
            a = SortedMerge(x, y);
        }

I implemented following helper methods to implement merge sort
AlternateSplitting: This method will split the list into 2 lists
public static void AlternateSplitting(SSL src, SSL odd, SSL even)
        {

            while (src.Head != null)
            {
                MoveNode(odd, src);
                if (src.Head != null)
                    MoveNode(even, src);
            }

        } // end of AlternateSplitting

This method will merge the 2 list and return a new list
public static SSL SortedMerge(SSL a, SSL b)
        {
            SSL c = new SSL();
            if (a.Head == null)
                return b;
            else
                if (b.Head == null)
                    return a;
                else
                {
                    bool flagA = false;
                    bool flagB = false;
                    Node currentA = new Node();
                    Node currentB = new Node();

                    while (!flagA && !flagB)
                    {
                        currentA = a.Head;
                        currentB = b.Head;
                        if (currentA.Data < currentB.Data)
                        {
                            MoveNodeToEnd(a, c);
                            currentA = a.Head;
                            if (currentA== null)
                                flagA = true;
                        }
                        else
                            if (currentA.Data > currentB.Data)
                            {
                                MoveNodeToEnd(b, c);
                                currentB = b.Head;
                                if (currentB== null)
                                    flagB = true;

                            }
                    } // end of while

                    if (flagA)
                    {

                        while (currentB != null)
                        {
                            MoveNodeToEnd(b, c);
                            currentB = b.Head;
                        }

                    }
                    else
                        if(flagB)
                        {

                            while (currentA != null)
                            {
                                MoveNodeToEnd(a, c);
                                currentA = a.Head;
                            }

                        }
                    return c;

                } // end of outer else

        } // end of function sorted merge

A:
I am not able to figure out what is
  wrong Can you guys help me out?

Find a bug and you fix it for a day. Teach how to find bugs and believe me, it takes a lifetime to fix the bugs. :-)
Your fundamental problem is not that the algorithm is wrong -- though, since it gives incorect results, it certainly is wrong. But that's not the fundamental problem. The fundamental problem is that you don't know how to figure out where a program goes wrong. Fix that problem first! Learn how to debug programs.
Being able to spot the defect in a program is an acquired skill like any other -- you've got to learn the basics and then practice for hundreds of hours. So learn the basics.
Start by becoming familiar with the basic functions of your debugger. Make sure that you can step through programs, set breakpoints, examine local variables, and so on.
Then write yourself some debugging tools. They can be slow -- you're only going to use them when debugging. You don't want your debugging tools in the production version of your code.
The first debugging tool I would write is a method that takes a particular Node and produces a comma-separated list of the integers that are in the list starting from that node. So you'd say DumpNode(currentB) and what would come back is, say "{10,20,50,30}".  Obviously doing the same for SSL is trivial if you can do it for nodes.
I would also write tools that do things like count nodes in a list, tell you whether a given list is already sorted, and so on.
Now you have something you can type into the watch window to more easily observe the changes to your data structures as they flow by. (There are ways to make the debugger do this rendering automatically, but we're discussing the basics here, so let's keep it simple.)
That will help you understand the flow of data through the program more easily. And that might be enough to find the problem. But maybe not. The best bugs are the ones that identify themselves to you, by waving a big red flag that says "there's a bug over here".  The tool that turns hard-to-find bugs into self-identifying bugs is the debug assertion.
When you're writing your algorithm, think "what must be true?" at various points. For example, before AlternateSplitting runs, suppose the list has 10 items. When it is done running, the two resulting lists had better have 5 items each. If they don't, if they have 10 items each or 0 items each or one has 3 and the other has 7, clearly you have a bug somewhere in there. So start writing debug-only code:
public static void AlternateSplitting(SSL src, SSL odd, SSL even)
{
#if DEBUG
  int srcCount = CountList(src);
#endif
  while (src.Head != null) { blah blah blah }
#if DEBUG
  int oddCount = CountList(odd);
  int evenCount = CountList(even);
  Debug.Assert(CountList(src) == 0);
  Debug.Assert(oddCount + evenCount == srcCount);
  Debug.Assert(oddCount == evenCount || oddCount == evenCount + 1);
#endif
}

Now AlternateSplitting will do work for you in the debug build to detect bugs in itself. If your bug is because the split is not working out correctly, you'll know immediately when you run it.
Do the same thing to the list merging algorithm -- figure out every point where "I know that X must be true at this point", and then write a Debug.Assert(X) at that point. Then run your test cases. If you have a bug, then the program will tell you and the debugger will take you right to it.
Good luck!


Q: Test DeltaSpike Repositories cannot inject EntityManager I am trying to run a simple test for DeltaSpike repository. However, I cannot get the Entity Manager injected. I am using producer which is located and test sources:
@ApplicationScoped
public class EntityManagerProducer {

    @Produces
    public EntityManager getEntityManager() {
        return Persistence
          .createEntityManagerFactory("primary-test")
          .createEntityManager();
    }
}

In META-INF folder under test resources I have a persistence.xml file with primary-test persistence unit defined:
<persistence version="2.0"
         xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
    <persistence-unit name="primary-test" transaction-type="RESOURCE_LOCAL">
        <properties>
            <!-- Configuring JDBC properties -->
            <property name="javax.persistence.jdbc.url" value="jdbc:h2:mem:test"/>
            <property name="javax.persistence.jdbc.driver" value="org.h2.Driver"/>

            <!-- Hibernate properties -->
            <property name="hibernate.dialect" value="org.hibernate.dialect.H2Dialect"/>
            <property name="hibernate.hbm2ddl.auto" value="create-drop"/>
            <property name="hibernate.format_sql" value="false"/>
            <property name="hibernate.show_sql" value="true"/>
        </properties>
    </persistence-unit>
</persistence>

In very simple Unit I am trying to inject Entity Manager:
@RunWith(CdiTestRunner.class)
public class UserRepositoryTest {

    @Inject
    private EntityManager entityManager;

    @Test
    public void shouldReturnEmptyListWhenDBIsEmpty() {
        // dummy test here
    }
}

However, when I am running it I am getting the exception:
 WELD-001408 Unsatisfied dependencies for type [EntityManager] with qualifiers [@Default] at injection point [[field] @Inject private com.repository.UserRepositoryTest.entityManager]

My pom.xml has dependencies to Apache DeltaSpike Test Module and Weld:
<properties>
  <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  <deltaspike.version>1.8.2</deltaspike.version>
  <weld.version>1.1.10.Final</weld.version>
</properties>

<dependency>
  <groupId>org.apache.deltaspike.modules</groupId>
  <artifactId>deltaspike-test-control-module-api</artifactId>
  <version>${deltaspike.version}</version>
  <scope>test</scope>
</dependency>

<dependency>
  <groupId>org.apache.deltaspike.modules</groupId>
  <artifactId>deltaspike-test-control-module-impl</artifactId>
  <version>${deltaspike.version}</version>
  <scope>test</scope>
</dependency>

<dependency>
  <groupId>org.apache.deltaspike.cdictrl</groupId>
  <artifactId>deltaspike-cdictrl-weld</artifactId>
  <version>${deltaspike.version}</version>
  <scope>test</scope>
</dependency>

<dependency>
  <groupId>org.jboss.weld.se</groupId>
  <artifactId>weld-se-core</artifactId>
  <version>${weld.version}</version>
  <scope>test</scope>
</dependency>

Any ideas why Entity Manager cannot be injected? I do not want to use Arquillian.
EDIT:
Current pom.xml:
<groupId>com.us</groupId>
<artifactId>deltaspike-samples</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>

<name>DeltaSpike samples</name>

<properties>
  <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
  <deltaspike.version>1.8.1</deltaspike.version>
  <weld.version>3.0.4.Final</weld.version>
</properties>

<dependencyManagement>
  <dependencies>
    <dependency>
      <groupId>org.apache.deltaspike.distribution</groupId>
      <artifactId>distributions-bom</artifactId>
      <version>${deltaspike.version}</version>
      <type>pom</type>
      <scope>import</scope>
    </dependency>
    <dependency>
      <groupId>org.wildfly.bom</groupId>
      <artifactId>jboss-javaee-7.0-with-hibernate</artifactId>
      <version>8.2.2.Final</version>
      <type>pom</type>
      <scope>import</scope>
    </dependency>
  </dependencies>
</dependencyManagement>

<dependencies>
  <dependency>
    <groupId>javax</groupId>
    <artifactId>javaee-api</artifactId>
    <version>7.0</version>
    <scope>provided</scope>
  </dependency>

  <dependency>
    <groupId>org.apache.deltaspike.core</groupId>
    <artifactId>deltaspike-core-api</artifactId>
    <scope>compile</scope>
  </dependency>

  <dependency>
    <groupId>org.apache.deltaspike.core</groupId>
    <artifactId>deltaspike-core-impl</artifactId>
    <scope>runtime</scope>
  </dependency>

  <dependency>
    <groupId>org.apache.deltaspike.modules</groupId>
    <artifactId>deltaspike-data-module-api</artifactId>
    <scope>compile</scope>
  </dependency>

  <dependency>
    <groupId>org.apache.deltaspike.modules</groupId>
    <artifactId>deltaspike-data-module-impl</artifactId>
    <scope>runtime</scope>
  </dependency>

  <!--Test dependencies-->
  <dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.12</version>
    <scope>test</scope>
  </dependency>

  <dependency>
    <groupId>org.apache.deltaspike.modules</groupId>
    <artifactId>deltaspike-test-control-module-api</artifactId>
    <scope>test</scope>
  </dependency>

  <dependency>
    <groupId>org.apache.deltaspike.modules</groupId>
    <artifactId>deltaspike-test-control-module-impl</artifactId>
    <scope>test</scope>
  </dependency>

  <dependency>
    <groupId>org.apache.deltaspike.cdictrl</groupId>
    <artifactId>deltaspike-cdictrl-api</artifactId>
    <version>${deltaspike.version}</version>
    <scope>compile</scope>
  </dependency>

  <dependency>
    <groupId>org.apache.deltaspike.cdictrl</groupId>
    <artifactId>deltaspike-cdictrl-weld</artifactId>
    <version>${deltaspike.version}</version>
    <scope>test</scope>
  </dependency>

  <dependency>
    <groupId>javax.enterprise</groupId>
    <artifactId>cdi-api</artifactId>
    <version>2.0</version>
  </dependency>

  <dependency>
    <groupId>org.jboss.weld.se</groupId>
    <artifactId>weld-se-shaded</artifactId>
    <version>3.0.4.Final</version>
    <scope>test</scope>
  </dependency>

  <dependency>
    <groupId>org.hibernate.javax.persistence</groupId>
    <artifactId>hibernate-jpa-2.1-api</artifactId>
    <scope>test</scope>
  </dependency>

  <dependency>
    <groupId>org.jboss.spec.javax.annotation</groupId>
    <artifactId>jboss-annotations-api_1.2_spec</artifactId>
    <scope>test</scope>
  </dependency>

</dependencies>

A: Using CDI in JAVA SE requires the beans.xml to be put in META-INF
although this is optional since Java EE 7.
Then, set discovery mode to annotated and your producer should be detected.
Here is a working configuration :
<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.target>1.8</maven.compiler.target>
    <maven.compiler.source>1.8</maven.compiler.source>
    <deltaspike.version>1.8.2</deltaspike.version>
    <weld.version>3.0.4.Final</weld.version>
</properties>

Now, here is how you setup the base DeltaSpike dependency :
<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.apache.deltaspike.distribution</groupId>
            <artifactId>distributions-bom</artifactId>
            <version>${deltaspike.version}</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>

In the dependencies, you should have theses specs :
<dependency>
    <groupId>javax.enterprise</groupId>
    <artifactId>cdi-api</artifactId>
    <version>2.0</version>
    <scope>provided</scope>
</dependency>

<dependency>
    <groupId>javax.transaction</groupId>
    <artifactId>javax.transaction-api</artifactId>
    <version>1.3</version>
</dependency>

<dependency>
    <groupId>javax.persistence</groupId>
    <artifactId>javax.persistence-api</artifactId>
    <version>2.2</version>
</dependency>

Now it's time to depend on implementations.
First, Deltaspike itself :
<dependency>
    <groupId>org.apache.deltaspike.core</groupId>
    <artifactId>deltaspike-core-api</artifactId>
    <scope>compile</scope>
</dependency>

<dependency>
    <groupId>org.apache.deltaspike.core</groupId>
    <artifactId>deltaspike-core-impl</artifactId>
    <scope>runtime</scope>
</dependency>

<dependency>
    <groupId>org.apache.deltaspike.cdictrl</groupId>
    <artifactId>deltaspike-cdictrl-api</artifactId>
    <scope>compile</scope>
</dependency>

Then JBoss Weld 3 (CDI 2.0 impl)
<dependency>
    <groupId>org.jboss.weld.se</groupId>
    <artifactId>weld-se-shaded</artifactId>
    <version>${weld.version}</version>
    <scope>runtime</scope>
</dependency>

And Weld controler for DeltaSpike :
<dependency>
    <groupId>org.apache.deltaspike.cdictrl</groupId>
    <artifactId>deltaspike-cdictrl-weld</artifactId>
    <scope>runtime</scope>
</dependency>

Then the DeltaSpike Data module :
<dependency>
    <groupId>org.apache.deltaspike.modules</groupId>
    <artifactId>deltaspike-data-module-api</artifactId>
    <version>${deltaspike.version}</version>
    <scope>compile</scope>
</dependency>

<dependency>
    <groupId>org.apache.deltaspike.modules</groupId>
    <artifactId>deltaspike-data-module-impl</artifactId>
    <version>${deltaspike.version}</version>
    <scope>runtime</scope>
</dependency>

Now it's time for the JPA implementation (EclipseLink JPA 2.7.1) and an embedded database server H2 :
<dependency>
    <groupId>org.eclipse.persistence</groupId>
    <artifactId>org.eclipse.persistence.jpa</artifactId>
    <version>2.7.1</version>
</dependency>

<dependency>
    <groupId>com.h2database</groupId>
    <artifactId>h2</artifactId>
    <version>1.4.197</version>
    <scope>runtime</scope>
</dependency>

To create unit test with JUnit 5, you need this :
<dependency>
    <groupId>org.junit.jupiter</groupId>
    <artifactId>junit-jupiter-api</artifactId>
    <version>5.1.0</version>
    <scope>test</scope>
</dependency>

<dependency>
    <groupId>org.junit.jupiter</groupId>
    <artifactId>junit-jupiter-engine</artifactId>
    <version>5.1.0</version>
    <scope>test</scope>
</dependency>

<dependency>
    <groupId>org.junit.vintage</groupId>
    <artifactId>junit-vintage-engine</artifactId>
    <version>5.1.0</version>
    <scope>test</scope>
</dependency>

<dependency>
    <groupId>org.junit.platform</groupId>
    <artifactId>junit-platform-launcher</artifactId>
    <version>1.1.0</version>
    <scope>test</scope>
</dependency>

<dependency>
    <groupId>org.junit.platform</groupId>
    <artifactId>junit-platform-runner</artifactId>
    <version>1.1.0</version>
    <scope>test</scope>
</dependency>

And to be able to launch CDI with a single annotation in a JUnit class, you need this as well :
<dependency>
    <groupId>org.jboss.weld</groupId>
    <artifactId>weld-junit5</artifactId>
    <version>1.2.2.Final</version>
    <scope>test</scope>
</dependency>

To enable JUnit 5 in Maven, you must configure maven-surefire-plugin :
<build>
    <plugins>
        <plugin>
            <artifactId>maven-surefire-plugin</artifactId>
            <version>2.19.1</version>
            <dependencies>
                <dependency>
                    <groupId>org.junit.platform</groupId>
                    <artifactId>junit-platform-surefire-provider</artifactId>
                    <version>1.0.3</version>
                </dependency>
                <dependency>
                    <groupId>org.junit.jupiter</groupId>
                    <artifactId>junit-jupiter-engine</artifactId>
                    <version>5.0.3</version>
                </dependency>
            </dependencies>
        </plugin>
    </plugins>
</build>

And, I'll use Lombok and SLF4J :
<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <version>1.16.20</version>
</dependency>

<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-api</artifactId>
    <version>1.7.25</version>
</dependency>

<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-simple</artifactId>
    <version>1.7.25</version>
    <scope>test</scope>
</dependency>

Here is my project structure :
main/java/fr/fxjavadevblog
          +-- VideoGame.java (JPA Entity)
          +-- VideoGameFactory.java
          +-- VideoGameRepository.java (interface)
          +-- InjectedUUID.java (annotation def.)
          +-- Producers.java (produces EntityManager and UUID has string)
    /resources/META-INF
          +-- beans.xml
          +-- persistence.xml

test/java/fr/fxjavadevblog
          +-- VideoGameReposityTest.java (JUnit 5)
    /resources/META-INF
          +-- beans.xml
          +-- persistence.xml

Here is  are my CDI producers, needed by DeltaSpike Data and to inject UUID as private keys :
package fr.fxjavadevblog;

import javax.enterprise.context.ApplicationScoped;
import javax.enterprise.inject.Produces;
import javax.persistence.EntityManager;
import javax.persistence.Persistence;
import java.util.UUID;

/**
 * composite of CDI Producers.
 *
 * @author robin
 */
@ApplicationScoped
public class Producers
{
    public static final String UNIT_NAME = "cdi-deltaspike-demo";

    /**
     * produces the instance of entity manager for the application and for DeltaSpike.
     */
    @Produces
    @SuppressWarnings("unused") // just remove the warning, because the field serves as CDI Producer and the IDE cannot detect it.
    private static EntityManager em = Persistence.createEntityManagerFactory(UNIT_NAME).createEntityManager();

    /**
     * produces randomly generated UUID for primary keys.
     *
     * @return UUID as a HEXA-STRING
     *
     */
    @Produces
    @InjectedUUID
    @SuppressWarnings("unused") // just remove the warning, because the method serves as CDI Producer and the IDE cannot detect it.
    public String produceUUIDAsString()
    {
        return UUID.randomUUID().toString();
    }
}

this class uses a custom CDI Qualifier called @InjectedUUID :
package fr.fxjavadevblog;

import javax.inject.Qualifier;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;

import static java.lang.annotation.ElementType.*;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

/**
 * CDI Qualifier for UUID Producers
 *
 * @author robin
 */

@Qualifier
@Retention(RUNTIME)
@Target({METHOD, FIELD, PARAMETER, TYPE})
public @interface InjectedUUID
{
}

Here is my JPA entity, using Lombok and CDI annotations :
package fr.fxjavadevblog;

import lombok.*;

import javax.enterprise.context.Dependent;
import javax.inject.Inject;
import javax.persistence.*;
import java.io.Serializable;

/**
 * simple JPA Entity, using Lombok and CDI Injected fields (UUID).
 *
 * @author robin
 */

// lombok annotations
@NoArgsConstructor(access = AccessLevel.PROTECTED) // to avoid direct instanciation bypassing the factory.
@ToString(of = {"id","name"})
@EqualsAndHashCode(of="id")

// CDI Annotation
@Dependent

// JPA Annotation
@Entity
public class VideoGame implements Serializable {

    @Id
    @Inject @InjectedUUID // ask CDI to inject an brand new UUID
    @Getter
    private String id;

    @Getter @Setter
    private String name;

    // this field will work as a flag to know if the entity has already been persisted
    @Version
    @Getter
    private Long version;
}

Here is a simple factory for my entity class :
/**
 * simple Factory for creation VideoGame instances populated with UUID, ready to persist.
 * This factory is need to get a proper Entity. Entities must not be created with the "new" operator, but must be build
 * by invoking CDI.
 *
 * @author robin
 */
public class VideoGameFactory
{
    /**
     * creates and brand new VideoGame instance with its own UUID as PK.
     *
     * @return instance of a VideoGame
     */
    public static VideoGame newInstance()
    {
        // ask CDI for the instance, injecting required dependencies.
        return CDI.current().select(VideoGame.class).get();
    }
}

And last but not least, the DeltaSpike Data Resposity for my entity :
package fr.fxjavadevblog;

import org.apache.deltaspike.data.api.EntityRepository;
import org.apache.deltaspike.data.api.Repository;

/**
 * CRUD (and much more) interface, using DeltaSpike Data module.
 *
 * @author robin
 */

@Repository
interface VideoGameRepository extends EntityRepository <VideoGame, String>
{
    // nothing to code here : automatic Repo generated by DeltaSpike
}

Here are the configuration files :
beans.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/beans_2_0.xsd"
       bean-discovery-mode="annotated" version="2.0">
</beans>

persistence.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.2" xmlns="http://xmlns.jcp.org/xml/ns/persistence"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence
                                 http://xmlns.jcp.org/xml/ns/persistence/persistence_2_2.xsd">
    <persistence-unit name="cdi-deltaspike-demo" transaction-type="RESOURCE_LOCAL">

        <class>fr.fxjavadevblog.VideoGame</class>

        <properties>
            <property name="javax.persistence.jdbc.url" value="jdbc:h2:mem:test"/>
            <property name="javax.persistence.jdbc.driver" value="org.h2.Driver"/>
            <property name="javax.persistence.schema-generation.database.action" value="create"/>
        </properties>

    </persistence-unit>
</persistence>

These files are duplicated into the test/resources/META-INF folder as well.
And finally, here is the unit test :
package fr.fxjavadevblog;

import org.jboss.weld.junit5.EnableWeld;
import org.jboss.weld.junit5.WeldInitiator;
import org.jboss.weld.junit5.WeldSetup;
import org.junit.Assert;
import org.junit.jupiter.api.Test;

import lombok.extern.slf4j.Slf4j;

import javax.inject.Inject;

/**
 * simple test class for the VideoGameRepository, using LOMBOK and WELD.
 *
 * @author robin
 */

@Slf4j
@EnableWeld
class VideoGameRepositoryTest
{
    @WeldSetup // This is need to discover Producers and DeltaSpike Repository functionality
    private WeldInitiator weld = WeldInitiator.performDefaultDiscovery();

    @Inject
    private VideoGameRepository repo;

    @Test
    void test()
    {

        VideoGame videoGame = VideoGameFactory.newInstance();
        videoGame.setName("XENON");
        repo.save(videoGame);
        // testing if the ID field had been generated by the JPA Provider.
        Assert.assertNotNull(videoGame.getVersion());
        Assert.assertTrue(videoGame.getVersion() > 0);
        log.info("Video Game : {}", videoGame);
    }

}

Usage of Lombok and the UUID producer is optional.
You can find the full code source, and clone the repo, on github : https://github.com/fxrobin/cdi-deltaspike-demo

A: I had similar issues with Deltaspike and a Junit5 integration test of a database repository.
Basically, I could not inject the repository when using Junit5 @Test annotations. I had to use Junit4 @Test annotations as a workaround.


Q: Linking GSL statically using Cmake I'm linking GNU GSL with a pybind11 module. It works if GSL is linked as a shared library:
cmake_minimum_required(VERSION 2.8.12)
project(st)

# Paths
set(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} "${CMAKE_SOURCE_DIR}/cmake/")

# Packages
add_subdirectory(pybind11)
find_package(GSL REQUIRED)

# Includes
set(DIRS ${GSL_INCLUDE_DIRS} ${GSLCBLAS_INCLUDE_DIRS})
include_directories(${DIRS})

# Python module
pybind11_add_module(st src/st.cpp)

# Libraries
set(LIBS ${LIBS} ${GSL_LIBRARIES} ${GSLCBLAS_LIBRARIES})
target_link_libraries(st PRIVATE ${LIBS})

How can I link it statically? I've tried a lot of different options but it doesn't work.

A: The trouble is that CMake resets the contents of CMAKE_FIND_LIBRARY_SUFFIXES during the PROJECT statement, see the file Modules/CMakeGenericSystem.cmake in the installation of CMake. For example, this CMakeLists.txt
cmake_minimum_required(VERSION 2.8.12)

message("CMAKE_FIND_LIBRARY_SUFFIXES = ${CMAKE_FIND_LIBRARY_SUFFIXES}")
project(st)
message("CMAKE_FIND_LIBRARY_SUFFIXES = ${CMAKE_FIND_LIBRARY_SUFFIXES}")

set(CMAKE_FIND_LIBRARY_SUFFIXES ".a")  # <--- this is needed to replace the default

# Packages
find_package(GSL REQUIRED)

# Libraries
message("Libraries: ${GSL_LIBRARIES} ${GSLCBLAS_LIBRARIES}")

when executed as
cmake -D CMAKE_FIND_LIBRARY_SUFFIXES=".a" .

produces the output
CMAKE_FIND_LIBRARY_SUFFIXES = .a
-- The C compiler identification is GNU 9.2.1
-- The CXX compiler identification is GNU 9.2.1
-- Check for working C compiler: /usr/bin/cc
-- Check for working C compiler: /usr/bin/cc -- works
-- Detecting C compiler ABI info
-- Detecting C compiler ABI info - done
-- Detecting C compile features
-- Detecting C compile features - done
-- Check for working CXX compiler: /usr/bin/c++
-- Check for working CXX compiler: /usr/bin/c++ -- works
-- Detecting CXX compiler ABI info
-- Detecting CXX compiler ABI info - done
-- Detecting CXX compile features
-- Detecting CXX compile features - done
CMAKE_FIND_LIBRARY_SUFFIXES = .so;.a
-- Found PkgConfig: /usr/bin/pkg-config (found version "1.6.3")
-- Found GSL: /opt/gsl-2.6/include (found version "2.6")
Libraries: /opt/gsl-2.6/lib64/libgsl.a;/opt/gsl-2.6/lib64/libgslcblas.a
-- Configuring done
-- Generating done

Apparently, a possible solution seems to be to redefine the variable (by manually modifying the script) right after the PROJECT statement, as done in the above sample code.


Q: C: speed up for permutation of bits from given permutation table; searching for the minimum I'm searching for a fast permutation of bits within a number in C.
I have an integer value and table of permutation positions. Not all possible permutations are listet, just n!*2n of the 2n! possible permutations.
For simplicity I will show the data as 4-Bit numbers (n=2, lutsize = 8), in reality they are 32-Bit numbers (n=5, lutsize=3840):
static const uint8_t lut[lutsize][4] = {
{0, 1, 2, 3},
{1, 0, 3, 2},
{2, 3, 0, 1},
{3, 2, 1, 0},
{0, 2, 1, 3},
{1, 3, 0, 2},
{2, 0, 3, 1},
{3, 1, 2, 0}};

So the first entry is the identity, for the second entry the bits 1&2 and 2&3 switch places and so on. I wrote a method which calculates the values and returns the minimal value:
#include <stdio.h>
#include <stdint.h>
#include <assert.h>

enum { n = 2 };
enum { expn = 1<<n };

enum { lutsize = 8 };
static const uint8_t lut[lutsize][4] = {
    {0, 1, 2, 3},
    {1, 0, 3, 2},
    {2, 3, 0, 1},
    {3, 2, 1, 0},
    {0, 2, 1, 3},
    {1, 3, 0, 2},
    {2, 0, 3, 1},
    {3, 1, 2, 0}
};

uint32_t getMin(uint32_t in, uint32_t* ptr){
    uint32_t pos, i, tmp, min;
    uint8_t bits[expn];

    tmp = in;
    for (i = 0; i < expn; ++i){ // extract bits into array
        bits[i] = tmp & 1;
        tmp = tmp >> 1;
    }
    min = in;
    for (pos = 0; pos < lutsize; ++pos){ // for each row in the permutation table
        tmp = 0;
        for (i = 0; i < expn; ++i){ // for each bit
            tmp = tmp | (bits[i] << lut[pos][i]);  // put bit i on position lut[pos][i]
        }
        ptr[pos] = tmp; // store result (optional)
        //printf("%d: %d\n", pos, tmp);
        if (tmp<min) { min = tmp; }  // track minimum
    }
    //printf("min: %d\n", min);
    return min;
}

void main(int argc, const char * argv[]) {
    uint32_t ptr[lutsize];
    printf("%u\n", (unsigned)getMin(5, ptr));
    assert(getMin(5, ptr) == 3);
    assert(getMin(0b0110, ptr) == 6);
}

gives the output for the example number 5 if you uncomment the printf's:
0: 5
1: 10
2: 5
3: 10
4: 3
5: 3
6: 12
7: 12
min: 3

I do calculate each permutation in a naive way by separating the bits into an array and then pushing them into their new position. I write the results into an array and keep track of the minimum which is returned at the end.
How do improve the performance of the procedure getMin for n=5?
I'm primarily interested in the minimum.
Additional input:

*

*the permutation table can be read as "bit value comes from position" or "bit value shifts to position". The results are the same, just the order of the entries differs.

*it is not necessary (but a bonus) to use the array (ptr)

*the goal is to reduce the time to compute the smallest bit permutation number for all 32-bit numbers in random order. Precalculating all possible minimum numbers is ok. Using multiple versions of the lut is ok. Anything is ok as long it does not take more than 4GB of ram like storing all possible input/output pairs would do.

*sorry for the not so c-like code. I'm out of training.

Here is the python code to generate the look up table for n=5:
from itertools import permutations
import numpy as np
import math

for n in [5]:
    expn = 1<<n #2:4 3:8; 4:16; 5:32
    order = np.zeros((int(math.factorial(n))*expn, expn), dtype=np.int8) # n!*2^n x 2^n matrix
    cnt = 0 # current entry
    permneg = np.zeros(expn, dtype=int)
    for perm in permutations(list(range(n))): #shuffle order
        ini = np.array(list(range(expn)), dtype=int) # list 0 to expn-1
        out = np.zeros(expn, dtype=int)
        for i in range(n): # apply permutation on position level
            tmp = ini & 1 # get value on least bit
            out += tmp << perm[i] #put it on the right postion
            ini = ini >> 1 # next bit as least bit
        for neg in range(expn): # include 0/1 swaps (negation)
            for i in range(len(out)): # for all 2^n negation cases
                permneg[i] = out[i] ^ neg # negate on negation bits
            order[cnt]=permneg # store
            cnt += 1 # increase counter

    print("enum { lutsize = "+str(len(order))+" };")
    s='},\n{'.join(', '.join(map(str,sl)) for sl in order)
    print("static const uint8_t lut[lutsize]["+str(expn)+"] = {\n{"+s+"}\n};")

A: I would suggest two optimizations : 1) store the value of the set bit in the table instead. 2) Don't store each bit in an array but compute it on the fly instead. The result is the same, but it's probably a little bit faster.
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>

#define lutsize 8

static const uint8_t lutn[lutsize][4] = {
    {1, 2, 4, 8},
    {2, 1, 8, 4},
    {4, 8, 1, 2},
    {8, 4, 2, 1},
    {1, 4, 2, 8},
    {2, 8, 1, 4},
    {4, 1, 8, 2},
    {8, 2, 4, 1}};

uint32_t getMin(uint32_t in, uint32_t* ptr)
{
    uint32_t pos, i, tmp, min;
    uint8_t bits[expn];
    tmp = in;
    min = in;
    for (pos = 0; pos < lutsize; ++pos){
        tmp = 0;
        for (i = 0; i < expn; ++i) {
            // If the bit is set
            if (in & (1<<i))
                // get the value of the permuted bit in the table
                tmp = tmp | lutn[pos][i];
        }
        ptr[pos] = tmp;
        //printf("%d: %d\n", pos, tmp);
        if (tmp<min) { min = tmp; }  // track minimum
    }
    //printf("min: %d\n", min);
    return min;
}

void main(int argc, const char * argv[]) {
    uint32_t *ptr;

    ptr = (uint32_t*) malloc(lutsize * sizeof(uint32_t));
    getMin(5, ptr);
}

A: It seems to me that, not having all the possible permutations, you need to check all of those you have. Calculating the best permutation is not fruitful if you aren't sure that permutation is available.
So, the two optimizations remaining you can hope for are:

*

*Stop the search if you achieve a minimum.

For example, if I have understood, you have the binary number 11001101. What is the minimum permutation value? Obviously 00011111, with all ones to the right. What exact permutation does this for you - whether the last 1 is the first, second, fifth, sixth or eight bit - matters not to you.
As soon as a permutation hits the magic value, that is the minimum and you know you can do no better, so you can just as well stop searching.
In your own example you hit the minimum value 3 (or 0011, which is the minimum from 1001 or 5) at iteration 4. You gained nothing from iterations five to seven.

*If you have 1101, Go from { 0, 1, 3, 2 } to the bit-permutated value "1110" as fast as possible.

Not sure about the performances, but you could try precalculating the values from the table, even if this requires a 32x32 = 1024 32-value table - 4M of memory.
Considering the first position (our number is 1101), the permutation can have in position 0 only these values: 0, 1, 2, or 3. These have a value of 1___, 1___, 0___ or 1___. So our position 0 table is { 1000, 1000, 0000, 1000 }.
The second position is identical: { 1_, 1_, 0_, 1_ } and so we have { 0100, 0100, 0000, 0100 }.
The next two rows are { 0010, 0010, 0000, 0010 }
{ 0001, 0001, 0000, 0001 }.
Now, you want to calculate the value if permutation { 3, 0, 1, 2 } is applied:
for (i = 0; i < 4; i++) {
    value |= table[i][permutation[i]];
}

===
But (again, if I understood the problem), let us say that the number has one fourth zeroes (it is made up of 24 1's, 8 0's) and the table is sizeable enough.
There is a very significant chance that you very soon hit both a permutation that puts a bit 1 in the 31st position, yielding some 2 billion, and another that puts a 0 there, yielding one billion.
The minimum will then surely be below two billions, so from now on, as soon as you check the first permutated bit and find it is a 1, you can stop calculating, you won't get a better minimum out of that permutation. Skip immediately to the next.
If you do this check at every cycle instead of only the first,
for (i = 0; i < 4; i++) {
    value |= table[i][permutation[i]];
    if (value > minimum) {
        break;
    }
}

I fear that you might eat any gains, but on the other hand, since values are automatically ordered in descending order, the first bits would get eliminated the most, avoiding the subsequent checks. It might be worth checking.
Nothing stops you from doing the calculation in two steps:
for (i = 0; i < 8; i++) {
    value |= table[i][permutation[i]];
    if (value > minimum) {
        break;
    }
}
if (value < minimum) {
    for (; i < 32; i++) {
        value |= table[i][permutation[i]];
    }
}


Q: WEB API returning TSV instead of XML/Json How can i make MVC or WEBAPI return TSV instead of XML or Json?
Is there any converter that will make this possible for me?
I have this API which returns either XML or Json, but i now want it to return tsv:
http://api.friliv.dk/api/miintoproducts