text:
Q: How to fit the table? I'm sorry for my English.
I just need to make a table with some long sentences. When I'm doing it I get the following result (see the picture), using the following code:
\begin{center}
\begin{tabular}{|c|c|c|c|c|}
    \hline
    Система & Кинетическая энергия $T$ & Потенциальная энергия $U$ & \multicolumn{2}{|c|}{Степени однородности} \\ \cline{4-5}
    & & & $h_T$ & $h_U$ \\ \hline
    Одномерный гармонический осциллятор & $\sim (\dot{x})^2$ & $\sim -x^2$ & 2 & 2
\end{tabular}
\end{center}

How do I write the code to make the table fit right?

A: You can use the makecell package: it allows for linebreaks in cells. Here is solution that uses tabularx to fit text width:
\documentclass[a4paper]{article}
\usepackage[utf8]{inputenc}
\usepackage[T2A ,T1]{fontenc}
\usepackage[russian]{babel}
\usepackage[showframe, nomarginpar]{geometry}
\usepackage{fourier, erewhon}
\usepackage{array, tabularx,multirow, makecell}
\setcellgapes{3pt}

\begin{document}

\begin{center}
\makegapedcells
\begin{tabularx}{\linewidth}{|c|c|c| >{\centering\arraybackslash}X | >{\centering\arraybackslash}X|}
\hline
& & & \multicolumn{2}{c|}{\makecell{Степени\\ однородности}} \\ \cline{4-5}
\multirowcell{-2}{Система} &\multirowcell{-3}{Кинетическая\\ энергия $T$} &\multirowcell{-3}{Потенциальная\\ энергия $U$} & $h_T$ & $h_U$ \\ \hline
\makecell{ Одномерный гармонический \\ осциллятор} & $\sim (\dot{x})^2$ & $\sim -x^2$ & 2 & 2 \\
\hline
\end{tabularx}
\end{center}

\end{document}

A: Like this?
\documentclass{article}

\begin{document}

\begin{center}
\begin{tabular}{|p{1in}|p{1in}|p{1in}|p{1in}|c|}
        \hline
        Hello & a very long sentence $T$ & a very long sentence $U$ & \multicolumn{2}{|c|}{a very long sentence} \\ \cline{4-5}
        & & & $h_T$ & $h_U$ \\ \hline
        I'm afraid I don't speak Russian & $\sim (\dot{x})^2$ & $\sim -x^2$ & 2 & 2
    \end{tabular}
\end{center}

\end{document}

A: This is used explicitly from JPi's solution above, so I don't expect neither upvotes nor downvotes.
Regarding the vertical spacings/alignment, Bernards solution is better than mine of course.
\documentclass{article}

\usepackage{array}

\newcolumntype{C}[1]{>{\centering\arraybackslash}p{#1}}

\begin{document}

\begin{center}
\begin{tabular}{|*{4}{C{1in}|}c|}
        \hline
        Hello & a very long sentence $T$ & a very long sentence $U$ & \multicolumn{2}{c|}{a very long sentence} \\ \cline{4-5}
        & & & $h_T$ & $h_U$ \\ \hline
        I'm afraid I don't speak Russian & $\sim (\dot{x})^2$ & $\sim -x^2$ & 2 & 2
    \end{tabular}
\end{center}

\end{document}


text:
Q: Empty Array of AnyObject in Swift Im declaring and empty array to be used with a fetch request as followed:
var myList: Array<AnyObject> = []

However, was this code entered, I get this message that pops up and disables the editor:
"SourceKitService Terminated. Editor Functionality temporarily limited"
Anybody know what this is about? Should I be declaring my array differently using Swift. I want an array to store my fetch request.
myList = context.executeFetchRequest(freq, error: nil)

Here is the whole code:
import UIKit
import CoreData

class ListTableViewController: UITableViewController {

var myList: [AnyObject] = []

override func viewDidLoad() {
    super.viewDidLoad()

}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

override func viewDidAppear(animated: Bool) {

    let appDel: AppDelegate = UIApplication.sharedApplication().delegate as AppDelegate
    let context:NSManagedObjectContext = appDel.managedObjectContext
    let freq = NSFetchRequest(entityName: "List")

    //populate array
    myList = context.executeFetchRequest(freq, error: nil)

    tableView.reloadData()

}

// #pragma mark - Table view data source

override func numberOfSectionsInTableView(tableView: UITableView!) -> Int {
    // #warning Potentially incomplete method implementation.
    // Return the number of sections.
    return 1
}

override func tableView(tableView: UITableView!, numberOfRowsInSection section: Int) -> Int {
    // #warning Incomplete method implementation.
    // Return the number of rows in the section.
    return myList.count
}

override func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell? {
    let CellID:NSString = "Cell"
    var cell: UITableViewCell = tableView?.dequeueReusableCellWithIdentifier(CellID) as UITableViewCell

    return cell
}

/*
// Override to support conditional editing of the table view.
override func tableView(tableView: UITableView!, canEditRowAtIndexPath indexPath: NSIndexPath!) -> Bool {
    // Return NO if you do not want the specified item to be editable.
    return true
}
*/

/*
// Override to support editing the table view.
override func tableView(tableView: UITableView!, commitEditingStyle editingStyle: UITableViewCellEditingStyle, forRowAtIndexPath indexPath: NSIndexPath!) {
    if editingStyle == .Delete {
        // Delete the row from the data source
        tableView.deleteRowsAtIndexPaths([indexPath], withRowAnimation: .Fade)
    } else if editingStyle == .Insert {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }
}
*/

/*
// Override to support rearranging the table view.
override func tableView(tableView: UITableView!, moveRowAtIndexPath fromIndexPath: NSIndexPath!, toIndexPath: NSIndexPath!) {

}
*/

/*
// Override to support conditional rearranging of the table view.
override func tableView(tableView: UITableView!, canMoveRowAtIndexPath indexPath: NSIndexPath!) -> Bool {
    // Return NO if you do not want the item to be re-orderable.
    return true
}
*/

/*
// #pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
override func prepareForSegue(segue: UIStoryboardSegue!, sender: AnyObject!) {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

}

A: The simplest way of declaring Empty array for any type of object in swift is
    var emptyArray = [AnyObject]()

A: No this is perfectly fine.
This error was coming because of problem in Xcode
Close your xcode and try again
var myList: Array<AnyObject> = []

I have tested it on Xcode beta 3
There are also other syntax to declare array.You can use
in xcode beta 3
var myList: Array<AnyObject> = Array<AnyObject>()
var myList2: [AnyObject] = []

in xcode beta 1 & 2
var myList: Array<AnyObject> = Array<AnyObject>()
var myList2: AnyObject[] = []

EDIT Actually problem is not of mylist.As you comment the myList: Array<AnyObject> = [] line this will create error so compiler stops compiling.If you remove error by hard-coding the values it start giving sourcekiterror again.
Actual problem is in this line
      var cell: UITableViewCell = tableView?.dequeueReusableCellWithIdentifier(CellID) as UITableViewCell

remove the ? from tableView? as this is not needed.It is for declaring optional not for unwrapping.For unwrapping you can use !.But as tableView: UITableView! is declared as implicit optional so it will unwrap automatically.No need to do any unwrapping.
Replace the cellForRowAtIndexPath: with below function all will work fine.
override func tableView(tableView: UITableView!, cellForRowAtIndexPath indexPath: NSIndexPath!) -> UITableViewCell? {
    let CellID:NSString = "Cell"
    //Removed ? from tableview?
    var cell: UITableViewCell = tableView?.dequeueReusableCellWithIdentifier(CellID) as UITableViewCell

    return cell
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: unable to set retrofit timeout along with picasso and okhttp I am unable to set timeout to retrofit. The code below does not work with picasso . I get a blank screen and the data and image does not load. How can I fix it with gradle:
compile 'com.squareup.picasso:picasso:2.3.2'
compile 'com.squareup.retrofit:retrofit:1.9.0'

COde:
    final OkHttpClient okHttpClient = new OkHttpClient();
    okHttpClient.setReadTimeout(60, TimeUnit.SECONDS);
    okHttpClient.setConnectTimeout(60, TimeUnit.SECONDS);

        RestAdapter restAdapter = new RestAdapter.Builder()
.setClient(new OkClient(okHttpClient))
          .setEndpoint(URL).build();
        myapi myapi_rest = restAdapter.create(myapi.class);
        myapi_rest.my_call(
                sno,
                new Callback<Response>() {

                    @Override
                    public void success(Response result, Response response) {

                    }

                    @Override
                    public void failure(RetrofitError error) {
                        // Log.i("Failure", "Error"+error.getMessage());

                    }
                });

Gradle:
compile 'com.squareup.picasso:picasso:2.3.2'
compile 'com.squareup.retrofit:retrofit:1.9.0'

    compile "com.squareup.okhttp:okhttp:1.6.0"
    compile "com.squareup.okhttp:okhttp-urlconnection:1.6.0"

A: To use your OkHttpClient with Picasso, you need to use the following code.
// Create the downloader for Picasso to use
OkHttpDownloader downloader = new OkHttpDownloader(okHttpClient);
Picasso picasso = new Picasso.Builder(context).downloader(downloader).build();

Specify the OkHttpClient for which you specified the Timeouts.


text: Q: What is a covalent bond? What is a covalent bond, quantum mechanically? How does it hold the two atoms together, and at one point can you qualify the electron as being shated between two atoms, versus feeling attractive forces?


text:
Q: Is there a need to use public OUI numeration for "private" Ethernet ports? So I'm working on a product which will have two Ethernet ports:
One for "public" network, which will be used by the customer, and one internal, within the machine chassis, which needs to be opened, which should be only used by the service technician and internal accessories.
The dogma to which I was exposed to during my network training says that all Ethernet ports should use registered OUI numbers, but on the other hand, I'm can't really think of a reason why would we need an official MAC address in this case.
So my question is:
Is there any reason why to use the officially registered OUI numbers for the internal Ethernet port?

A: As Marcus suggested, this is where the locally administered MAC addresses come handy. Here is the structure of a MAC address (taken from Wikipedia):

So, set b0 of the first byte to 0 (unicast) and b1 of the first byte to 1, and then you're free to set the other bits as you wish.
However, this requires that you can ensure the following thing: this port should never be connected to a network where there might potentially be other nodes with locally administered MAC addresses.
But equipments with locally administered MAC addresses are not supposed to be found on the market. If the only equipment that can potentially be connected to this port is a regular laptop, or even a whole newtork containing only regular switches/routers and computers, there is no such risk.
Now, there are two strategies: either you decide on a single MAC address and assign it to all your devices (they will all have the same address), or you define a scheme with a fixed and a variable part (the variable part can be taken from the serial number of the device if there is one available somewhere), so that each device has a unique (locally administered) MAC.
The single MAC address scheme is only possible is you can ensure that:

*

*There will never be two such devices on the same subnet at the same time. This is easy to guarantee if the service laptop is always directly connected to the device (not through a network with potentially multiple nodes).

*You don't disconnect one of your devices from the network and plug another one before the ARP cache of the service laptop (or any other equipment that needs to talk to your device) has expired. On typical linux/windows computers, the ARP cache expires after a few minutes. On other equipments, it can be much longer.

Regarding your concern of potential MAC address filters set by the IT: this isn't likely. MAC address filters are typically set on a network equipment (wifi access point, network switch, ...), and are set so that only registered nodes can connect to the network. If this is the case, you'll have a problem anyway, because your device won't be registered whether it has a regular OUI-assigned address or a locally administered one. I have never seen a MAC address filter set on a computer station, even in totally paranoiac IT environments.
As a conclusion, I think having a locally administered address in this case likely won't lead to a problem. However, problems are more likely to arise if you assign the same address to all your devices. I'd rather use unique addresses per device if it is achievable.


text:
Q: How to return a queryable sub-instance of a TableQuery? I'm trying to build an function which takes an optional sort or filter attribute for a query and apply these on a TableQuery if the attribute exists, if not, returns something queryable on which I can then apply other filters.
What I want to end up with is something like this:
MyTableInstance.applySearchTerm(termOption).applySorting(sortOption).filter(do other stuff here)

What I came up with until now is this:
  private implicit def applySearchTerm[U <: Query[IssueDao#IssueTable, Issue, Seq]](table: U)(
      term: Option[String]): U =
    term match {
      case Some(term) => table.filter(_.title === term)
      case None => table
    }

  private def applyFilters(filters: Filters) =
    IssueTable.applySearchTerm(filters.term)

From what I understand, the TableQuery extends the Query class, while calling filter or other query methods returns a Query[T, T#TableElementType,Seq], so what I tried was defining an upper type bound and return this, but this gives me
[error]  found   : slick.lifted.Query[dao.IssueDao#IssueTable,models.Issue,Seq]
[error]  required: U
[error]       case Some(term) => table.filter(_.title === term)

I'm not quite sure what the error here is. Is the compiler complaining because the returned value is no upper type bound but the exact type?
I saw a solution proposing implementing a custom trait which seems to solve this problem, but I'm not sure this is the best way and I try to understand how these type limitations are applied in Scala.
It would be great if someone could point me in the right direction.
Thanks in advance!


text:
Q: requisição Fetch com ASP .Net Core 3.0 Estou tentando substrituir os métodos Ajax pelo Fetch na aplicação, porém não consigo receber um objeto com o Fetch, fiz um pequeno objeto de teste para tentar receber, no Ajax, consigo passando parâmetro pelo Data
    public class ObjetoTeste
    {
        public string Nome { get; set; }
        public string NomeFantasia { get; set; }
    }

No meu controller, recebo da seguinte forma
    public JsonResult Teste(long s, ObjetoTeste obj)
    {
        return Json(obj);
    }

Com Ajax, recebo o objeto normalmente, já no Fetch, não consigo enviar nada, ele sempre recebe nulo no Controller, no Javascript, montei 2 métodos que recebem o mesmo objeto, idêntico, e ambos se comportam de forma diferente.
    var data = {
        s: 500,
        obj: {
            Nome: 'Nome',
            NomeFantasia: 'NomeFantasia'
        }
    }

    _private.Ajax = function () {
        console.log('Ajax')
        $.ajax({
            url: "/Home/Teste",
            type: "POST",
            data: data,
            success: function (response) {
                console.log(response)
            },
            error: function (jqXHR, textStatus, errorThrown) {
                console.log(textStatus, errorThrown);
            }
        });
    }

    _private.Fetch = function () {
        console.log('Fetch')
        fetch('/Home/Teste', {
            method: 'POST',
            body: data,
        }).then((resp) => resp.json())
        .then(function (data) {
            console.log(data)
        })
    }

É apenas um trecho de exemplo, porém caso dê certo, irei implementar o método Fetch como padrão em minhas requisições.


text:
Q: Any way to make sessionStorage reactive in Vue3? Lets say I built an app, that fetches data through axios.get from a database every time it loads or is refreshed. This makes the app slow, so I want to only get the data in the initial load of the app and put it into sessionStorage.
Problem is that sessionStorage is not reactive. When I do this:
const state = reactive({
    image: sessionStorage.image
})

and want to render:

it only works, if the sessionStorage has been updated in the previous page load. For the initial page load state.image throws a 404 not found.
Is there any way to make sessionStorage reactive? I've read about watchers, set and get but can't quite figure it out.
Solution (new):
Aaaaactually, I just found a way to make sessionStorage behave as if it was reactive during initial load and I don't even need vuex for it:

This way the reactive function chooses an empty string, if sessionStorage is undefined during the initial load and assigns value from axios.get to sessionStorage. On all consecutive page loads, the reactive function uses sessionStorage, which now has a value assigned to it.
Coding is fun. Sometimes you learn how to replace 100 lines of code with 1 LOC.
Solution (old):
Ok, now my storage works how I want it to. It is global, reactive, persistent and easy to use. I will accept @Elsa's answer because she helped me look into vuex.
I created a store in a seperate store.js file:
import {createStore} from "vuex";

const store = createStore({
    state() {
        return {
            image: sessionStorage.image || ""
        }
    }
})
export default store

then register it in app.js:
require('./bootstrap');

import {createApp} from 'vue';
import app from "../vue/app";
import store from "./store";

createApp(app)
    .use(store)
    .mount("#app");

and now I can use store in my components like so:
<template>

</template>

The axios request runs only if sessionStorage.image is undefined, otherwise its value is rendered directly. If the link exists, the image does not get newly loaded in the template first, but rendered instantly.
I might omit state = reactive completely now, since I can use store.state instead globally and even link it to ss/ls. The only thing I have to maintain is the fields inside:
const store = createStore({
    state() {
        return {
            image: sessionStorage.image || ""
        }
    }
})

because vue throws 404 errors if I don't (but renders the elements anyway because of reactivity).

A: I had this problem a week ago and I try 3 ways to make a sessionStorage reactive in vue3.
1.vuex
2.create event listener
3.setInterval
I found a temporary solution for my problem with setInterval.
1.vuex
const state = () => {
  return {
    latInfo: sessionStorage.getItem('lat') || 0
  }
}

const getters = {
  latInfo: state => state.latInfo
}

3.setInterval
  setup() {
    setInterval(() => {
      if (infoData) {
        infoData.lat = sessionStorage.getItem('lat')
      }
    }, 1000)

A: Firstly, sessionStorage cannot be reactive.
If my understanding correct, you just want a global variable to be reactive. You can simply achieve it via provide and inject:
const yourGlobalVar = sessionStorage.getItem('image');
app.provide('yourImage', ref(yourGlobalVar))

Where used it:
setup(){
   ...
   const image = inject('yourImage');
   ...
   return {image}
}


text:
Q: How to do positional indexing on a pandas series with multi-index I have a series
s

card  city
c1    t1      0.500000
      t2      0.250000
      t3      0.250000
c2    t2      0.666667
      t1      0.333333
Name: city, dtype: float64

I want to get the top (or n-th) city entry for each card. I essentially want something of s.iloc[:,n] type i.e., a way to do positional indexing into a pandas series with multi-index. I am using pandas-1.3.2.

A: You can use groupby.head:
s.groupby(level='card').head(1)

card  city
c1    t1      0.500000
c2    t2      0.666667
Name: city2, dtype: float64

To get the n-th entry per group, group first and then use iloc in each group. For instance, to get the 2nd entry for each card:
n = 1
(s.groupby(level='card', group_keys=False)
  .apply(lambda g: g.iloc[n:n+1]))

card  city
c1    t2      0.250000
c2    t1      0.333333
Name: city2, dtype: float64


text:
Q: angular2: http post not executing This is my first experience with angular 2. I have created a simple form and try to submit it but when http.post is executed nothing happens. There is no request made in the network tab, there is not errors.
Here is my code:
 save(model) {
        var uri = this._baseUri + "/api/contact/AddContact";

        let md = JSON.stringify(model);

        this.http.post(uri,
            JSON.stringify(md),
            {
                headers: new Headers({
                    'Content-Type': 'application/json'
                })
            })
           .map(res => res.json());

    }

I have set a breakpoint on save method and is going through there but as I said nothing happens. What am I missing?

A: Observables are lazy so you need to subscribe on them to make the request execute even if you don't want to handle the response.
Something like that:
save(model) {
  var uri = this._baseUri + "/api/contact/AddContact";
  let md = JSON.stringify(model);

  this.http.post(uri,
    JSON.stringify(md),
    {
      headers: new Headers({
        'Content-Type': 'application/json'
      })
    })
    .map(res => res.json()).subscribe();
  }

Hope it helps you,
Thierry


text:
Q: Open set is union of countable disjoint class of open interval It's been a while since I've touched topology so please bear with me.

Theorem: Every non-empty open set on the real line is the union of countable disjoint class of open intervals.
proof:

Let $G$ be a non - empty open set on the real line. Since $G$ is non-empty, it's order is at least one. Since $G$ is an open set, this implies that for every element $x$ in $G$, there exists a positive radius $r$ such that an open interval $I$ may be centred on $x$ such that $I$ is contained in $G$.
But for each of these open intervals $I_{i}$, there exists some radius $\bar{r}$ such that an open interval $\bar{I_{i}}$ is contained in $I_{i}$. Hence, $I_{i}$ is class of open set.
The union of $\bar{I_{i}}$ then is an open set.
Hence, $I$ is the union of open sets.

If y is another point then $I_{x} = I_{y}$.

Why is this so?

A: Your solution is a bit unclear, I'm not sure what $I_x, I_y$ are so here's another approach:
Let $G\subseteq\mathbb{R}$ be a nonempty open subset of $\mathbb{R}$. Let $x\in G$. Denote by $C(x)$ the connected component of $x$ in $G$, i.e. the maximal connected subset of $G$ containing $x$.

Lemma 1. Each $C(x)$ is an open interval.

Proof. Let $a,b\in C(x)$ are such that $a<b$. Assume that $a<c<b$. If $c\not\in C(x)$ then $(-\infty, c)$ and $(c,+\infty)$ would be a nontrivial decomposition of $C(x)$ into open subsets. That contradicts $C(x)$ being connected. Therefore $c\in C(x)$ and so $C(x)$ is an interval. We will show it is open:
Since $G$ is open then there is an open interval $I$ around $x$ such that $I\subseteq G$. Since $I$ is connected and $x\in I$ then $I\subseteq C(x)$ which completes the proof. $\Box$

Lemma 2. Every open subset of $G\subseteq\mathbb{R}$ is a countable union of disjoint open intervals.

Proof. Obviously $G=\bigcup_{x\in G} C(x)$ and $C(x)$ are either disjoint or equal. So the only question is: can we take only countably many of them? The answer is yes. That's because for a given $C(x)$ there exists $q\in\mathbb{Q}$ such that $q\in C(x)$ and $C(x)=C(q)$. Indeed, you take an open interval $I$ around $x$ fully contained in $C(x)$ and then you pick any rational from $I$ (rationals are dense). Therefore
$$G=\bigcup_{x\in G\cap\mathbb{Q}} C(x)$$
which completes the proof. $\Box$


text:
Q: Apply function to create mean for filtered columns across multiple columns r I have a data frame with likert scoring across multiple aspects of a course (about 40 columns of likert scores like the two in the sample data below).
Not all rows contain valid scores. Valid scores are 1:5. Invalid scores are allocated 96:99 or are simply missing.
I would like to create an average score for each individual ID for each of the satisfaction columns that:
1) filters for invalid scores,
2) creates a mean of the valid scores for each id .
3) places the mean satisfaction score for each id in a new column labelled [column.name].mean as in Skill.satisfaction.mean below
I have included a sample data frame and the transformation of the data frame that I would like on a single row below.
####sample score vector
possible.scores <-c(1:5, 96,97, 99,"")

####data frame
ratings <- data.frame(ID = c(rep(1:7, each =2), 8:10), Degree = c(rep("Double", times = 14), rep("Single", times = 3)),
                      Skill.satisfaction = sample(possible.scores, size = 17, replace = TRUE),
                      Social.satisfaction = sample(possible.scores, size = 17, replace = TRUE)
                      )

####transformation applied over one of the satisfaction scales
ratings<- ratings %>%
  group_by(ID) %>%
  filter(!Skill.satisfaction %in% c(96:99), Skill.satisfaction!="") %>%
  mutate(Skill.satisfaction.mean = mean(as.numeric(Skill.satisfaction), na.rm = T))

A: library(dplyr)
ratings %>%
        group_by(ID) %>%
        #Change satisfaction columns from factor into numeric
        mutate_at(vars(-ID,-Degree), list(~as.numeric(as.character(.)))) %>%
        #Get mean for values in 1:5
        mutate_at(vars(-ID,-Degree), list(mean=~mean(.[. %in% 1:5], na.rm = T)))

# A tibble: 6 x 6
# Groups:   ID [3]
     ID Degree Skill.satisfaction Social.satisfaction Skill.satisfaction_mean Social.satisfaction_mean
  <int> <fct>               <dbl>               <dbl>                   <dbl>                    <dbl>
1     1 Double                 96                  99                       2                      NaN
2     1 Double                  2                  97                       2                      NaN
3     2 Double                  1                  97                       1                      NaN
4     2 Double                 97                  NA                       1                      NaN
5     3 Double                 96                  96                     NaN                        3
6     3 Double                 99                   3                     NaN                        3


text:
Q: Convergence of Poisson integral at boundary of half plane. My question is given $f\in L^1(\mathbb{R})$ and defining
$$
f_{\epsilon}(u)=\frac{1}{\pi}\int_{\mathbb{R}}f(t)\frac{\epsilon}{(t-u)^2+\epsilon^2}dt,
$$
whether $f_\epsilon$ converges to $f$ in $L^1$? If not, then is it true if $f$ has compact support or for $L^p$ spaces with $p>1$?


text:
Q: How to find which is the really slow query? I am testing a web page (wordpress) , I have this log but I cant understand which is the really slow query here is the link to read the queries of my website , please find time to tell me what is the dangerous query in this log that kills my CPU
http://balkanweb.com/mysql_slow.log

A: The best free tool to use to work with the slow query log is pt-query-digest. By default, this produces a report showing you where your aggregate response time is going, broken down by query fingerprint.
I downloaded your log and ran it through pt-query-digest. Here's part of the output, which is a ranked list of queries and some statistics about how much time they take:
# Profile
# Rank Query ID           Response time    Calls R/Call   V/M   Item
# ==== ================== ================ ===== ======== ===== ==========
#    1 0xC52F6DEC37D30D44 15065.0357 51.6%    80 188.3129  3.18 SELECT bwp_options
#    2 0x4876D9B1B390C783  4989.7583 17.1%    28 178.2057  7.91 SELECT bwp_options
#    3 0xE6593111E942BBD2  2337.6846  8.0%    10 233.7685  2.10 UPDATE bwp_options
#    4 0xF25CBDE8A6D65826  1784.7358  6.1%     8 223.0920  1.23 SELECT bwp_postmeta
#    5 0xC19DB36FFE85363C  1225.1890  4.2%     5 245.0378  0.09 SELECT bwp_terms bwp_term_taxonomy
#    6 0x7AC4A4CA8054E73D   981.1785  3.4%     4 245.2946  0.10 SELECT bwp_terms bwp_term_taxonomy bwp_term_relationships
#    7 0x3C55C7D48BD1B7C5   714.0035  2.4%     3 238.0012  0.00 SELECT bwp_term_relationships bwp_term_taxonomy
#    8 0x3A5E09EFF2C9AA73   487.4629  1.7%     2 243.7314  0.08 UPDATE bwp_postmeta
#    9 0x6545AED3996807BC   460.0886  1.6%     2 230.0443  0.22 SELECT bwp_postmeta
#   13 0x7AEDF19FDD3A33F1   207.8139  0.7%    30   6.9271  1.11 SELECT wp_options
# MISC 0xMISC               962.7022  3.3%    25  38.5081   0.0 <12 ITEMS>

You can see that the #1 query is not the slowest at 188 sec on average, but the number of calls (80) is higher than others, so it accounts for the most total response time. That #1 query is the following:
SELECT option_value FROM bwp_options WHERE option_name = 'ossdl_https' LIMIT 1

I would recommend that you need an index on the option_name column on that table.
Several other queries are very long-running, ranging between 178 and 245 seconds on average. You should optimize all of these queries with indexes. In fact, they are so slow that I wonder if you simply have a server with inadequate resources. Are you swapping?
Here are a few nice blog posts that introduce you to pt-query-digest:

*

*Identifying the load with the help of pt-query-digest and Percona Server

*High-load problems? Investigate them with pt-query-digest

*Tools and tips for analysis of MySQL's Slow Query Log
pt-query-digest is part of Percona Toolkit, a free, open-source collection of script tools for working with MySQL and Percona Server.

A: Time taking queries are,
Count: 1  Time=2.90s (2s)  Lock=0.00s (0s)  Rows=1.0 (1), balkanwe_site[balkanwe_site]@localhost
  SELECT   bwp_posts.* FROM bwp_posts  WHERE N=N  AND (((bwp_posts.post_title LIKE 'S') OR (bwp_posts.post_content LIKE 'S')) AND ((bwp_posts.post_title LIKE 'S') OR (bwp_posts.post_content LIKE 'S')))  AND (bwp_posts.post_password = 'S')  AND bwp_posts.post_type IN ('S', 'S', 'S', 'S', 'S') AND (bwp_posts.post_status = 'S')  ORDER BY (CASE WHEN bwp_posts.post_title LIKE 'S' THEN N WHEN bwp_posts.post_title LIKE 'S' AND bwp_posts.post_title LIKE 'S' THEN N WHEN bwp_posts.post_title LIKE 'S' OR bwp_posts.post_title LIKE 'S' THEN N WHEN bwp_posts.post_content LIKE 'S' THEN N ELSE N END), bwp_posts.post_date DESC

Count: 1  Time=2.96s (2s)  Lock=0.00s (0s)  Rows=1.0 (1), balkanwe_site[balkanwe_site]@localhost
  SELECT SQL_CALC_FOUND_ROWS  bwp_posts.ID FROM bwp_posts  WHERE N=N  AND (((bwp_posts.post_title LIKE 'S') OR (bwp_posts.post_content LIKE 'S')) AND ((bwp_posts.post_title LIKE 'S') OR (bwp_posts.post_content LIKE 'S')))  AND (bwp_posts.post_password = 'S')  AND bwp_posts.post_type IN ('S', 'S', 'S', 'S', 'S') AND (bwp_posts.post_status = 'S')  ORDER BY (CASE WHEN bwp_posts.post_title LIKE 'S' THEN N WHEN bwp_posts.post_title LIKE 'S' AND bwp_posts.post_title LIKE 'S' THEN N WHEN bwp_posts.post_title LIKE 'S' OR bwp_posts.post_title LIKE 'S' THEN N WHEN bwp_posts.post_content LIKE 'S' THEN N ELSE N END), bwp_posts.post_date DESC LIMIT N, N

Count: 2  Time=1.57s (3s)  Lock=0.00s (0s)  Rows=20.0 (40), balkanwe_wp[balkanwe_wp]@localhost
  (SELECT n.IDNotizia, n.Titolo, n.IDCategoria, n.Data, n.Descrizione, N AS Notizia FROM notizie AS n, notizie_legami AS nl WHERE n.IDNotizia=nl.IDNotizia AND n.Online='S' AND (n.Pubblicail='S' OR n.Pubblicail IS NULL) AND  (n.Titolo LIKE 'S' OR n.Sottotitolo LIKE 'S' OR n.Descrizione LIKE 'S' OR n.Notizia like 'S')  GROUP BY nl.IDCollegamento) UNION (SELECT IDNews, Titolo, IDCategoria, Data, News, N AS Notizia FROM news WHERE id_ext!='S' AND  (Titolo LIKE 'S' OR News LIKE 'S') ) ORDER BY Data DESC LIMIT N

Count: 1  Time=1.88s (1s)  Lock=0.00s (0s)  Rows=16.0 (16), root[root]@localhost
  SELECT TABLE_SCHEMA as DB,SUM(DATA_LENGTH)+SUM(INDEX_LENGTH) AS SPACEUSED from information_schema.tables GROUP BY TABLE_SCHEMA

Count: 1  Time=1.06s (1s)  Lock=0.00s (0s)  Rows=20.0 (20), balkanwe_wp[balkanwe_wp]@localhost
  (SELECT n.IDNotizia, n.Titolo, n.IDCategoria, n.Data, n.Descrizione, N AS Notizia FROM notizie AS n, notizie_legami AS nl WHERE n.IDNotizia=nl.IDNotizia AND n.Online='S' AND (n.Pubblicail='S' OR n.Pubblicail IS NULL) AND  ((n.Titolo LIKE 'S' OR n.Sottotitolo LIKE 'S' OR n.Descrizione LIKE 'S' OR n.Notizia LIKE 'S') AND (n.Titolo LIKE 'S' OR n.Sottotitolo LIKE 'S' OR n.Descrizione LIKE 'S' OR n.Notizia LIKE 'S'))  GROUP BY nl.IDCollegamento) UNION (SELECT IDNews, Titolo, IDCategoria, Data, News, N AS Notizia FROM news WHERE id_ext!='S' AND  ((Titolo LIKE 'S' OR News LIKE 'S') AND (Titolo LIKE 'S' OR News LIKE 'S')) ) ORDER BY Data DESC LIMIT N

Count: 1  Time=1.21s (1s)  Lock=0.00s (0s)  Rows=34.0 (34), balkanwe_wp[balkanwe_wp]@localhost
  SELECT n.IDNotizia FROM notizie AS n, notizie_legami AS nl WHERE n.IDNotizia=nl.IDNotizia AND n.Online='S' AND (n.Pubblicail='S' OR n.Pubblicail IS NULL) AND  ((n.Titolo LIKE 'S' OR n.Sottotitolo LIKE 'S' OR n.Descrizione LIKE 'S' OR n.Notizia LIKE 'S') AND (n.Titolo LIKE 'S' OR n.Sottotitolo LIKE 'S' OR n.Descrizione LIKE 'S' OR n.Notizia LIKE 'S'))  GROUP BY nl.IDCollegamento

Count: 4  Time=1.82s (7s)  Lock=0.01s (0s)  Rows=199.8 (799), balkanwe_wp[balkanwe_wp]@localhost
  SELECT n.IDNotizia FROM notizie AS n, notizie_legami AS nl WHERE n.IDNotizia=nl.IDNotizia AND n.Online='S' AND (n.Pubblicail='S' OR n.Pubblicail IS NULL) AND  (n.Titolo LIKE 'S' OR n.Sottotitolo LIKE 'S' OR n.Descrizione LIKE 'S' OR n.Notizia like 'S')  GROUP BY nl.IDCollegamento

Count: 5  Time=1.52s (7s)  Lock=0.00s (0s)  Rows=19.4 (97), balkanwe_site[balkanwe_site]@localhost
  SELECT ID, post_title, post_type, post_status FROM bwp_posts WHERE ( post_title REGEXP 'S' OR post_content REGEXP 'S' ) AND post_type = 'S'  AND ID != N  AND post_status NOT IN ('S', 'S') ORDER BY post_date DESC LIMIT N

You can check the slowest queries by running the command ,
mysqldumpslow -s -t 5 slow.log
this will show top 5 slow queries.


text:
Q: MOXy JAXB unable to unmarshall into List I was able to unmarshall the structure below to List using Oracle JDK 1.8 standard library.
<parent>
    <child>1234 1234 1234</child>
    <child>1231 1313 1331</child>
</parent>

where I have a and XmlAdapter class like below to tokenize String to int[] vice versa  and using XMlJavaTypeAdapter on the root XML class like below.
class ChildAdapter extends XmlAdapter<String,int[]> {
    ...
}

@XmlRootElement(name="parent")
class Parent {
    ...
    private List<int[]> children;
    ...
    @XmlElement(name="child")
    @XmlJavaTypeAdapter(ChildAdapter.class)
    public void setChildren(List<int[]> children) {
        ...
    }
    ...
}

but I got an Exception when I switch to use EclipseLink MOXy implementation.
Has anyone tried this before?
Exception [EclipseLink-33] (Eclipse Persistence Services - 2.7.3.v20180807-4be1041): org.eclipse.persistence.exceptions.DescriptorException
Exception Description: Trying to invoke [setChildren] on the object with the value [[I@1f9f6368].  The number of actual and formal parameters differs, or an unwrapping conversion has failed.
Internal Exception: java.lang.IllegalArgumentException: argument type mismatch
Mapping: org.eclipse.persistence.oxm.mappings.XMLDirectMapping[childrenList-->child/text()]
Descriptor: XMLDescriptor(mypackage.Parent --> [DatabaseTable(Parent)])
at org.eclipse.persistence.exceptions.DescriptorException.illegalArgumentWhileSettingValueThruMethodAccessor(DescriptorException.java:714)
at org.eclipse.persistence.internal.descriptors.MethodAttributeAccessor.setAttributeValueInObject(MethodAttributeAccessor.java:286)
at org.eclipse.persistence.internal.descriptors.MethodAttributeAccessor.setAttributeValueInObject(MethodAttributeAccessor.java:239)

...
Using Moxy, the only way is I need to create a Wrapper class to holds the int[] like below, but it is not what I really want.
class ChildWrapper {
    private int[] childs;
    public void setChilds(int[] childs) {
        this.childs = childs
    }
    public int[] getChilds() {
        return childs;
    }
}

Changed the adapter to class ChildAdapter extends XmlAdapter<String, ChildWrapper>.
Suprizingly the List<int[]> children has now become List<ChildWrapper> children in the resulting object. I didn't change parent, so the unmarshaller now create a different object through reflection or something? Isn't this broken?

A: I have a workaround.
Seems like the problem here Moxy do not like List of List List<List<T>>.
I created an XML Adapter of type <String,Object> and casted the object to List and use this for @XMLJavaTypeAdapter(ChildAdapter.class) annotation.
public class ChildAdapter extends XmlAdapter<String, Object> {

    @Override
    public Object unmarshall(String v) {
         List<Integer> result = new ArrayList<>();
         ...Tokenize your String v and add them to result...
         return result;
    }

    @Override
    public String marshall(Object v) {
         List<Integer> l = (List<Integer)v;
         StringBuilder b = new StringBuilder();
         ...Loop l and append b...
         return b.toString();
    }
}


text:
Q: What's the longest possible worldwide phone number I should consider in SQL varchar(length) for phone What's the longest possible worldwide phone number I should consider in SQL varchar(length) for phone.
considerations:

*

*+ for country code

*() for area code

*x + 6 numbers for Extension extension (so make it 8 {space})

*spaces between groups (i.e. in American phones +x xxx xxx xxxx = 3 spaces)

*here is where I need your help, I want it to be worldwide

Consider that in my particular case now, I don't need cards etc. number begins with country code and ends with the extension, no Fax/Phone etc. comments, nor calling card stuff needed.

A: Well considering there's no overhead difference between a varchar(30) and a varchar(100) if you're only storing 20 characters in each, err on the side of caution and just make it 50.

A: As for "phone numbers" you should really consider the difference between a "subscriber number" and a "dialling number" and the possible formatting options of them.
A subscriber number is generally defined in the national numbering plans. The question itself shows a relation to a national view by mentioning "area code" which a lot of nations don't have. ITU has assembled an overview of the world's numbering plans publishing recommendation E.164 where the national number was found to have a maximum of 12 digits. With international direct distance calling (DDD) defined by a country code of 1 to 3 digits they added that up to 15 digits ... without formatting.
The dialling number is a different thing as there are network elements that can interpret exta values in a phone number. You may think of an answering machine and a number code that sets the call diversion parameters. As it may contain another subscriber number it must be obviously longer than its base value. RFC 4715 has set aside 20 bcd-encoded bytes for "subaddressing".
If you turn to the technical limitation then it gets even more as the subscriber number has a technical limit in the 10 bcd-encoded bytes in the 3GPP standards (like GSM) and ISDN standards (like DSS1). They have a seperate TON/NPI byte for the prefix (type of number / number plan indicator) which E.164 recommends to be written with a "+" but many number plans define it with up to 4 numbers to be dialled.
So if you want to be future proof (and many software systems run unexpectingly for a few decades) you would need to consider 24 digits for a subscriber number and 64 digits for a dialling number as the limit ... without formatting. Adding formatting may add roughly an extra character for every digit. So as a final thought it may not be a good idea to limit the phone number in the database in any way and leave shorter limits to the UX designers.

A: Assuming you don't store things like the '+', '()', '-', spaces and what-have-yous (and why would you, they are presentational concerns which would vary based on local customs and the network distributions anyways), the ITU-T recommendation E.164 for the international telephone network (which most national networks are connected via) specifies that the entire number (including country code, but not including prefixes such as the international calling prefix necessary for dialling out, which varies from country to country, nor including suffixes, such as PBX extension numbers) be at most 15 characters.
Call prefixes depend on the caller, not the callee, and thus shouldn't (in many circumstances) be stored with a phone number. If the database stores data for a personal address book (in which case storing the international call prefix makes sense), the longest international prefixes you'd have to deal with (according to Wikipedia) are currently 5 digits, in Finland.
As for suffixes, some PBXs support up to 11 digit extensions (again, according to Wikipedia). Since PBX extension numbers are part of a different dialing plan (PBXs are separate from phone companies' exchanges), extension numbers need to be distinguishable from phone numbers, either with a separator character or by storing them in a different column.

A: In the GSM specification 3GPP TS 11.11, there are 10 bytes set aside in the MSISDN EF (6F40) for 'dialing number'.  Since this is the GSM representation of a phone number, and it's usage is nibble swapped, (and there is always the possibility of parentheses) 22 characters of data should be plenty.
In my experience, there is only one instance of open/close parentheses, that is my reasoning for the above.

A: It's a bit worse, I use a calling card for international calls, so its local number in the US + account# (6 digits) + pin (4 digits) + "pause" + what you described above.
I suspect there might be other cases

A: Digits range for all countries 4 - 13 https://en.wikipedia.org/wiki/List_of_mobile_telephone_prefixes_by_country


text:
Q: Awk print with pipes not working iPython in Jupyter Notebook So the command below does not give me any output in Jupyter Notebook with iPython:
IP = '62.172.72.131'
!cat hits.csv | grep {IP} | awk '{print $1}'

I have tried both double and single "$" sign and none of them works. If I only use one pipe in the command, it works fine. For example:
IP = '62.172.72.131'
!cat hits.csv | grep {IP}
!cat hits.csv | awk '{print $1}'

Anyone know why this is happening?
Thanks!

A: I think I figured this out. The "$" and "{" and "}" are all special characters in iPython, so I have to escape them by doubling them.
IP = '62.172.72.131'
!cat hits.csv | grep {IP} | awk '{{print $$1}}'


text:
Q: How to return the contents of jar files as an array of bytes? I am trying to get the contents of the file as an array of bytes.
public static void main(String[] args) {

    final IServiceClient client = StorageConsumerProvider.getStorageServiceClient("dev");

    String name = new File("C:\\Storage\\Model-1.0.0.jar").getName();

    StorageObjectIdentifier objIdentifier = new StorageObjectIdentifier("Model", "1.0.0", name);

// I need to pass the bytes here
    client.createObject(objIdentifier, name.getBytes());

}

Interface is like this-
public void createObject(StorageObjectIdentifier objIdentifier, byte[] obj)

createObject method accepts two parameters, one of them is - the contents of the file as an array of bytes
I am not sure how should I pass that as an array of bytes? Can anybody help me with this? The file is a jar file in my case.

A: You have to load all file content in bytearray manually using a function like this:
public final static byte[] load(FileInputStream fin) throws Exception
{
      ByteArrayOutputStream baos = new ByteArrayOutputStream();

      int readCnt = fin.read(readBuf);
      while (0 < readCnt) {
        baos.write(readBuf, 0, readCnt);
        readCnt = fin.read(readBuf);
      }

      fin.close();

      return bout.toByteArray();
  }

but works if file is small else, for large files, you will run to NPE.
Better choice is to change your interface passing InputStream instead of byte[] and let intf implementor decide how to operate.

A: Well currently you're just passing a byte array representation of the name of the file. You need to open the file and read it. You can do that with FileInputStream etc, but if you're happy to use Guava, that makes it easy with Files.toByteArray():
File file = new File("C:\\Storage\\Model-1.0.0.jar");
byte[] data = Files.toByteArray(file);
StorageObjectIdentifier objIdentifier =
    new StorageObjectIdentifier("Model", "1.0.0", name);

client.createObject(objIdentifier, data);

A: You are passing a byte array containing the name of the file to your createObject method. To pass a byte array containing the contents of the file first you have to read the file into a byte array.
Use FileReader or FileInputStream, create an instance passing either the name of file or the File object,
then use one of the read() methods to read bytes into an array.

A: You can use BufferedInputStream to load a file as a byte stream with buffering.
File iFile = new File("C:\\Storage\\Model-1.0.0.jar");
BufferedInputStream bis = new BufferedInputStream(new FileInputStream(iFile));

int read = 0;
ByteArrayOutputStream os = new ByteArrayOutputStream();
byte[] buffer = new byte[1024]; // buffer size
while ((read = bis.read(buffer)) != -1) {
    os.write(buffer, 0, read);
}
bis.close();

StorageObjectIdentifier objIdentifier =
                        new StorageObjectIdentifier("Model", "1.0.0", iFile.getName());
client.createObject(objIdentifier, os.toByteArray());

Or, using FileUtils from Apache Commons IO
client.createObject(objIdentifier, FileUtils.readFileToByteArray(iFile));


text:
Q: enabledelayedexpansion concat string every time come in block batch script I have below code which print(else code) error in command prompt when control come into it.But I want a string which contains all error in one string (Concat previous Strings), and use that string to send mail.
  @echo off
echo Working !!!
setlocal enabledelayedexpansion
for /f "delims=" %%a in ('type test.log ^| findstr "Queue_ID"') do (
   set $Line=%%a
   for /f "tokens=2 delims=^=," %%b in ('echo !$Line!') do (
      set $Value=%%b
      set $Value=#Queue_id!$Value: =!
      if not defined !$Value! (set !$Value!=1) else (echo Error with [!$Value!])
))
endlocal
echo Done !!!
Pause

and mail sending code is
S:\blat.exe -body " error_String came from else code" -subject "KSD Error" -tf %recipients% -server %smtpserver% -f %sender%

A: This will send an E-mail ONLY if there is some error :
  @echo off
echo Working !!!
setlocal enabledelayedexpansion
for /f "delims=" %%a in ('type test.log ^| findstr "Queue_ID"') do (
   set $Line=%%a
   for /f "tokens=2 delims=^=," %%b in ('echo !$Line!') do (
      set $Value=%%b
      set $Value=#Queue_id!$Value: =!
      if not defined !$Value! (set !$Value!=1) else (set $liste=!$Liste!,[!$Value!])
))

if defined $Liste (
  echo Error List : !$Liste!
  echo sending Mail...
  S:\blat.exe -body !$Liste! -subject "KSD Error" -tf %recipients% -server %smtpserver% -f %sender%)
endlocal
echo Done !!!
Pause


text:
Q: Are there browsers for windows or linux that still using actual webkit engine version not blink engine? Is there any browser for windows or linux that still using actual webkit engine version not blink engine?

A: This is a question that I also ask, periodically, so I can give an updated reply:

*

*for Linux, there are several more-or-less platform-specific browsers that use webkit2-gtk (a more-or-less up-to-date WebKit2 implementation): notably Web/Epiphany and Midori. Both are rather simple/lightweight browsers.

*for MS Windows, there is still the more full-fledged Maxthon 5 browser (or virus, according to some), but I have been unable to determine what WebKit version it really uses (based on its user agent string it might NOT be WebKit2). Some quick testing suggests it's a good alternative for slower hardware (many hybrid tablet PCs!) as WebKit is noticeably less resource-hungry than WebEngine (aka Chromium aka Blink). Note however that Maxthon 6 will become just another blink on the block (unless they decide to keep the dual-engine feature).

*for Linux AND MS Windows (Qt-based, cross platform) there are Konqueror and Otter-Browser. The former is mostly focussed on its QtWebEngine backend, but the latter is indeed focussed on the "rebooted" QtWebKit (and aims to reimplement Opera 12; it provides installers for MS Windows).

The QtWebKit reboot is largely a 1-person effort at the moment that could probably stand a few more contributors, notably to merge a more recent WebKit version.

A: according to wikipedia, maxthon browser still uses webkit (You can switch engines in Maxthon though)

As of version 3, Maxthon supports two web browser engines: WebKit and
Trident
Wikipedia


text:
Q: SQL Update MS ACCESS UPDATE calendar SET eventDays = null WHERE ??
Problem:
168 eventDays | 24 weeks each day assigned a week number
if dayCount >=2 in a eventWeeks (24) remove eventDay for entire eventWeeks (7)
any eventWeek with total of just 1 would remove only that single date.
5/16/2017 to 5/22/2017 would remove date.
5/23/2017 to 5/29/2017 would just remove #5/24/2017#
do it for each group of eventWeeks (24)
eventDays | eventWeeks | dayCount
5/16/2017 | 1 | 1
5/18/2017 | 1 | 0
5/19/2017 | 1 | 0
5/20/2017 | 1 | 0
5/21/2017 | 1 | 1
5/22/2017 | 1 | 0
5/23/2017 | 2 | 0
5/24/2017 | 2 | 1
5/25/2017 | 2 | 0
5/26/2017 | 2 | 0
5/27/2017 | 2 | 0
5/28/2017 | 2 | 0
5/29/2017 | 2 | 0

I tried several WHERE, HAVING and whatever, to no avail.

A: This calculates the eventWeeks to be deleted.
SELECT eventweeks FROM calendar WHERE daycount = 2
UNION
SELECT eventweeks FROM calendar WHERE daycount = 1
  GROUP BY eventweeks HAVING SUM(daycount) = 2;

This deletes all days of every week for the weeks found.
This will not delete all days of a week, if dayCount = 3, as you requested.
And it will not delete all days of a week, if 3 days have dayCount = 1 for a sum of 3, also by your request.
Query F
UPDATE calendar SET eventdays = NULL
WHERE eventweeks IN (
  SELECT eventweeks FROM calendar WHERE daycount = 2
  UNION
  SELECT eventweeks FROM calendar WHERE daycount = 1
    GROUP BY eventweeks HAVING SUM(daycount) = 2);

Query F behaviour is
eventWeeks | dayCount
    1      |     1    DELETE
    1      |     1    DELETE
    1      |     0    DELETE

    2      |     1    KEEP
    2      |     1    KEEP
    2      |     1    KEEP
    2      |     0    KEEP

    3      |     0    DELETE
    3      |     2    DELETE

    4      |     1    KEEP
    4      |     2    KEEP

EDIT A
Because MS Access 2000 does not seem to accept UNION in subqueries, here is an alternative SELECT query (see SO):
SELECT DISTINCT eventweeks FROM calendar x
WHERE daycount = 2
  OR EXISTS (
    SELECT y.eventweeks FROM calendar y
    WHERE x.eventweeks = y.eventweeks AND y.daycount = 1
    GROUP BY y.eventweeks HAVING SUM(y.eventweeks) = 2
);

And the appropriate UPDATE
UPDATE calendar SET eventdays = NULL
WHERE eventweeks IN (
  SELECT DISTINCT eventweeks FROM calendar x
  WHERE daycount = 2
    OR EXISTS (
      SELECT y.eventweeks FROM calendar y
      WHERE x.eventweeks = y.eventweeks AND y.daycount = 1
      GROUP BY y.eventweeks HAVING SUM(y.eventweeks) = 2
  ));

A: Please try the following...
UPDATE calendar
SET eventDays = NULL
WHERE eventDays IN ( SELECT eventDays
                     FROM calendar
                     JOIN ( SELECT eventWeeks AS eventWeeks,
                                   SUM( dayCount ) AS daysCountSum
                            FROM calendar
                            GROUP BY eventWeeks
                          ) AS daysCounter ON calendar.eventWeeks = daysCounter.eventWeeks
                                          AND daysCounter.daysCountSum <= 1
                                          AND calendar.dayCount = 0
                   );

This statement works by first grouping all of the records in calendar by eventWeeks and calculating the total of dayCount for each group.  The results are then joined to calendar in such a way that eventWeeks who have a total of 2 or more for dayCount are omitted, and only those records that have a 0 value for dayCountare included.
The resulting data is then used to select which records from calendar are updated.
If you have any questions or comments, then please feel free to post a Comment accordingly.


text:
Q: Can I connect android(Eclipse) to SQL Server(2005) using php web services? I have read a number of questions on this site itself on accessing db from android.
But I still can't make out if I can connect android(Eclipse) to SQL Server(2005) using php web services?
I am required to connect an android app to SQL server and I am familiar with using JSON and PHP web services to connect to MySQL Server.
Most sites suggest to use B4A and ASP.Net  to connect to SQL Server ,which I don't know.How about using Eclipse and ASP.Net (Well, that requires me to learn ASP.Net )?
What would be the differences in connecting to SQL server than MySQL server?

A: Connection to a MySQL server and a MSSQL server should just be using a different database driver in PHP. For example mysql would use mysql_connect and mssql would use mssql_connect. What you use for a database should not matter for your android application. Your android application is isolated on your phone unless you want to use a database on the phone like SQLlite. For your situation you will want to create a restful API that you android application can call. I have done the same thing in my own android application that connects to a restful api. I use json to pass the data back and forth you can also use XML. I just find json to be easier to work with. No need to a SOAP web service then. Think of a web service as a location you setup to execute a set of php commands and then return a result it's as simple as that.


text:
Q: Sort a Collection of POJOs based on a List of integers So,
I have a situation where I use a list of Integers to fetch some data from different sources. As a result, I get two Lists, both have the same POJOs Type as content and include exactly all of the elements from my input list, however in an unknown order.
What I need is to get these POJOs sorted in the same order as my first list (this Integer is a field with getter/setter in the POJO), so I get a List with POJOs in exactly the same order as my Integer list.
So, the steps I'm thinking of are:

*

*Join the two POJO lists into one, so I at least have 2 identically sized lists (Integer and POJO) that I know contain matching elements.

*Sort the resulting POJO list to match the Integer list.

However, for step 2 I need to find the good (that means, efficient and neat) way to do it... I am thinking of creating a Comparator somewhat like this:
public class POJOComparable implements Comparator<MyPOJO>{

  private List<Integer> values;

  public POJOComparable(List<Integer> values) {
    this.values = values;
  }

  @Override
  public int compare(MyPOJO o1P, MyPOJO o2P) {
      int o1 = values.indexOf(o1P.getId());
      int o2 = values.indexOf(o2P.getId());
      return (o1>o2 ? -1 : (o1==o2 ? 0 : 1));
  }
}

Now, is this a good approach to do such a sorting or is there some nicer or more efficient way to do it? The lists will be of about 20 items, but this sorting will be performed quite often so I'm looking for the efficient way to do it.

A: Store the values of your List<MyPojo> in a TreeMap<Integer, MyPojo> and let that this collection do the sorting for you. A simple way to accomplish this would be:
TreeMap<Integer, MyPojo> aSortedMap = new TreeMap<Integer, MyPojo>();
for(MyPojo pojo : aListOfMyPojo) {
    aSortedMap.put(values.indexOf(pojo.getId()), pojo);
}

Note that this approach assumes that every pojo.getId() has a single unique value inside List<Integer> values.

Based on @BoristheSpider comment, instead of having a List<Integer> values and seek each value of pojo.getId() using List#indexOf, it would be better using a Map<Integer, Integer> where you store the value of pojo.getId() and the desired Integer value to accelerate the searching process. So, the resultant algorithm should look like this:
//replace the List<Integer> by a Map<Integer>
Map<Integer, Integer> values = new HashMap<Integer, Integer>();
//store the pojo.getId() value with its associated int value
values.put(pojo.getId(), ...);

//...
TreeMap<Integer, MyPojo> aSortedMap = new TreeMap<Integer, MyPojo>();
for(MyPojo pojo : aListOfMyPojo) {
    aSortedMap.put(values.get(pojo.getId()), pojo);
}

A: Sorting is expensive, it takes O(nlgn). I would say use a Map to map the Pojos by id and then retrieve them from the Map in the List order. This takes a little more memory but should be faster:
    final Map<Integer, Pojo> pojoMap = new HashMap<>(pojos.size(), 1f);
    for (final Pojo pojo : pojos) {
        pojoMap.put(pojo.id, pojo);
    }

    final List<Pojo> sortedPojos = new ArrayList<>(ids.size());
    for (final int id : ids) {
        sortedPojos.add(pojoMap.get(id));
    }

So

*

*Loop over the Pojos and create a Map by the property.

*Loop over the original List and populate a new List by looking up the Pojos in the Map.

A: Change the POJO class to include the index as an int. If you only have order tens of objects at a time, the wasted space is trivial. The gain is simplicity, directness, and reduced risk of confusion.
The Comparator just looks at a field in each object - no expensive list searches.

A: Divide and conquer, first sort both lists independently and then merge them together, comparing the first elements of both lists each time you iterate (using your comparator). This is the most efficient way.
You can sort both lists with the default java sorting.


text:
Q: ASP.NET MVC on IIS falls through to the static file handler I have a problem with an ASP.NET MVC site.
These are the details:

*

*ASP.NET MVC 2

*ASP.NET 4 integrated pipeline

*IIS 7.5 on Windows Web Server 2008 R2

Whenever I make a request for the app I get the "HTTP Error 404.0 - Not Found"-error and the detailed error information shows it is the static file handler that reports the error:

*

*Module: IIS Web Core

*Notification: MapRequestHandler

*Handler: StaticFile

*Error Code: 0x80070002
meaning that the request never entered the MVC stack.
I should note that the IIS already serves a ASP.NET MVC 3 on the same app pool and a MVC 2 on a ASP.ENT 2 app pool. So it's the combo ASP.NET 2 on the ASP.NET 4 app pool that are giving me headaches.
Basically I want to upgrade the app from ASP.NET MVC 2 on a ASP.NET 2.0 app pool to a ASP.NET MVC 2 on a ASP.NET 4.0 app pool.
So any ideas?

A: I see you fixed your issue, but for anyone googling:
I had this issue and in my case I just needed to register ASP.NET 4 with IIS. I was deleting and re-adding webs to fix other issues and simply forgot to do that. The command that worked for me was:
C:\Windows\Microsoft.NET\Framework64\v4.0.30319>aspnet_regiis -i
Your own .net version may be different, especially if you are in the future, so the above path may not be exactly right.

A: I had the same problem when I installed IIS after installing Visual Studio, etc.
I was able to fix the problem by changing my Web.config file, adding the runAllManagedModulesForAllRequests="true" to the <modules> tag:
<system.webServer>
    <modules runAllManagedModulesForAllRequests="true">
        ...
    </modules>
</system.webServer>

(More details/copied from here: http://www.west-wind.com/weblog/posts/2011/Mar/27/ASPNET-Routing-not-working-on-IIS-70)

A: Chris' answer got me to check whether the app pool was actually configured for .net 4. Sure enough, this server defaults to creating 32-bit .net 2 pools in classic mode.
Ensure that your app is using 4.0 and you'll probably want Integrated pipeline for all new development. 32/64 is mainly up to your dependencies. The default is leaving "allow 32 bit allocations" set to false.

A: In my case, a similar error was thrown because StaticFile Handler was disabled / not working properly. I eventually fixed it by removing the handler and re-adding it through the web.config. Also, in case of a 403.3 error, change the RequireAccess-property value from "Write" to "Read"
<configuration>
    <system.webServer>
        <handlers>
           <remove name="StaticFile"
            <add
                name="StaticFile"
                path="*" verb="*"
                modules="StaticFileModule,DefaultDocumentModule,DirectoryListingModule"
                resourceType="Either"
                requireAccess="Read" />
        </handlers>
    </system.webServer>
</configuration>

A: So I found the error. There was a left over default document in the root, which isn't necessary for apps using the integrated pipeline. Also some changes to Global.ascx and route registration was neessary, but after that it worked.


text:
Q: Access child component from within the children tree of a parent component Let's say I have a <Page> component which displays anything the user of this component wants to display. But I want this page component to allow the use of a <StickyElement> component that will prevent an element to go outside of the view if the scroll of the <Page> component goes beyond a certain limit. And this <StickyElement> component can be placed anywhere in the page:
import { Page, StickyElement } from 'components/page'

<Page>

Title

Lorem Ipsum

  {/* Could be anywhere */}
  <StickyElement>dolor</StickyElement>
</Page>

How can the <Page> component pass its scroll value to the <StickyElement> component without creating state or ref outside of the scope of the page component?


text:
Q: Is it possible to run multiple robot framework in an interactive scenario? I have a question about is it possible to run multiple robot framework in an interactive scenario?
For instance, if robot framework A running on computer A, robot framework B running on computer B, robot framework C running on computer C.
I want an scenario that A can send a message to B, and after B received the message from A, B will send another message to C, and after C received the message from B, C will send an ACK to A. Is it possible on robot framework? Thanks for the help.


text:
Q: How does the synchronized keyword work on an instance variable? I'm looking at some legacy code that's of the form
public class Client {
  private final Cache cache;
  .....
   Client( final Cache cache) {
    this.cache = cache;
   }

  public Value get(Key key) {
     synchronized(cache){
       return this.cache.get(key);
     }
    }
   public void put(Key k , Value v) {
        synchronized(this.cache){
            return cache.put(k, v);
        }
    }
   }
}

I've never seen an instance variable that could be modified being used as a lock Object, since typically locks are usually final Object instances or just direct Locks via the Java API.

*

*How does the synchronized key word have any effect in this case? Isnt a new lock created for each instance of the Client object?

*Would the usage of the synchronized keyword force the cache to be updated before a get/put operation is applied?

*Why would synchronization be necessary before a get? Is it to get the cache to be updated to the latest values assuming another thread applied a put interim.

A: synchronized provides the same guarantees irrespective of whether it is used on a  static variable or an instance variable. i.e., memory visibility and atomicity. In your case, it provides thread safety at instance level for the attribute cache.
So, coming to your questions

*

*You are right. Each instance of Clientwill have its own lock. But this is useful when an instance of Client is shared between multiple clients.

*After the execution of the synchronized block, CPU local caches will be flushed into the main memory and this ensures memory visibility for other threads. At the start of execution of the synchronized block, local CPU caches will be invalidated and loaded from the main memory. So yes, synchronized will cause the instance variable cache to have the up to date values. Please see Synchronization for more details.

*The reason is the same as 2. i.e., to provide memory visibility.


text:
Q: Setting title to displayDialogAsync() dialog box in Microsoft Office Add-In In taskpane.js of an Office Add-In, I'm calling displayDialogAsync(), which puts up a dialog box.  The title of the dialog box is (name changed to protect the innocent) "My Word AddIn - https://myapp.web.core.windows.net/Dialog.html".  Is there any way to change this title to something more user-friendly and reflective of the product?  I can't seem to find anything in the Microsoft doc.

A: Try adding Titlename in header component of the html file.
<head>
<title>Titlename</title>
.....
</head>


text:
Q: Python compare-sort only compares neighbors Following code sorts a list of objects.
What I want to achieve is to sort objects of type 'boring' by their value. I don't care about their position in the list, but at the end they need to be sorted. My code only compares neighbors, therefore in the end  and  are still in wrong order.
What type of sort algorithm needs to be applied to have them sorted correctly?
class SortMe:
    def __init__(self, type, value):
        self.type = type
        self.value = value
    def __repr__(self):
        return "<%s %s %s>" % (self.__class__.__name__, self.type, self.value)

stack = (
    SortMe('fancy', 15),
    SortMe('fancy', 3),
    SortMe('boring', 3),
    SortMe('boring', 1),
    SortMe('fancy', 1),
    SortMe('boring', 22),
    SortMe('fancy', 22),
    SortMe('fancy', 17),
    SortMe('boring', 5),
    )

def compare(a1, a2):
    if a1.type == 'boring' and a2.type == 'boring':
        if a1.value > a2.value:
            return 1
        elif a1.value < a2.value:
            return -1
        else:
            return 0
    else:
        return 0

stack = sorted(stack, cmp=compare)

print '\n'.join(map(str, stack))

Current output (boring objects in wrong order):
<SortMe fancy 15>
<SortMe fancy 3>
<SortMe boring 1>
<SortMe boring 3>
<SortMe fancy 1>
<SortMe boring 22>
<SortMe fancy 22>
<SortMe fancy 17>
<SortMe boring 5>

Intended output (boring in right order, position doesn't matter):
<SortMe fancy 15>
<SortMe fancy 3>
<SortMe boring 1>
<SortMe boring 3>
<SortMe fancy 1>
<SortMe boring 5>
<SortMe boring 22>
<SortMe fancy 22>
<SortMe fancy 17>

or:
<SortMe fancy 15>
<SortMe fancy 3>
<SortMe fancy 1>
<SortMe fancy 22>
<SortMe fancy 17>
<SortMe boring 1>
<SortMe boring 3>
<SortMe boring 5>
<SortMe boring 22>

or so.

A: Don't use a cmp key, just extract the value directly using key function instead:
sorted(stack, key=lambda v: v.value if v.type == 'boring' else None)

which produces:
>>> for sm in sorted(stack, key=lambda v: v.value if v.type == 'boring' else None):
...     print sm
...
<SortMe fancy 15>
<SortMe fancy 3>
<SortMe fancy 1>
<SortMe fancy 22>
<SortMe fancy 17>
<SortMe boring 1>
<SortMe boring 3>
<SortMe boring 5>
<SortMe boring 22>

Your cmp key approach still returns 0 when comparing any fancy SortMe object with a boring one, in whatever order they were in, creating an inconsistent sorting. You'd need to consistently return -1 or 1 when comparing two objects that differ in type instead:
def compare(a1, a2):
    if a1.type == 'boring' and a2.type == 'boring':
        return cmp(a1.value, a2.value)
    else:
        # sort fancy before boring, reverse order
        return cmp(a2.type, a1.type)

where I reused the cmp() built-in function to return the appropriate -1, 0 or 1 values:
>>> def compare(a1, a2):
...     if a1.type == 'boring' and a2.type == 'boring':
...         return cmp(a1.value, a2.value)
...     else:
...         return cmp(a2.type, a1.type)
...
>>> for sm in sorted(stack, compare):
...     print sm
...
<SortMe fancy 15>
<SortMe fancy 3>
<SortMe fancy 1>
<SortMe fancy 22>
<SortMe fancy 17>
<SortMe boring 1>
<SortMe boring 3>
<SortMe boring 5>
<SortMe boring 22>


text:
Q: pass a parameter into serilazer under ListModelMixin I am passing a parameter to a serilaizer like this:
serializer = AttractionTicketSerializer(attraction, context={'api_consumer':request.auth.application})

I have a view which inherits from ListModelMixin, I need to pass this context param to the serilizer as well.
here is a summarized view:
class AttractionView(mixins.ListModelMixin, generics.GenericAPIView):
    authentication_classes = AUTHENTICATION_CLASSES
    permission_classes = [IsAuthenticatedOrTokenHasReadWriteScope]
    queryset = Attraction.objects.all()
    serializer_class = AttractionSerializer

    def get(self, request: Request, *args, **kwargs):
        attractions: Dict[str, Any] = self.list(request, *args, **kwargs)
        return attractions

Is there a way to do it?
Thanx in advance

A: You can override the get_serializer_context() function to add additional context to be passed to the serializer.
class AttractionView(mixins.ListModelMixin, generics.GenericAPIView):
    <...already_defined_attributes...>

    def get_serializer_context(self):
        # you can access self.request here
        # if you need to get some data from your request

        context = super().get_serializer_context()
        context.update({
            'new_key': <new_value>
        })

        return context

You can also override the list function to achieve it.
def list(self, request, *args, **kwargs):
    queryset = self.filter_queryset(self.get_queryset())
    page = self.paginate_queryset(queryset)

    context = self.get_serializer_context()
    context.update({
        'new_key': 'new_value'
    })

    if page is not None:
        serializer = self.get_serializer(page, context=context, many=True)
        return self.get_paginated_response(serializer.data)

    serializer = self.get_serializer(queryset, context=context, many=True)
    return Response(serializer.data)

Based on your specific requirement you can choose any of the above approaches.


text:
Q: Copy text from one text file to another Could someone demonstrate how to copy all lines of a text file to another one (without overwriting the destination file, e.g.:
File A copies lines to File B (without overwriting the existing lines in FileB - adding them)

A: This looks like homework, so I'll just give you some pointers.
Open the first file with the FileMode.Open and FileAccess.Read parameters. Open the second file with FileMode.Append and FileAccess.Write parameters.
Loop through the first file, writing to the second one what you're reading from the first.
Look at the FileStream class for more information.

A: Here is my solution. Hope it helps:
    Dim fileAContent As String = ""

    Using strR As New IO.StreamReader(fileAPath)
        fileAContent = strR.ReadToEnd
    End Using

    Using strW As New IO.StreamWriter(fileBPath, True)
        strW.Write(fileAContent)
        strW.Flush()
    End Using

Second parameter of StreamWriter is the key. It will append content to the end of file.
First read all lines from the first file and after that append all of them to second file.

A: Hope this answer helps you. I wrote it in a way that you can follow to give you a good understanding of the steps.
To start, replace the files with yours then run the code to see if it gives you the result that you want.
var file1 = @"C:\Users\User\Desktop\file1.txt";
var file2 = @"C:\Users\User\Desktop\file2.txt";

var file1Lines = File.ReadAllLines(file1);
var file2Lines = File.ReadAllLines(file2).ToList();

// before the copy
Console.WriteLine("**Before the copy**");
Console.WriteLine(File.ReadAllText(file2));

foreach (var l in file1Lines)
{
    file2Lines.Add(l);
}
File.WriteAllLines(file2, file2Lines);

// after the copy
Console.WriteLine("**After the copy**");
Console.WriteLine(File.ReadAllText(file2));


text:
Q: Android best way to call only a method in another class I have a Class and I need to use it's method only once in another class. What will be the best way to call it? (Considering Memory management and performance)

Assume I can not use static methods and these are the sample codes for question

public class UpdateApp {
    String text;

    public UpdateApp(String text) {
        this.text = text;
        //Some other works and initialization
    }

    public void update() {
        //Code for update somethings
    }

    //other methods
}

Below code shows usage of only one method

public class MainClass {
    public void main() {
//        Method 1
        UpdateApp updateApp = new UpdateApp("path");
        updateApp.update();

//        Method 2
        new UpdateApp("path").update();

    }
}

*

*What method is best for only executing one method ?

*Will method 2 object destroyed after the execution of update method by GC?

A: Both methods are effectively the same (memory and performance wise). One advantage of method 1 is that it will be easier to debug issues if some exception happens, since it will be easier to know if exception happened during construction of UpdateApp or during update() method. Advantage of method 2 is less code ofc. There are probably some more delicate advantages, this is just of top of my mind.
And yes, in method 2 object will be destroyed by GC.


text:
Q: Check user's location on Google Apps Script using Geolocation API I'm trying to design a simple spreadsheet that allows employees to clock-in and clock-out at work. I'm trying to restrict the clock-in/out functions so that they check the user's location and if they're not within a 20km radius of a latlong coordinate, the function stops and throws an error.
This is what I have so far, but it keeps showing me as outside the radius even when I'm not. I've removed the API key. Would appreciate any help or advice!
function clockIn() {
  // Get the user's location using the Google Maps API
  var location = getLocation();

  // Check if the user's location is within 20km of a specific coordinate
  if (location && checkLocation(location.lat, location.lng, -8.5388697, 115.2454651, 20000)) {
    var ui = SpreadsheetApp.getUi();
    var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("DATA");
    var mainSheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("MAIN");
    var name = mainSheet.getRange("A1").getValue();
    var lastRow = sheet.getRange("A:A").getValues().filter(String).length;
    var lastEmployeeRow = 0;
    var values = sheet.getRange(1, 1, lastRow, 1).getValues();

    for (var i = 0; i < values.length; i++) {
      if (values[i][0] === name) {
        lastEmployeeRow = i + 1;
      }
    }

    if (lastEmployeeRow !== 0 && sheet.getRange(lastEmployeeRow, 3).getValue() === "") {
      ui.alert("You must clock-out before you can clock-in again!");
    } else {
      var date = new Date();
      sheet.getRange(lastRow + 1, 1).setValue(name);
      sheet.getRange(lastRow + 1, 2).setValue(date);
    }
  } else {
    // Show an error message if the user's location is outside the allowed range
    var ui = SpreadsheetApp.getUi();
    ui.alert("You must be within 20km of -8.5388697,115.2454651 to clock in.");
  }
}

// Function to get the user's location using the Google Maps API
function getLocation() {
  try {
    var response = UrlFetchApp.fetch("https://www.googleapis.com/geolocation/v1/geolocate?key=API-KEY-HERE", {
      "method": "post",
      "muteHttpExceptions": true
    });
    var data = JSON.parse(response.getContentText());
    return data.location;
  } catch (e) {
    if (e.message.includes("SSL")) {
      throw new Error("The URLFetchApp request failed due to an SSL error. Please check your internet connection and try again.");
    } else if (e.message.includes("timeout")) {
      throw new Error("The URLFetchApp request timed out. Please check your internet connection and try again.");
    } else if (e.message.includes("Request failed for")) {
      throw new Error("The URLFetchApp request failed. Please check your internet connection and try again.");
    } else {
      throw new Error("An unexpected error occurred. Please try again later.");
    }
  }
}

// Function to check if the user's location is within a certain distance from a coordinate
function checkLocation(lat1, lng1, lat2, lng2, distance) {
  var R = 6371 * 1000; // Radius of the earth in meters
  var dLat = (lat2 - lat1) * Math.PI / 180;  // deg2rad below
  var dLng = (lng2 - lng1) * Math.PI / 180;
  var a =
    Math.sin(dLat / 2) * Math.sin(dLat / 2) +
    Math.cos(lat1 * Math.PI / 180) * Math.cos(lat2 * Math.PI / 180) *
    Math.sin(dLng / 2) * Math.sin(dLng / 2);
  var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));
  var d = R * c; // Distance in meters
  return (d <= distance);
}

I tried the above code, and was expecting the function to allow me to clock in, but instead it threw up the 'You must be within 20km of..." error.


text:
Q: Uncaught TypeError: Cannot read property 'ngOriginalError' of undefined at getOriginalError - when httpClient returned string When I tried to call an API using HttpClient which returns a string, subscribe method's error handler was invoked.
Front End Code :
this.httpClient.get<string>(`${this.baseUrl}/account/getname`).subscribe(
      (accountName)=> console.log(accountName),
      () => console.log("Failure")
    );

Backend Code in controller:
[HttpGet]
public string GetName()
{
   return "Sample Account Name";
 }

The front end code will log "Failure" to the console.
If the error notification method is removed from subscribe(), following error occurs

Uncaught TypeError: Cannot read property 'ngOriginalError' of
  undefined  at getOriginalError

A:
Uncaught TypeError: Cannot read property 'ngOriginalError' of undefined at getOriginalError

This happens because response from the server side goes as an error and there is no handler for error. I guess, the solution is always handle error when making http request by HttpClient:
import { catchError } from 'rxjs/operators';

makeHttpRequest(url): Observable<any> {
  return this.httpClient.get(url)
   .pipe(
     catchError(err => console.log(err))
   );
}

makeHttpRequest(`${this.baseUrl}/account/getname`).subscribe(
  (accountName) => console.log(accountName);
);

A: Since the default response type of HttpClient is JSON, it expected the response object to be a json value.
But our response was a string.
This was the reason behind the error.
When an API returns non JSON data, we need to specify it using responseType option in the get request.
There are different options like 'blob','text','arraybuffer','json'
For the above case, if we do not specify the get call's type prameter as string (get<string>), we just need to set responseType as {responseType : 'text'}
return this.httpClient.get(`${this.baseUrl}/account/getname`,
       {responseType : 'text' }).subscribe(
             (data)=> console.log(data),
             () => console.log("Failure")
       );

But if we specify the get call's type prameter as string, there will be an error

Type '"text"' is not assignable to type '"json"'

To avoid that we need to modify the requestType option to {responseType : 'text' as 'json'}
 return this.httpClient.get<string>(`${this.baseUrl}/account/getname`,
        {responseType : 'text' as 'json'}).subscribe(
             (data)=> console.log(data),
             () => console.log("Failure")
        );

A: Please check your response type in your http method(post/get/put) because its by default json type but some time your response has blob or text then this type of error occurs.
responseType?: 'arraybuffer'|'blob'|'json'|'text' in angular lib


text:
Q: How to Pick Column names from table I have tables which have columns and tables
Name
EmpId
Empname
DeptID
DeptName
Employee
Department

I have INFORMATION_SCHEMA.COLUMNS to get Table names
Script :
I have got table names
Select T.Name from  INFORMATION_SCHEMA.COLUMNS I
INNER JOIN @tbl_columns T
ON T.name = I.Table_name

Here I got table names
Output :
Name
Employee
Department

I need to get output which table have which column
Tbl_Name    ColName
Employee    EmpId
Employee    Empname
Department  DeptID
Department  DeptName

A: You would include the column name in your select:
select c.table_name, c.Column_name
from INFORMATION_SCHEMA.COLUMNS c join
     @tbl_columns t
     on t.name = c.Table_name
order by c.table_name, c.Column_name;

Note that you do not include the table_schema, so you can get duplicates.

A: I believe you want to connect table name and column name from @tbl_column. If yes I think you can use following script:
SELECT   T2.NAME
        ,C.NAME
FROM SYS.TABLES T1
INNER JOIN @tbl_columns T2 ON T1.name = T2.NAME
INNER JOIN (SELECT C2.*,C1.object_id
            FROM SYS.COLUMNS C1
            INNER JOIN @tbl_columns C2 ON C1.name = C2.NAME
            ) C ON C.object_id = T1.object_id


text:
Q: PDF inline Image does not work I defined an image within a pdf stream. It works correctly an shows me a red 4 pixel palette:
%PDF-1.7
1 0 obj
<<
  /Type     /Catalog
  /Pages    2 0 R
  /PageMode /UseNone
>>
endobj
2 0 obj
<<
  /Type  /Pages
  /Count 1
  /Kids  [3 0 R]
>>
endobj
3 0 obj
<<
  /Type      /Page
  /Parent    2 0 R
  /MediaBox  [0 0 50 20]
  /Contents  4 0 R
  /Resources
  <<
    /XObject << /Im1 5 0 R >>
  >>
>>
endobj
4 0 obj
<<
  /Length 38
>>
stream
  40 0 0 10 5 5 cm
  /Im1          Do
endstream
endobj
5 0 obj
<<
  /Type             /XObject
  /Subtype          /Image
  /Width            4
  /Height           1
  /ColorSpace       /DeviceRGB
  /BitsPerComponent 2
  /Filter           /ASCIIHexDecode
  /Length 10
>>
stream
 01 08 30
endstream
endobj
xref
0 6
0000000000 65535 f
0000000009 00000 n
0000000090 00000 n
0000000155 00000 n
0000000311 00000 n
0000000400 00000 n
trailer
<<
  /Size 6
  /Root 1 0 R
>>
startxref
720
%%EOF

But when I try to show the same image as an inline image, there is only a blank page:
...
...same as above...
...
3 0 obj
<<
  /Type      /Page
  /Parent    2 0 R
  /MediaBox  [0 0 50 20]
  /Contents  4 0 R
>>
endobj
4 0 obj
<<
  /Length 92
>>
stream
 40 0 0 10 5 5 cm
 BI
  /W   4
  /H   1
  /CS  /RGB
  /BPC 2
  /F   /AHx
 ID
  01 08 30
 EI
endstream
endobj
...

When I use no abbreviations for the image properties, there is already a blank page.
Does anyone has an idea what could be the problem?
Thank you for any hint and help!

A: Okay, the last two days I read the specification again and again. But it was worthwhile.
There were two mistakes. Only the correction of both of them gave me my wanted result...
First of all I did not end the ASCIIHexDecodeFilter portion between ID and ED. The specification says: "A right angle bracket character (>) indicates EOD." If there is a full stream filtered with ASCIIHexDecodeFilter, the Adobe Reader knows about the end of the stream by reading the /Length attribute. But as part of the stream itself it needs the > character.
The second thing is that my page object (3 0 obj) requires a /Resources attribute mandatory. It may be empty (/Resources << >>) but it may not be missing.
Thanks for everyone who tried to answer or help!!
Here the correct working inline image PDF file stream:
%PDF-1.7
1 0 obj
<<
  /Type     /Catalog
  /Pages    2 0 R
  /PageMode /UseNone
>>
endobj
2 0 obj
<<
  /Type  /Pages
  /Count 1
  /Kids  [3 0 R]
>>
endobj
3 0 obj
<<
  /Type      /Page
  /Parent    2 0 R
  /MediaBox  [0 0 50 20]
  /Contents  4 0 R
  /Resources << >>
>>
endobj
4 0 obj
<<
  /Length 90
>>
stream
q
 40 0 0 10 5 5 cm
 BI
  /W 4
  /H 1
  /CS/RGB
  /BPC 2
  /F /AHx
 ID
  01 08 30 >
 EI
Q
endstream
endobj
xref
0 5
0000000000 65535 f
0000000009 00000 n
0000000090 00000 n
0000000155 00000 n
0000000277 00000 n
trailer
<<
  /Size 5
  /Root 1 0 R
>>
startxref
418
%%EOF


text:
Q: I need to get sum of income for each user in January. Which of these 3 MySQL queries is more efficient? I need to get the sum of income for each user in January 2016 which is represented by the payments and commissions, not deposits. Table of records looks something like this (millions of records):
USERNAME  AMOUNT   TRANSACTION        DATE
user_1       1     Deposit #1       2015-12-12 23:19:00
user_2       2     Payment #2       2015-12-23 13:45:00
user_2       7     Commission #3    2016-01-04 23:45:00
user_1       1     Payment #4       2016-01-09 20:25:00
user_3       2     Payment #5       2016-01-17 02:42:00
user_1       3     Commission #6    2016-01-23 18:30:00
user_3       2     Deposit #5       2016-01-29 09:58:00
...         ...    ...              ...

My 3 queries are:
SELECT username, SUM( amount ) AS monthly_amount
FROM balance_history
WHERE MONTH( date ) = 1
AND YEAR( date ) = 2016
AND (transaction LIKE 'Payment%' OR transaction LIKE 'Commission%')
GROUP BY username

Or
SELECT username, SUM( amount ) AS monthly_amount
FROM balance_history
WHERE '2015-12-31 23:59:59' < date AND date < '2016-02-01 00:00:00'
AND (transaction LIKE 'Payment%' OR transaction LIKE 'Commission%')
GROUP BY username

Or
SELECT username, amount, transaction
FROM balance_history
WHERE '2015-12-31 23:59:59' < date and date < '2016-02-01 00:00:00'

AND THEN DOING THE SORTING, SUM, AND OTHER CALCS WITH PHP

I would go with the 3rd one, but I would appreciate other inputs.
Also, Is there any tool to measure the "efficiency" of a query?
Thank you all and happy new year!

A: If there is no index on date column, then the 1st and the 2nd query should take approximately the same amount of time (as they both scan the full table)
I would not go for the third one : if you have a lot of data, you can possibly reach the PHP memory limit, furthermore MySQL have good algorithms to do the calculations you want to do, why not using them ? :-)
however I would suggest you create an index on the column date
ALTER TABLE `balance_history`
ADD INDEX `idx_date` (`DATE` ASC);

important note :  depending on your production server performance and load this could block your table for several minutes - test it on your development environment first !
once the index is created, the second query will be the most efficient one :
SELECT username, SUM( amount ) AS monthly_amount
FROM balance_history
WHERE '2015-12-31 23:59:59' < date AND date < '2016-02-01 00:00:00'
AND (transaction LIKE 'Payment%' OR transaction LIKE 'Commission%')
GROUP BY username

if you use MONTH( date ) or YEAR( date ) in a WHERE clause the index on date is useless : you will be scanning the full table ...


text:
Q: unrecognized selector sent to instance (_setViewDelegateContentOverlayInsetsAreClean) It looks like there is a lot of way to get this error. I couldn't find any solution that worked in my case. The difference with most thread with the same error, is that the view that throw the error is my initial view and not called by a segue.
Here Is my error log:
Tabuleo[87837:3767493] -[loginViewController _setViewDelegateContentOverlayInsetsAreClean:]:
unrecognized selector sent to instance 0x7fb513d104e0
2018-07-03 13:37:25.365645+0200 Tabuleo[87837:3767493]
*** Terminating app due to uncaught exception
'NSInvalidArgumentException', reason: '-[loginViewController _setViewDelegateContentOverlayInsetsAreClean:]:
unrecognized selector sent to instance

I can't figure out by myself where it comes from because in my code I don't have any method called "_setViewDelegateContentOverlayInsetsAreClean".
At this point I don't have any clue and I read almost all post related to that.
My code is about 350 lines so I put a link to download it if it helps.
loginViewController.m
Thanks for your help.

A: I figured it out finally.
I don't know exactly where it was messed up but redo every link of my elements in my storyboard for this view finally ended up working !
So if that happen just redo your links from storyboard to .h file.


text:
Q: Azure Storage Table and data migrations Is it possible to refactor TableEntities used by Azure Table Storage? For example, consider the following entity:
class MyEntity: TableEntity
{
    public string SomeID { get; set; }
}

Is it possible to maintain values when doing the refactorings like:

*

*Renaming SomeID to SomeOtherID?

*Changing the property type from string to Guid? (considering all existing values are actual GUIDs)

If yes, what is the recommended approach to handling those schema changes in a consistent manner, like migrations for EF6?

A: One of the options that you could explore is to use a custom EntityProperty resolver.
If you change the name of a property in your class from SomeID to SomeOtherID and insert the entities with the new name to table storage, you will have entities with SomeID and/or SomeOtherID fields in table storage.
When you query them back you can provide a custom EntityProperty Resolver delegate that will be used by the storage SDK to create from the raw property dictionary  your concrete entity type. In that delegate you can put in logic to handle this scenario to create the actual type you want.
The overloaded ExecuteQuery method in CloudTable takes the EntityProperty resolver:
public virtual IEnumerable<TResult> ExecuteQuery<TResult>(
    TableQuery query,
    EntityResolver<TResult> resolver,
    TableRequestOptions requestOptions = null,
    OperationContext operationContext = null
)

And EntityProperty resolver is a delegate where you decide how to construct your strong type entity from property dictionary:
public delegate T EntityResolver<T>(
    string partitionKey,
    string rowKey,
    DateTimeOffset timestamp,
    IDictionary<string, EntityProperty> properties,
    string etag
);

So in this delegate you put code to handle kvp s with keys SomeID and SomeOtherID while constructing your T type return value.
You could also use the same to handle type changes. Insert with the new schema and changed property type and when you read it back handle these in your EntityProperty resolver.
I would still recommend a data migration to the new data model instead of though maintaining custom resolvers. The custom resolvers may help you while you are in the middle of data migration process and still serving requests while you are in that transition stage.

A: I don't think there is a way to do this from Azure Storage architecture. What you can do is just to read entities and update them one by one (or batch by batch using EntityGroupTransaction).


text:
Q: Trying to send a string of words in a particular format Right now I'm dealing with socket.io on objective -c and I'm working on sending event requests. I'm working with pkyeck socket.io api and to send an event, they way he set it up you put the args value in a dictionary with which is handled in the sentevent function with takes the dictionary of variables you sent and matches it with the args key. So if I follow that pattern, the event I send to the socket.io server looks like this.
{"args":[{"username":"yeah", "id":"2"}],"name":"login"}

However for my server to properly handle a socket.io call the call needs to look like this.
{"args":["yeah","2"],"name":"login"}

But I'm not able to send the variables in such a way for the dictionary to set it up like that. If I use a NSArray the request is sent as such.
{"args":[["yeah","2"]}],"name":"login"}

If I send an appended string it looks like this.
{"args":[{"'yeah','2'"}],"name":"login"}

This is what I have done so far
- (void) socketIO:(SocketIO *)socket onMessage:(NSString *)status{
NSLog(@"Current status %@", status);
if([status isEqualToString:@"ready"]){
    SocketIOCallback cb = ^(id argsData) {
        NSDictionary *response = argsData;
        // do something with response
        NSLog(@"ack arrived: %@", response);

        // test forced disconnect
        //[socketIO disconnectForced];
    };
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setObject:@"Yeah" forKey:@"username"];
    [dict setObject:@"eqe74squbaah9eqvk7bok3rh09" forKey:@"session"];
    [dict setObject:userid forKey:@"user_id"];
    NSMutableArray *arr=[NSArray arrayWithObjects:@"Yeah", @"eqe74squbaah9eqvk7bok3rh09", userid, nil];

    NSString *eventName=@"'Yeah',";
    eventName=[eventName stringByAppendingString:@"'eqe74squbaah9eqvk7bok3rh09',"];
    eventName=[eventName stringByAppendingString:@"'"];
    eventName=[eventName stringByAppendingString:userid];
    eventName=[eventName stringByAppendingString:@"'"];

   // NSLog(@"This is the string to be sent %@",eventName);

    [socketIO sendEvent:@"login" withData:eventName andAcknowledge:cb];
    [socketIO sendEvent:@"subscribe" withData:@"47058" andAcknowledge:cb];
}

This is the method that sends the socket.io event request.
- (void) sendEvent:(NSString *)eventName withData:(id)data andAcknowledge:(SocketIOCallback)function
{
        NSMutableDictionary *dict = [NSMutableDictionary dictionaryWithObject:eventName forKey:@"name"];

    // do not require arguments
    if (data != nil) {
        [dict setObject:[NSArray arrayWithObject:data] forKey:@"args"];
    }

    SocketIOPacket *packet = [[SocketIOPacket alloc] initWithType:@"event"];
    packet.data = [SocketIOJSONSerialization JSONStringFromObject:dict error:nil];
    packet.pId = [self addAcknowledge:function];
    if (function) {
        packet.ack = @"data";
    }
    [self send:packet];
}

A: The first thing that comes to my mind would be to make the string entirely yourself with something like:
NSString Query = [stringFormatWithString "{\"args\":[{\"username\":\"%@\",     \"id\":\"%@\"}],\"name\":\"%@\"}", usernameVariable,idVariable,nameVariable];


text:
Q: Ubuntu 20.4.3 & Ubuntu 20.04.4 LTS Network Cable Issues First I want to Thank you I am much apricate this website and the help of you all, without you I think I didn't know ubuntu at all.
My issue is this:
I have downloaded the ISO of LTS from the official website I came across an issue that is persist for both of the LTS's versions 3 and 4.
I install the 20.04.3 LTS on Asus ROG G14 and had the network issue fixed it with change netplan to Network manager. Also came across this on a PC that's build by my company basic as they come and same issue on Ubuntu 20.4.3 LTS after change to network-manger no issue at all Wifi and LAN working.
now I need to set up the Ubuntu 20.4.4 LTS and the issue is persist here also..
only wifi no Ethernet cable I have the issue that on
lshw -C network
LAN show as unclaimed
not recognize on ip a or ifconfig at all..
changed to NetWork-manger as usual  but still not helping...
now again no matter which PC or Laptop 20.4.4 LTS only have wifi's now tests on Dell XPS's and latitude also on ROG and on our build PC's same to all only Wifi is shown..
I mention at the beginning that I download form the official Ubuntu website last time changing the ISO image to 20.4.4 was actually the solution...
also format and reinstall ubuntu didn't helped.
( I tried a lot of manuals none of them helped I will glad try everything you suggest except 22.04 LTs)
Fire away and sending all of you a hug because each and one of you helped at lease one time :)


text:
Q: The norm of a derivation Let $E$ be an infinite-dimensional complex Hilbert space. For $A\in \mathcal{L}(E)$, consider
\begin{eqnarray*}
W_{0}(A)
&=&\{\alpha\in \mathbb{C}:\;\exists\,(z_n)\subset E\;\;\hbox{such that}\;\|z_n\|=1,\displaystyle\lim_{n\rightarrow+\infty}\langle A z_n,z_n\rangle=\alpha,\\
&&\phantom{++++++++++}\;\hbox{and}\;\displaystyle\lim_{n\rightarrow+\infty}\|Az_n\|= \|A\| \}.
\end{eqnarray*}
Moreover, we define the map
\begin{align*}
\delta_A:
&\mathcal{L}(E)\longrightarrow \mathcal{L}(E)\\
& X\longmapsto AX-XA .
\end{align*}
I want to understand the proof of the following theorem:

Theorem: Let $A\in \mathcal{L}(E)$. If $\lambda\in  W_{0}(A)$, then
  $$\|\delta_A\|\geq2(\|A\|^2-|\lambda|^2)^{1/2}.$$

Proof: If $\lambda\in  W_{0}(A)$, then there exists $(x_n)\subset E\;\;\hbox{such that}\;\|x_n\|=1,\displaystyle\lim_{n\rightarrow+\infty}\langle A x_n,x_n\rangle=\lambda,$
and $\displaystyle\lim_{n\rightarrow+\infty}\|Ax_n\|= \|A\|$.
let
$Ax_n = \alpha_nx_n + \beta_ny_n$, with $y_n$ a unit vector orthogonal to $x_n$ ; thus
$\alpha_n=\langle Ax_n,x_n\rangle\to \lambda$ and $|\alpha_n|^2+|\beta_n|^2=\|Ax_n\|^2\to \|A\|^2$. Let $V_n=x_n\otimes x_n-y_n\otimes y_n$
; then $\|V_n\|=1$ and $(AV_n - V_n A)x_n = 2y_n \beta_n$. Thus,
\begin{align*}
\|\delta_A\|
& \geq \|\delta_A(V_n)\|\\
 & \geq \|(AV_n - V_n A)x_n\|=2|\beta_n|\\
 &=2(\|Ax_n\|^2-|\langle A x_n,x_n\rangle|^2)^{1/2} \to 2(\|A\|^2-|\lambda|^2)^{1/2}.
\end{align*}

I don't understant the following facts:

*

*Why we can write $Ax_n = \alpha_nx_n + \beta_ny_n$ , with $y_n$ a unit vector orthogonal to $x_n$?

*Why $\|V_n\|=1$ and $(AV_n - V_n A)x_n = 2y_n \beta_n$?

Thank you for your help.

A: Let $F$ be a closed subspace of $E$. Then you have $E=F\oplus F^\perp$, ie every vector of $E$ has a unique decomposition to a "part in $F$" and a "part orthogonal to $F$". Look specifically at $F=\mathrm{span}(x_n)$, this is a closed subsoace. It follows every vector can be decomposed into a sum of a vector proportional to $x_n$ and a vector orthogonal to $x_n$. Doing this with the vector $Ax_n$ is what is happening the first part of your question.
For the second part, the key is to understand that the operator $x_n\otimes x_n$ is a projection operator (because the norm of $x_n$ is $1$). $y_n\otimes y_n$ is a projection onto an orthogonal space, thus (for example by choosing an ONB that contains $x_n$ and $y_n$) you can see that
$$\| a\,x_n\otimes x_n+b\, y_n\otimes y_n\|=\max(|a|,|b|).$$
Also $V_n x_n = x_n$, $V_ny_n=-y_n$ and thus:
$$(AV_n-V_nA)x_n = (\alpha_n x_n+\beta_n y_n) - V_n(\alpha_n x_n+\beta_n y_n)= 2\beta_n y_n.$$

A: For your first question, each vector $x\in E$ gives a decomposition $E=\text{span}\{x\}\oplus\text{span}\{x\}^\perp$.
For your second question, if $z\in E$ we have
$$\|V_nz\|^2=|\langle z,x_n\rangle|^2+|\langle z,y_n\rangle|^2\leq\|z\|^2,$$
since $x_n\perp y_n$, so $\|V_n\|\leq1$.  Furthermore, since $V_nx_n=x_n$ we have  $\|V_n\|=1$.
Now the last is just a computation:
$$(AV_n-V_nA)x_n=Ax_n-V_nAx_n=(\alpha_nx_n+\beta_ny_n)-(\alpha_nx_n-\beta_ny_n)=2\beta_ny_n$$