Q: Can floating point multiplication by zero be optimised at runtime? I am writing an algorithm to find the inverse of an nxn matrix. Let us take the specific case of a 3x3 matrix.
When you invert a matrix by hand, you typically look for rows/columns containing one or more zeros to make the determinant calculation faster as it eliminates terms you need to calculate.
Following this logic in C/C++, if you identify a row/column with one or more zeros, you will end up with the following code:
float term1 = currentElement * DetOf2x2(...);
//           ^
//           This is equal to 0.
//
// float term2 = ... and so on.

As the compiler cannot know currentElement will be zero at compile time, it cannot be optimised to something like float term = 0; and thus the floating point multiplication will be carried out at runtime.
My question is, will these zero values make the floating point multiplication faster, or will the multiplication take the same amount of time regardless of the value of currentElement? If there is no way of optimising the multiplication at runtime, then I can remove the logic that searches for rows/columns containing zeros.

A: float term1 = currentElement * DetOf2x2(...);

The compiler will call DetOf2x2(...) even if currentElement is 0: that's sure to be far more costly than the final multiplication, whether by 0 or not.  There are multiple reasons for that:

*

*DetOf2x2(...) may have side effects (like output to a log file) that need to happen even when currentElement is 0, and

*DetOf2x2(...) may return values like the Not-a-Number / NaN sentinel that should propagate to term1 anyway (as noted first by Nils Pipenbrinck)

Given DetOf2x2(...) is almost certainly working on values that can only be determined at run-time, the latter possibility can't be ruled out at compile time.
If you want to avoid the call to Detof2x2(...), try:
float term1 = (currentElement != 0) ? currentElement * DetOf2x2(...) : 0;

A: Modern CPUs will actually handle a multiply-by-zero very quickly, more quickly than a general multiply, and much more quickly than a branch. Don't even bother trying to optimize this unless that zero is going to propagate through at least several dozen instructions.

A: The compiler is not allowed to optimize this unless the calculation is trival (e.g. all constants).
The reason is, that DetOf2x2 may return a NAN floating point value. Multiplying a NAN with zero does not return zero but a NAN again.
You can try it yourself using this little test here:
int main (int argc, char **args)
{
  // generate a NAN
  float a = sqrt (-1);

  // Multiply NAN with zero..
  float b = 0*a;

  // this should *not* output zero
  printf ("%f\n", b);
}

If you want to optimize your code, you have to test for zero on your own. The compiler will not do that for you.

A: Optimisations performed at runtime are known as JIT (just-in-time) optimisations. Optimisations performed at translation (compilation) are known as AOT (ahead-of-time) optimisations. You're referring to JIT optimisations. A compiler might introduce JIT optimisations into your machine code, but it's certainly a far more complex optimisation to implement than the common AOT optimisations. Optimisations are typically implemented based on significance, and this kind of "optimisation" might be seen to affect other algorithms negatively. C implementations aren't required to perform any of these optimisations.
You could provide the optimisation manually, which would be "the logic that searches for rows/columns containing zeros", or something like this: float term1 = currentElement != 0 ? currentElement * DetOf2x2(...) : 0;

A: The following construct is valid at compile time when the compiler can guess the value of "currentElement".
float term1 = currentElement ? currentElement * DetOf2x2(...) : 0;
If it cannot be guessed at compile time, it will be checked at run-time and the performance depends on processor architecture : the trade-off between a branch (include branch latency and the delay to rebuild the instruction pipeline can be up to 10 or 20 cycles) and flat code (some processors run 3 instructions per cycle) and hardware branch prediction (when the hardware supports branch prediction).
Since multiplications throughput is close to 1 cycle on a x86_64 processor, there is no perf differenec depending on operand values like 0.0, 1.0, 2.0 or 12345678.99. if such a difference exists, that would be perceived as a covert channel in cryptographic-style software.
GCC allows to check function parameters at compile time
inline float myFn(float currentElement, myMatrix M)
{
#if __builtin_constant_p(currentElement) && currentElement == 0.0
return 0.0;
#else
return currentElement * det(M);
#endif
}
you need to enable inlining and interprocedural optimizations in the compiler.


Q: In Openpyxl - want to convert the excel cell value into a integer while copying data into csv I am copying a csv values into excel using openpyxl.
  with open('file_modified.csv', 'r') as f:
    reader = csv.reader(f, delimiter="|")
    next(reader, None) #skip the headers in the csv file
    i = 2 # paste into second row of the excel
  for row in reader:
        for j in range(1, len(row)):
            if(j==1 or j==10):
                ws_1.cell(row=i, column=j).value = float(row[j - 1])
                ws_1.cell(row=i, column=j).number_format = '0000000000'
            else:
                # writing the read value to destination excel file
                ws_1.cell(row=i, column=j).value = row[j-1]
        i +=1
     wb_1.save(destination_file)

But still when i open excel the column 1, column 10 still shows error. I need to manually go and convert it to string. Also when i open excel its throws recover error. Not sure why.

-Prasanna.K


Q: Using git as backup tool with cron and ssh aliases I have a repository for storing all my configs (e. g. .ssh/config). From time to time I need a backup them, so I need to run these commands
git commit -am 'Auto git backup `date -I`'
git push origin master

It is pretty annoying so I decided to make a cron job, which runs simple script with these lines above. I ran crontab -e and added new line at the end of file. I also replaced git with which git inside of script. git commit command works perfectly in contrast with git push. When I made some debug prints I got
ssh: Could not resolve hostname bitbucket.org: Name or service not known
fatal: Could not read from remote repository.
Please make sure you have the correct access rights
and the repository exists.

But when I run script manually, it works. I think it is because of SSH aliases in my .ssh/config, which looks like
Host     bitbucket.org-personal
HostName bitbucket.org
PreferredAuthentications publickey
IdentityFile ~/.ssh/id_rsa

Host    bitbucket.org-work
HostName bitbucket.org
PreferredAuthentications publickey
IdentityFile ~/.ssh/another_id_rsa

Does somebody have idea, how to propagate SSH aliases to environment, which runs cron jobs? Also maybe I am wrong and problem is caused by something else.

A: The issue was a network connection. When I added sleep (or modified solution from here How to check internet access using bash script in linux?) at the begging of the script, it works perfectly.


Q: How to add more data into LocalStorage instead of overwriting it in contenteditable attribute? I want to create contenteditable in div when user add something in it then it should add in local storage. but right now it is overwrite when add another data.
HTMl code
<!DOCTYPE html>

        Here is the element's original content

    <input type="button" value="save my edits" onclick="saveEdits()" />

 - Edit the text and click to save for next time

Your Name

JS code
function saveEdits() {

    //get the editable element
    var editElem = document.getElementById("edit");

    //get the edited element content
    var userVersion = editElem.innerHTML;

    //save the content to local storage
    localStorage.userEdits = userVersion;

    //write a confirmation to the user
    document.getElementById("update").innerHTML = "Edits saved!";

}

function checkEdits() {

    //find out if the user has previously saved edits
    if (localStorage.userEdits != null)
        document.getElementById("edit").innerHTML = localStorage.userEdits;
}

A: You need to change your saveEdits function to check is there anything saved on storage with the same key or not. To achieve it I will recommend you to use get and set item from API here some example how you can do it.
function saveEdits() {

  //get the editable element
  var editElem = document.getElementById("edit");

  //get the edited element content
  var userVersion = editElem.innerHTML;

  //get previously saved
  const previousEditsStr = localstorage.getItem('userEdits');

  // parse allready saved edits or create empty array
  const savedEdits = previousEditsStr ? JSON.parse(previousEditsStr) : [];

  // push the latest one
  savedEdits.push(userVersion);

  //stringify and save the content to local storage
  localStorage.setItem('userEdits', JSON.stringify(savedEdits));

  //write a confirmation to the user
  document.getElementById("update").innerHTML = "Edits saved!";
}

Please be noticed that the memory here is limited and you need to take it under your control. For example you can limit previously saved comments.
Since we are saving an array thats men you need to change your reading part as well
function checkEdits() {
  const userEdits = localStorage.getItem('userEdits');

  //find out if the user has previously saved edits
  if (userEdits) {

    // here is the saved edits
    const comments = JSON.parse(userEdits);

    // showing previously saved message
    document.getElementById("edit").innerHTML = comments[comments.length - 1];
  }
}


Q: Read data from json This is my JSON file
{
 "styleMapping": {
  "1": {
  "zIndex": 1,
  "StyleMappingCollection": {
    "636404903145791477": {
      "border": {
        "color": "#FF000000",
        "width": "Small",
        "type": "Solid"
      },
      "background": {
        "bgOption": "Image",
        "thumbOption": "Pointer",
        "opacity": 1.0,
        "bgColor": "#FFF5F5DC",
        "bgImage": "C:\Users\raj\Downloads\images\image.jpg",
      }
 }
}

i want to capture bgImage parameter in my javascript.
My script code is
 $http.get('Data//xyz.json').then(successCallback, errorCallback);

                function successCallback(response)
                {
                   sliderCtrlPtr.sliderParams = response.data;
                   sliderCtrlPtr.sliderParams.height = response.data.deviceHeight;

                   console.log("After JSON read : ",sliderCtrlPtr.sliderParams);

                }
                function errorCallback(error)
                {
                    //error code
                }

                sliderCtrlPtr.GetsliderStyle = function ()
                {
                    if(sliderCtrlPtr.sliderParams != undefined)
                    {
                        var styleObj = sliderCtrlPtr.sliderParams;
                        canvas.color = styleObj.StyleMappingCollection.
 636404903145791477.background.bgColor;
             }
          };
    }]);
})();

i want to retrieve bgColor or bgImage parameter from my json file in my script. How can I do that?

A: I think the line should be. From the JSON provided which is not complete, I could only find this error!
sliderCtrlPtr.GetsliderStyle = function() {
    if (sliderCtrlPtr.sliderParams != undefined) {
      var styleObj = sliderCtrlPtr.sliderParams;
      canvas.color = styleObj["styleMapping"]["1"]["StyleMappingCollection"]
      ["636404903145791477"]["background"]["bgColor"];
      canvas.image = styleObj["styleMapping"]["1"]["StyleMappingCollection"]
      ["636404903145791477"]["background"]["bgImage"];
    }
}

A: Dot notation:
First you need to parse the JSON with
obj = JSON.parse(json);

Since the JSON contains objects, you then use the dot notation, e.g.
var backColor = obj.StyleMappingCollection.background.bgcolor;

The thing is, those numeric field names in the JSON could cause problems in using this.
This is en excerpt from a program I've written, in which I have a partners.json file (which contains nested objects in different levels) and I want to store the JSON offices field in an object.
The JSON file is in this form:
    [
      {
        "id": 1,
        "urlName": "test-url",
        "organization": "Test Organization",
        "customerLocations": "Global",
        "willWorkRemotely": true,
        "website": "http://www.testurl.com/",
        "services": "This is a test services string",
        "offices": [
          {
            "location": "Random, Earth",
            "address": "Randomness 42, 109 Some St \nRandomville 2000",
            "coordinates": "-33.8934219,151.20404600000006"
          }
        ]
      }, {"id": 2, ... }]

I import the JSON in my JavaScript code:
/* import partner information from the supplied JSON file */
var partners = require('./partners.json');

And then I parse and stringify the required "offices" fields accordingly:
/* extract all office locations */
var officeLocations = {};
for (var i = 0; i < partners.length; i++) {
    officeLocations[i] = JSON.parse(JSON.stringify(partners[i].offices));
}

Hope this helps.


Q: What is the solution to Check internet connectivity getnetworkInfo' is deprecated , what is the solution? I am using compilesdkversion 24.

A: Simple way !
  public static boolean isConnectingToInternet(@NonNull Context context) {
        ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivity != null) {
            NetworkInfo info = connectivity.getActiveNetworkInfo();
            if (info != null) {
                if (info.getType() == ConnectivityManager.TYPE_WIFI || info.getType() == ConnectivityManager.TYPE_MOBILE || info.getType() == ConnectivityManager.TYPE_ETHERNET || info.getType() == ConnectivityManager.TYPE_WIMAX) {
                    return true;
                }
            }
        }
        return false;
    }

How to use just check
if (!isConnectingToInternet(getContext())) {
   // here no internet connection
}

A: you can use getActiveNetworkInfo() instead of getnetworkinfo , because there were some other factors which weren't considered before ,like network state can vary app to app while using getnetworkinfo hence deprecated docs
ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo activeNetwork = connectivityManager.getActiveNetworkInfo();
if(activeNetwork!=null && activeNetwork.isConnectedOrConnecting()){
  // yeah we are online
}else{
  // oops! no network
}

Note : put a nullity check too to confirm it is not null before accessing the network  status

A:     public class NetworkUtils {

        public static boolean isConnected(Context context) {
            ConnectivityManager connectivityManager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo activeNetwork = connectivityManager.getActiveNetworkInfo();

            return (activeNetwork != null)
                    && activeNetwork.isConnectedOrConnecting();
        }

}

Use this class to check network connection as:
if(NetworkUtils.isConnected(getContext())) {
     //Call your network related task
  } else {
     //Show a toast displaying no network connection
    }

A: Use ConnectivityManager to get network access. you can use BroadcastReceiver to get constant updates of your network status.
package your_package_name;

import android.content.Context;
import android.content.ContextWrapper;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;

public class ConnectivityStatus extends ContextWrapper{
public ConnectivityStatus(Context base) {
    super(base);
}

public static boolean isConnected(Context context){

    ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo connection = manager.getActiveNetworkInfo();
    if (connection != null && connection.isConnectedOrConnecting()){
        return true;
    }
    return false;
 }
}

Receive updates from your network class, use this in your main class where to update status.
Register Receiver on class
getContext().registerReceiver(receiver, new IntentFilter(ConnectivityManager.CONNECTIVITY_ACTION));
private BroadcastReceiver receiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
        if(!ConnectivityStatus.isConnected(getContext())){
            //not connected
        }else {
            //connected
        }
    }
};


Q: How to change facebook comment box if params change in current component (angular6) in current i use facebook comments plugin it can show comment only first params if i router to current component (but send new params)
comment box it's not update

My Question: Is it possible, if i router to current component but
  change params (http://localhost:4000/content?contentId=1 to
  http://localhost:4000/content?contentId=2) than ( commentBox Id=1 will
  change to commentBox Id=2 )

sorry for my english,
thank for your help

** i try to use angular2+lazyload , angular6+universal , ngx-facebook but it not work!! ( or i have a mistake ?)

A: This is the approach you want:
ngOnInit() {
    this.activeRoute.queryParams.subscribe(queryParams => {
        // do something with the query params
    });

    this.activeRoute.params.subscribe(routeParams => {
        this.loadUserDetail(routeParams.id);
    });
}

See https://kamranahmed.info/blog/2018/02/28/dealing-with-route-params-in-angular-5/


Q: How to trigger the change event of Kendo Jquery Spreadsheet when using custom Paste function? I tried the below custom paste function to paste only values but it doesn't trigger the change event in order for me to sync the data to the data source.
Dojo Demo Link
...
change: onExcelChange,
paste: function(e) {
            e.preventDefault()

            var currentRange = e.range;
            var fullData = e.clipboardContent.data;
            var mergedCells = e.clipboardContent.mergedCells;
            var topLeft = currentRange.topLeft();
            var initialRow = topLeft.row;
            var initialCol = topLeft.col;
            var origRef = e.clipboardContent.origRef;
            var numberOfRows = origRef.bottomRight.row - origRef.topLeft.row + 1;
            var numberOfCols = origRef.bottomRight.col - origRef.topLeft.col + 1;
            var spread = e.sender;
            var sheet = spread.activeSheet();
            var rangeToPaste =  sheet.range(initialRow, initialCol, numberOfRows, numberOfCols);

            sheet.batch(function() {
                for(var i = 0; i < fullData.length; i += 1) {
                    var currentFullData = fullData[i];

                    for(var j = 0; j < currentFullData.length; j += 1 ) {
                        var range = sheet.range(initialRow + i, initialCol + j);
                        var value = currentFullData[j].value;

                        if (value !== null) {
                            range.input(value);
                            range.format(null);
                        }
                    }
                }
                 sheet.select(rangeToPaste);
            }, { layout: true, recalc: true });
        } ...

I have tried to use recalc: true in sheet.batch to trigger the change to no avail. Any help would be greatly appreciated.

A: All Kendo widgets inherit from Observable, which has a trigger method:
var obj = new kendo.Observable();
obj.bind("myevent", function(e) {
    console.log(e.data); // outputs "data"
});
obj.trigger("myevent", { data: "data" });

You need to manually trigger the Spreadheet's change event with its correct parameters.


Q: Showing Popup Async I want an alert to be shown according to an async logic.
This is my code :
@IBAction func AddToFavoriteButton(_ sender: Any)
    {
        IsItemInFavoritesAsync(productId: productToDisplay.UniqueID())
        {
            success in

            // Product exists in favorite tree
            Constants.showAlert(title: "Item in Tree", message: "Yes it is", timeShowing: 1, callingUIViewController: self)
        }
        // Product doesn't exist in favorite tree
        Constants.showAlert(title: "Item NOT in Tree", message: "Isn't", timeShowing: 1, callingUIViewController: self)
        Product.RegisterProductOnDatabaseAsFavorite(prodToRegister: productToDisplay, productType: productType)
    }

    private func IsItemInFavoritesAsync(productId: String, completionHandler: @escaping (Bool) -> ())
    {
        let favoriteTree = productType == Constants.PRODUCT_TYPE_SALE ? Constants.FAVORITE_TREE_SALE : Constants.FAVORITE_TREE_PURCHASE
        Constants.refs.databaseRoot.child(favoriteTree).child((Constants.refs.currentUserInformation!.uid)).observeSingleEvent(of: .value, with: {(DataSnapshot) in

            return DataSnapshot.hasChild(self.productToDisplay.UniqueID()) ? completionHandler(true) : completionHandler(false)

        })

    }

What this code snippet does is:

*

*Check if a product was saved to favorites

*If it has, show popup A

*If it has not, show popup B

I followed another post on StackOverflow that stated that's how I was supposed to call the async function. (Can Swift return value from an async Void-returning block?)
What actually happens is that only popup B shows (the one outside the IsItemInFavoritesAsync closure). What is my mistake?
I guess that IsItemInFavoritesAsync enters the closure upon finishing, and the function IsItemInFavoritesAsync continues onwards to the "Product not in tree" section.
Notice: the function IsItemInFavoritesAsync reads from Firebase.
How do I fix this?

A: Both actions (positive result and negative result) need to be inside the completion handler.
So something like this:
IsItemInFavoritesAsync(productId: productToDisplay.UniqueID()) { success in
    if success {
      // Product exists in favorite tree
      Constants.showAlert(title: "Item in Tree", message: "Yes it is", timeShowing: 1, callingUIViewController: self)
    }
    else {
      // Product doesn't exist in favorite tree
      Constants.showAlert(title: "Item NOT in Tree", message: "Isn't", timeShowing: 1, callingUIViewController: self)
      Product.RegisterProductOnDatabaseAsFavorite(prodToRegister: productToDisplay, productType: productType)
    }
}


Q: double quotes pandas.read_csv I have large txt file with multiple words and chars and I'm trying to read this file into a pandas dataframe, with each word or char in a different row.
The problem is that " is one of the chars, and the function reads all the words between two " as a single word (because of the quoting).
How can I address this char as another regular char and not as a quoting char? I tried to play with the parameters of the read_csv function but couldn't manage to fix it.
My code now: data = pd.read_csv(filepath, header=None, delimiter = "\t")
Thanks in advance!

A: you can use the parameter quotechar
data = pd.read_csv("a.txt", delim_whitespace=True, header=None,quotechar="~")
print(data.head())

a.txt
abc def xyz
"abc xyz" def

Output
      0     1    2
0   abc   def  xyz
1  "abc  xyz"  def

there are qoutes left this way.

A: Try via numpy's genfromtxt() method:
import numpy as np

data=np.genfromtxt('data.csv',dtype='str',delimeter='\t',skip_header=1)

columns=np.genfromtxt('data.csv',dtype='str',delimiter='\t',skip_footer=len(data))

Finally:
df=pd.Dataframe(data=data,columns=columns)


Q: How to create calculated field based on another time series I have a set of prices as data source for given timeseries and I would like to create a calculated field by combining two prices for each date: i.e.,
 Price A *5 - Price B.
Data source:
Date    Product Price
01.01.2018  A   10
01.01.2018  B   15
02.01.2018  A   20
02.01.2018  B   30
03.01.2018  A   10
03.01.2018  B   30

I don't know how to write the formula correctly for the Calculated field.
What I expect is to build the following table:
Date    A   B   Combined Price (A *5 - B)
01.01.2018  10  15  35
02.01.2018  20  30  70
03.01.2018  10  30  20

Thank you

A: Answer from Mohfooj can be found in Tableau forum here: https://community.tableau.com/message/900181#900181


Q: Why is this VBA line erroring out? Little bit of context, I'm updating a VBA macro from the early 2000's to work in 2021 AutoCAD... Lots of little bugfixes mostly related to changes in language or references.
Here is the line that errors out with a "Run-time error '-2147221164(80040154)': Class not registered.".
Dim OutPDF as ABCpdf.Doc 'init the ABCpdf
'uses the OutPDF a few times, works fine
Set OutPDF = New ABCpdf.Doc

The ABCpdf.Doc works fine in between those two lines, everything executes correctly up until it hits that Set OutPDF line.
If there is more context needed for this, I can elaborate further.


Q: If my entity has a (0-1):1 relation to another entity, how would I model that in the database? For example, lets say I have an entity called user and an entity called profile_picture. A user may have none or one profile picture.
So I thought, I would just create a table called "user" with this fields:
user: user_id, profile_picture_id
(I left all other attributes like name, email, etc. away, to simplify this)
Ok, so if an user would have no profile_picture, it's id would be NULL in my relational model. Now someone told me that I have to avoid setting anything to NULL, because NULL is "bad".
What do you think about this? Do I have to take off that profile_picture_id from the user table and create a link-table like user__profile_picture with user_id, profile_picture_id?
Which would be considered to be "better practice" in database design?

A: This is a perfectly reasonable model. True, you can take the approach of creating a join table for a 1:1 relationship (or, somewhat better, you could put user_id in the profile_picture table), but unless you think that very few users will have profile pictures then that's likely a needless complication.
Readability is an important component in relational design. Do you consider the profile picture to be an attribute of the user, or the user to be an attribute of the profile picture? You start from what makes logical sense, then optimize away the intuitive design as you find it necessary through performance testing. Don't prematurely optimize.

A: "NULL is bad" is a rather poor excuse for a reason to do (or not do) something.
That said, you may want to model this as a dependent table, where the user_id is both the primary key and a foreign key to the existing table.
Something like this:
  Users                     UserPicture                   Picture
----------------          --------------------          -------------------
| User_Id (PK) |__________| User_Id (PK, FK) |__________| Picture_Id (PK) |
| ...          |          | Picture_Id (FK)  |          | ...             |
----------------          --------------------          -------------------

Or, if pictures are dependent objects (don't have a meaningful lifetime independent of users) merge the UserPicture and Picture tables, with User_Id as the PK and discard the Picture_Id.
Actually, looking at it again, this really doesn't gain you anything - you have to do a left join vs. having a null column, so the other scenario (put the User_Id in the Picture table) or just leave the Picture_Id right in the Users table both make just as much sense.

A: NULL isn't "bad".  It means "I don't know."  It's not wrong for you or your schema to admit it.

A: Your user table should not have a nullable field called profile_picture_id. It would be better to have a user_id column in the profile_picture table. It should of course be a foreign key to the user table.

A: Since when is a nullable foreign key relationship "bad?"  Honestly introducing another table here seems kind of silly since there's no possibility to have more than one profile picture.  Your current schema is more than acceptable.  The "null is bad" argument doesn't hold any water in my book.
If you're looking for a slightly better schema, then you could do something like drop the "profile_picture_id" column from the users table, and then make a "user_id" column in the pictures table with a foreign key relationship back to users.  Then you could even enforce a UNIQUE constraint on the user_id foreign key column so that you can't have more than one instance of a user_id in that table.
EDIT:  It's also worth noting that this alternate schema could be a little bit more future-proof should you decide to allow users to have more than one profile picture in the future.  You can simply drop the UNIQUE constraint on the foreign key and you're done.

A: It is true that having many columns with null values is not recommended. I would suggest you make the picture table a weak entity of user table and have an identifying relationship between the two. Picture table entries would depend on user id.

A: Make the profile picture a nullable field on the user table and be done with it. Sometimes people normalize just for normalization sake. Null is perfectly fine, and in DB2, NULL is a first class citizen of values with NULL being included in indices.

A: I agree that NULL is bad. It is not relational-database-style.
Null is avoided by introducing an extra table named UserPictureIds. It would have two columns, UserId and PictureId. If there's none, it simply would not have the respective line, while user is still there in Users table.
Edit due to peer pressure
This answer focuses not on why NULL is bad - but, on how to avoid using NULLs in your database design.
For evaluating (NULL==NULL)==(NULL!=NULL), please refer to comments and google.


Q: Aggregation matrices in subgroups I have few matrix. They are in few subgroups (I have vector which shows these subgroups - for example matrix 1 and 2 are in group A, matrix 3 in group B, matrix 4,5,6 in group C, and so on). I want to add all matrices in one group to have new matrix.
To sum up: input - matrices in some subgroups, output - matrices in amount of dimension of vector of subgroups)
How can I do it? I tried with 'aggregate' and 'tapply', but it doesn't work:
aggregate(list1,list2,func)
where
list1 contains all my matrices
list2 contains subgroups
func - my function to add matrices (it could be standard "+")
EXAMPLE
> subgroups=c(1,1,2,3,3,3)
> M1<-matrix(c(2,3,1,4),2,2)
> M1
     [,1] [,2]
[1,]    2    1
[2,]    3    4
> M2<-matrix(c(3,0,1,1),2,2)
> M2
     [,1] [,2]
[1,]    3    1
[2,]    0    1
> M3<-matrix(c(0,0,1,1),2,2)
> M3
     [,1] [,2]
[1,]    0    1
[2,]    0    1
> M4<-matrix(c(0,2,-9,-3),2,2)
> M4
     [,1] [,2]
[1,]    0   -9
[2,]    2   -3
> M5<-matrix(c(0,0,1,1),2,2)
> M5
     [,1] [,2]
[1,]    0    1
[2,]    0    1
> M6<-matrix(c(-1,2,2,1),2,2)
> M6
     [,1] [,2]
[1,]   -1    2
[2,]    2    1
> result=list(M1+M2,M3,M4+M5+M6)
> result
[[1]]
     [,1] [,2]
[1,]    5    2
[2,]    3    5

[[2]]
     [,1] [,2]
[1,]    0    1
[2,]    0    1

[[3]]
     [,1] [,2]
[1,]   -1   -6
[2,]    4   -1

A: Use tapply as shown:
L <- list(M1, M2, M3, M4, M5, M6)  # or mget(ls(pattern = "^M\\d$"))
tapply(L, subgroups, Reduce, f = "+")

giving:
$`1`
     [,1] [,2]
[1,]    5    2
[2,]    3    5

$`2`
     [,1] [,2]
[1,]    0    1
[2,]    0    1

$`3`
     [,1] [,2]
[1,]   -1   -6
[2,]    4   -1


Q: West Europe Cloud Service on Azure shows in the United States I have a deployed application on Windows Azure in West Europe. However, the IP I have been assigned (168.63.108.xx) is marked as being in the US on http://cqcounter.com/whois/
Is there something wrong with my deployment? If not, what is the reason that it is shown in the US?
Thanks in advance

A: This is probably an issue with the whois and how it maps the IP to a location. Take a look at this file, it contains the IP address ranges for the Azure datacenters. Here's what you'll see for West Europe:
<subregion name="West Europe">
  ..
  <network>168.63.0.0/19</network>
  <network>168.63.96.0/19</network>
  ..
</subregion>

Now, since this is IP range is in CIDR notation, there are a few tools which make it easy to find the complete range, like this one. So actually, 168.63.96.0/19 = 168.63.96.0 - 168.63.127.255. And this range includes 168.63.108.xx. So there's no issue with your deployment and you can be sure it's located in West Europe.


Q: two tables into one? My question is simple I just want to joint two tables into one table without any PK
first table is completely different they have nothing same
table1.            table2.
|в|q|              |@|John |
|ы|a|              |£|Sara |
|в|f|              |$|ciro |
|с|g|              |%|Jo.  |
|ф|s|

what I need is this
Table3
|в|q|@|John |
|ы|a|£|Sara |
|в|f|$|ciro |
|с|g|%|Jo.  |
|ф|s|-|-    |

A: This is a little complicated.  You want a "vertical" list but have nothing to match the columns.  You can use row_number() and union all:
select max(t1_col1), max(t1_col2), max(t2_col1), max(t2_col2)
from ((select t1.col1 as t1_col1, t1.col2 as t1_col2,
              null as t2_col1, null as t2_col2, row_number() over () as seqnum
       from table1 t1
      ) union all
      (select null, null, t2.col1, t2.col2, row_number() over () as seqnum
       from table2 t2
      )
     ) t
group by seqnum;

Here is a db<>fiddle.
Note that this will keep all rows in both tables, regardless of which is longer.  The specific ordering of the rows in each column is not determinate.  SQL tables represent unordered sets.  If you want things in a particular order, you need a column that specifies the ordering.
If you want to save this in a new table, put create table as table3 before the select.  If you want to insert into an existing table, use insert.


Q: How can I stub a gRPC or HTTP/2 request using WireMock.NET? I have a netcore web service that makes additional calls out to other webservices. One of those other web services is gRPC-based. I would like to write some tests at the protocol level by stubbing out the gRPC-based service with a simulated server.
How can I stub a gRPC or HTTP/2 request using WireMock.NET?

A: WireMock.NET does not currently support simulating HTTP/2 servers. This would require a change to the library to allow configuring the Protocol on the WireMockServer and a change to the internal ResponseMessage to better support stream bodies and trailing headers.


Q: Enforce single click in angular js I am creating a client and calling my API  but it takes at least 2 seconds to respond so I want to that user cannot click the REGISTER twice.
I am incorporating this fiddle in my controller.
https://jsfiddle.net/zsp7m155/
But What happening is that first function takes 2 second to disable the button and after that it enables he button and send request to API.
Am I doing something wrong here?
Code my my controller
CONTROLLER.JS
$scope.createClient = function() {

        ClientService.createClient($scope.theClient).then(function (aCreateClientResponse) {
            if(aCreateClientResponse[0] == $scope.RESPONSE_CODE.CM_SUCCESS) {
                alert('success');
            }
             else if(aCreateClientResponse[0] == $scope.RESPONSE_CODE.CM_DOMAINNAME_ERROR) {
                 alert('Check your domain name');
            }
            else if(aCreateClientResponse[0] == $scope.RESPONSE_CODE.CM_INVALID_INPUT) {

                alert('Invalid request');
            }
            else {

                alert('Service is not available');
            }
        });
 };

Code of my service
SERVICE.JS
 App.factory('ClientService', function($http,  API_URL, REQUEST_HEADER, RESPONSE_CODE) {

        createClient: function(aClient) {

        var myCreateClientRequest = {
            "CreateClientRequest": {
                "Header": {
                    "CMMHeader": {
                        "Id": uuid2.newuuid()
                    }
                },
                "Client": {
                    "OrganizationName": aClient.Name,
                    "OrganizationDomain": aClient.Domain,
                },
            }
        };

        //API Call
        var promise = $http.post(API_URL.CREATE_CLIENT, myCreateClientRequest, REQUEST_HEADER).then(
        function(aCreateClientResponse) { //Success Callback

            return [aCreateClientResponse.data.CreateClientResponse.Result.ResponseCode,''];
        },
        function(aCreateClientResponse) { //Error Callback

            return [aCreateClientResponse.status,''];
        });

        return promise;
    },

              });

HTML
<button id="register-btn" name="register-btn" class="btn btn-primary" ng-disabled="((Client.User.UserPassword !== Client.User.UserconfirmPassword) || CreateClientForm.domain.$invalid || CreateClientForm.username.$invalid || CreateClientForm.email.$invalid || CreateClientForm.password.$invalid || CreateClientForm.confirmpassword .$invalid || CreateClientForm.organizationname.$invalid )" single-click="createClient()">{{ running ? 'Please wait...' : 'Register' }}</button>

A: You have a couple of options, the most simple is just to disable the button when you call your API and re-enable when it resolves. You could do it like this:
<button id="register-btn" name="register-btn" class="btn btn-primary" ng-disabled="isRegistering" single-click="createClient()">{{ running ? 'Please wait...' : 'Register' }}</button>

and in your controller
$scope.isRegistering = false;

$scope.createClient = function() {

    $scope.isRegistering = true;
    return $timeout(function() {
        ClientService.createClient($scope.theClient).then(function (aCreateClientResponse) {
            $scope.isRegistering = false;
            if(aCreateClientResponse[0] == $scope.RESPONSE_CODE.CM_SUCCESS) {
                alert('success');
            }
             else if(aCreateClientResponse[0] == $scope.RESPONSE_CODE.CM_DOMAINNAME_ERROR) {
                 alert('Check your domain name');
            }
            else if(aCreateClientResponse[0] == $scope.RESPONSE_CODE.CM_INVALID_INPUT) {

                alert('Invalid request');
            }
            else {

                alert('Service is not available');
            }
        }, function(){
            $scope.isRegistering = false;
        });
    }, 1000);
 };


Q: Setting param to an element through jquery to ng-click I need to set param inside the ng-click i.e.,
I am able to set the id for the element, but I need to set the param inside the ng-click like ng-click="editorder(5)"
Here is the html

Script :
$(".order-edit").attr("id",message.data.id)

Help pls

A: Assign the id to a $scope
$scope.id = message.data.id
And use it as:

UPDATE:
Assigned a DOM Id to the li element in above and fetched the element as:
var editOrder = document.getElementById("editOrder");
Now, binding the ng-click with the id.
editOrder.bind('ng-click', { id: message.data.id}, function(event) {
    var data = event.data;
    alert(data.id);
});

PS: The update works for the javascript click event, its not tested for ng-click.
EDIT:
Tested for 'ng-click', it doesnt work.
You could look into this Fiddle and create a custom directive that suits the requirement.


Q: Spring cloud config doesn't detect git uri How do I reference resources directory (Or a directory relative to my source files) as my local git uri for the config server (On Windows)?
I've tried file:///resources and file:///full/path/to/resources, all seem to fail.
As requested, here's some code:
ConfigServiceApplication.java
@EnableConfigServer
@SpringBootApplication
public class ConfigServiceApplication {

    public static void main(String[] args) {
        SpringApplication.run(ConfigServiceApplication.class, args);
    }
}

application.properties
spring.cloud.config.server.git.uri=file:///full/path/to/resources
spring.application.name=config-service
server.port=8888

A: If you want to use file system as a backend, simply try this settings:
spring.profiles.active=native
spring.cloud.config.server.native.searchLocations: file:///full/path/to/resources

See also this documentation

A: I'm embarrassed to write this but intellij wouldn't clean the build. I ran the gradle task and it all worked out.


Q: What is the point of a Facade in Java EE? I'm not really understanding the point of a facade.
public abstract class AbstractFacade<T> {

    private Class<T> entityClass;

    public AbstractFacade(Class<T> entityClass) {
        this.entityClass = entityClass;
    }

    protected abstract EntityManager getEntityManager();

    public void create(T entity) {
        getEntityManager().persist(entity);
    }

    public void edit(T entity) {
        getEntityManager().merge(entity);
    }

    public void remove(T entity) {
        getEntityManager().remove(getEntityManager().merge(entity));
    }

    public T find(Object id) {
        return getEntityManager().find(entityClass, id);
    }

    public List<T> findAll() {
        CriteriaQuery cq = getEntityManager().getCriteriaBuilder().createQuery();
        cq.select(cq.from(entityClass));
        return getEntityManager().createQuery(cq).getResultList();
    }

    public List<T> findRange(int[] range) {
        CriteriaQuery cq = getEntityManager().getCriteriaBuilder().createQuery();
        cq.select(cq.from(entityClass));
        Query q = getEntityManager().createQuery(cq);
        q.setMaxResults(range[1] - range[0]);
        q.setFirstResult(range[0]);
        return q.getResultList();
    }

    public int count() {
        CriteriaQuery cq = getEntityManager().getCriteriaBuilder().createQuery();
        Root<T> rt = cq.from(entityClass);
        cq.select(getEntityManager().getCriteriaBuilder().count(rt));
        Query q = getEntityManager().createQuery(cq);
        return ((Long) q.getSingleResult()).intValue();
    }
}

If I have this code and then I have an EJB like this.
@Stateless
public class WrapSpecFacade extends AbstractFacade<WrapSpec> {
    @PersistenceContext
    private EntityManager em;

    @Override
    protected EntityManager getEntityManager() {
        return em;
    }

    public WrapSpecFacade() {
        super(WrapSpec.class);
    }

}

What is the point of this?  Why call this a facade?  To me it's just an abstract class that groups similar functionality.  Thanks.

A: Typically this pattern is used to either hide the implementation of the underlying classes it is presenting an interface for, or to simplify the underlying implementation of something that may be complex.
A facade may present a simple interface to the outside world, but under the hood do things like create instances of other classes, manage transactions, handle files or TCP/IP connections -- all stuff that you can be shielded from by the simplified interface.

A: In your particular context, this is not really a Facade. What you have in that code is basically a DAO (Data Access Object).
A DAO can be seen as a Facade for DB operations, but this is not its main purpose. It mainly intends to hide the DB internals. In your example, if you're switching the underlying storage system to XML files or to some key-value store like HBase, you can still use the methods defined in that "Facade" and no change is required in the client code.
A (traditional) Facade deals with complex designs that need to be hidden from the clients. Instead of exposing a complex API and complex flows (get this from this service, pass it to this converter, get the result and validate it with this and then send it to this other service), you just encapsulate all that in a Facade and simply expose a simple method to clients. This way, along with the fact that your API is a lot easier to use, you are also free to change the underlying (complex) implementation without breaking your clients code.

A: Facade is a design pattern. A pattern, a software pattern, is a set of rules in order to organize code and provide a certain structure to it. Some goals can be reached by using a pattern.
A design pattern is used when designing the application.
The Facade pattern allows programmers to create a simple interface for objects to use other objects.
Consider working with a very complex group of classes, all implementing their own interfaces.
Well, you want to provide an interface to expose only some functionality of the many you have.
By doing so, you achieve code simplicity, flexibility, integration and loose-coupling.
Facade, in your example, is used in order to manage coupling between many actors. It is a design issue. When you have many components interacting together, the more they are tied the harder it will be to maintain them (I mean code maintenance). Facade allows you to reach loose coupling, which is a goal a programmer should always try to reach.
Consider the following:
public class MyClass1 implements Interface1 {
   public void call1() {}
   public call call2() {}
}

public class MyClass2 implements Interface2 {
   public void call3() {}
   public void call4() {}
}

public class MyClass {
   private MyClass1 a;
   private MyClass2 b;
   //calling methods call1 call2 call3 and call4 in other methods of this class
   ...
   ...
}

If you had to change business logic located in a class used by call1 or call2... by not changing the interface, you would not need to change all these classes, but just the class inside the method used by one of the interface methods of the first two classes.
Facade lets you improve this mechanism.
I am sorry but I realize that it does not look so wonderful. Design patterns are heavily used in the software industry and they can be very useful when working on large projects.
You might point out that your project is not that large and that may be true, but Java EE aims to help business and enterprise-level application programming. That's why sometimes the facade pattern is used by default (some IDEs use it too).


Q: Programmatically Presenting and Dismissing Views SwiftUI I am working on a project that is attempting to present and dismiss views in a NavigationView using state and binding. The reason I am doing this is there is a bug in the @Environment(.presentationMode) var presentaionMode: Binding
model. It's causing odd behavior. It's discussed in this post here.
The example below has three views that are progressively loaded on to the view. The first two ContentView to NavView1 present and dismiss perfectly. However, once NavView2 is loaded, the button that is used to toggle the state of presentNavView2 ends up adding another NavView2 view on the stack and does not dismiss it as expected. Any thoughts as to why this would be?
ContentView
struct ContentView: View {
    @State private var presentNavView1 = false

    var body: some View {
        NavigationView {
            List {
                NavigationLink(destination: NavView1(presentNavView1: self.$presentNavView1), isActive: self.$presentNavView1, label: {
                    Button(action: {
                        self.presentNavView1.toggle()
                    }, label: {
                        Text("To NavView1")
                    }) // Button
                }) // NavigationLink
            } // List
            .navigationTitle("Home")
        } // NavigationView
    } // View
}

NavView1
struct NavView1: View {

    @State private var presentNavView2 = false

    @Binding var presentNavView1: Bool

    var body: some View {
        List {
            NavigationLink(destination: NavView2(presentNavView2: self.$presentNavView2), isActive: self.$presentNavView2, label: {
                Button(action: {
                    self.presentNavView2.toggle()
                }, label: {
                    Text("To NavView2")
                }) // Button
            }) // NavigationLink
            Button(action: {
                self.presentNavView1.toggle()
            }, label: {
                Text("Back")
            })
        } // List
        .navigationTitle("NavView1")
    } // View
}

NavView2
struct NavView2: View {
    @Binding var presentNavView2: Bool

    var body: some View {
        VStack {
            Text("NavView2")
            Button(action: {
                self.presentNavView2.toggle()
            }, label: {
                Text("Back")
            }) // Button
        } // VStack
        .navigationTitle("NavView2")
    }
}

A: You can use DismissAction, because PresentationMode will be deprecated. I tried the code and it works perfectly! Here you go!
import SwiftUI

struct MContentView: View {
    @State private var presentNavView1 = false

    var body: some View {
        NavigationView {
            List {
                NavigationLink(destination: NavView1(), isActive: self.$presentNavView1, label: {
                    Button(action: {
                        self.presentNavView1.toggle()
                    }, label: {
                        Text("To NavView1")
                    })
                })
            }
            .navigationTitle("Home")
        }
    }
}

struct NavView1: View {
    @Environment(\.dismiss) private var dismissAction: DismissAction

    @State private var presentNavView2 = false

    var body: some View {
        List {
            NavigationLink(destination: NavView2(), isActive: self.$presentNavView2, label: {
                Button(action: {
                    self.presentNavView2.toggle()
                }, label: {
                    Text("To NavView2")
                })
            })
            Button(action: {
                self.dismissAction.callAsFunction()
            }, label: {
                Text("Back")
            })
        }
        .navigationTitle("NavView1")
    }
}

struct NavView2: View {
    @Environment(\.dismiss) private var dismissAction: DismissAction

    var body: some View {
        VStack {
            Text("NavView2")
            Button(action: {
                self.dismissAction.callAsFunction()
            }, label: {
                Text("Back")
            })
        }
        .navigationTitle("NavView2")
    }
}

struct MContentView_Previews: PreviewProvider {
    static var previews: some View {
        MContentView()
    }
}


Q: Setting quality levels to Plyr player with HLS from .m3u8 file I am using Plyr player with HLS implementation in an angular component, I did all the settings mentioned in the below post
Adding Quality Selector to plyr when using HLS Stream
Still, I can't get the quality setting option in UI. Upon clicking gear icon, only speed options with 8 options showing(.75 to 4 ). For the .m3u8 file, even if I set the quality level to player quality option, it won't be showing in UI.
In the console, from player.config.speed attribute i can find the speed options showing in the player UI, but the player.config.quality is showing some in build value like { default: 576, options: [4320, 2880, 2160, 1440, 1080, 720, 576, 480, 360, 240] } same as plyr README.md file
I tried to set the quality level from Hls.Event.Manifest.Parsed event.
Does anybody know how to set quality levels from .m3u8 file to Plyr player? Please help


Q: Autofilter a range of time in excel using VBA I have tried to create a macro to auto filter the time range from 12:00:00 am to 3:00:00 am. But the code gave me an error. What is wrong with my code?
Sub TIME()

 T1 = TimeSerial(0, 0, 0)
 T2 = TimeSerial(0, 3, 0)

 ActiveSheet.Range("$B$1:$L$597064").AutoFilter Field:=3, Criteria1:=">=" & T1, Operator:=xlAnd, Criterial2:="<" & T2

End Sub


Q: Unsupported Media Type 415 Error in Angular 7 & .NET Core API I'm passing in a selected row to delete in my Angular Application using selection on a material data table. For some reason though, I'm getting a 415 error. Not sure what I'm doing wrong, either on the server or the client side, but I'm not sure even if I'm passing the correct object.
What's the issue here? I'm using Angular 7 for the client and making the API in .NET Core
ActionsController.cs .NET Core
 [HttpDelete("deleteRow")]
    public Msg DeleteRows(string sessionId, T table, Tag[] rows)
    {
        try
        {
            UserState userState = GetUserState(sessionId);

            Msg m = CheckTableAccess(sessionId, table, TableAccessLevel.ReadModifyCreateDelete, userState);

            if (m.IsNotOk)
                return m;

            if (table == T.Action)
            {
                foreach (Tag t in rows)
                {
                    m = CheckUpdatableAction(sessionId, rows[0]);
                    if (m.IsNotOk)
                        return m;
                }
            }

            if (table == T.RouteStop)
            {
                XioTransaction xt = new XioTransaction(userState);
                XioWriter xwd = null;
                xwd = xt.CreateDeleteWriter(table);
                foreach (Tag t in rows)
                {
                    XioTable routeStop = new XioTable(userState, T.RouteStop);
                    Tag ownerTag = ((DbrRouteStop)routeStop.LoadSingleRow(t, C.RouteStop_RouteTag)).RouteTag;
                    xwd.DeleteRow(t, ownerTag);
                }
                xt.WriteAll();
            }
            else if (table == T.RouteEvent)
            {
                XioTransaction xt = new XioTransaction(userState);
                XioWriter xwd = null;
                xwd = xt.CreateDeleteWriter(table);

                foreach (Tag t in rows)
                {
                    XioTable routeEvent = new XioTable(userState, T.RouteEvent);
                    Tag ownerTag = ((DbrRouteEvent)routeEvent.LoadSingleRow(t, C.RouteEvent_RouteTag)).RouteTag;
                    xwd.DeleteRow(t, ownerTag);
                }
                xt.WriteAll();
            }
            else if (table == T.CompanyResource)
            {
                XioTransaction xt = new XioTransaction(userState);
                XioWriter xwd = null;
                xwd = xt.CreateDeleteWriter(table);

                foreach (Tag t in rows)
                {
                    XioTable cr = new XioTable(userState, T.CompanyResource);
                    DbrCompanyResource crRec = (DbrCompanyResource)cr.LoadSingleRow(t, C.CompanyResource_CompanyTag, C.CompanyResource_Tab);

                    XioTable xtr = new XioTable(userState, crRec.Tab);
                    // the critical where is on divisiontag and all tables that are passed in will have a divion tag
                    // luckily the code will just look at the field name
                    xtr.WhereList.Where(C.Driver_DivisionTag, ComparisonOp.EqualTo, crRec.CompanyTag);
                    xtr.LoadData();
                    if (xtr.GetAllRows().Length > 0)
                        return new Msg(M.ResourcesExistAtCompanyLevel);
                    xwd.DeleteRow(t);
                }
                xt.WriteAll();
            }
            else
                DbRow.DeleteRecursive(userState, table, rows);

            userState.Completed(LogEntryType.DeleteRows, null);
        }
        catch (MsgException e)
        {
            return e.Msg;
        }

        catch (SqlException e)
        {
            if (e.Number == 547)
            {
                return new Msg(M.CannotDeleteOwnerRowWithComponent);
            }
            else
                return new Msg(M.UnexpectedViewDeleteError, e.ToString());
        }
        catch (Exception e)
        {
            return new Msg(M.UnexpectedViewDeleteError, e.ToString());
        }

        return Msg.Ok;
    }

ViewComponent.ts
    export class ViewComponent implements OnInit, OnDestroy {

  // User Fields
  currentUser: User;
  users: User[] = [];
  currentUserSubscription: Subscription;

  loading : boolean;
  // Action Fields
  viewData: any;
  viewName: string;
  refNumber: number;
  currentActionSubscription: Subscription;
  displayedColumns: string[] = [];
  dataSource: any = new MatTableDataSource([]);
  pageSizeOptions: number[] = [10, 20, 50];

  @ViewChild(MatSort) sort: MatSort;
  @ViewChild(MatPaginator) paginator: MatPaginator;

  selection = new SelectionModel<TableRow>(true, []);

  defaultSort: MatSortable = {
    id: 'defColumnName',
    start: 'asc',
    disableClear: true
  };

  defaultPaginator: MatPaginator;

  constructor(
    private iconRegistry: MatIconRegistry,
    private sanitizer: DomSanitizer,
    private actionService: ActionService
  ) {
    this.loading = false;
    this.iconRegistry.addSvgIcon(
      'thumbs-up',
      this.sanitizer.bypassSecurityTrustResourceUrl(
        'assets/img/examples/thumbup-icon.svg'
      )
    );
  }

  loadAction(action: any) {

    this.loading = true;
    // If there is already data loaded into the View, cache it in the service.
    if (this.viewData) {
      this.cacheAction();
    }

    if (this.sort) {
      // If there is sorting cached, load it into the View.
      if (action.sortable) {
        // If the action was cached, we should hit this block.
        this.sort.sort(action.sortable);
      } else {
        // Else apply the defaultSort.
        this.sort.sort(this.defaultSort);
      }
    }

    if (this.paginator) {
      // If we've stored a pageIndex and/or pageSize, retrieve accordingly.
      if (action.pageIndex) {
        this.paginator.pageIndex = action.pageIndex;
      } else { // Apply default pageIndex.
        this.paginator.pageIndex = 0;
      }

      if (action.pageSize) {
        this.paginator.pageSize = action.pageSize;
      } else { // Apply default pageSize.
        this.paginator.pageSize = 10;
      }
    }

    // Apply the sort & paginator to the View data.
    setTimeout(() => this.dataSource.sort = this.sort, 4000);
    setTimeout(() => this.dataSource.paginator = this.paginator, 4000);

    // Load the new action's data into the View:
    this.viewData = action.action;
    this.viewName = action.action.ActionName;
    this.refNumber = action.refNumber;

    // TODO: add uniquifiers/ids and use these as the sort for table

    const displayedColumns = this.viewData.Columns.map((c: { Name: any; }) => c.Name);
    displayedColumns[2] = 'Folder1';
    this.displayedColumns = ['select'].concat(displayedColumns);
    // tslint:disable-next-line: max-line-length
    const fetchedData = this.viewData.DataRows.map((r: { slice: (arg0: number, arg1: number) => { forEach: (arg0: (d: any, i: string | number) => any) => void; }; }) => {
      const row = {};
      r.slice(0, 9).forEach((d: any, i: string | number) => (row[this.displayedColumns[i]] = d));
      return row;
    });

    this.dataSource = new MatTableDataSource(fetchedData);
    this.loading = false;
  }

  // Stores the current Action, sort, and paginator in an ActionState object to be held in the action service's stateMap.
  cacheAction() {
    let actionState = new ActionState(this.viewData);

    // Determine the sort direction to store.
    let cachedStart: SortDirection;
    if (this.sort.direction == "desc") {
      cachedStart = 'desc';
    } else {
      cachedStart = 'asc';
    }

    // Create a Sortable so that we can re-apply this sort.
    actionState.sortable = {
      id: this.sort.active,
      start: cachedStart,
      disableClear: this.sort.disableClear
    };

    // Store the current pageIndex and pageSize.
    actionState.pageIndex = this.paginator.pageIndex;
    actionState.pageSize = this.paginator.pageSize;

    // Store the refNumber in the actionState for later retrieval.
    actionState.refNumber = this.refNumber;
    this.actionService.cacheAction(actionState);
  }

  ngOnInit() {
    // Subscribes to the action service's currentAction, populating this component with View data.
    this.actionService.currentAction.subscribe(action => this.loadAction(action));
  }

    /** Whether the number of selected elements matches the total number of rows. */
    isAllSelected() {
      const numSelected = this.selection.selected.length;
      const numRows = this.dataSource.data.length;
      return numSelected === numRows;
    }

    /** Selects all rows if they are not all selected; otherwise clear selection. */
    masterToggle() {
      this.isAllSelected()
        ? this.selection.clear()
        : this.dataSource.data.forEach((row: TableRow) => this.selection.select(row));
    }

    // Delete row functionality

    deleteRow() {
      console.log(this.selection);
      this.selection.selected.forEach(item => {
        const index: number = this.dataSource.data.findIndex((d: TableRow) => d === item);
        console.log(this.dataSource.data.findIndex((d: TableRow) => d === item));
        this.dataSource.data.splice(index, 1);
        this.dataSource = new MatTableDataSource<Element>(this.dataSource.data);
      });
      this.selection = new SelectionModel<TableRow>(true, []);
      this.actionService.deleteRow(this.selection).subscribe((response) => {
        console.log('Success!');
      });
    }

ActionsService.ts
  deleteRow(selection: any): Observable<{}> {
    console.log('testing service');
// create an array of query params using the property that you use to identify a table row
    const queryParams = [selection._selection].map((row: { value: any; }) => `id=${row.value}`);
// add the query params to the url
    const url = `http://localhost:15217/actions/deleteRow`;
    return this.http.delete<any>(url);
  }

A: You need to add an http header to specify the content type for your http request body. If you are sending a json body, the header is content-type: application/json
You can update actionService.ts
deleteRow(selection: any): Observable<{}> {

    let headers = new Headers();
    headers.append('Content-Type', 'application/json');
    const queryParams = [selection._selection].map((row: { value: any; }) => `id=${row.value}`);
    const url = `http://localhost:15217/actions/deleteRow`;

    const options = {
        headers: new HttpHeaders({
            'Content-Type': 'application/json'
        }),
        body: {}
    }

    return this.http.delete<any>(url, options);
  }


Q: MSSQL variable = null Anyone know why a situation like the following would run fine on MSSQL 2005 and not MSSQL 2008:
declare @X int = null;

select A, B, C from TABLE where X=@X

Without going into detail, I've got a stored proc which calls another stored proc that takes a hard coded Null as one of the parameters and it runs fine apparently on MSSQL2005 but not 2008.

A: The code is poorly written regardless of which version of SQL you're using, because NULL is never "equal" to anything (even itself). It's "unknown", so whether or not it's equal (or greater than, or less than, etc.) another value is also "unknown".
One thing that can affect this behavior is the setting of ANSI_NULLS. If your 2005 server (or that connection at least) has ANSI_NULLS set to "OFF" then you'll see the behavior that you have. For a stored procedure the setting is dependent at the time that the stored procedure was created. Try recreating the stored procedure with the following before it:
SET ANSI_NULLS ON
GO

and you'll likely see the same results as in 2008.
You should correct the code to properly handle NULL values using something like:
WHERE X = @X OR (X IS NULL AND @X IS NULL)

or
WHERE X = COALESCE(@X, X)

The specifics will depend on your business requirements.

A: That might be due to your ansi_null settings in two servers.

When SET ANSI_NULLS is ON, a SELECT statement that uses WHERE
  column_name = NULL returns zero rows even if there are null values in
  column_name. A SELECT statement that uses WHERE column_name <> NULL
  returns zero rows even if there are nonnull values in column_name.
When SET ANSI_NULLS is OFF, the Equals (=) and Not Equal To (<>)
  comparison operators do not follow the SQL-92 standard. A SELECT
  statement that uses WHERE column_name = NULL returns the rows that
  have null values in column_name. A SELECT statement that uses WHERE
  column_name <> NULL returns the rows that have nonnull values in the
  column. Also, a SELECT statement that uses WHERE column_name <>
  XYZ_value returns all rows that are not XYZ_value and that are not
  NULL.

You can find detailed information here: https://msdn.microsoft.com/en-us/library/ms188048(v=sql.90).aspx

A: Try this:
select A, B, C from TABLE where X IS NULL

The reason why your original query did not return the expected result is explained here

A: SET ANSI_NULLS OFF
GO
^^That made the stored procs work the way I expected.


Q: Function isn't working with a gobal variable. Should it be expected? As title says, I can't have the variable "countDash" being used on my function if it's globaly, only local. Should it be like this?
What am I missing something? Thanks in advance.
//count
let countEl = document.getElementById("count-el");
let saveEl = document.getElementById("save-el");
let count = 0;

//message to user
let username = "Mr. Unknown";
let message = "You have three new notifications";
let messageToUser = `${message}, ${username}!`;

//welcome message
let welcomeEl = document.getElementById("welcome-el");
let name = "Eduardo";
let greeting = "Welcome back";
welcomeEl.innerHTML = `${greeting}, ${name}!`;

function increment() {
    count += 1;
    countEl.innerHTML = count;
}

// let countDash = ` ${count} -`; //does not work
function save() {
    let countDash = ` ${count} -`; //it only works if I have it here localy
    saveEl.innerHTML += countDash;
}

A: When you declare CountDash in the global scope, the code is only being run once, so CountDash is initialised with the value ' 0 - '. So even when you update count in your increment function, countDash will not be updated. If you'd like to keep countDash as a global variable for whatever reason (although we should reduce global variable use where possible) you can just update it after you update count in the increment function :)


Q: How to implement fill constructor and range constructor for sequence containers unambiguously Sequence containers need to have fill constructors and range constructors, i.e. these must both work, assuming MyContainer models a sequence container whose value_type is int and size_type is std::size_t:
// (1) Constructs a MyContainer containing the number '42' 4 times.
MyContainer<int> c = MyContainer<int>(4, 42);

// (2) Constructs a MyContainer containing the elements in the range (array.begin(), array.end())
std::array<int, 4> array = {1, 2, 3, 4};
MyContainer<int> c2 = MyContainer<int>(array.begin(), array.end());

Trouble is, I'm not sure how to implement these two constructors. These signatures don't work:
template<typename T>
MyContainer<T>::MyContainer(const MyContainer::size_type n, const MyContainer::value_type& val);

template<typename T>
template<typename OtherIterator>
MyContainer<T>::MyContainer(OtherIterator i, OtherIterator j);

In this case, an instantiation like in example 1 above selects the range constructor instead of fill constructor, since 4 is an int, not a size_type. It works if I pass in 4u, but if I understand the requirements correctly, any positive integer should work.
If I template the fill constructor on the size type to allow other integers, the call is ambiguous when value_type is the same as the integer type used.
I had a look at the Visual C++ implementation for std::vector and they use some special magic to only enable the range constructor when the template argument is an iterator (_Is_iterator<_Iter>). I can't find any way of implementing this with standard C++.
So my question is... how do I make it work?
Note: I am not using a C++11 compiler, and boost is not an option.

A: I think you've got the solution space right: Either disambiguate the call by passing in only explicitly size_t-typed ns, or use SFINAE to only apply the range constructor to actual iterators. I'll note, however, that there's nothing "magic" (that is, nothing based on implementation-specific extensions) about MSVC's _Is_iterator. The source is available, and it's basically just a static test that the type isn't an integral type. There's a whole lot of boilerplate code backing it up, but it's all standard C++.
A third option, of course, would be to add another fill constructor overload which takes a signed size.


Q: what is the easy way to make suffix from this js code? Note the code below shows the array in the console, not in the snippet output

var nodes = ["maria", "mary", "marks", "michael"];

function insert_word(split_nodes) {
  var rest = [];
  for (var i = 0; i < split_nodes.length; i++) {
    //console.log(current);
    var word = split_nodes[i];
    var letters = word.split("");
    var current = rest;
    console.log(current);
    for (var j = 0; j < letters.length; j++) {
      var character = letters[j];
      var position = current[character];
      if (position == null) {
        current = current[character] = j == letters.length - 1 ? 0 : {};
      } else {
        current = current[character];
      }
    }
  }
}
insert_word(nodes);

Above outputs this
M :{a : {r :{i :{a :0},
    k :0,
    y :
    },
},
    i :{c :{h :{a :{e :{l :0}}}}}}}

but I want to output this :
M :{ar:{ia:0,
    k :0,
    y :0
    },
 ichael :0
}

can anyone help me to find out this output from my code? how could i make suffeix from this code?

A: This solution take a sightly changed object structure for the end indicator with a property isWord, because the original structure does not reflect entries like 'marc' and 'marcus', because if only 'marc' is uses, a zero at the end of the tree denotes the end of the word, but it does not allowes to add a substring, because the property is a primitive and not an object.
Basically this solution creates first a comlete tree with single letters and then joins all properties which have only one children object.

function join(tree) {
    Object.keys(tree).forEach(key => {
        var object = tree[key],
            subKeys = Object.keys(object),
            joinedKey = key,
            found = false;

        if (key === 'isWord') {
            return;
        }
        while (subKeys.length === 1 && subKeys[0] !== 'isWord') {
            joinedKey += subKeys[0];
            object = object[subKeys[0]];
            subKeys = Object.keys(object);
            found = true;
        }
        if (found) {
            delete tree[key];
            tree[joinedKey] = object;
        }
        join(tree[joinedKey]);
    });
}

var node = ["maria", "mary", "marks", "michael"],
    tree = {};

node.forEach(string => [...string].reduce((t, c) => t[c] = t[c] || {}, tree).isWord = true);
console.log(tree);

join(tree);
console.log(tree);
.as-console-wrapper { max-height: 100% !important; top: 0; }

A recursive single pass approach with a function for inserting a word into a tree which updates the nodes.
It works by

*

*Checking the given string with all keys of the object and if string start with the actual key, then a recursive call with the part string and the nested part of the trie is made.

*Otherwise, it checks how many characters are the same from the key and the string.
Then it checks the counter and creates a new node with the common part and two nodes, the old node content and a new node for the string.
Because of the new node, the old node is not more necessary and gets deleted, as well as the iteration stops by returning true for the update check.

*If no update took place, a new property with string as key and zero as value is assigned.

function insertWord(tree, string) {
    var keys = Object.keys(tree),
        updated = keys.some(function (k) {
            var i = 0;

            if (string.startsWith(k)) {
                insertWord(tree[k], string.slice(k.length));
                return true;
            }
            while (k[i] === string[i] && i < k.length) {
                i++;
            }
            if (i) {
                tree[k.slice(0, i)] = { [k.slice(i)]: tree[k], [string.slice(i)]: 0 };
                delete tree[k];
                return true;
            }
        });

    if (!updated) {
        tree[string] = 0;
    }
}

var words = ["maria", "mary", "marks", "michael"],
    tree = {};

words.forEach(insertWord.bind(null, tree));
console.log(tree);

insertWord(tree, 'mara');
console.log(tree);
.as-console-wrapper { max-height: 100% !important; top: 0; }


Q: How to check if there is a specific user in PFUser's Pointer Array in Parse Subclass? My class has a PFUser Pointer Array.
I'm trying to check if PFUser.current () in Pointer Array or not.
Here is my snippet code.
class News: PFObject, PFSubclassing {

    @NSManaged var notiBy: PFUser?
    @NSManaged var notiTo: PFUser?
    //[News]()
//    @NSManaged var notiArray: [PFUser]?
    @NSManaged var notiArray: Array<String>

   var newsLiveQuery: PFQuery<News> {
        return News.query()?
            .whereKeyExists("objectId")
            .includeKeys(["notiBy", "postObj", "notiTo", "notiArray"])
            .whereKey("notiArray", equalTo: PFUser.current()!)
            .order(byDescending: "createdAt")
            as! PFQuery<News>
    }

But I got an JSON Error message.
But I can get result of PFObject like this
[<News: 0x1740b5480, objectId: zyCEHc78l6, localId: (null)> {
    checked = 0;
    messageText = Hellow;
    notiArray =     (
        "<PFUser: 0x1742ee800, objectId: a85SoYwEiE, localId: (null)>"
    );
    notiBy = "<PFUser: 0x1742ed100, objectId: tmWHuptLmd, localId: (null)>";
    notiTo = "<PFUser: 0x1742ede00, objectId: a85SoYwEiE, localId: (null)>";
    postObj = "<Post: 0x1742ee700, objectId: CXaSlvrW4G, localId: (null)>";
    type = comment;
}]

Look at that
I think It should be working but...why I can't run query?
Anyone knows about that?

A: I believe you are not get back the username as a string.  Try using PFUser.current()!.username instead


Q: pyspark - Join two RDDs - Missing third column I'm very new at Pyspark please take in consideration :)
Basically I've this two textfiles:
file1:
  1,9,5
  2,7,4
  3,8,3

file2:
 1,g,h
 2,1,j
 3,k,i

And the Python code:
file1 = sc.textFile("/user/cloudera/training/file1.txt").map(lambda line: line.split(","))

file2 = sc.textFile("/user/cloudera/training/file2.txt").map(lambda line: line.split(","))

Now doing this join:
join_file = file1.join(file2)

I was hoping to get this:
(1,(9,5),(g,h))
(2,(7,4),(i,j))
(3,(8,3),(k,1))

However, I am getting a different result:
(1, (9,g))
(3, (8,k))
(2, (7,1))

Am I missing any parameter on Join?
Thanks!

A: This should do the trick:
file1 = sc.textFile("/FileStore/tables/f1.txt").map(lambda line: line.split(",")).map(lambda x: (x[0], list(x[1:])))
file2 = sc.textFile("/FileStore/tables/f2.txt").map(lambda line: line.split(",")).map(lambda x: (x[0], list(x[1:])))
join_file = file1.join(file2)
join_file.collect()

returns with Unicode u':
Out[3]:
[(u'2', ([u'7', u'4'], [u'1', u'j'])),
 (u'1', ([u'9', u'5'], [u'g', u'h'])),
 (u'3', ([u'8', u'3'], [u'k', u'i']))]


Q: How to make electron app configurable in the release version? I have created an electron app having angular as frontend.And in backend i have used MySql db. I want to do following things after i make release version of this app:-

*

*Make a json file in the release directory which contains info like db name,password,port,or any other info etc.
I want this file to work as a config file which can be edited by end user (In the release version)

The changes that users make in the file should be reflected in my app too
Like changing the whole database etc
I am not sure how to achieve this.

A: You don't need to generate your json config file during your build process (unless you generate the users initial username, password , database name, etc during any application registration / purchase process). Instead, make this function part of your applications start-up / first run code.
During the initialisation phase of your application starting, look for existence of the json config file.

The best place for this file to be stored is in the user’s data directory, appended by your applications name. See app.getPath('userData') for more information.

If the json config file exists, load it (obviously in your main process) and reference it's values as per normal.
If the file does not exist (IE: First run), create it with default values. You can also give the user (if you want) the option to change the default values during the first run by popping up a dialog (or something similar) with the appropriate config fields.
The json config values should be changeable by your applications UI for users who are not comfortable editing the json config file directly.
Those who do edit the json config file directly will see their changes take effect immediately upon application restart. You could also make any changes hot reloadable though that would require a file watcher, etc (or a manual 'reload' button in the UI).
If the json config file is allowed to be edited by the user, you should validate the structure and content of the file during application start-up (or after hot reloading), else any malformed json config file would crash your application.


Q: Sqoop Not able to detect updates when no lastmodified date I have Orders Mysql Table which have auto incremet id  and order status will get updated and don't have any last modified date and It is very big table.Now I planned to create real time sink  to HDFS using Sqoop.
I am not able to capture updates in sqoop.
I tried both append and merge key option with lastmodified but both not able to solve problem.
I can't reload entire table since it is very huge.
I am looking for a way using sqoop how we can detect updates like status changes and move to hdfs


Q: Way to know what Windows service pack version is from the browser? Is there a way to find what service pack is installed from the browser? It doesn't look like it's in the System.Web.HttpBrowserCapabilities in asp.net. I need a way to warn users that they need to update to XP Service Pack 3 before proceeding and installing some software.

A: Not directly, no. Unless it's in the browser's UA, there's no way of detecting it without some kind of plugin.

A: If you can use VBSCRIPT you can get what you are looking for.
The WMI class Win32_OperatingSystem has the properties ServicePackMajorVersion, ServicePackMinorVersion, Name and Version.
Try samples here: WMI Tasks
Hope this can help


Q: Count unique values by group eliminating duplicates across groups by in Excel NOTE: I have already checked this count unique text values based on condition in another column between date criteria and it does not solve my problem.
I have an Excel chart with names and their groups. I want to distinct count by group with no-repetition. See Unique (Requirement) column for desired output. The purpose is to count how many people appeared first time by month.
Name    Group    Unique-(NEED THIS COLUMN)

Ryan    Jan-16   1
Ryan    Jan-16   0
Sam     Jan-16   1
Sally   Feb-16   1
Ryan    Feb-16   0
Sam     Mar-16   0
Tom     Mar-16   1
Peter   Mar-16   1

Note: Although Ryan appears three times, he is only counted the first time he appears in any group. The requirement is for last Column "Unique" to have a 1 or 0 so we can create a pivot table to group by "Group" like below:
Group      Count
Jan-16     2
Feb-16     1
Mar-16     2

The names are listed only once per group by month and do not repeat even if their name appears in a subsequent month.

A: If the names are starting in A2 with a heading in A1, you can just use this starting in C2 and pulled down:-
=COUNTIF(A$1:A1,A2)=0

to get true/false values, or
=--(COUNTIF(A$1:A1,A2)=0)

to get ones and zeroes.


Q: Intellij IDEA, when open new task - it doesn't create local branch from origin IDEA version - 2017.2.
If create task from Jira (for which branch have been already created in remote)

and select this branch for this Jira from dialog

it wont create local branch on my computer and just point to commit instead

Of course if try to commit you will not succeed without local branch.
So it would be very handy to say IDEA to create local branch automatically. How to do it?

A: Idea currently does not allow checking out remote branches without creating a local one that tracks it. Here is the request: https://youtrack.jetbrains.com/issue/IDEA-140077
Since there is no local branch that matches the remote one, you need to use the Create branch and select the remote one in the From dropdown.


Q: ImageView show different output on different resolution device I have a ImageView which is 450px*450px，it show perfectly on Note 3(1080*1920), but when I run the app on other smaller resolution device, the ImageView shown larger, and some other contents doesn't fit in the screen. Any solution to solve this kind of problem? is it about the unit(px, dp)?

A: The reason is every devices has different screen dimensions, so either you have to re-size the ImageView based on the screen size or simply use different size Images for your ImageView which will be used automatically based on the screen dimension. To do so, check this,
A. Getting the screen dimension programmatically and settings the appropriate size into the ImageView,
Display display = getWindowManager().getDefaultDisplay();
DisplayMetrics outMetrics = new DisplayMetrics ();
display.getMetrics(outMetrics);

float density  = getResources().getDisplayMetrics().density;
float dpHeight = outMetrics.heightPixels / density;
float dpWidth  = outMetrics.widthPixels / density;

B. Adding different image sizes for different screens,
res/drawable-mdpi/my_icon.png        // bitmap for medium density
res/drawable-hdpi/my_icon.png        // bitmap for high density
res/drawable-xhdpi/my_icon.png       // bitmap for extra high density

The following code in the Manifest supports all dpis.
<supports-screens android:smallScreens="true"
          android:normalScreens="true"
          android:largeScreens="true"
          android:xlargeScreens="true"
          android:anyDensity="true" />

A: Your Screen Resolution Represents that you are Setting the ImagevIew height and width for xxhdpi resolution device and the Second thing use dp for density pixel it cover the screen according to resolution use 150dpX150dp for ImageView use the following link for px to dp conversion http://pixplicity.com/dp-px-converter/


Q: Mockito: creating a parameter matcher for a class Given a method definition as follows:
MyClass.myMethod(SecondClass secondClass);

and a mock of MyClass:
MyClass myClass = mock(MyClass.class);

how would you match the method parameter when defining the expecation?
when(myClass.myMethod(???)).thenReturn(null);

Thanks

A: when(myClass.myMethod(Mockito.any(SecondClass.class))).thenReturn(null);

A: You can use
Mockito.any(SecondClass.class)

or
(SecondClass)any()

A: Actually the best way to do it is
doReturn(object).when(myClass).myMethod(???);

in ??? you have some possibilities.

*

*You can pass a given object and then you wait for an especific one

*Or you can pass Mockito.any(Clazz.class) and then you will accept any object of that kind


Q: git show logs exclude some user or committer I don't know how to do this
I try these already:

git log -p --author="user" --not Sites/Web/Templates

git log -p --author="!user" Sites/Web/Templates

still show log of that user. Help, please.


Q: libtorch c++ doesn't release tensor memory I'm having an issue when using libTorch C++.
I load a module
torch::jit::script::Module net = torch::jit::load(universal_path);

As this takes some time to load, I store it to use it later on different images that I want to process :
    net.to(device);
    net.eval();

    torch::Tensor out_tensor = net.forward({ input_tensor.to(device) }).toTensor().to(cpy);

The problem is that the forward function allocates a lot of memory (between 2 to 8MB) but it's not released when out_tensor is going out of scope.
The only way to release the memory is to delete the module as well, but this is not efficient.
Am I missing something?
I'm using libtorch 1.5.1, a bit old, is there known leaks with this version?
Thanks


Q: Rails fuzzy searching on title and description I have a simple rails 3 application that lists restaurants as a training exercise. I want to be able to search name and description using one textfield on the restaurant index page.
Given the query pizza. The matches should be

*

*name: Tony's, description: ... is a pizzeria that has been around since the 1950's ...

*name: Domino's Pizza, description: ...

*name: The Hall, description: ... pizzas, pastas and steaks ...

Because:

*

*the word pizza is a fuzzy match to " pizz eri a " using similar logic as TextMate's Cmd-T. (the spaces in the word pizzeria are only used to get the mini-Markdown to work)

*pizza is a lowercase match to Pizza

*pizza is a substring of pizzas (should work with ends-with begins-with and includes)

How would I go about doing this in rails 3? Do I use thinking_sphinx, tire, sunspot-rails or just a custom query for my application.

A: The only tricky one is pizza/pizzeria and it's an issue called stemming.
Both sphinx and solr/sunspot support stemming but I imagine you will need to teach them both that pizza is a stem of pizzeria.

A: One way to remove false positives is to run a user defined function (UDF) to compute the edit distance between a candidate answer and the original string, and ignore those answers whose edit distance is too large.

A: I found a very simple solution that serves my needs.
"%#{"pizza".scan(/./).join("%")}%"

This creates a string that looks like this
"%p%i%z%z%a%"

Then I use it in a LIKE query and I get the expected results. Now all that remains is to solve the non-trivial problem of determining the order of relevance :)
UPDATE:
Found a quick and dirty way of determining order of relevance base on the assumption that a shorter string will most likely be a closer match than a longer one.
ORDER BY length(sequence) ASC


Q: how to get the value from button on click I am having some buttons which are created dynamically based on the number of phone numbers present.Suppose I have 3 names in DB so there will be three buttons.So when I click on the 1st button then it should give the value of first button,if 2nd is clicked then 2nd button value should display.This is simple jsfiddle which describes about my requirement.I thought of assigning the each button a different id which should be the phone number.In the jsfiddle when i am clicking on a particular button then alert pops but it does not give any value.
i did like this
$('.btn').click(function(){
var number1 = $('#s2').val();
alert(number1);
});

A: You have to use event delegation using jQuery's on() method. From its documentation:

When a selector is provided, the event handler is referred to as delegated. The handler is not called when the event occurs directly on the bound element, but only for descendants (inner elements) that match the selector. jQuery bubbles the event from the event target up to the element where the handler is attached (i.e., innermost to outermost element) and runs the handler for any elements along that path matching the selector.

In your case, you'll need to delegate the .btn click event to an ancestor which exists prior to that element being dynamically added to the page:
$('body').on('click', '.btn', function() {
    var number1 = $('#s2').val();
    alert(number1);
});

The closer you get to the .btn element, the better, so unless your document's body is the nearest non-dynamic ancestor then you'll want to change this to something a bit closer.

Edit: Further question in comments:

can I get the ID of each button

To get the id of each button, simply use this.id:
$('body').on('click', '.btn', function() {
    var id = this.id;
    alert(id);
});

Edit 2: Further question in comments

So as I said,ID are numbers.So if i click button1 then it will print s1 in the inputfield.Can you please tell me how to do?

As your input has an id of "number", you can simply use jQuery's .val() method to set the value of the input to the id of the clicked button:
$('body').on('click', '.btn', function(){
    $('#number').val(this.id);
});

Working JSFiddle demo.

A: $(document).on('click', '.btn', function(){
   alert($(this).val());
});

Should work. The "on" is a way of working with dynamically placed elements.

A: Put value attribute in button input
  <button type="button" class="btn" value="test2" >test</button>
  <button type="button" class="btn" value="test1" id="s1">test</button>
  <button type="button" class="btn" value="test" id="s2">test</button>

And then use script
 $('.btn').on('click', function() {
       var number = $('#s2').val();//get value

 });

A: If you want to get the id of the clicked button you should use attr:
$('.btn').click(function(){
   var number1 = $('#s2').attr('id');
   alert(number1);
});


Q: Error in my trigger I am working on a project using SqlSiteMapProvider.  I have two tables Articles and SiteMap
Articles table:
CREATE TABLE [dbuser].[Articles](
 [ArticleId] [uniqueidentifier] NOT NULL,
 [Title] [nvarchar](500) NULL,
 [Description] [ntext] NULL,
 [CategoryId] [int] NULL,
 [pubDate] [datetime] NULL,
 [Author] [nvarchar](255) NULL,
 [Hit] [int] NULL,
 [Auth] [bit] NULL
)...

And SiteMap Table:
CREATE TABLE [dbuser].[SiteMap](
 [ID] [int] IDENTITY(0,1) NOT NULL,
 [Title] [nvarchar](50) NULL,
 [Description] [nvarchar](512) NULL,
 [Url] [nvarchar](512) NULL,
 [Roles] [nvarchar](512) NULL,
 [Parent] [int] NULL,
 CONSTRAINT [PK_SiteMap] PRIMARY KEY CLUSTERED
(...

When I insert an Article my asp.net page also inserts that articles url and such information into SiteMap table. What I am trying to do is when I delete an Article from my Articles table (from asp.net page) the related row from SiteMap table with a trigger.
My asp.net page inserts the Article info into Sitmap table in this format:
Dim SMUrl As String = "~/c.aspx?g=" & ddlCategoryId.SelectedValue & "&k=" & BaslikNo.ToString

I mean there is no one column exactly matchin in two tables.
My Trigger is as follows:
USE [MyDB]
GO
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
SET NOCOUNT ON
GO
SET ROWCOUNT 1
GO
ALTER TRIGGER [dbuser].[trig_SiteMaptenSil] ON [dbuser].[Articles]
AFTER DELETE
AS
BEGIN
DECLARE  @AID UNIQUEIDENTIFIER, @ttl NVARCHAR,@CID INT
SELECT @AID=ArticleId, @ttl = Title, @CID=CategoryId  FROM DELETED
IF EXISTS(SELECT * FROM dbuser.SiteMap WHERE Url = N'~/c.aspx?g=' + CONVERT(nvarchar(5), @CID) + N'&k=' + CONVERT(nvarchar(36), @AID))
BEGIN
 DELETE FROM dbuser.SiteMap WHERE Url = N'~/c.aspx?g=' + CONVERT(nvarchar(5), @CID) + N'&k=' + CONVERT(nvarchar(36), @AID)
END
END
GO

I am using SSMSE 2008 and my remote db server's version is 8.0
The Error I get is:
No rows were deleted.
A problem occurred attempting to delete row 1.
Error Source: Microsoft.VisualStudio.DataTools.
Error Message: The row value(s) updated or deleted either do not make the row unique or they alter multiple rows(2 rows).
Correct the errors and attempt to delete the row again or press ESC to cancel the change(s).
May you help me how to get this working? I have searched for this for about a few days.. Couldn't find a solution for my case...
Thanks in advance

A: To deal with the original issue and cope with deletions of multiple rows your trigger could be rewritten as follows.
ALTER TRIGGER [dbuser].[trig_SiteMaptenSil] ON [dbuser].[Articles]
AFTER DELETE
AS
BEGIN
 SET NOCOUNT ON

DELETE
FROM   s
FROM   dbuser.SiteMap     AS s
       INNER JOIN Deleted AS d
       ON     s.Url = N'~/c.aspx?g=' + CONVERT(nvarchar(5), d.CategoryId) + N'&k='
                                     + CONVERT(nvarchar(36), d.ArticleId)

END


Q: Get jsondata value in javascript JSON
   var jsondata={"id": "10", "skills": "english", "post": "devloper", "emp_name": "jaydeep","timestemp":"10:45"}

I am trying to get each element key and value:
javascript
..
}).done(function(data){
    console(data['post']);
});

Expected Output :
emp_name = jaydeep
post = devloper
I am getting undefined in console. WHY? I tried data.post, i tried loop but no success..

A: I think you'll need to decode the JSON first.
}).done(function(data){
    data = JSON.parse(data);
    console(data['post']);
});

A: You can use basic JS too to attain this.

// property is an optional parameter.
function disp(obj, property) {
  var prop;
  if (property) {
    obj[property] && (console.log(obj[property]));
  } else {
    for (prop in obj) {
      if (obj.hasOwnProperty(prop)) {
        console.log(prop + " = " + obj[prop])
      }
    }
  }
}
var jsondata = {
  "id": "10",
  "skills": "english",
  "post": "devloper",
  "emp_name": "jaydeep",
  "timestemp": "10:45"
}
//disp(jsondata, "post");
disp(jsondata);