text:
Q: Cannot transfer user files to new owner I'm trying to transfer users files to owner but drive api still responses with insufficientFilePermissions or invalidSharingRequest error

*

*insufficientFilePermissions - when firstly add writer permission to admin user and then update permission to owner and transfer ownership

*invalidSharingRequest - first step is create new permission to admin user and transfer ownership

These errors are documented here: https://developers.google.com/drive/api/v3/handle-errors and I think all is ok - sharing settings should be set, both users are active (not suspended), and superadmin account has writer permission
I'm using drive api methods create and update for example code looks like this
const drive = google.drive({ auth, version: 'v3' });
const permission = await drive.permissions.create({
    fileId: file.id,
    transferOwnership: true,
    requestBody: {
            role: 'owner',
            emailAddress: ownerEmail, // new owner email
            type: 'user',
        },
    });

I'm quite sure the code is right.
IMPORTANT NOTES

*

*users are in same domain and files are in drive folder under this domain and superadmin is owner of this folder

*auth is google.auth.JWT with our service account info and impersonation email - its our gsuite superadmin account

*used scopes: https://www.googleapis.com/auth/drive and https://www.googleapis.com/auth/drive.file
The problem is that owner can transfer files ownership to another users but as admin in script I cannot transfer these files.
I dont know what is wrong, do you have some ideas? We have basic google plan, should we switch to business plan for a right working? Or is there some advanced settings?
I am really tired and without any other ideas.
Thank you


text:
Q: How to downgrade Laravel Sail PHP version to 7.4 I am having an error when I my change my php version in docker-compose.yml form 8.1 to 7.4 it cause an error.
 services:
    laravel.test:
        build:
            context: ./vendor/laravel/sail/runtimes/8.1
            dockerfile: Dockerfile
            args:
                WWWGROUP: '${WWWGROUP}'
                NODE_VERSION: '14'
        image: sail-8.1/app

to
 services:
    laravel.test:
        build:
            context: ./vendor/laravel/sail/runtimes/7.4
            dockerfile: Dockerfile
            args:
                WWWGROUP: '${WWWGROUP}'
                NODE_VERSION: '14'
        image: sail-7.4/app

when running sail build --no-cache causes error:
ERROR [ 4/11] RUN apt-get update     && apt-get install -y gnupg gosu curl ca-certificates zip unzip git supervisor sqlite3 libcap2-bin libpng-dev python2     && mk
but when I return it to 8.1 it works smoothly.

redpajama_set_name: RedPajamaStackExchange


text:
Q: k-Nearest-Neighbor for Factorial Based Data This week I read about using the kNN algorithm to predict the outcome of a continuous variable based on the input of one or more continuous variables. The example was predicting the price of a wine bottle based on rating and age.
Is it possible for this to be used to predict a continuous outcome based on factorial based data? For example, predicting the cost of a car based on manufacturer, model, warranty, etc? Or perhaps predicting the attendance of a basketball game based on opponent, day of week, time of day, etc?
In similar situations in the past I have converted each factor to a number, but I'm curious to know if there's a way to skip that step.

A: The idea of KNN is to use the known labels of data points to predict that of a closeby data point for which you do not have a label. So, you can apply KNN to a dataset as long as there is a measure of distance between objects.
The challenge in your case would be what distance measure to define between two objects (cars). Ask yourself, when would I consider two cars to be similar? Are there manufacturers that are more similar to one another? Of course you can always trivially use a measure in which the distance is 0 if the factor is similar or large otherwise.
Another question is then if you have different types of distance measures for different types, how to combine them. You can always standardize each feature and then use something like euclidean distance, but there a lot of other ways to go, specifically you could give different weights to different features and use that to scale them differently.
The last point is that you have a lot of different options here - you can evaluate everything with appropriate cross-validations and pick the best.


text:
Q: Sequential Queries in PL/SQL Bear with me. I'm new at this.
So, I have three queries, one after the other, the first two ending with semi-colons. It's the same data from the same tables but sliced three different ways. The 'ORDER-BY's are all the same. The results come out on three separate tabs. How do I combine the results into a single output?

A: Use the UNION or UNION ALL syntax and put the order by at the end
e.g
SELECT A, B
  FROM X
UNION {ALL}
SELECT A, C
  FROM Y
UNION {ALL}
SELECT D, E
  FROM Z
order by 2;
Notes:  UNION is usually a bit slower because it will remove duplicates from the results if more that one section returns the same row.  UNION ALL will return all rows.
The data types for columns in each section must be the same.


text:
Q: Timelike Loop Spaces as Projective Null Twistor Spaces Let $\mathcal{M}$ be a spacetime, and let $\Omega\mathcal{M}$ denote the loop space of the spacetime. My idea is that the set of all closed timelike curves of $\mathcal{M}$ forms  the projective null twistor space. The following is an excerpt from my own essay:

Consider the projective null twistor space of $\mathcal{M}$. This space has light rays equivalent to points, and light cones as Riemann spheres. Let us define $\Omega_t\mathcal{M}$ as the timelike loop space of $\mathcal{M}$, i.e., the set of all timelike curves in $\mathcal{M}$. Consider a closed timelike curve in $\mathcal{M}$. Restrict the curve so that one can deform it into a line.
  Define a subclass of spacetime $\mathcal{M}$ as the class $\mathbb{A}\subset\Omega_t\mathcal{M}$ of closed timelike curves in $\mathcal{M}$ such that all curves $\varsigma\in\mathbb{A}\subset\Omega_t\mathcal{M}$ are homeomorphic to a portion of the real line $\mathbb{P}$ which lies on the null cone of any point. This class is trivial, as homeomorphisms are equivalence relations.
  Thus, the class of CTCs forms a light ray in spacetime. This corresponds to a point in $\Omega_t\mathcal{M}$. Similarly, consider a region on the spacelike hypersurface such that the region is bounded by the sections of light rays that fall on the hypersurface. This corresponds to a Riemann sphere in $\Omega_t\mathcal{M}$. Thus, $\Omega_t\mathcal{M}$ is isomorphic to the projective null twistor space of $\mathcal{M}$.
Evolve $\Omega_t\mathcal{M}=\Sigma_T$ (This relation holds since Riemann spheres on $\Omega_t\mathcal{M}\mbox{ and }\Sigma_T$ correspond to sections of light cones on $\mathcal{M}$ and light rays $\mathcal{M}$ to points on $\Omega_t\mathcal{M}\mbox{ and }\Sigma_T$. Therefore, by the above theorem and the transitivity of homeomorphisms, $\Omega_t\mathcal{M}=\Sigma_T$.) with respect to time, where $\Sigma_0\times\mathbb{R}^1=\mathcal{M}$, with respect to time to get the the ``positive'' part of $\mathcal{M}$, i.e., the part $\mathcal{M}_+$ of $\mathcal{M}$ with all points $x(t)$ in $\mathcal{M}_+$ having $t>T$.

Does this method of thinking make sense? I have done some research on the topic and it seems to be consistent with earlier established results.


text:
Q: Recompiling old cocoa app without sandbox I have a couple of Cocoa apps that are distributed privately and do not use the app store.  They haven't been touched for at least a year.  I need to make some changes.  They don't work properly with Apple's sandbox.  I've tried to turn off sandboxing in Xcode (9.4.1), but the absence of an entitlements file seems to be interpreted as sandboxed.  I've noticed that command line applications don't have this problem (yet). How can I get the old behavior back?  In the past I signed the apps to minimize user confusion, so I would like to continue signing the apps, if possible.
Update: I created a simple app that only calls NSOpenPanel(), like this -
@IBAction func browseFile(sender: AnyObject) {

        let dialog = NSOpenPanel()

        dialog.title                   = "Choose a .pdf file"
        dialog.showsResizeIndicator    = true
        dialog.showsHiddenFiles        = false
        dialog.canChooseDirectories    = true
        dialog.canCreateDirectories    = false
        dialog.allowsMultipleSelection = false
        dialog.allowedFileTypes        = ["pdf"]

        if (dialog.runModal() == NSApplication.ModalResponse.OK) {
            let result = dialog.url // Pathname of the file

I tried building under Xcode 8 and Xcode 9.  It seems something in the signing process has changed.  If I enable sandboxing and give the appropriate entitlements, then the app runs without errors.  Otherwise, I get the following error:
Faild to get owner UUID for url: file:///Users/david/Public error: Error

Note that this is with an entitlements file containing:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>com.apple.security.app-sandbox</key>
    <false/>
</dict>
</plist>

Also, I'm not clear where "david" comes into this.

A: Apparently this is a bug in NSOpenPanel, per Apple Technical Support.  Currently they can not explain the contents of the error message, or why it only occurs when sandboxing is turned off.  I filed a bug report with Apple.


text:
Q: How to make a HTTP Request within another subscribe()? EDIT: So I just tried my code again and now it works as intended.. I don't know what changed. Anyway, I am still  open to answers regarding the question "How to do it properly"
so I have been playing around with angular and typescript for some days now. (I am coming from .NET and Java).
It works well so far, but I encountered a problem.
See this example:
When User logs SUCCESSFULLY in, I want to request additional user-information immediately to store/work with. Thats what I came up with.
this._authService.login(this.username, this.password).subscribe(
  (loginResult: LoginResult) => {
    if (loginResult) {
      console.log(loginResult)

      // NOW COLLECT MORE DATA FROM SERVICE
      this.userService.getMoreUserData().subscribe(
        (data) => {
          console.log(data);
        },
        (err) => {
          console.error(err);
        },
        () => {console.log("Second Sub finished");}
      );

      this.shared.changeLoginStatus(true);
      this.shared.changeUser(decodedUser);

      console.log("Redirect to Profile Page");
      this.router.navigate(["/profile"]);

    } else { console.log("Error in responseObj"); }
  },
  (err) => {},
  ()=>{}
);

Sadly, this does not work. It always returns "undefined" when printing the "data". The Observable itself works fine when implemented in a standard-fashion-way in ngInit.
So can someone tell me, why doesn't it work and how to properly solve my problem?
I think, theoretically it should work.. but it does not. Maybe it is because I redirect to another Component quite immediately, thus leaving the subscription no time to execute? Nah.. That does not make sense because it prints the "data", but as undefined.
Any ideas?

A: Instead of nested subscriptions, you could try RxJS higher order mapping operators like switchMap. Try the following
this._authService.login(this.username, this.password).pipe(
  switchMap(loginResult: LoginResult) => {
    console.log(loginResult)
    if (loginResult) {
      return this.userService.getMoreUserData();
    } else {
      throwError("Error in responseObj");       // <-- throw error if `loginResult` isn't defined
    }
  }
).subscribe(
  (data) => {
    console.log(data);
    this.shared.changeLoginStatus(true);
    this.shared.changeUser(decodedUser);

    console.log("Redirect to Profile Page");
    this.router.navigate(["/profile"]);    // <-- redirect only if the inner observable emits
  },
  (err) => {
    console.error(err);
  },
  () => { }
);

Update - Explanation
switchMap operator maps to the source observable (here this._authService.login(this.username, this.password)) to an inner observable (here this.userService.getMoreUserData()) and returns the modified observable from the inner observable. So essentially it obtains the values from the source observable, modifies it and returns another modified observable.
Other higher order mapping operators would be mergeMap, concatMap and exhauseMap. Each has their own unique properties when dealing with a stream of notifications from the source observable. You could learn more about them here.

A: Authentication is based on a single request for user validation.
You don't actually need a stream of data to authenticate. If you want to keep your code structure you can follow Michael answer. Here's my solution using a Promise to get the first value of the Observable provided by the HttpClient.
const loginResult: LoginResult = await this._authService.login(this.username, this.password).toPromise();

if (loginResult === true)  {
  this.userService.getMoreUserData().subscribe((data) => { ///do stuff });
  this.shared.changeLoginStatus(true);
  this.shared.changeUser(decodedUser);
  console.log("Redirect to Profile Page");
  this.router.navigate(["/profile"]);
} else {
  console.error('Auth error');
}


text:
Q: Upload files to firebase storage via function I am trying to allow ability for user to select file and pass to firebase function to store in storage.
I am uploading file in react client like following:
const formData = new FormData();
formData.append("myFile", aFile);
const aRequesObject= {
  method: "POST",
  body: formData,
};
const response = await fetch(aUrl, aRequesObject);

Then I have a serverless function like following where i want to save this file to cloud storage.
import firebase from "firebase";
import "firebase/storage";
import { config } from "./Config";
firebase.initializeApp(config);

const file = request.body.myFile;
const ref = firebase.storage().ref().child(file.name);
ref.put(file).then(() => {
    console.log("Uploaded file", file.name);
  }); */

I have tried several variations from firebase documentation. All the examples i have found are uploading directly to storage from client as opposed to passing file to function and extracting from the request and then saving to storage. I am looking for a simple example of this or a link to where someone has done this scenario.


text:
Q: SQL Query is good, but get error I have the following code:
function GetSetting($key)
{
    $Result = mysql_query("SELECT * FROM settings WHERE keys='$key'") or die(mysql_error());
    while($Row = mysql_fetch_array($Result))
    {
        return $Row['value'];
    }
    return false;
}

But I get the following error:

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'keys='header_title'' at line 1

What is wrong with my SQL query?

A: keys is a reserved word, so you'll have to escape it:
SELECT ... WHERE `keys`='$key';
                 ^----^--

In other words, your query actually isn't good, and MySQL was telling you exactly where the problem was...


text:
Q: Switch Statement in SRSS i want to have conditional formatting of the background color of a textbox. i want something like this. IF i ican use the If - else statement its still ok.
  =Switch

     (
       (First(Fields!Risk_Level.Value, "BBS_ID") = "high","Red"),
       (First(Fields!Risk_Level.Value, "BBS_ID") = "Medium","Orange"),
       (First(Fields!Risk_Level.Value, "BBS_ID") = "Low","Green")
      )

A: The following should work:
=Switch(
        Fields!Risk_Level.Value = "high","Red",
        Fields!Risk_Level.Value = "Medium","Orange",
        Fields!Risk_Level.Value = "Low","Green"
       )


text:
Q: How to wrap the center content and make it take the remaining width of the div I have an  tag, which has two span tags floated, left and right and content in the center. How do I make the content wrap itself to the center? The content should take the remaining width after floating the span tags and their widths. Note: : I cannot add a span container for the text.
HTML:

    hello how are you

CSS:
.container {
    width:200px;
    height:200px;
    border:1px solid;
    display:block;
}
.left {
    width:50px;
    height:200px;
    background:red;
    float:left;
}
.right {
    height:200px;
    width:100px;
    background:blue;
    float:right;
}

DEMO:

A: Flexbox can do that

.container {
  width: 50%;
  margin: auto;
  height: 200px;
  border: 1px solid;
  display: flex;
  text-align: center;
  justify-content: space-between;
}
.left {
  width: 50px;
  height: 200px;
  background: red;
}
.right {
  height: 200px;
  width: 100px;
  background: blue;
}

  hello how are you

A: Rearrange your HTML, first the floating elements, then the text:

.container {
    width:200px;
    height:200px;
    border:1px solid;
    display:block;

}
.left {
    width:50px;
    height:200px;
    background:red;

    float:left;
}
.right {
    height:200px;
    width:100px;
    background:blue;
    float:right;

}

    hello how are you

A: Your problem is that the span left came after the text, so the span is displayed under the text. Try with this html code:

  hello how are you


text:
Q: How to calculate binary segmentation metrics? I am working on a binary segmentation problem using Pytorch. I want to know the correct way of calculating metrics like precision, recall, f1-score, mIOU, etc for my test set. From many of the online codes available, I found different ways of calculation, which I have mentioned below:
Method 1

*

*Calculate metrics for individual images separately.

*Compute the sum of each metric of all test images.

*Divide the metrics by the number of test images.

Example:
for i, (x, y) in enumerate(zip(test_x, test_y)):
           ...
           Score += calc_metrics(mask1, pred1)
         # Score could be any of the metrics
Final_Score = Score/ len(test_x)

Method 2

*

*Add TP, FP, TN, and FN pixel count of all the images and prepare a confusion matrix.

*Calculate all metrics at the end using the total TP, FP, TN, and FN pixel count and confusion matrix.

Example:
for i, (x, y) in enumerate(zip(test_x, test_y)):
         ...
        FP += np.float(np.sum((pred1==1) & (mask1==0)))
        FN += np.float(np.sum((pred1==0) & (mask1==1)))
        TP += np.float(np.sum((pred1==1) & (mask1==1)))
        TN += np.float(np.sum((pred1==0) & (mask1==0)))
Score = calc_metrics(TP, FP, TN, TP)

Method 3
Calculate batch-wise metrics and divide them by the number of test images at the end.
Method 4
Unlike all the above methods, which use 0.5 as the threshold on the predicted mask (after applying sigmoid), this method uses a range of thresholds and computes metrics on different thresholds for each metric and takes the mean of these values at the end.
Example:
for i, (x, y) in enumerate(zip(test_x, test_y)):
           ...
    for t in range(len(threshold)):
        thresh = threshold(t)
        thresh_metric(t) = calc_metrics(mask1, pred1, thresh)
    thresh_final(i,:) = thresh_metric
Score = np.sum(mean(thresh_final))/len(test_x)

I am confused about which way to use to report my model's results on the test set.


text:
Q: MariaDB slow left join using modified index I have an old MySQL query to find a free ID that always worked fine (0.0325 seconds). But now I have changed to MariaDB and it's extremely slow (over 30 seconds)
SELECT
   START AS codice
FROM (
    SELECT
       codice +1 AS START
    FROM  `clfoco`
    WHERE
       SUBSTRING(codice,9) BETWEEN '0000001' AND '9999999' AND codice LIKE '1201__%'
) AS a
LEFT JOIN (
    SELECT
        codice
    FROM  `clfoco`
    WHERE
        SUBSTRING(codice,9) BETWEEN '0000001' AND '9999999' AND codice LIKE '1201__%'
) AS b ON a.start = b.codice
WHERE b.codice IS NULL
LIMIT 1

"codice" is the primary index
The old database was MySQL 5.1.73 and the new one is MariaDB 5.5.52.
I have replicated the table(import/export db and data), deleted and recreated the index but the query in the new database is always slow.
I have read answers where the changed index (codice+1) breaks the indexes and force MySQL to scan the whole table, but I dont think this is the case since in the old MySQL database the query is fast.
Any suggestion?
EDIT
TABLE
CREATE TABLE IF NOT EXISTS `clfoco` (
  `codice` varchar(20) NOT NULL,
  `id_anagra` int(9) NOT NULL,
  `descri` varchar(100) DEFAULT NULL,
   ....
   ....
   ....
   PRIMARY KEY (`codice`),
  KEY `id_anagra` (`id_anagra`),
  FULLTEXT KEY `descri` (`descri`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8;

Explain with Maria Db
| id|select_type|table |type    |possible_keys|key      |key_len|ref |rows  |Extra
    ------------------------------------------------------------------------------
| 1 | SIMPLE    |clfoco|range   |PRIMARY      |PRIMARY  |62     |NULL|24549 |Using where; Using index
| 1 | SIMPLE    |clfoco|index   |PRIMARY      |PRIMARY  |62     |NULL|25182 |Using where; Using index; Using join buffer (flat, BNL join)

Explain with Mysql 5.1.73
| id|select_type|table      |type   |possible_keys|key      |key_len|ref |rows  |Extra
    ------------------------------------------------------------------------------
| 1 |PRIMARY    |<derived2> |ALL    |NULL         |NULL     |NULL   |NULL|24661
| 1 |PRIMARY    |<derived3> |ALL    |NULL         |NULL     |NULL   |NULL|24661 |Using where; Not exists
| 3 | DERIVED   |clfoco     |index  |PRIMARY      |PRIMARY  |62     |NULL|25182 |Using where; Using index
| 2 | DERIVED   |clfoco     |index  |PRIMARY      |PRIMARY  |62     |NULL|25182 |Using where; Using index;

NEW EDIT
After Rick James suggestion I have changed the query.
SELECT  a.codice+1 AS START
    FROM  `clfoco` a
    WHERE codice LIKE '1201__%'
      AND(substring(b.codice,9) between '0000001' and '9999999')
      AND NOT EXISTS (
                SELECT *
                FROM  `clfoco`
                WHERE codice LIKE '1201__%'
                  AND (substring(b.codice,9) between '0000001' and '9999999')
                  AND codice = a.codice+1 )
    LIMIT 1;

The execution time on MariaDB is 0.0294 seconds
EXPLAIN EXTENDED:
id|select_type       |table |type |possible_keys|key    |key_len|ref |rows  |filtered|Extra
1 |PRIMARY           |a     |range|PRIMARY      |PRIMARY|62     |NULL|24549 |100.00  |Using where; Using index
2 |DEPENDENT SUBQUERY|clfoco|range|PRIMARY      |PRIMARY|62     |NULL|24549 |100.00  |Range checked for each record (index map: 0x1)

A: The subselects seem a little obfuscatory, which is always dangerous, because even if it doesn't confuse the optimizer now, it may in a future version (as seems to have happened).  I would have written this, with no subselects:
select a.codice+1 as codice
from clfoco a
left join clfoco b
    on b.codice=a.codice+1
    and (substring(b.codice,9) between '0000001' and '9999999')
    and b.codice like '1201__%'
where b.codice is null
and (substring(a.codice,9) between '0000001' and '9999999')
and a.codice like '1201__%'
limit 1;

Does this confuse the optimizer less?
From the explain you added of the NOT EXISTS version, it looks like it is using the like '1201__%' for indexing the dependent subquery when it shouldn't.  Try this:
select a.codice+1 as codice
from clfoco a
left join clfoco b on b.codice=a.codice+1
where b.codice is null
and (substring(a.codice,9) between '0000001' and '9999999')
and a.codice like '1201__%'
and (substring(a.codice+1,9) between '0000001' and '9999999')
and a.codice+1 like '1201__%'
limit 1;

A: SELECT  a.codice+1 AS START
    FROM  `clfoco` a
    WHERE codice LIKE '1201__%'
      AND NOT EXISTS (
                SELECT *
                FROM  `clfoco`
                WHERE codice LIKE '1201__%'
                  AND codice = a.codice+1 )
    LIMIT 1;

Notes:

*

*EXISTS may optimize better.  (But your versions are quite old.)

*SUBSTRING gets in the way of index usage.

*The SUBSTRING check seems to be useless.

*codice needs to be VARCHAR, else LIKE will be problematical.

Please provide SHOW CREATE TABLE and EXPLAIN SELECT ....


text:
Q: UIView screen freeze when calling dispatch_async(dispatch_get_main_queue()) I have a popup which need to be show until all the images are uploaded on the view controller,  I use dispatch-async method to show the popup before all the images are uploaded and hide as the images display.
But the UIView screen freezes displaying hang popup on calling dispatch_async method  where I was wrong in the code or whats the best way to achieve this.
func imageIconTapped(gesture: UITapGestureRecognizer){
        self.loadingPopUp = showPopUp(self, txt: "Processing..")
        self.navigationController!.view.addSubview(self.loadingPopUp!)

        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {

           code to getting the image   // getting the images is time taking therefore it work in the background.

            dispatch_async(dispatch_get_main_queue()) {

        method to upload the images on the view controller and hide the popup.
        }

A: The function "imageIconTapped" is UIKit method which is already run on main thread.So no need to dispatch code to main queue.
Main thread is block when you dispatch code from main thread to main queue.


text:
Q: Can I use ActionCable to refresh the page? I've recently been trying to create a live-scoring system for squash matches. I've managed to use ActionCable with Rails 5 to auto-update the score on the page, but I'd like to know if it's possible to tell Rails to refresh the page if a certain condition is met.
For example, if the game has finished, a different page is shown to say that the players are having a break between games. I need the page to refresh completely for this to happen.
In my database the boolean 'break' is marked as true when a game ends, and then the view uses a conditional if/else statement to decide what to show.
The code I use to update the score is attached below, I was thinking something along the lines of if data.break == true then the page will automatically refresh.
// match_channel.js (app/assets/javascripts/channels/match_channel.js)

$(function() {
  $('[data-channel-subscribe="match"]').each(function(index, element) {
    var $element = $(element),
        match_id = $element.data('match-id')
        messageTemplate = $('[data-role="message-template"]');

    App.cable.subscriptions.create(
      {
        channel: "MatchChannel",
        match: match_id
      },
      {
        received: function(data) {
          var content = messageTemplate.children().clone(true, true);
          content.find('[data-role="player_score"]').text(data.player_score);
          content.find('[data-role="opponent_score"]').text(data.opponent_score);
          content.find('[data-role="server_name"]').text(data.server_name);
          content.find('[data-role="side"]').text(data.side);

          $element.append(content);
        }
      }
    );
  });
});

I don't know if this sort of thing is possible, and I'm not much good at anything Javascript related so I'd appreciate any help on this.
Thanks.

A: Reloading the current page is relatively straightforward. If you are using Turbolinks, you can use Turbolinks.visit(location.toString()) to trigger a revisit to the current page. If you aren't using Turbolinks, use location.reload(). So, your received function might look like:
received: function(data) {
  if (data.break) {
    return location.reload();
    // or...
    // return Turbolinks.visit(location.toString());
  }

  // your DOM updates
}

Either way is the equivalent to the user hitting the reload button, so it will trigger another GET, which calls your controller and re-renders the view.


text:
Q: NSXMLParser: How to extract a string with the tags and attributes untouched I I'm doing something a bit strange. Is it possible to extract part of an XML file with XML parser without parsing it, and instead extract it as a string.
<root>
    <element>
      <don't parse>it amet, consectetur<tag> adipiscing</tah> elit. Vestibulum ac viverra nulla. Donec dapibus, eros dapibus eleifend aliquet, turpis nulla aliquam libero
      </don't parse> //resume parsing
    </element>
</root>

A: You can try to use CDATA tag
<root>
    <element>
      <![CDATA[
          <don't parse>it amet, consectetur<tag> adipiscing</tah> elit. Vestibulum ac viverra nulla. Donec dapibus, eros dapibus eleifend aliquet, turpis nulla aliquam libero
          </don't parse> //resume parsing
    ]]>
    </element>
</root>


text:
Q: VBA ActiveX controls grow in size over Remote Desktop Connection We have an Excel workbook with a number of ActiveX controls, running in Excel 2003 on Windows XP.  When connecting using Remote Desktop, the ActiveX controls change font, sometimes font size, and sometimes orientation (in the case of a spinner control).  This happens on first connection and also as the workbook is used - some of the controls then enlarge in size, often overlapping other controls and part of the workbook.
I read somewhere this may be caused by improper connection management (not closing them) leading to increasing memory usage; are there other reasons why the display is so different over Remote Desktop and are there workarounds?  (the properties of each control usually remain the same, so force-resizing them doesn't always have an effect)

A: Please read this. Hope it helps you. Thanks!

A: Have you tried installing this hotfix: http://support.microsoft.com/kb/976938/en-us


text:
Q: call public method after static method in php I have class sample and first call static method and return to call other public method:
class foo{
 public static $var;
    public static function first()
    {
       self::$var = 1;
       return self::class;
    }
    public function second()
    {
       return self::$var;
    }
}

and I need call public method after static method sample here:
foo::first()->second();

A: No, you can't do that, because from your static method you return just the string - class name. For calling your public method, you need that static method is returning an instance of your object, like this
return new self();


text:
Q: Is Cassandra Update IF statement where the condition is an inequality expression supported? Is UPDATE IF [condition] where [condition] is an inequality, supported by Cassandra CQL?
I had a look over the language reference and it seems that CQL should not be able to support the inequality through its grammar. I used the language reference from here: https://cassandra.apache.org/doc/cql3/CQL.html#updateStmt
What is confusing is that using the C# driver or CQLSH the query is executed successfully, but when doing the same thing from Datasax DevCenter I get an error.
I'm using a query similar to the one below:
UPDATE product
SET edit_date = [new_value]
WHERE customer_id = '4' AND code = 'AMZ-ISMDB'
IF edit_date < [new_value]

The results are as follows:

*

*Datasax DevCenter throws an error when trying to execute the script snippet. The error I get is complaining about the inequality in the UPDATE IF part of the script.
There is one syntax error in the current script (see details below).
Please fix it and try again.
  Line 29: no viable alternative at input '<'

*If I use CLINQ with the Datasax C# driver the query is generated as above and when executed the update is persisted if the new edit_date is after the existing edit_date which is the expected behaviour.

*Using CQLSH the query runs successfully and the update is persisted

A: The issue is most likely that DevCenter has not been updated to support the latest syntax.
Inequality conditions were added in:
CASSANDRA-6839
Looks like they missed updating the docs when that was added.  I open CASSANDRA-10752 to get that fixed.

A: This issue has been fixed in DevCenter version 1.6.0.


text:
Q: Flag in new column in text equals Yes in one of multiple columns I've got a large dataset with multiple flags already set up. Now I want to aggregate it to have an overall flag if it is flagged in one or more of the colums
For example, I have a mixture of columns: Product, Product ID and then Flag 1, Flag 2, Flag 3. Now my new column needs to say if there is a Y in either Flag 1,2 or 3.
Thanks for your help!

A: You can use this base R solution:
Reproducible data:
set.seed(123)
df <- data.frame(
  col1 = sample(c("something", "nothing", "Y", "anotherthing"), 20, replace = T),
  col2 = sample(c("nothing", "Y", "anotherthing"), 20, replace = T),
  col3 = sample(c("something", "nothing", "Y", "anotherthing", "yetanotherthing"), 20, replace = T))

First create a new column into which to place the Flag value:
df$Flag <- NA

Then, using grepl to match Y as well as apply and pasteto collapse the rows into strings, identify those rows that contain Y and update NA by Flag:
df$Flag[which(grepl("Y", apply(df, 1, paste0, collapse = " ")))] <- "Flag"

Result:
df
           col1         col2            col3 Flag
1       nothing anotherthing       something <NA>
2  anotherthing anotherthing               Y Flag
3       nothing            Y               Y Flag
4  anotherthing anotherthing         nothing <NA>
5  anotherthing            Y       something Flag
6     something anotherthing       something <NA>
7             Y            Y         nothing Flag
8  anotherthing            Y               Y Flag
9             Y      nothing         nothing Flag
10      nothing      nothing yetanotherthing <NA>
11 anotherthing anotherthing       something <NA>
12      nothing anotherthing               Y Flag
13            Y anotherthing    anotherthing Flag
14            Y anotherthing       something Flag
15    something      nothing               Y Flag
16 anotherthing            Y         nothing Flag
17    something anotherthing       something <NA>
18    something      nothing    anotherthing <NA>
19      nothing      nothing yetanotherthing <NA>
20 anotherthing      nothing         nothing <NA>

A: Assuming all flag columns are of the same type as Y:
flags = c("Flag1","Flag2","Flag3")

df <- cbind(df,
            Y %in% df[,flags] %>% as.matrix)

A: A solution with rowwise
library(dplyr)
library(tidyr)

d <- tribble(~id, ~flag1, ~flag2, ~flag3,
             1, "Y", "N", NA,
             2, "Y", "Y", "Y",
             3, NA,"N","N")
d
#> # A tibble: 3 x 4
#>      id flag1 flag2 flag3
#>   <dbl> <chr> <chr> <chr>
#> 1     1 Y     N     <NA>
#> 2     2 Y     Y     Y
#> 3     3 <NA>  N     N

d %>%
  rowwise() %>%
  mutate(overallStatus = if_else(any(c(flag1, flag2, flag3) == "Y", na.rm = T), "Y", "N"))
#> Source: local data frame [3 x 5]
#> Groups: <by row>
#>
#> # A tibble: 3 x 5
#>      id flag1 flag2 flag3 overallStatus
#>   <dbl> <chr> <chr> <chr> <chr>
#> 1     1 Y     N     <NA>  Y
#> 2     2 Y     Y     Y     Y
#> 3     3 <NA>  N     N     N

Created on 2020-05-20 by the reprex package (v0.3.0)


text:
Q: How to get a value from Firebase Database and assign it to a value in Firebase Cloud Functions? So I'm using firebase as a backend to a demo app, and I like the stack quite a bit, but I'm hung up on one issue, I can't figure out how to retrieve values from the database (I've got keys just fine).
Simply put, I'm sending information from one device that contains the "friendly-name" of another device it is trying to reach to a firebase function.
The function code looks like this:
exports.connectMe = functions.https.onRequest((req, res) => {
    cors(req, res, () => {
    admin.database().ref('calls/' + req.body.id + '/').set({
        target: req.body.target,
        caller: req.body.caller,
        time: req.body.time
    });

    const target = req.body.target;
    console.log(`target: ${target}`);
    const targetCall = admin.database().ref(`tokens/${target}/token`);
    console.log(targetCall);
    // const targetValue = targetCall.val();
    res.status(200).send("Thanks For The Call!");
    });
});

The variable, targetCall is correctly pointed at the db entry that I want to reach, but I cannot extract the value for the life of me. The token located at admin.database.ref is required to be placed in a http request. How do I get the value? The commented out code shows the variable I would want to store it in, but I know that .val() is not a method of reference. For the record, admin is set to require('firebase-admin'); earlier in the code.

A: You need to call the function once(), as found in the documentation:
targetCall.once("value", function(data) {
  const targetValue = data.val();
  res.status(200).send("Thanks For The Call!");
});

A: You are very close to getting the database query to work.
Take a look at the Firebase Documentation. It explains how to access the structured data.
exports.connectMe = functions.https.onRequest((req, res) => {
    cors(req, res, () => {
        const callRef = admin.database().ref('calls/' + req.body.id + '/').set({
            target: req.body.target,
            caller: req.body.caller,
            time: req.body.time
        });

        const target = req.body.target;
        console.log(`target: ${target}`);

        const takenRef = admin.database().ref(`tokens/${target}/token`)
            .once('value');

        Promise.all([callRef, takenRef])
            .then(results => {
                const snapshot = results[1]; // Promise of `takenRef`
                console.log(snapshot.val()); // This is the data from the database...

                res.status(200).send("Thanks For The Call!");
            });
    });
});

See the updated code, I've added .once('value').then(snapshot onto your query which gives you access to the data.


text:
Q: What is wrong with my Swing application? EDITED 2/2/2013
With the help of some of your answers and a simple Swing application guide I found, I was able to make a little bit of progress and I put it all in one class for now. However, I still can't get it to close and I had to make a button to do it because it was getting really annoying having to pull up task manager. The tooltips aren't working either. I don't know if it matters, but I'm doing it in Eclipse.
import javax.swing.SwingUtilities;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.JButton;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class Thing extends JFrame
{
    private static final long serialVersionUID = 1L;

    public Thing()
    {
        setTitle("Thing");
        setSize(1024, 768);
        setLocationRelativeTo(null);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setResizable(false);

        JPanel panel = new JPanel();
        getContentPane().add(panel);
        panel.setLayout(null);
        panel.setToolTipText("A panel container");

        JButton quit = new JButton("Quit");
        quit.setBounds(50, 60, 80, 30);
        quit.setToolTipText("A button component");
        quit.addActionListener(new ActionListener()
        {
            public void actionPerformed(ActionEvent event)
            {
                System.exit(0);
            }
        });
        panel.add(quit);
    }

    public static void main(String[] args)
    {
        SwingUtilities.invokeLater(new Runnable()
        {
            public void run()
            {
                Thing thing = new Thing();
                thing.setVisible(true);
            }
        });
    }
}

This is the error it gives when I try to close it with the X. (The closing works fine with the button)
java.lang.NoClassDefFoundError: sun/awt/TimedWindowEvent
    at sun.awt.windows.WToolkit.eventLoop(Native Method)
    at sun.awt.windows.WToolkit.run(Unknown Source)
    at java.lang.Thread.run(Unknown Source)

A:
For some reason, I can't close it and have to use task manager.

Use SwingUtilies.invokeLater() to create GUI.
http://docs.oracle.com/javase/tutorial/uiswing/concurrency/initial.html

A: Toolkit.getDefaultToolkit().getImage("image.jpg") is likely using a background loader to load the image off the main paint thread (or Event Dispatching Thread, AKA EDT).
This basically means, the method will return immeditly, but the image won't actually have loaded.
This was done (way back in the olden days) for low capacity bandwidth systems, to prevent the systems from stalling while images where downloaded and loaded into memory.  Now days, this is much less of a concern.
Instead, in the constructor of Title you should pre-load the image...
private BufferedImage background;
public Title() throws IOException {
    background = ImageIO.read(new File("image.jpg"));
}

And in your paintComponent method...
public void paintComponent(Graphics g)
{
    super.paintComponent(g);
    if (background != null) {
        g.drawImage(background, 0, 0, this);
    }
}

The other problems with you current approach to loading the images deals with how it handle errors.  Your current method will tend to silently consume the errors and it's difficult to determine what's actually gone wrong.
You could take a look at JButton only show up on mouseover for more of a complete example

A: I'm not sure if you fixed your problem, but I had a similar problem: For my application I extended JFrame, but was not able to close or hide it with any setDefaultCloseOperation(...). I got the same error you showed above when minimizing, restoring or maximizing the frame.I fixed it updating both jdk and jre to latest Java 1.7 and using it. In eclipse, go to Window > Preferences > Java > Installed JREs and select your latest Java if working on 64 bit System, best use also 64 bit Java. In the submenu > Execution Environment select your Java 1.7 on the left hand and compatible Java 1.7 64 bit JRE on the right hand.
I'm not sure what exactly was the problem, but possibly some incompatibility between Java 64 bit Application and 32 bit runtime environment I guess.


text:
Q: Simplesaml Auth error when clearing cache I'm doing a local install of a Drupal 8 site and when I try to clear the cache with Drush, I get this error:

Is anyone familiar with this?  I can't find anything relevant with a Google search.  Thank you in advance for any suggestions or help.

A: I suggest you to install the library with composer. If you did it, run the next code:
composer update

You can find more information in the next link
https://simplesamlphp.org/modules


text:
Q: ORA-06502: PL/SQL: numeric or value error with stored procedure and ASP.NET MVC I am trying to insert data into Oracle database from ASP.NET MVC application. I am using a stored procedure to do so, but I get this error:

ORA-06502: PL/SQL: numeric or value error: character string buffer too
  small ORA-06512: at "C##AET.KATEGORIJA_PKG", line 40 ORA-06502:
  PL/SQL: numeric or value error: character string buffer too small
  ORA-06512: at line 1

Procedure code is:
PROCEDURE INS_KATEGORIJA
  (
    P_NAZIV IN KATEGORIJA.NAZIV%TYPE,

    P_KATEGORIJA_ID OUT KATEGORIJA.KATEGORIJA_ID%TYPE,
    P_REZULTAT OUT NUMBER,
    P_PORUKA OUT VARCHAR2
  )
  IS
  BEGIN
    P_REZULTAT := 1;

    SELECT KATEGORIJA_SEQ.NEXTVAL INTO P_KATEGORIJA_ID FROM DUAL;

    INSERT INTO KATEGORIJA
    VALUES (P_KATEGORIJA_ID, P_NAZIV);

    P_REZULTAT := 0;
    P_PORUKA := 'DB: Kategorija uspesno uneta.';

    EXCEPTION
    WHEN OTHERS THEN
      P_REZULTAT := 1;
      P_PORUKA := 'DB: ' ||SQLCODE|| ' - ' ||SQLERRM;
  END INS_KATEGORIJA;

And the method calling it:
List<OracleParameter> izvrsiTransakciju(string nazivProcedure, List<OracleParameter> parametri, OracleTransaction transakcija)
        {
            try
            {
                using (OracleCommand komanda = new OracleCommand(nazivProcedure, konekcija))
                {
                    komanda.Transaction = transakcija;
                    komanda.CommandType = CommandType.StoredProcedure;
                    komanda.BindByName = true;

                    List<OracleParameter> izlazniParametri = new List<OracleParameter>();

                    foreach (OracleParameter p in parametri)
                    {
                        komanda.Parameters.Add(p);

                        if (p.Direction != ParameterDirection.Input) izlazniParametri.Add(p);
                    }

                    komanda.ExecuteNonQuery();

                    return izlazniParametri;
                }
            }
            catch (Exception ex)
            {

                throw new Exception("Greška pri izvršavanju transakcije: " + ex.Message);
            }
        }

The methods that communicates with the database are:
    public  List<OracleParameter> PokreniTransakciju(string nazivProcedure, List<OracleParameter> parametri)
            {
                try
                {
                    List<OracleParameter> listaParametara;
                    using (konekcija)
                    {
                        konekcija.Open();

                        using (OracleTransaction transakcija = konekcija.BeginTransaction())
                        {
                            listaParametara = izvrsiTransakciju(nazivProcedure, parametri, transakcija);

                            int rezultat = Convert.ToInt32(listaParametara.FirstOrDefault(x => x.ParameterName == "P_REZULTAT"));
                            if (rezultat != 0)
                                transakcija.Rollback();
                            else
                                transakcija.Commit();

                            return listaParametara;
                        }
                    }
                }
                catch (Exception ex)
                {
                    throw ex;
                }
            }

    List<OracleParameter> izvrsiTransakciju(string nazivProcedure, List<OracleParameter> parametri, OracleTransaction transakcija)
            {
                try
                {
                    using (OracleCommand komanda = new OracleCommand(nazivProcedure, konekcija))
                    {
                        komanda.Transaction = transakcija;
                        komanda.CommandType = CommandType.StoredProcedure;
                        komanda.BindByName = true;

                        List<OracleParameter> izlazniParametri = new List<OracleParameter>();

                        foreach (OracleParameter p in parametri)
                        {
                            komanda.Parameters.Add(p);

                            if (p.Direction != ParameterDirection.Input) izlazniParametri.Add(p);
                        }

                        komanda.ExecuteNonQuery();

                        return izlazniParametri;
                    }
                }
                catch (Exception ex)
                {

                    throw new Exception("Greška pri izvršavanju transakcije: " + ex.Message);
                }
            }

public OracleParameter NapraviParametar(string naziv, object vrednost, OracleDbType? tip, ParameterDirection pravac)
        {
            OracleParameter param = new OracleParameter();

            param.ParameterName = naziv;
            param.Direction = pravac;

            if (tip != null)
                param.OracleDbType = (OracleDbType)tip;

            dodajVrednost(param, vrednost);

            return param;
        }

        void dodajVrednost(OracleParameter param, object vrednost)
        {
            if (vrednost == null) return;

            if (vrednost is int)
                param.Value = (int)vrednost;
            else if (vrednost is decimal)
                param.Value = (decimal)vrednost;
            else if (vrednost is string)
                param.Value = (string)vrednost;
            else if (vrednost is DateTime)
                param.Value = (DateTime)vrednost;
        }

Any ideas? Thank you in advance!
[SOLUTION]
With much appreciated assistance from LauDec, I figured out that one must specify the Size attribute of an OracleParameter object when defining Varchar2 parameters. Added that, and the problem was solved.

A: apparently, it comes from variable affected to the P_PORUKA out parameter when calling the INS_KATEGORIJA procedure which is too small to store the message you are trying to put in ( based on discussion in comments ).
If you called the INS_KATEGORIJA from inside your package, I would have understood the behavious :
  DECLARE
    PORUKA VARCHAR2(10);
    KATEGORIJA_ID NUMBER;
    REZULTA NUMBER;
  BEGIN
    INS_KATEGORIJA('TEST',KATEGORIJA_ID,REZULTA,PORUKA);
  END;

This will definitely raise the mentionned error message. But I didn't expect when calling from the outside. ( Does your code calls directly the  INS_KATEGORIJA or does it call another procedure from your package which calls INS_KATEGORIJA ? )
I Guess you have to change the code in the caller of PokreniTransakciju, the one who defines the out variable(and their size) used to call the procedure
Edit : The reasons was the following based on OP's comment :

When one defines OracleParameter of Varchar2 type,
  OracleParameter.Size is required (it seems it is set to 0 if it isn't
  manually set).


text:
Q: changing friction in c# Unity I am working on a project in my game programming class, and I want to change the friction of a physics2D material, and I can't find anything about changing it. Do you need to import anything, and what would the code be? thanks!

A: There are a couple ways you can do this.
From the UI
From the code (in C#)
gameObject.GetComponent(CircleCollider2D).sharedMaterial.friction = 0.0f
Where gameObject is your gameObject
Refs

*

*
Physics Material 2d

*Box Collider 2d

*Shared Material


text:
Q: How to remove similar rows from a oracle table(a complex one)? I need to remove duplicate rows from a table i.e. the original and the duplicate one.
I have a table as below where I need to remove all duplicates records for users, 'John' and 'James' users records in below case
**Input Table**
| Name  | email       | N  | country|operation|
| ----  | -----  ---  |----| -------|--------
| John  |john@abc.com | 90 | Canada | Delete |
| John  |john@abc.com | 90 | Canada | Insert |
| John  |john@abc.com | 50 | USA    | Insert |
| Thomas|tom@abc.com  | 50 | USA    | Delete |
| David |dav@abc.com  | 60 | Mexico | Insert |
| James |jams@abc.com | 70 | Spain  | Delete |
| James |jams@abc.com | 70 | Spain  | Insert |
| James |jams@abc.com | 66 | UK     | Insert |
| Alex  |alex@abc.com | 65 | Denmark| Insert |

**Expected Output**
| name |  email       | N  | country| operation
| ----  | ------------| ---|--------| ---------|
| Thomas|tom@abc.com  | 50 | USA    | Delete
| John  |john@abc.com | 50 | USA    | Insert
| David |dav@abc.com  | 60 | Mexico | Insert
| Alex  |alex@abc.com | 65 | Denmark| Insert
| James |jams@abc.com | 66 | UK     | Insert

A: delete from table
where name in (
  select name from table
  group by name
  having count(*) > 1)

A: Withh your data as in the question:
Create table A_TBL  AS

            Select 'John'  "A_NAME", 'john@abc.com' "EMAIL", 90 "N", 'Canada' "COUNTRY", 'Delete' "OPERATION" From Dual Union All
            Select 'John'  "A_NAME", 'john@abc.com' "EMAIL", 90 "N", 'Canada' "COUNTRY", 'Delete' "OPERATION" From Dual Union All
            Select 'John'  "A_NAME", 'john@abc.com' "EMAIL", 50 "N", 'USA' "COUNTRY", 'Delete' "OPERATION" From Dual Union All
            Select 'Thomas'  "A_NAME", 'thomas@abc.com' "EMAIL", 50 "N", 'USA' "COUNTRY", 'Delete' "OPERATION" From Dual Union All
            Select 'David'  "A_NAME", 'david@abc.com' "EMAIL", 60 "N", 'Mexico' "COUNTRY", 'Delete' "OPERATION" From Dual Union All
            Select 'James'  "A_NAME", 'james@abc.com' "EMAIL", 70 "N", 'Spain' "COUNTRY", 'Delete' "OPERATION" From Dual Union All
            Select 'James'  "A_NAME", 'james@abc.com' "EMAIL", 70 "N", 'Spain' "COUNTRY", 'Delete' "OPERATION" From Dual Union All
            Select 'James'  "A_NAME", 'james@abc.com' "EMAIL", 66 "N", 'UK' "COUNTRY", 'Delete' "OPERATION" From Dual Union All
            Select 'Alex'  "A_NAME", 'alex@abc.com' "EMAIL", 65 "N", 'Denmark' "COUNTRY", 'Delete' "OPERATION" From Dual;

here is the solution:
DELETE FROM A_TBL
WHERE A_NAME || '-' || EMAIL || '-' || To_Char(N) || '-' || COUNTRY IN
    (
        SELECT
            A_NAME || '-' || EMAIL || '-' || To_Char(N) || '-' || COUNTRY "MY_KEY"
        FROM
            (
                Select
                    t.A_NAME, t.EMAIL, t.N, t.COUNTRY, t.OPERATION,
                    Sum(1) OVER(PARTITION BY t.A_NAME || '-' || t.EMAIL || '-' || To_Char(t.N) || '-' || t.COUNTRY
                                          ORDER BY t.A_NAME || '-' || t.EMAIL || '-' || To_Char(t.N) || '-' || t.COUNTRY
                                          ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW) "ORD",
                    COUNT(OPERATION) OVER(PARTITION BY t.A_NAME || '-' || t.EMAIL || '-' || To_Char(t.N) || '-' || t.COUNTRY
                                          ORDER BY t.A_NAME || '-' || t.EMAIL || '-' || To_Char(t.N) || '-' || t.COUNTRY) "CNT"
                From
                    A_TBL t
            )
        WHERE CNT > 1 AND ORD = 1
    )

There is a column MY_KEY created to be like an index. Besides there are two more columns - CNT with numbers of rows for that new key and ORD with ordering the duplicate keys. The rest is ease just delete from table having concatinated table values in the list of keys from the subset where CNT > 1 and ORD = 1. Hope this could help you.
The result is:
/*
4 rows deleted.
SELECT * FROM A_TBL;
A_NAME EMAIL                   N COUNTRY OPERATION
------ -------------- ---------- ------- ---------
John   john@abc.com           50 USA     Delete
Thomas thomas@abc.com         50 USA     Delete
David  david@abc.com          60 Mexico  Delete
James  james@abc.com          66 UK      Delete
Alex   alex@abc.com           65 Denmark Delete
*/

The OPERATION column created with all the same values, sorry. But that doesn't change anything.. Regards...

A: Thank you all for your inputs but I have found a simpler solution to delete all duplicates including the original record:
delete from table where (column1,    column2,    column3,    column4)
in (SELECT
column1,    column2,    column3,    column4
FROM
table
GROUP BY     column1,    column2,    column3,    column4
having count(*) >1)


text:
Q: Multiply an array (k,) or (k, n) by 1D array (k,) I sometimes work with 1D arrays:
A = np.array([1, 2, 3, 4])

or 2D arrays (mono or stereo signals read with scipy.io.wavfile):
A = np.array([[1, 2], [3, 4], [5, 6], [7,8]])

Without having to distinguish these 2 cases with an if A.ndim == 2:..., is there a simple one-line solution to multiply this array A by an 1D array B = np.linspace(0., 1., 4)?
If A is 1D, then it's just A * B, and if A is 2D, what I mean is multiply each line of A by each element of B.

Note: this question arises naturally when working with both mono and stereo sounds read with scipy.io.wavfile.

A: Approach #1
We can use einsum to cover generic ndarrays -
np.einsum('i...,i->i...',A,B)

The trick that works here is the ellipsis that broadcasts for the trailing dimensions after the first axis as they are in A and keeps them in the output, while keeping the first axes for the two inputs aligned, which is the intended multiplication here. With A as 1D array, there's no broadcasting and that essentially reduces to : np.einsum('i,i->i',A,B) under the hoods.
Schematically put :
A   :  i x ....
B   :  i
out :  i x ....

Hence, covers for A with any number of dimensions.
More info on the use of ellipsis from the docs :

To enable and control broadcasting, use an ellipsis. Default
  NumPy-style broadcasting is done by adding an ellipsis to the left of
  each term, like np.einsum('...ii->...i', a). To take the trace along
  the first and last axes, you can do np.einsum('i...i', a), or to do a
  matrix-matrix product with the left-most indices instead of rightmost,
  you can do np.einsum('ij...,jk...->ik...', a, b).

Approach #2
Using the fact that we are trying to align the first axis of A with the only axis of 1D array B, we can simply transpose A, multiply with B and finally transpose back -
(A.T*B).T


text:
Q: How to delete a exist symbolic link used by Sublime Text 2? I used this at first, but I found I am using Sublime Text 3
sudo ln -s /Applications/Sublime\ Text\ 2.app/Contents/SharedSupport/bin/subl /usr/bin

How do I delete it and use this instead:
sudo ln -s /Applications/Sublime\ Text.app/Contents/SharedSupport/bin/subl /usr/bin

A: Run this:
sudo ln -fs /Applications/Sublime\ Text.app/Contents/SharedSupport/bin/subl /usr/bin

There's an issue here: You don't know how to delete a soft-link you created, yet you're doing it as the super-user. Knowing how to create and delete files (which includes soft-links) is critical, and is an elementary skill for working with the command-line. Doing so as the system administrator without understanding what you're doing is asking for trouble.
Take some time to learn your OS; If you're serious about programming you're going to spend a lot of time there and will be manipulating a lot of files and their names.


text:
Q: Why is an HTML tag 'closing itself' in javascript and not including iterated content? I am trying to open an HTML tag, iterate a for loop to add content from an array, then after the loop is created, close the HTML tag.
However I am seeing that it renders the HTML tag opening and closing and then the iterated content outside the HTML tag.
Example:
    block.innerHTML += "";
    for (var i = 0; i < 9; i++) {
        block.innerHTML += letterArray[i] + ", ";
    }
        block.innerHTML += "___?";

What I'd got was:

    a, b, c, d, e, f, g, h, i, ___?

What I'D expected was:
    a, b, c, d, e, f, g, h, i, ___?

I am interested why it appears as though the closing tag is parsed out from the .innerHTML following the for loop.
Note:
I did get some advice, and solved it by declaring variables for everything, and then only using .innerHTML one time.
    var openSpan = "";
    var closeSpan = "___?";
    var arrayAsString = "";

    for (var i = 0; i < 9; i++) {
        arrayAsString += letterArray[i] + ", ";
    }
    block.innerHTML += (openSpan + arrayAsString + closeSpan);

But I am still wondering what went wrong on my first logic


text:
Q: Is there a way to drop a table/view if you do not know which it is in postgresql? I want to drop a view, but sometimes it is a table. How do I drop it whatever the case?
Example:
The state of t2 is ambiguous {table, view} due to another system:
create table t1 as (select 1);
create table t2 as (select 1);

or
create table t1 as (select 1);
create view t2 as select * from t1;

All I need to do is drop t2, but it seems I am constrained to drop either a table or a view. I tried doing both sequentially, but IF EXISTS does not suppress the following errors when it hits the opposing case:
drop view if exists t2;
ERROR:  "t2" is not a view
HINT:  Use DROP TABLE to remove a table.

or
drop table if exists t2;
ERROR:  "t2" is not a table
HINT:  Use DROP VIEW to remove a view.

How do I drop t2, regardless of its type?

A: You will need dynamic SQL for that:
do
$$
declare
  l_type text;
begin
  select case relkind
            when 'r' then 'table'
            when 'p' then 'table'
            when 'v' then 'view'
            when 'm' then 'materialized view'
            when 'f' then 'foreign table'
         end as object_type
     into l_type
  from pg_class
  where oid = 't2'::regclass;
  execute format ('drop %s if exists t2 cascade', l_type);
end;
$$


text:
Q: Fantasy novel where first death is celebrated I can't remember what this book is. In it, a particular culture of people (who may or may not be human) celebrate each individual's first death as a coming-of-age ritual. I think that the person is intentionally killed by members of the community as part of the ritual, since they all reincarnate in some way. This novel is probably aimed at middle-grade readers. I can't remember any other details.

A: Since this has gone 36 hours without an answer I'll expand Garret Gang's comment into an answer. The book is A World Without Heroes from the Beyonders series by Brandon Mull. The people who die and are reincarnated are the Amar Kabal. In chapter 18 Jasher tells Jason and Rachel:

Jasher paused, regarding them with icy blue eyes. "'Amar' means 'seed.' The Amar Kabal are the People of the Seed." He turned his head and lifted the roll of hair. At the base of his skull was a raised portion of flesh the size of a walnut.
Jason winced. It looked like a huge cyst. "What's it for?"
"The amar is the vehicle of our immortality. It dislodges at our death, granting new life when planted in the earth."
"You mean you grow?" Rachel asked in amazement. "Like a plant?"
"Buried in fertile soil, the man grows from the seed within a few months. Less fertile soil requires more time. If my seed dislodged in extremely arid terrain, I might never be reborn."

And there is indeed a ceremony to mark their first death:

Jasher laughed as if the idea were absurd. "No, we are reborn into the prime of adulthood, the age at which we first die. Our First Death is a ceremony held around age twenty."


text:
Q: UIGestureRecognizers interfering with UIToolbar? I'm working on an OpenSource Magazine Engine that you can look at on GitHub:
https://github.com/interactivenyc/Defrag
I've set up a UIToolbar in a UIView I've called MenuPanel. For some reason the UIBarButtonItems in the UIToolbar aren't calling their actions properly.  Here is the syntax I'm using for the buttons:
UIBarButtonItem *homeItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"home.png"] style:UIBarButtonItemStylePlain target:self action:@selector(buttonClicked:)];

What is happening is that anywhere I click on my screen, the UITapGestureRecognizer declared in my main UIViewController is being called instead.  This gets setup in this block of code in my main UIViewController:
- (void)setupGestureRecognizers {

//NSLog(@"setupGestureRecognizer NEW");

UISwipeGestureRecognizer *swipeRecognizer;

swipeRecognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(handleGesture:)];
swipeRecognizer.direction = UISwipeGestureRecognizerDirectionRight;
[self.view addGestureRecognizer:swipeRecognizer];
[swipeRecognizer release];

swipeRecognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(handleGesture:)];
swipeRecognizer.direction = UISwipeGestureRecognizerDirectionLeft;
[self.view addGestureRecognizer:swipeRecognizer];
[swipeRecognizer release];

swipeRecognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(handleGesture:)];
swipeRecognizer.direction = UISwipeGestureRecognizerDirectionUp;
[self.view addGestureRecognizer:swipeRecognizer];
[swipeRecognizer release];

swipeRecognizer = [[UISwipeGestureRecognizer alloc] initWithTarget:self action:@selector(handleGesture:)];
swipeRecognizer.direction = UISwipeGestureRecognizerDirectionDown;
[self.view addGestureRecognizer:swipeRecognizer];
[swipeRecognizer release];

UITapGestureRecognizer *tapRecognizer;

tapRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(handleTap:)];
[self.view addGestureRecognizer:tapRecognizer];
[tapRecognizer release];
}

I'm sure I have something pretty basic conceptually wrong with how I'm trying to do this.  Can someone tell me how I can fix this problem?
For reference, you can see my main DefragViewController: UIViewController here:
https://gist.github.com/1431722
And my MenuPanel: UIView here:
gist.github.com/1431728

A: I solved my own question.
I had to tell my UIViewController to ignore touches from any UIToolbar like this:
- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch{

    //ignore any touches from a UIToolbar

    if ([touch.view.superview isKindOfClass:[UIToolbar class]]) {
        return NO;
    }

    return YES;
}


text:
Q: How to handle multiple database schema creation scripts with Maven? I have an application in development that supports several databases including SQL*Server 2008, Oracle 10G, Oracle 11G, MYSQL 5, etc.   Already within Maven I have done three things:
1) There is a profile for each database so that the system can use it for integration testing during the build.
2) Maven invokes the hibernate3 plugin to automatically generate a schema script using hbm2ddl.
3) A Hudson matrix build is set up so that integration tests are run against every database automatically.
I have noticed (with no surprise) that the script created by hbm2ddl is different depending on the database dialect.
However, when packaging the system for customers we have to manually go into the various Hudson builds and pluck the database specific scripts from there.  A tedious process that I am sure will bite us at the worst possible moment!!
Is there anyway that we can have Maven automatically generate and then gather up all these database scripts so that they can be packaged along side the WAR file we ship to customers?  I was thinking of the Maven assembly plugin to zip it all up, but am not sure!

A:
Is there anyway that we can have Maven automatically generate and then gather up all these database scripts so that they can be packaged along side the WAR file we ship to customers?
  I was thinking of the Maven assembly plugin to zip it all up, but am not sure!

The problem is that the scripts are generated for each profile run (at least this is my understanding) and unless you package them in some kind of distinct artifacts (could be assemblies) and install/deploy them at each run, you won't be able to grab them in a subsequent step with Maven.
The alternative would be to have a module with several executions of the hbm2ddl goal defined. But I'm afraid this will defeat the whole profile stuff.
Or you could maybe use the M2 Extra Steps Plugin to rely on Hudson and add some post-build steps to your Maven builds (not sure if this can help).


text:
Q: Unable to insert multiple rows containing huge Twitter Response strings in MySQL DB? The following is the code that adds 200 recent tweets (JSON provided by Twitter API) into the DB for a Twitter-User. Here the  $users array just holds one user (eg: @katyperry) but eventually it would hold more. For each of the users in the array 200 tweets are being brought in through the Twitter API. All this data collection works fine.
Here is the problem now: For each user I am inserting 200 tweets in the MySQL DB (I have to use MySQL only, no other choice) table. Now I understand that each TwitterResp JSON stringified is huge (maybe that is the issue).
Example of TwitterResp:
{"created_at":"Thu Jul 23 18:25:30 +0000 2015","id":624284214704390145,"id_str":"624284214704390145","text":"when your fragrance is ud83dudd25#madpotion https://t.co/UfyPQIwIj4","source":"Instagram","truncated":false,"in_reply_to_status_id":null,"in_reply_to_status_id_str":null,"in_reply_to_user_id":null,"in_reply_to_user_id_str":null,"in_reply_to_screen_name":null,"user":{"id":21447363,"id_str":"21447363","name":"KATY PERRY","screen_name":"katyperry","location":"","description":"CURRENTLYu2728BEAMINGu2728ON THE PRISMATIC WORLD TOUR 2014/2015!","url":"http://t.co/fxFJjKX30d","entities":{"url":{"urls":[{"url":"http://t.co/fxFJjKX30d","expanded_url":"http://www.katyperry.com","display_url":"katyperry.com","indices":[0,22]}]},"description":{"urls":[]}},"protected":false,"followers_count":73404466,"friends_count":157,"listed_count":143175,"created_at":"Fri Feb 20 23:45:56 +0000 2009","favourites_count":1663,"utc_offset":-28800,"time_zone":"Alaska","geo_enabled":false,"verified":true,"statuses_count":6566,"lang":"en","contributors_enabled":false,"is_translator":false,"is_translation_enabled":true,"profile_background_color":"CECFBC","profile_background_image_url":"http://pbs.twimg.com/profile_background_images/378800000168797027/kSZ-ewZo.jpeg","profile_background_image_url_https":"https://pbs.twimg.com/profile_background_images/378800000168797027/kSZ-ewZo.jpeg","profile_background_tile":false,"profile_image_url":"http://pbs.twimg.com/profile_images/609748341119844352/7dUd606e_normal.png","profile_image_url_https":"https://pbs.twimg.com/profile_images/609748341119844352/7dUd606e_normal.png","profile_banner_url":"https://pbs.twimg.com/profile_banners/21447363/1428015534","profile_link_color":"D55732","profile_sidebar_border_color":"FFFFFF","profile_sidebar_fill_color":"78C0A8","profile_text_color":"5E412F","profile_use_background_image":true,"has_extended_profile":false,"default_profile":false,"default_profile_image":false,"following":true,"follow_request_sent":false,"notifications":false},"geo":null,"coordinates":null,"place":null,"contributors":null,"is_quote_status":false,"retweet_count":5366,"favorite_count":10510,"entities":{"hashtags":[{"text":"madpotion","indices":[24,34]}],"symbols":[],"user_mentions":[],"urls":[{"url":"https://t.co/UfyPQIwIj4","expanded_url":"https://instagram.com/p/5fRc5mP-YB/","display_url":"instagram.com/p/5fRc5mP-YB/","indices":[35,58]}]},"favorited":false,"retweeted":false,"possibly_sensitive":false,"lang":"en"}

So when I am inserting in a loop as shown in the code for TwitterResp being a huge string, in the end I see something like 154 rows in the table not 200. For some other user I see 186 not 200 and so on. Now matter how many times I run the code for katy perry I get 154 only and similar for other users. I was wondering why may this be? Is the insertion process slow for this loop with huge string insertions that it is skipping some rows?
$users = array("result" => ["@katyperry"]);

    foreach ($users['result'] as $user) {

        // strip the initial character '@' and get 200 Twitter Responses for that screen-name.
        $twitterResp = getTweet(substr($user, 1), 200);

        $count = 1;

        mysqli_query(getConnection(), "START TRANSACTION;");

        foreach($twitterResp as $response){

            $object = $response;

            $query = "INSERT INTO Tweets(Number, TwitterHandle, TwitterResp) VALUES('".(string)$count."', '".$user."', '".json_encode($object)."');";

            $count += 1;

            $res = mysqli_query(getConnection(),$query);

        }
        mysqli_query(getConnection(), "COMMIT;");
    }

PS: I also tried adding the tweets in one query by basically Adding a lot of VALUES(), VALUES(), .....
That also didn't work.
How can I fix this? Any Suggestions?

A: At first, modify your code to handle MySQL errors. This will definitely give you a hint what's going wrong.
$res = mysqli_query(getConnection(),$query);
if(false === $res) {
   echo "Insertion error: " . mysqli_error();
}

My guess is that you're exceeding max length for TEXT or BLOB type, whatever you've used for TwitterResp column.
It may seem that data length for TEXT or BLOB type is unlimited, but it's not. TEXT / BLOB may handle up to 65536 bytes (~64KB), while MEDIUMTEXT / MEDIUMBLOB have capacity of ~16MB and LONGTEXT / LONGBLOB up to ~4GB.
Note that these are only type limits, you also have to consider size of connection buffer, number of available memory, etc, which may also cause data truncation. See MySQL documentation for more info.
In conclusion, you may try to change column type to MEDIUMTEXT or MEDIUMBLOB which have higher capacity. Yet if it is not enough I'd suggest to store data in file instead and save file path into database.


text:
Q: Pressing tab doesn't expand autocompleted chat @names in Opera When using chat, if I start typing someone's name preceded by an @ I see the autocomplete suggestions pop up above the input box as I would expect, but pressing Tab shifts focus from the text box to the "Send" button instead of expanding the name. I have to either type the name out in its entirety or click on the autocomplete suggestion to get it to expand, which is much slower. This only appears to be happening in Opera (latest stable); Chrome works as expected.

A: Oh, Opera...Chat special cases Opera when binding the handler used to catch the tab key because historically Opera would not allow a tab to be cancelled on keydown, so keypress had to be used instead.
Now, Opera apparently doesn't even fire the keypress event in the input field because it switches focus to the button on keydown. On the flip side, cancelling the tab key in keydown now seems to work correctly in Opera, so chat could stop special-casing the handler binding...the only downside being that I don't see a particularly clean way to support both the current and historic behaviours, so Opera users who haven't upgraded recently would likely be out of luck.
Incidentally it looks like this was already done for the comment tab completer on the full site, although someone missed the change in the unbind:
j && j.unbind($.browser.opera ? "keypress" : "keydown", e).unbind("keyup click", h);


text:
Q: закрытие блока по клику на кнопку и вне блока Есть выпадающее меню которое открывается по клику на бургер, не могу сделать закрытие меню и по клику снова на бургер и закрытие по клику вне области
если добавляю код закрытия по клику вне блока то закрытие меню по клику на кнопку не работает
$('.header__hamburger').on('click', function(){
        $('.header__menu-mobile').toggleClass('mobile-menu-active');
});

Вот код закрытия меню по клику вне области
$(document).mouseup(function (e) {
        var container = $(".header__menu-mobile");
        if (container.has(e.target).length === 0){
            $('.header__menu-mobile').removeClass('mobile-menu-active');
        }
    });

Совместить эти функции не получается что бы закрывало и по клику на кнопку и по клику вне области
Вот разметка

                Подарунковий набір
                Подарунковий сертифікат

                Доставка і повернення
                Політика конфіденційності

A: Ты удалил класс, а надо задать другой, вроде бы

С помощью события mouseup вы можете щелкнуть в другом месте на экране, удерживать нажатой кнопку мыши и переместить указатель на элемент mouseup, а затем отпустить указатель мыши.
Событие с кликом требует, чтобы в этом элементе выполнялось событие mousedown и mouseup.
Обычное ожидание состоит в том, что для клика требуется как событие mousedown, так и mouseup, поэтому я рекомендую событие click.
Из возможного дубликата видно, что события mouseup и mousedown также могут быть вызваны кнопками мыши, кроме кнопки левого щелчка. Это очень отличается от того, что ожидал общий пользователь.


text:
Q: Entity Framework Code First custom migrations Transaction Exception I have defined a custom migration class, like so:
public class MyMigrate<TMigrationsConfiguration> : IDatabaseInitializer<MyContext>
    where TMigrationsConfiguration : DbMigrationsConfiguration<MyContext>, new()
{
    private readonly TMigrationsConfiguration _config;

    public MyMigrate(string connectionString, string invariantProvider)
    {
        var typeInitialCreate = typeof(MyConfiguration);

        var migrationsAssembly = Assembly.GetAssembly(typeInitialCreate);
        var migrationsNamespace = typeInitialCreate.Namespace;

        _config = new TMigrationsConfiguration
        {
            TargetDatabase = new DbConnectionInfo(connectionString, invariantProvider),
            MigrationsAssembly = migrationsAssembly,
            MigrationsNamespace = migrationsNamespace,
        };
    }

    public void InitializeDatabase(MyContext context)
    {
        // Update the migrator with the config containing the right connection string
        var dbMigrator = new DbMigrator(_config);

        var dbm = dbMigrator.GetDatabaseMigrations();
        var local = dbMigrator.GetLocalMigrations();
        var pending = dbMigrator.GetPendingMigrations();

        dbMigrator.Update();
    }
}

This is the actual configuration class, that does some additional seeding stuff. This class is located in another assembly.
public sealed class MyMigrationConfiguration : DbMigrationsConfiguration<MyContext>
{
    public MigrationConfiguration()
    {
        AutomaticMigrationsEnabled = false;
        ContextKey = "MyContext";
    }
}

This is the generated Configuration file you get after you enable migrations. It is used, to identify and load the assembly with the generated migration files.
internal sealed class MyConfiguration : DbMigrationsConfiguration<MyContext>
{
    public Configuration()
    {
        AutomaticMigrationsEnabled = false;
        ContextKey = "MyContext";
    }
}

}
I execute it like so:
private static void MigrateToLatest()
    {
        var conString = System.Configuration.ConfigurationManager.ConnectionStrings["MyContext"].ConnectionString;

        Database.SetInitializer(new MyMigrate<MigrationConfiguration>(conString, Migrate.SqlInvariantProvider));

        using (var fctx = new MyContext(conString, "SYSTEM"))
        {
            if (!fctx.Database.CompatibleWithModel(false))
            {
                fctx.Database.Initialize(false);
            }
        }
    }

I get the following error message when i call Initialize(false):
`An unhandled exception of type 'System.InvalidOperationException' occurred in EntityFramework.dll
Additional information: The transaction passed in is not associated with the current connection. Only transactions associated with the current connection may be used.`
I have checked the connection strings, they seem fine. If i uncomment the Initializer line, or replace it with SetInitializer(null), i will get the "model has changed" error message, but transactions don't seem to be a problem. Somehow it must have to do with my custom migrator class. I used this code in EF 4.3 and it worked. In 6.1.3 it no longer executes.


text:
Q: Sometimes when I click AngularJS links, the page reloads I have a single-page app that has several views. On one view, I list all the orders, on another page, I modify those orders. I want to be able to go between the two pages without needing to save any data to a database.
On my development box, this works well. I just save the orders on $window and when I load the details page, I look through window.orders for it. Great. However, when deployed, all my links act like they link to a new page... so the page reloads. This means that when I try to link from my main list page to my details page, the details page doesn't get access to anything on window. Isn't the whole point of a single page app that it doesn't reload the page when changing views? How do I get my links to not load a new page? they're all in the format of <a href="#!/<view>">text.
So here's part of my orders-list.template.html:

        Part #
        Customer
        Job #
        Due Date
        {{day}}

        {{order.PartNumber}}
        {{order.Customer}}
        {{order.JobNumber}}
        {{order.DueDate|date:'shortDate'}}

            <input type="number" style="width:60px;" ng-model="order.Weeks[day].Pieces" ng-change="calculateHoursOfWork();"/>
            {{(order | runTimePlusSetupPlusEfficiency:options:order.Weeks[day].Pieces) | number:3}}

Note that the part number is a link to #!/orders/{{order.ID}}. I was under the impression this link wouldn't reload the web page.
This is in my main script:
            $routeProvider.
                when("/orders", {
                    template: "<orders-list></orders-list>"
                }).
                when("/orders/:orderId", {
                    template: "<order-detail></order-detail>"
                }).
                when("/options", {
                    template: "<options></options>"
                }).
                when("/printable", {
                    template: "<orders-printable></orders-printable>"
                }).
                otherwise("/orders");

So it should be clear that /orders refers to my ordersDetail component. Here's part of it:
angular.module("orderDetail").component("orderDetail", {
    templateUrl: "AngularModules/order-detail/order-detail.template.html",
    controller: ['$routeParams', "$http", "$window", function OrderDetailController($routeParams, $http, $window) {
        var self = this;
        self.TotalNonSetupRunTime = 0.0;
        self.options = $window.options;

        self.order = null;
        $.each($window.orders, function (idx, elem) {
            if (elem.ID == $routeParams.orderId) {
                self.order = elem;
            }
        });
        if (self.order === null) {
            var orderID = null;
            if ($routeParams.hasOwnProperty('orderId')) {
                orderID = $routeParams.orderId;
            }
            var windowOrders = "undefined";
            if ($window.hasOwnProperty('orders')) {
                windowOrders = $window.orders.length;
            }
            alert("couldn't find order " + orderID + " among " + windowOrders + " orders! try going back and selecting again.");
        }
    }]
});

because the page is getting reloaded, I'm seeing windowOrders as undefined. Is there some setting in IIS I could change to make links to #<something> not reload the page (as expected)? or do I have to do something on the angularJS side?
Confounding it further... I did find this: hash link reloads page and apparently having a <base> directive screws with this? is there an angular-safe way to do this? I don't think it would make sense to get rid of that directive. I'm actually writing this on an asp.net-MVC page, so I have
<base ng-href="@Url.HttpRouteUrl("Default", new { }).Replace("?httproute=True", "")" />

in my _Layout.cshtml page. This way when it gets deployed (to http://<server>/<app>/) it works as well as when I'm debugging (on locahost:<some port>/).


text:
Q: application/ld+json and javascript data exchange I have some jQuery code which constructs an array called myList[]. This array appears in the console like this: ["2 items", "3items", "so on"], so this part goes well.
<script type="text/javascript">
var myList = [];
function buld myList(){
...
}

I need to pass myList[] to the application/ld+json like
<script type="application/ld+json">
{
    "@context": "http://schema.org/",
    "@type": "Recipe",
    "recipeIngredients": myList, //this one doesn't work
}

..

How can I pass the values from javascript to the application/ld+json? Thanks in advance!

A: Please try this:
<script id="myJSONID" type="application/ld+json"></script>

Then:
var myList = [];

function buildMyList() {
    return ["2 items", "3items", "so on"];
}

$("#myJSONID").text(function() {
    return JSON.stringify({
        "@context": "http://schema.org/",
        "@type": "Recipe",
        "recipeIngredient": buildMyList()
    });
});

Or:
<script type="text/javascript">
  var myList = [];
  function buildMyList() {
      return ["2 items", "3items", "so on"];
  }

  var el = document.createElement('script');
  el.type = 'application/ld+json';

  el.text = JSON.stringify({
        "@context": "http://schema.org/",
        "@type": "Recipe",
        "recipeIngredient": buildMyList()
    });

  document.querySelector('body').appendChild(el);
</script>

Demo: https://jsfiddle.net/iRbouh/9po7dtg4/
Note: Please make sure you change recipeIngredients to recipeIngredient, singular. (Thank you @AlexKudryashev).


text:
Q: Twig not defined property seems to not work This is my part of code
{% if form.offer.increment_order_quantity.vars is defined %}
   1
{% else %}
   2
{% endif %}

It shows me "1" even if form.offer.increment_order_quantity.vars is not defined. And if instead of "1", I want to dump {{ form.offer.increment_order_quantity.vars }}, it tells me that vars is not defined.
Since i launched an update of composer in my Symfony environment ....


text:
Q: How to get Column header value of selected row in gridview in asp.net? I have this code
protected void btn_Check_Click(object sender, EventArgs e)
    {
 int Index = ((GridViewRow)((sender as Control)).NamingContainer).RowIndex;
        Response.Write("btn_Check_Click event called" + Index.ToString());
}

in which each cell of the gridview is having a button.
Please tell how to get the column value of the selected row in this.
here Index of each cell is accessed.

A: if you have the cell (column) index you can use something like yourGridView.HeaderRow.Cells[i].Text.


text:
Q: How to hide scrollbar from animated image which is larger than screen width without affecting the body? So for example, if i have an image of width 2000px whic is larger than screen width, animated from left to right. Here. How do i code it so that a scroll bar wont appear when it is animating? Also it won't affect my body for example when i restore down the window a scroll bar will appear for my body only.

A: You will have to wrap the element in a wrapper that basically "eats" the excess width:
JavaScript:
$('#a').wrap($('<div />', {'class': 'wrapper'}));

CSS:
.wrapper {
    position: relative;
    overflow: hidden;

    height: 200px;  /* .wrapper collapses if there is no height
                       and your elements are absolutely positioned */
}

Demo: http://jsfiddle.net/x2YGX/3/

A: Use CSS overflow
.animation
{
/*other properties*/
overflow:hidden;
}

A: just changing position to fixed will also do
#a {
    width: 2000px;
    position: fixed;
 }

Demo


text:
Q: Select-Object returns the first result as my column name instead of as a result The following script checks mailboxes in a specified OU for users with the default permission set to Owner. I have tried everything to add the column "Name" from the variable $Mailbox to the Select-Object results in the following code. The result will add a column header with the first results name as the header. If there are multiple results the first name found will be the column header with the column blank for the others. Is there a way to add the "Name" column from the variable $Mailbox to the Select-Object results?
$AllMailBox = Get-Mailbox   -OrganizationalUnit "XXXXXXXXXX.com/DomainUsers/Users" -resultsize unlimited
ForEach ($MailBox in $AllMailbox) {Get-mailboxfolderpermission $Mailbox | Where-object {$_.User -match "Default" -AND $_.AccessRights -match "Owner"} | Select-Object  Identity, AccessRights, $MailBox.Name}

A: $MailBox.Name lives in outer scope.  It isn't a valid property of item returned from Get-mailboxfolderpermission.
You can use calculated property in Select-Object to add additional data to the result:
{Get-mailboxfolderpermission $Mailbox | Where-object {$_.User -match "Default" -AND $_.AccessRights -match "Owner"} | Select-Object  Identity, AccessRights,@{Name="Name"; Expression={$MailBox.Name}}

Calculated property is declared by hash table with keys:

*

*Name — the name of the property

*Expression — script block that returns a value

See "EXAMPLE 4" here for another example of calculated property.

A: Instead of
Select-Object  Identity, AccessRights, $MailBox.Name}

Add this
Select-Object  Identity, AccessRights, @{l="Name";e={$MailBox.Name}}}

where l stands for Label and e stands for Expression.
You can read more about custom tables here https://technet.microsoft.com/en-us/library/ee692794.aspx?f=255&MSPPError=-2147217396


text:
Q: How to add control to the page programatically in page load? I am trying to add controls to the page from the code behind in the page load stage like this:
foreach (FileInfo fi in dirInfo.GetFiles())
{
    HyperLink hl = new HyperLink();
    hl.ID = "Hyperlink" + i++;
    hl.Text = fi.Name;
    hl.NavigateUrl = "../downloading.aspx?file=" + fi.Name + "&user=" + userIdpar;
    Page.Controls.Add(hl);
    Page.Controls.Add(new LiteralControl("
"));
}

The error which I am getting is on Page.Controls.Add(hl) and here is the explanation:

The control collection cannot be modified during DataBind, Init, Load, PreRender or Unload phases.

What can I do to fix this issue? Thanks in advance.

A: Create your own container collection and add these to it, instead of directly to the page controls collection.
On .aspx:
<asp:Panel id="links" runat="server" />

In code behind (I suggest using the Init event handler rather than page load):
foreach (FileInfo fi in dirInfo.GetFiles())
{
  HyperLink hl = new HyperLink();
  hl.ID = "Hyperlink" + i++;
  hl.Text = fi.Name;
  hl.NavigateUrl = "../downloading.aspx?file=" + fi.Name + "&user=" + userIdpar;
  links.Controls.Add(hl);
  links.Controls.Add(new LiteralControl("
"));
}

A: Add your controls into Init() event of Page.


text:
Q: Search query with contains Is it possible with either KQL or FQL to query for title:*or* and get back items where the tile is e.g "A.B.PZ.3_MS_Form" ? Another query would be title:*PZ*.
Background: I have a custom advanced search and fight with the contains drop down for the title property. Starts-with, ends-with and equals are working. Its for SP2010+FS4SP

A: This is NOT possible with Managed Property keyword queries.  The only wildcard capability that Sharepoint Search Server 2010 supports is "Stemming".  Stemming expects the characters to be matched by the characters at the start of a string in the index.
e.g. Item contains Title string "TestMe"
You're query can be :  Title:"Tes" and that would pick up the TestMe item.
You would have to enable stemming in your Core Results Webpart or in a custom scenario, enable it on a FullTextSqlQuery object.

A: If you do a KQL query with title:or* you will see the results you are asking for.  You do not need to put the leading wildcard as it does that automatically.

A: Your best approach is to get titles on those weird formats into a separate managed property. Then you can do word searches on that property in FQL with less chance of the query bombing.
It's all about term expansion in the search engine core and how many terms would match and how big(slow) will the end query be.
The other approach is to create a full text index with n-grams enabled.


text:
Q: C#, I want to display a DataTable in a DataGrid Here is my Code:
There are some new Rows in the DataGrid, but they are all empty. Or is there any other Methode I can use?
private void btnFill_Click(object sender, RoutedEventArgs e)
{
    var url = string.Empty;
    using (var web = new System.Net.WebClient())
    {
        url = web.DownloadString(txtMainUrl.Text + "/sitemap.xml");
    }

    var dataTablesummary = new DataTable();
    dataTablesummary.Columns.Add("Test", typeof(string));
    dataTablesummary.Columns.Add("Check", typeof(bool));

    var link = string.Empty;

    for (int i = 0; i < url.Length; i++)
    {
        char letter = url[i];

        if (url[i] == '<' && url[i + 1] == 'l' && url[i + 2] == 'o' && url[i + 3] == 'c' && url[i + 4] == '>')
        {
            i += 5;
            do
            {
                link += url[i];
                i++;
            } while (url[i] != '<');
            dataTablesummary.Rows.Add(link, true);
        }
        link = string.Empty;
    }
    gridAdditionalUrls.ItemsSource = dataTablesummary.AsDataView();
}


text:
Q: Different timing samples' analysis How can I put my data in a sheet if I have a number of patients and each patient have different number of samples with different timing? How can I analyse data grouping data samples for each different patient?

A: You can store your data using the so-called "long data format".
In other words, in your data spreadsheet, define four columns:
PatientID   SampleNumber  SampleDate  SampleValue

Then record the data available for each patient along these lines:
PatientID   SampleNumber    SampleDate     SampleValue
     1           1        Jan 1, 2019          20.5
     1           2        Jan 2, 2019          19.3
     2           1        Jan 3, 2019          21.2
     2           2        Jan 4, 2019          17.8
     2           3        Jan 5, 2019          18.5
     Etc.

How you analyze your data will ultimately depend on what questions you want to be able to answer on the basis of these data. You will need to provide more specifics to that end.


text:
Q: AngularJS double value in table I have problem with when I want print a table, I have a double value. This is my print on page:
A 2.14 2.14 B 4.57 C 6.00 6.00 D 3.43 E 3.86 F 3.29

     {{item.currency}}
    {{item.price}}
    {{item.price}}
    {{item.price}}

Which condition I have to set to overcome duplicate values? tnx for help

A: The value is double printed because you have the {{item.price}}	 that will show every time and the ng-show directive that will be right at least once.

     {{item.currency}}
    {{item.price}}
    {{item.price}}

If none of the show conditions are true, display your last .
{{item.price}}


text:
Q: TIme Machine IP Change Loses Backup History I have a time machine setup where the backup location is on a Synology NAS drive; having recently moved house, and ended up with a different router, I setup the NAS drive again, and it has a different IP address (formerly in the 10.* range, now in the 192.* range).
I couldn't - no matter what I tried - get Time Machine on the iMac to recognise the drive as the existing TM location; despite it showing up as an available disk in TM preferences. In the end, I deleted the old backups (nothing required from them yet, so it won't hurt to start again, I suppose). What I'd like to know, for future reference, is if/how I can get TM to recognise the NAS as the backup location if the IP address changes again. None of the hardware changed, so I can't see why this was an issue.

A: The new router (the hardware did change) is obviously using one of the default 192.* ranges instead of the 10.* range the old router was using. Your iMac and NAS picked up an address in the new IP range, (that's why the iMac could 'see' the NAS,) but because the IP in the NAT changed, Time Machine failed.
When you change routers in the future, you should make sure the iMac and NAS pick up an IP in the same range as the old router so there is no mismatch.


text:
Q: Python - Accessing and modifying a list from several modules In a nutshell: Is it possible and in good practice to have a list in one module be accessed and modified from several others or it better be restructured to be used in only the one in which they were created?
I am writing a game and as it got above 1500 lines, i thought it would be high time to restructure it into modules for easier maintaining.
In the original program there were several lists, that stored gameobjects like tiles and such.
These lists were accessed for iterating over, and also to be appended to from several classes.
I thought of putting all lists/dicts that need accessing from several others into their own storage module, and importing the appropriate containers into the modules they are needed in, but it didnt seem like it worked.
Can this be done properly?

A: There are good reasons to have an object that stores global state be accessible from several modules. The scenario you describe sounds like an appropriate use case for this.
The proper way to do this in python to maintain some good semantics is to create a Singleton class with all these lists (or separate Singleton classes if the lists represent information that is different conceptually to each other) and then have the other modules modify these Singleton objects (ie, call methods on them) to append things to the lists. Singletons are classes that can only be created once. If you try to create them again, the first object is returned and no new object is created, essentially. So you could have  Singleton called 'GameState'.
Python doesn't support creating Singleton objects natively, but there are ways to work around this, look around stackoverflow for how to create a singleton in python

A: The way, to write a storage module seems correct. But without knowing the details, I can only suggest some good practices, with might be not suitable for your case. Static objects, like tiles should be loaded/created only at one place. The access to these objects should happen over a definite interface implemented in one module.


text:
Q: In a Song of Ice and Fire, what are rushes? In A Song of Ice and Fire, what are rushes?  They are commonly referred to as being scattered on the floor, and are usually either fresh or old.

A: Rushes (Juncaceae family) are a sweet smelling, flowering plant that has been used for a number of domestic purposes including flooring material.  When fresh, they added both insulation and a pleasant aroma to cover up the--frequently--muddy earthen floor.  When old, some homes/cultures simply strew more rushes over the top to cover them and either rarely if ever cleaned them out.  Other families might clean them out weekly or monthly.
Straw is used for a similar purposes as bedding and floor covering for animals.  But as I grew up on a farm, I can attest straw is both itchier and not as sweet smelling as rushes.  :-)

From Wikipedia:

In medieval Europe, loose fresh rushes would be strewn on earthen floors in dwellings for cleanliness and insulation. Particularly favored for such a purpose was Acorus calamus (sweet flag), but despite its alternate vernacular name "sweet rush", it is a plant from a different monocot order, Acorales.

— Article on Juncaceae

A: Rushes are a plant material that cover the floor of most rooms. They are used in place of carpets though some richer places do have access to carpets.

The chamber was richly furnished. Myrish carpets covered the floor instead of rushes, and in one corner a hundred fabulous beasts cavorted in bright paints on a carved screen from the Summer Isles.
A Game of Thrones, Eddard IV

The rushes are usually fresh and sweet smelling when laid first.

The Queen's Ballroom was not a tenth the size of the castle's Great Hall, only half as big as the Small Hall in the Tower of the Hand, but it could still seat a hundred, and it made up in grace what it lacked in space. Beaten silver mirrors backed every wall sconce, so the torches burned twice as bright; the walls were paneled in richly carved wood, and sweet-smelling rushes covered the floors.
A Clash of Kings, Sansa V

Though they do go old, dirty and start to rot and so need changing, they are plant material after all.

The chambers stank of rotted food, and the rushes were crawling with vermin.
A Feast for Crows, Jaime III

The wall hangings were green with mildew, the mattress musty-smelling and sagging, the rushes old and brittle. Years had come and gone since these chambers had last been opened. The damp went bone deep. "I'll have a basin of hot water and a fire in this hearth," he told the crone. "See that they light braziers in the other rooms to drive out some of the chill. And gods be good, get someone in here at once to change these rushes."
A Clash of Kings, Theon I

A: I finally figured them out out of context.  Carpets/rugs are much preferred yet are a costly item in that period reserving them to the wealthy.  Tapestries also come in to play.  We think of them as soley decorative, but they also insulated rooms and helped in deading sound so castles would not seem to cavernous as sound bounced off stone walls.  Once again a luxury item not normally found in a smallfolk hovel.

A: The more modern interpretation is that, like other cultures around the world -- such as Japanese tatami mats -- they would weave the rushes into mats. It's really inefficient to just drop loose rushes on the floor.