text:
Q: Kendo grid removes row, but does not call destory URL I have a Kendo grid where I'm trying to add a delete feature. My datasource looks like:
var datasource = new kendo.data.DataSource({
    transport: {
        read: {
            url: Router.action("Admin", "GetScansForMailItem", { mailItemIdnt: detailinit.data.MailItemIdnt }),
            dataType: "json"
        },
        destroy: {
            url: Router.action("Admin", "DeleteScan"),
            type: "post"
        }
    },
    model: {
        id: "ScanIdnt",
        fields: {
            ScanIdnt: {editable: false, nullable: false}
        }
    },
    pageSize: 5
});

I added the model part because this answer, however it made no difference.
The actual grid looks like:
 .kendoGrid({
     dataSource: datasource
     scrollable: false,
     sortable: true,
     pageable: true,
     editable: "inline",
     columns: [{
         field: "ScanIdnt",
         title: "Scan ID"
     }, {
         field: "CreatedDate",
         title: "Created",
         template: "#= kendo.parseDate(CreatedDate, 'yyyy/MM/dd') #"
     }, {
         field: "ScanDocumentRelativePath",
         title: "File Path",
         template: "#= ScanDocumentRelativePath.substring(1) #"
     }, {
         field: "ScanUserIdnt",
         title: "Scanned By"
     },{
         command: "destroy",
         title: ""
     }]
 });

Strangely, clicking the delete button removes the from the gird on the UI, but there is absolutely no Ajax call is made the the destroy URL. I can't seem to figure out why. Any ideas?
EDIT I'd like to point out that this grid is in fact a nested grid inside of another grid (like here) I discovered that the parent grid handles actually makes a call, but to the wrong function. For some reason, it clicking delete on a to level item calls the read function of the nested grid, however, the nested grids do nothing

A: Figured it out (sorta). While I think there were many issues with my code and the grid, It seems that when it came down to it, Kendo didn't like how I had my data.
In the Kendo docs related to hierarchical grids, the data for the child grid is stored in a field of the data for the parent. For example, given the following JSON:
"ParentItems": [
    {
        "Id": 12345 ,
        "Name": "Test1",
        "ChildItems": [
            {"Id": 1, "Name": "Test"},
            {"Id": 2, "Name": "Test"}
        ]
    },
    {
        "Id": 12346 ,
        "Name": "Test2",
        "ChildItems": [
            {"Id": 1, "Name": "Test"},
            {"Id": 2, "Name": "Test"}
        ]
    }
]

In the parent grid, each ParentItem would display it's respective ChildItems in the child grid.
On the other hand, I was pulling both data sets separately. Basically, I pulled the ParentItems like:
"ParentItems": [
    {
        "Id": 12345,
        "Name" : "Test1"
    },
    {
        "Id": 12346,
        "Name" : "Test2"
    }
]

And then made a second request to pull the child items, based on the parent's id.
"ChildItems": [
    {"Id": 1, "Name": "Test", "ParentId": "12345"},
    {"Id": 2, "Name": "Test", "ParentId": "12345"}
]

I was able to modify the server side code to serve the data like in the very first example and managed to get things working. The specific document that helped me out can be found here


text:
Q: Need to Open Port 1111 in unix server I have a request to open port 1111.
Below is the output i get for netstat -nptl
Active Internet connections (only servers)
Proto Recv-Q Send-Q Local Address               Foreign Address             State       PID/Program name
tcp        0      0 0.0.0.0:3873                0.0.0.0:*                   LISTEN      -
tcp        0      0 0.0.0.0:39334               0.0.0.0:*                   LISTEN      -
tcp        0      0 0.0.0.0:57158               0.0.0.0:*                   LISTEN      -
tcp        0      0 0.0.0.0:5001                0.0.0.0:*                   LISTEN      -
tcp        0      0 0.0.0.0:59338               0.0.0.0:*                   LISTEN      -
tcp        0      0 0.0.0.0:1098                0.0.0.0:*                   LISTEN      -
tcp        0      0 0.0.0.0:3306                0.0.0.0:*                   LISTEN      -
tcp        0      0 0.0.0.0:1099                0.0.0.0:*                                   LISTEN      -
tcp        0      0 0.0.0.0:111                 0.0.0.0:*                   LISTEN      -
tcp        0      0 0.0.0.0:8080                0.0.0.0:*                   LISTEN      -
tcp        0      0 0.0.0.0:8083                0.0.0.0:*                   LISTEN      -
tcp        0      0 0.0.0.0:22                  0.0.0.0:*                   LISTEN      -
tcp        0      0 127.0.0.1:25                0.0.0.0:*                   LISTEN      -
tcp        0      0 0.0.0.0:3035                0.0.0.0:*                   LISTEN      -
tcp        0      0 0.0.0.0:4444                0.0.0.0:*                   LISTEN      -
tcp        0      0 0.0.0.0:4445                0.0.0.0:*                   LISTEN      -
tcp        0      0 0.0.0.0:4446                0.0.0.0:*                   LISTEN      -
tcp        0      0 0.0.0.0:959                 0.0.0.0:*                   LISTEN      -
tcp        0      0 :::6688                     :::*                        LISTEN      -
tcp        0      0 :::6689                     :::*                        LISTEN      -
tcp        0      0 :::8898                     :::*                        LISTEN      -
tcp        0      0 :::8899                     :::*                        LISTEN      -
tcp        0      0 :::24071                    :::*                        LISTEN      -
tcp        0      0 :::11111                    :::*                        LISTEN      -
tcp        0      0 :::3434                     :::*                        LISTEN      -
tcp        0      0 :::80                       :::*                        LISTEN      -

How can I open the port?
Below is the output of iptables
Chain INPUT (policy ACCEPT)
target     prot opt source               destination

Chain FORWARD (policy ACCEPT)
target     prot opt source               destination

Chain OUTPUT (policy ACCEPT)
target     prot opt source               destination

A: This should be a comment, but I can't do that on unix...
Do note that in your question you mention port 1111, but there is a service on port 111 for IPV4 and a service listening on port 11111 for IPV6. So I do not agree that there is a service listening on the port you mentioned like Rui F ribeiro said. Is this mixup where it goes wrong?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Usage of "in-tray" A recent CNBC.com article reads:

Britain's new Prime Minister Rishi Sunak is set to assume office Tuesday and, with it, one of the most daunting political in-trays in modern British history as he attempts to steer the country through an existing cost-of-living crisis, political and social disjuncture, and a looming recession.

I understand that an in tray is a tray where you can find all mails
received  that are still  to be dealt with.
In the above article "in-trays"
is used as a synonym of "difficult issues".
Is this metaphor a common usage? Or is it just a one-off usage?

A: Common usage. He's got a lot in his in box. There's also a saying that "you can't manage out of your in box,"
In box and in tray are the same thing.
He's got a lot on his plate also says the same thing.


text:
Q: How to set the font size of data label in fviz_pca_var of factoextra When I submitted a paper to a journal, the journal asked me to set the font size to  7.5, however when I used the following code, only the axis text changed, the label size remained unchanged,
    library(ggplot2)
    library(FactoMineR)
    library(factoextra)

    irispca <- PCA(iris,quali.sup = 5)
    fviz_pca_var(irispca)+
   theme(text = element_text(size = 7.5),
         axis.title = element_text(size = 7.5),
         axis.text = element_text(size = 7.5)
         )

Any suggestion is appreciated to  tell what code should I used to change the label size?

A: Getting into fviz_pca_var looks like you can just pass a labelsize in the function:
irispca <- PCA(iris,quali.sup = 5)
fviz_pca_var(irispca, labelsize = 3, repel = TRUE) +
  theme(text = element_text(size = 7.5),
        axis.title = element_text(size = 7.5),
        axis.text = element_text(size = 7.5))

A: The argument labelsize is passed as an aditional argument to the fviz() function. If you then go to the fviz help page, the argument is there.
I would rather add a comment to the above answer but I do not have the required reputation so pardon me...


text:
Q: Isekai shoujo manga identification In this isekai a god pulls a girl to take over the role of a villainess in this new world where she has to "act" the role and fulfill her purpose in order to save her sister's life in her own world. She accomplishes this but instead of being banished like she hoped she is turned into a maid.
Why does being a villainess in that world save her sister?
-She essentially makes a deal with the god of the fantasy world, her sister in modern Japan (i presume) is sick and dying, the deal entails for her to fulfill the role of villainess in the fantasy world as to "not disturb major events in the timeline of this world or something like that" is kinda vague, mind you all of this happens within the first few chapters of the manga, also she gets her engagement annulled because she was bullying the heroine, however since she never did anything violent or harmful, she is stripped of her noble title and made a maid for the palace, (she wanted to be banished).
Another detail that i remember is that when she was demoted to maid there was a head maid that whipped her arms as a form of punishment and a knight (captain?) gave her some medicine. that is all i can remember for now.

A: The Role of the Villainess Is No More!

Yukino Amaishi signed a contract with God to save her sister. She was then reborn in a different world as Lefina Eilferia, the daughter of a duke and the Crown Prince's fiancée. After successfully completing the objective of giving the heroine and the prince a happy end, Lefina, who played the role of the villainess, ends up working in the castle as a maid.

Found with a search for isekai manga villainess "save * sister" maid


text:
Q: Git, how to ignore switched lines? I have a config file that changes when I start the server but the only change is the switching lines. It does not affect the content of the file and doesn't matter where the lines are as the server rewrites the data where it got them. How can I prevent that?
I thought of having a static folder and put my config files here and then before I commit the changes I just copy them but I don't know if I can do that with git automatically.
Example of what I am talking about:
Before I run the server:
    frosted-ice:
      enabled: true
      delay:
        min: 20
        max: 40
    lootables:
      auto-replenish: false
      restrict-player-reloot: true
      reset-seed-on-fill: true
      max-refills: -1
      refresh-min: 12h
      refresh-max: 2d

After I run the server:
    lootables:
      auto-replenish: false
      restrict-player-reloot: true
      refresh-min: 12h
      refresh-max: 2d
      reset-seed-on-fill: true
      max-refills: -1
    frosted-ice:
      enabled: true
      delay:
        min: 20
        max: 40

A: You can consider inserting a clean filter into your commit process.  You will need to write the clean filter itself, then add a filter-driver configuration to your Git configuration—to tell Git how to invoke the clean filter—and add a .gitattributes file to mark this particular file as requiring a pass through the clean filter.
Background
Git stores commits, and commits hold content—file data for a collection of files, one collection-of-files per commit—but for the most part, Git has no idea what that content means.  And: each commit stores a full snapshot of every file—so if the file's meaning is the same, and you're making a new commit anyway, it's relatively harmless to just make a new snapshot with the rearranged lines.
I say relatively harmless because there are two obvious drawbacks:

*

*When you, a human, compare the previous commit (the parent of the new commit) to the subsequent (new, or child) commit, you'll see that config.yml, or whatever this file's name is, has changed.  That change is just noise, but you'll see it, because Git doesn't interpret the content, it just says: hey, this file changed.

*Git has clever techniques to keep the repository's overall size small, despite the fact that every commit stores a complete copy of every file.  The first technique is radically simple: Git hashes each content into what Git calls a blob object that is retrieved by its hash ID, the same way that Git retrieves commits by their unique hash IDs.  This hashing is exquisitely sensitive to the value and position of every byte (or bit, really) of input data.  So a file that exactly matches a previous copy of the file comes up with the same hash ID, but a file that is altered in any way—including just a rearrangement of some blocks within it—does not.
In other words, this file-content-rearranging defeats Git's first and most effective means of compressing away duplicate copies of files.
You say:

[It] doesn't matter where the lines are as the server rewrites the data where it got them. How can I prevent that?

and in a comment you add that:

the data [is encoded as] yaml [and represents an unordered map]

Swapping lines around randomly within a YAML file would change the stored data, but swapping the position of individual key-value pairs (which may or may not span one or more lines) within an unordered mapping does indeed leave the overall mapping unchanged (since the mapping itself is unordered).
The problem here is that Git has no idea that this is an unordered mapping represented as YAML lines.  You may know it, but Git doesn't—and there's no easy way to tell Git, as Git doesn't know YAML from JSON, nor either from a hole in a file.
In the end, then, you have only three options:

*

*Ignore the noise and lack-of-compression.  That is, put up with this.  It won't fail, it's just annoying.

*Teach whatever rewrites this file in place to use a stable order, despite the file containing an unordered mapping.  That is, in order for the data to be expressed as lines in YAML, whatever is expressing the mapping has to order the mapping because lines have order.  The program writing this YAML file can just sort the mapping before writing.  See What is stability in sorting algorithms and why is it important?

*Insert your own sorting.
Approach 1 is the simplest of all, but has the drawback of leaving you annoyed.  (Disk space is cheap, and Git's secondary compression techniques may eventually compress away most of this stuff anyway, so the saves-space argument may be weak, but the annoys-the-human argument is pretty strong.)
I personally view the second approach as the best, but if you don't control this other program, you might not be able to fix it.
The third approach means that you must write your own program.  If you have access to YAML readers and writers and can easily construct, then sort and write-back, an ordered mapping from the YAML file, consider doing that.
Using a clean filter
To use a clean filter, you need to provide a name for it.  You could call yours sort-yaml-dictionary or something along those lines.  These lines would then go into some .git/config or $HOME/.gitconfig or similar file:
[filter "sort-yaml-dictionary"]
    clean = the-program-you-wrote

You don't have to define a smudge filter here as well, but you can if you like, using a program that simply copies its input back to its output, such as cat.  See the gitattributes documentation for additional details here.
Then, in your .giattributes file, you would include the line:
config.yml  filter=sort-yaml-dictionary

This tells Git:

*

*Every time I run git add on config.yml, don't just copy the work-tree file into Git's index.  Instead, read the file.  Send its data to the clean filter for the sort-yaml-dictionary driver, as input to that filter.  Read the output from that filter back.  Store the resulting data in the index, under the file's original name—in this case, config.yml.

Since your program reads, then sorts (into a stable dictionary key-value order), then writes back, the configuration, the result will be that what goes into commits is a sorted version of the config.yml file, regardless of what's in the work-tree version.
It's up to you whether to try to have your program also sort the work-tree copy in-place (i.e., read and then rewrite the work-tree copy), but if you do, make sure you do this either completely before or completely after the file has been copied to the index.  Otherwise you run the risk of writing to the work-tree file while Git is trying to read the work-tree file to send the data to your filter program.
Do not filter the work-tree file.  Filter the input to your program.  This input may not actually match the work-tree file's content.  (The clean filter can be invoked via git merge, on content that is not in the work-tree at all.)


text:
Q: Function to pass parameter to perform group_by in R I am trying to write a function and pass in 2 parameters. I am getting an error and the function is not able recognize the 2nd parameter.
library(dplyr)

Test2 <- function(df, kk) {
  xx1 <- group_by_at(mtcars, vars(mpg, cyl, kk)) %>%
      summarise(FreqOG = length(cyl))
  xx1 <- data.frame(xx1)
}

yy1 <- Test2(mtcars,hp)

A: You have to enquo the variable and use the !! operator:
library(dplyr)
Test2 <- function(df,kk) {
   kk<-enquo(kk)
   xx1 <- group_by_at(mtcars,vars(mpg,cyl,!!kk)) %>% summarise(FreqOG = length(cyl))
   xx1 <- data.frame(xx1)}

yy1 <- Test2(mtcars,hp)

This question may provide more background information: Why is enquo + !! preferable to substitute + eval


text:
Q: wifi not working ubuntu Hi I just installed ubuntu 16.04 with third party stuff has well but once finished I dont see any option to enable wifi in desktop menu or in settings
Also, i won't be able to connect to ethernet
Any fix for this thanks


text:
Q: Detect ipad virtual keyboard events I am writing an HTML/CSS web app for the iPad.  How do I catch the Tab event when the user uses the 'Next' button on the virtual keyboard to tab between fields.  I want to capture this event, cancel it, and use my own custom handler.
Thanks


text:
Q: Работа серверного приложения Я, допустим, написал одно веб-приложение на php, которое располагается на моем сервере. То есть имеется один код. Но клиентов ведь много.
Допустим, сразу 10 человек подключаются к моему серверу. И как это один единственный код обрабатывает запросы всех человек сразу? Он ведь это делает одновременно.
Я слышал, это связано с потоками и процессами, какими-то экземплярами. В общем. объясните это, пожалуйста.
А ещё объясните, чем архитектура php приложения отличается от архитектуры node.js приложения. Слышал, разница в каких-то потоках, то есть в их количестве.

A: Есть HTTP. Он работает по схеме "клиент послал запрос @ сервер ответил".

В случае с PHP обычно есть вебсервер. Многопоточностью занимается обычно именно он. Он принимает запрос и передаёт его интерпретатору PHP.

Если вебсервер использует CGI, то получив запрос, он запускает новый процесс интерпретатора PHP, передаёт ему параметры запроса, передаёт выведенные интерпретатором данные обратно клиенту и дожидается, пока процесс закончит работу. Параллельная обработка может происходить за счёт того, что вебсервер контролирует несколько процессов интерпретатора PHP.
Запуск каждый раз нового процесса потребляет оперативную память, разумеется. И время. Припоминаю случаи, когда слишком много параллельных клиентов приводили к слишком большому потреблению ОЗУ и слабопредсказуемым последствиям.

Если вебсервер использует FastCGI, то он заранее, при запуске, поднимает набор процессов интерпретатора PHP в особом режиме. В наборе каждый интерпретатор может быть занят или свободен.
Вебсервер, получив запрос, берёт из своего набора свободный процесс интерпретатора (делая его занятым), сообщает ему (с помощью сокетов) параметры запроса, и выдаваемый ответ передаёт пользователю, после чего освобождает интерпретатор.
По сравнению с CGI, процессы больше не завершаются/запускаются на каждый запрос, что уже неплохо. И процессов конечное количество. Если каждый из них ограничить по памяти, они будут потреблять предсказуемое количество ресурсов.
Но осталась другая проблема, актуальная и для CGI: код приложения обычно перед непосредственно обработкой запроса выполняет некоторую подготовительную работу: загружает библиотеки, настройки, создаёт системные объекты. Это довольно внушительная часть кода, которая для разных запросов приводит к одним и тем же результатам. Но эти результаты не сохраняются, а выбрасываются в никуда после каждого запроса. Не круто.

На этой ноте выходим из мира PHP, пропуская экзотические способы заставить PHP обслуживать запросы, и переходим к более интересным темам. Про что вы там спрашивали... NodeJS! Окей.
JavaScript исторически достаточно сильно привязан к циклу событий. Сам по себе он не многопоточен, программы на JS принято разделять на небольшие порции, между которыми делать всё равно нечего и можно дать поработать кому-то ещё. Поэтому очень часто код на NodeJS "общается с внешним миром" асинхронно: он не просто говорит "сделай Х", а "сделай Х, и когда получишь результат, сообщи в Y, а я пойду отдыхать".
Действий, которые полезно выполнять асинхронно в мире веб-сайтов довольно много: ожидание поступления данных от клиента, ожидание результатов от базы данных, ожидание записи в файл, и прочая, прочая.
Вебсервер в Node.js собственный, встроенный. И поскольку он управляется непосредственно из интерпретатора, с контролем над тем, что выполнить до и после, можно заранее один раз подготовить объекты и выполнять запросы, не конструируя их по новой каждый раз.
Внутри Node.js крутится "цикл событий" вокруг "очереди событий" (упрощённо). Цикл событий: {берёт очередное событие из очереди, выполняет связанное с ним действие} и так по кругу, причём действия могут добавлять новые записи в очередь событий.
Когда запросы поступают по очереди, очередь событий не раздувается более чем на 1 запись и порядок выполнения кода в целом похож на обычный:

*

*приходит запрос (в очередь!)

*цикл событий обнаружиает пришедший запрос (из очереди!)

*

*вызвал обработчик f для запроса

*обработчик f попросил выполнить запрос в БД (в очередь!)

*

*а результат передать в обработчик g

*запрос в БД выполняется, ожидание, очередь событий пуста

*

*но есть обработчики, поэтому процесс ещё не закончен

*в цикл событий пришло уведомление о завершении запроса (из очереди!)

*

*вызвал обработчик g для результатов запроса

*обработчик g на основе результатов запроса составил страницу и отправил пользователю

Теперь вопрос: как Node.js выполняет несколько запросов параллельно?
Ответ: так только кажется. Просто из-за асинхронности код запроса разбит на отдельные небольшие кусочки, между которыми допускается ожидание. Если запросов мало, то это реально ожидание, а если много, то во время ожидания можно делать что-то полезное.
Выше описан типичный запрос простенького веб-приложения, где асинхронных действий всего два: получение запроса от вебсервера и запрос к БД. На практике их обычно больше.
В то время, как БД выполняет запрос для первого клиента, может прийти запрос от второго. Если событие о приходе второго запроса придёт раньше результатов из БД для первого, то Node.js:

*

*сначала обработает второй запрос (2.II)

*отправит второй запрос в БД (3.II)

*получит данные из БД к первому запросу (5.I), сформирует и запишет ответ первому

*

*(если запросы в БД более-менее одинаковые и новых запросов нет)

*получит данные из БД ко второму запросу (5.II), сформирует и запишет ответ второму

И выходит, что в каждый момент времени выполняется только одно действие, но при этом один процесс в каждый момент времени может обслуживать несколько клиентов. И допускаются долгие запросы отдельных клиентов. К примеру, не по HTTP а, скажем, Websockets.
В CGI и FastCGI, теоретически обслуживание Websocket-соединения занимает целый процесс и не даёт ему заняться ничем другим. N процессов, создаём N соединений и ба-бах -- на запросы отвечать больше некому. Вебсервер из Node.js и другие событийные вебсерверы этим не страдают.

Конечно, этого может быть недостаточно. С многоядерными процессорами даже процессы Node.js может иметь смысл поднимать не поодиночке, а сразу наборами. Но какая-то единая точка должна будет раскидывать по ним запросы от клиентов. Балансировщик нагрузки. nginx, HAProxy, Varnish или что-то ещё.

Встроенный в язык вебсервер может быть и менее умным: к примеру, есть язык Ruby, в нём принято использовать интерфейс Rack (в котором обработчик запроса -- одна здоровенная функция из кучи частей). Этот интерфейс реализуется вебсервером Unicorn. Получив запрос, он вызывает обработчик-функцию и отдаёт возвращённое ею значение.
Разумеется, каждый процесс Unicorn может обслуживать только один запрос. И если он торчит "наружу" (клиенты общаются непосредственно с ним), может возникнуть проблема, если клиент медленный: Unicorn будет терпеливо ждать, пока клиент примет ответ, сколько бы это времени ни заняло, пока клиент кажется живым.
N процессов, N медленных клиентов и вуаля -- запросы обслуживать больше некому.
Поэтому Unicorn всегда размещают "наружу" за балансировщиком нагрузки, потому что у балансировщика есть собственный буфер в который Unicorn может быстро выкинуть ответ и приступить к следующему запросу, пока балансировщик своим эффективным вводом/выводом (асинхронном событийным) вдалбливает ответы даже в медленных клиентов, освободив от неблагодарной работы Unicorn.

...так, сколько килобайт я уже тут понаписал... Почти 7! Ну... думаю, вы поняли, что это довольно обширная тема.


text:
Q: Не запускаются файлы Ruby через FAR менеджер Здравствуйте!
Установил с сайта версию Ruby 2.4.2-2 (x64). Также установил с сайта FAR менеджер. Ruby установил на C:\Ruby24-x64. Создал файл C:\Projects\MyApp1\app1.rb  с одной строкой puts "Hello"
При вводе в FAR менеджере команды ruby -v или ruby app1.rb появляется сообщение:

"ruby" не является внутренней или внешней командой или пакетным
  файлом.

При вводе аналогичной команды в командной строке Windows файл выполняется ( Hello)
Как исправить ситуацию? FAR менеджер поставил впервые, потому, что делаю все как в уроках
Прикладываю скрин

A: Судя по всему, инсталлятор Ruby прописывает свой каталог в переменную окружения %PATH%, чтобы при запуске ruby из командной строки его бинарники находились системой. Но значение этой переменной наследуется процессом из того процесса, который его запустил, и не обновляется само по себе. Поэтому нужна была перезагрузка, чтобы Explorer запустил Far с новым значением %PATH%.
Перезагрузите систему, всё должно заработать.


text:
Q: Is there a way to know the reason the app was launched? In my custom Application class, I want to know the reason that the app was launched. For example, was it launched because of a remote notification, the user launched the app directly, etc.
On iOS, When the application launches I can use the LaunchOptionsKey in the application(_:didFinishLaunchingWithOptions:) method in order to know the reason the app was launched.

launchOptions.
A dictionary indicating the reason the app was launched (if any).

Is there any equivalent on Android?


text:
Q: AWS S3 403 access denied issue with nodeJS The following is my bucket policy
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "AddCannedAcl",
            "Effect": "Allow",
            "Principal": {
                "AWS": "==mydetails=="
            },
            "Action": [
                "s3:PutObject",
                "s3:PutObjectAcl"
            ],
            "Resource": "arn:aws:s3:::etcetera-dev/*",
            "Condition": {
                "StringEquals": {
                    "s3:x-amz-acl": "public-read"
                }
            }
        }
    ]
}

This is my Iam user inline policy
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "s3:ListAllMyBuckets",
                "s3:PutObject",
                "s3:GetObject",
                "s3:PutObjectAcl"
            ],
            "Resource": [
                "arn:aws:s3:::*"
            ]
        }
    ]
}

Now I'm trying to upload a file using multer-s3 with acl:'public-read' and I am getting 403 access denied. If I don't use acl property in multer, I am able to upload with no issues.

A: You may have fixed this now, but if you haven't, there a many different possible fixes (See: https://aws.amazon.com/premiumsupport/knowledge-center/s3-troubleshoot-403/).
But I ran into the same problem, and what fixed it for me was the following.
I presume you're calling s3.upload() when trying to upload your file. I found that if there is not Bucket parameter within your upload() options, you will also receive a 403.
i.e ensure your upload() call is as the following:
await s3.upload({
  Bucket: // some s3Config.Bucket
  Body: // Stream or File,
  Key: // Filename,
  ContentType: // Mimetype
}).promise();

Bucket: // some s3Config.Bucket - I was missing this param in the function-call as I thought that new AWS.S3(config) handled the bucket. Turns out, you should always add the bucket to your upload params.


text:
Q: torquebox for production. Anyone? I want to migrate my infrastructure to jRuby. The most complete options as I see is torquebox. Anyone can share something about it? compared to tomcat/jetty?

A: We are using Torquebox 2.x with Sunspot/Solr for a number of search based websites for the NHS (UK). These sites have very high page views and caching is difficult so mostly we serve dynamic content.
I would highly recommend JRuby/Torquebox

*

*Torquebox has excellent support via IRC and the Mailing list

*Torquebox is open source, but commerically backed by Redhat

*Torquebox makes infrastructure easy, no separate message queue, background processes out of the box etc. etc.

*JRuby is threadsafe and fast

*JRuby has access to all the Java libraries (we use jsoup, fly saucer for PDF generation)

A: I am using TorqueBox 1.0 Release Candidate for 24x7 mission critical production solutions.  It has been adopted as the platform of choice for all new development on my project, replacing a very expensive commercial ESB.  Although HornetQ is not (yet) replacing our business's enterprise JMS provider, we are using HornetQ heavily to a growing collection of loosely coupled JRuby components.
In my view, TorqueBox is a superb blend of a world class application server with high-availability features built-in, a high performance messaging server (HA-JMS, HA-JNDI), and my favorite programming language.
As a bonus, my productivity has soared since working almost exclusively in JRuby.

A: We also use jboss AS7 (not Torquebox) with HornetQ and a mixed jruby java environment in critical projects for production. Assynchronous processes a treated in java in the background, the rest in jruby on rails (frontend stuff - user interaction)
It will go live this year.


text:
Q: Deformed drawables in runtime I am using drawables (exported from an SVG) in my app.
For android > 23 everything is all right, they are shown correctly, but in android <= 23 (particularly, the image attached is from android sdk version 23), the vector is deformed, showing edges that does not appears in drawables preview.

This happen in SOME devices, not in everyone, and in android <= 23, as I said before.
I have test a google material design icon svg and works perfectly in the same device, so, it cannot be fault of the android version.
Do you have any idea?
EDIT:
This is the code of the drawable exported by Android Studio:
<vector xmlns:android="http://schemas.android.com/apk/res/android"
        android:width="24dp"
        android:height="24dp"
        android:viewportWidth="24.0"
        android:viewportHeight="24.0">
    <path
        android:pathData="M12,21a0.473,0.473 0,0 1,-0.336 -0.139l-7.95,-7.955a5.782,5.782 0,0 1,-1.25 -1.808,5.788 5.788,0 0,1 -0.459,-2.528c0.12,-2.92 2.398,-5.307 5.298,-5.551 1.722,-0.142 3.473,0.529 4.696,1.777 1.224,-1.248 2.976,-1.92 4.697,-1.777 2.9,0.244 5.179,2.63 5.299,5.551a5.788,5.788 0,0 1,-0.46 2.528,5.79 5.79,0 0,1 -1.248,1.808l-7.951,7.955a0.474,0.474 0,0 1,-0.337 0.139zM7.77,3.958A4.851,4.851 0,0 0,2.957 8.61c-0.03,0.734 0.099,1.444 0.382,2.111a4.827,4.827 0,0 0,1.046 1.506L12,19.845l7.616,-7.619a4.827,4.827 0,0 0,1.045 -1.506,4.839 4.839,0 0,0 0.383,-2.11 4.851,4.851 0,0 0,-4.426 -4.636c-1.572,-0.132 -3.18,0.555 -4.21,1.794 -0.169,0.275 -0.622,0.283 -0.802,0.016A5.026,5.026 0,0 0,7.77 3.958z"
        android:fillColor="#000"/>
</vector>

And the other drawable:
<vector xmlns:android="http://schemas.android.com/apk/res/android"
        android:width="24dp"
        android:height="24dp"
        android:viewportWidth="24.0"
        android:viewportHeight="24.0">
    <path
        android:pathData="M16.466,15.396a7.306,7.306 0,0 0,2.01 -5.02c0,-4.062 -3.354,-7.367 -7.476,-7.367s-7.476,3.305 -7.476,7.367A7.292,7.292 0,0 0,5.536 15.4L11,20.782l5.466,-5.386zM17.202,16.098l-5.84,5.754a0.517,0.517 0,0 1,-0.724 0l-5.837,-5.751a8.315,8.315 0,0 1,-1.567 -2.322,8.176 8.176,0 0,1 -0.734,-3.403C2.5,5.757 6.313,2 11,2c4.687,0 8.5,3.757 8.5,8.376a8.181,8.181 0,0 1,-0.735 3.405,8.332 8.332,0 0,1 -1.563,2.317zM11,7.054c1.858,0 3.37,1.49 3.37,3.322 0,1.831 -1.512,3.32 -3.37,3.32s-3.37,-1.49 -3.37,-3.32c0,-1.832 1.512,-3.322 3.37,-3.322zM11,8.063c-1.293,0 -2.347,1.038 -2.347,2.312 0,1.274 1.054,2.312 2.347,2.312s2.345,-1.037 2.345,-2.31c0,-1.275 -1.053,-2.314 -2.345,-2.314z"
        android:fillType="nonZero"
        android:fillColor="#000"/>
</vector>


text:
Q: Issue with drag and drop I use the following code to drag and drop a file into a c# winforms application. The issue I have is that the DragDrop event handler takes a while, and during this time I can't use the window from which I dragged the file. How can this be fixed?
private void FormMain_DragDrop(object sender, DragEventArgs e)
{
    string[] s = (string[])e.Data.GetData(DataFormats.FileDrop, false);
    // do some long operation
}

private void FormMain_DragEnter(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(DataFormats.FileDrop))
    e.Effect = DragDropEffects.All;
else
    e.Effect = DragDropEffects.None;
}

A: You may use a BackgroundWorker to do the operation that you need in different thread like the following :
    BackgroundWorker bgw;

    public Form1()
    {
        InitializeComponent();
        bgw = new BackgroundWorker();
        bgw.DoWork += bgw_DoWork;
    }

    private void Form1_DragDrop(object sender, DragEventArgs e)
    {
        if (e.Data.GetDataPresent(DataFormats.FileDrop))
        {
            string[] s = (string[])e.Data.GetData(DataFormats.FileDrop, false);
            bgw.RunWorkerAsync(s);
        }

    }

Also for your issue "cross thread operation", try to use the Invoke Method like this :
    void bgw_DoWork(object sender, DoWorkEventArgs e)
    {
        Invoke(new Action<object>((args) =>
        {
            string[] files = (string[])args;

        }), e.Argument);
    }

Its better to check if the dropped items are files using GetDataPresent like above.

A: You can use a background thread for this long-running operation, if it is not ui-intensive.
ThreadPool.QueueUserWorkItem((o) => /* long running operation*/)


text:
Q: serverSocket cannot be creater - Java I'm writing a Server:
Server.java
package server;

import java.net.ServerSocket;
import java.net.Socket;
import java.util.Observer;
import java.util.Vector;
import java.util.Observable;
import java.io.IOException;
//import java.io.*;

public class Server implements Observer {
    private Socket socket;

/** This vector holds all connected clients.
 * May be used for broadcasting, etc. */
private Vector<ClientThread> clients;
private ServerSocket ssocket;  //Server Socket
private StartServerThread sst; //inner class

/**
 * Represents each currently connected client.
 * @label initiates
 * @clientCardinality 1
 * @supplierCardinality 0..*
 */
private ClientThread clientThread;

/** Port number of Server. */
private int port;
private boolean listening; //status for listening

public Server() {
    this.clients = new Vector<ClientThread>();
    this.port = 5555; //default port
    this.listening = false;
}

public void startServer() {
    if (!listening) {
        this.sst = new StartServerThread();
        this.sst.start();
        this.listening = true;
    }
}

public void stopServer() {
    if (this.listening) {
        this.sst.stopServerThread();
    //close all connected clients//

        java.util.Enumeration<ClientThread> e = this.clients.elements();
        while(e.hasMoreElements())
        {
        ClientThread ct = (ClientThread)e.nextElement();
            ct.stopClient();
        }
        this.listening = false;
    }
}

//observer interface//
public void update(Observable observable, Object object) {
    //notified by observables, do cleanup here//
    this.clients.removeElement(observable);
}

public int getPort() {
    return port;
}

public void setPort(int port) {
    this.port = port;
}

/** This inner class will keep listening to incoming connections,
 *  and initiating a ClientThread object for each connection. */

  private class StartServerThread extends Thread {
    private boolean listen;

    public StartServerThread() {
        this.listen = false;
    }

    public void run() {
        this.listen = true;
        try {

/**The following constructor provides a default number of
 * connections -- 50, according to Java's documentation.
 * An overloaded constructor is available for providing a
 * specific number, more or less, about connections. */

Server.this.ssocket =
                      new ServerSocket(Server.this.port);
                    System.out.println(TimeStamp.getTimeStamp() + " " + "Server socket created");

               while (this.listen) {
                   //wait for client to connect//

              Server.this.socket = Server.this.ssocket.accept();
                System.out.println(TimeStamp.getTimeStamp() + " " + "Client connected");
                try {
                    Server.this.clientThread =
                         new ClientThread(Server.this.socket);
                    Thread t =
                         new Thread(Server.this.clientThread);
                                      Server.this.clientThread.addObserver(Server.this);
                    Server.this.clients.addElement(
                       Server.this.clientThread
                          );
                    t.start();
                } catch (IOException ioe) {
                    //some error occurred in ClientThread //
                }
            }
        } catch (IOException ioe) {
            //I/O error in ServerSocket//
            this.stopServerThread();
        }
    }

    public void stopServerThread() {
        try {
            Server.this.ssocket.close();
        }
        catch (IOException ioe) {
            //unable to close ServerSocket
        }

        this.listen = false;
    }
}
}

I run the server in Main.java:
package server;

public class Main {

    public static void main(String[] args) {
        System.out.println("Main()\n");
        Server server = new Server();
        server.startServer();
    }
}

In the first time I run it, everything was fine.
Now from some reason I see that the ServerSocket cannot be created.
The dubbuging flow goes right to the catch block of the block that tries to create new ServerSocket.
I get in eclipse console:

Main()
Exception in thread "Thread-0" java.lang.NullPointerException     at
  server.Server$StartServerThread.stopServerThread(Server.java:127)     at
  server.Server$StartServerThread.run(Server.java:121)


text:
Q: Scaling of the hazard function and relationship with variance Say I have some random variable with known mean $\mu$, known variance $\sigma^2$ and known hazard function $\lambda(t)$. Is there a closed form expression for the variance of the random variable with hazard function $c\lambda(t)$ where $c>0$ is some constant? I wonder whether this might have been explored in relation to proportional hazards models...

A: The complementary CDF of the random variable $X$ with hazard rate $\lambda(t)$ is
$$1- F_X(x) = \exp\left(-\int_0^x \lambda(t) \,\mathrm dt\right).$$
The complementary CDF of the random variable $Y$ with hazard rate $c\lambda(t)$ is
\begin{align}
1-F_y(x) &= \exp\left(-\int_0^x c\lambda(t) \,\mathrm dt\right)\\
&= \left[\exp\left(-\int_0^x \lambda(t) \,\mathrm dt\right)\right]^c\\
&= \big[1- F_X(x)\big]^c.\end{align}
Thus,
$$f_Y(x) = -\left.\left.\frac{\mathrm d}{\mathrm dx}\right[1- F_Y(x)
\right] = c\big[1- F_X(x)\big]^{c-1}f_X(x)$$
showing that it is not a simple relation such that knowing the mean and variance of $X$ allows us to easily deduce that the mean and variance of $Y$ are; one needs to put in more work and perhaps consider specific examples of hazard rates to find the answer. Of course, a simple example of where very little effort is needed is the case of constant hazard rates when both $X$ and $Y$ are exponential random variables.


text:
Q: unfortunately k9-email has stopped I am trying to run K9 email android app in my emulator winXP using eclipse indigo. My project is completely error free but when i am running it in then whenever emulator launches then this error comes. "unfortunately k9-mail has stopped" in emulator.
apk installed in emulator successfully but i am receiving this error in logcat-:
03-10 16:30:23.620: E/AndroidRuntime(812): java.lang.RuntimeException: Unable to instantiate application com.fsck.k9.K9: java.lang.ClassNotFoundException: Didn't find class "com.fsck.k9.K9" on path: /data/app/com.fsck.k9-1.apk and
unfortunately k9mail has stopped message in emulator.. please do help.

A: The solution is to use the latest Oracle JAVA SE 6 JDK to run Eclipse/to build the apk. Java SE 7 DOES NOT work.


text:
Q: * is not collapsed even though
* are floated? What I know so far is that a parent with nothing but floated children has no height.
In the header for example, I have the left logo floated and the text has an absolute position. The only thing keeping the header from collapsing is the right logo.

header {
  position: relative;
  font-family: "Felix Titling Regular", Times, serif;
  border-bottom: 2px double white;
  font-size: 0;
}

header a {
  display: inline-block;
}

header>a:first-child {
  position: relative;
  padding-left: 3%;
}

header>a:last-child {
  float: right;
  padding-right: 3%;
}

#center-wrapper {
  position: absolute;
  left: 50%;
  top: 25%;
  font-size: 16px;
}

header h1 {
  font-size: 300%;
  display: inline-block;
  position: relative;
  text-transform: capitalize;
  right: 50%;
}

 loyal capos to the don

However, I don't understand why my first parent 'ul' in the 'nav' still has height even though all the li elements are floated.

nav {
  position: relative;
  border-top: 2px double #660000;
  text-align: center;
  font-size: 0;
  background-color: #660000;
}

nav>ul {
  display: inline-block;
  font-size: 16px;
  width: 100%;
}

ul {
  list-style-type: none;
}

nav>ul>li {
  min-width: 20%;
  float: left;
}

nav ul ul,
nav ul ul ul {
  position: absolute;
  display: none;
  width: 100%;
}

nav>ul>li:hover>ul {
  display: block;
}

nav>ul>li>ul>li:hover>ul {
  left: 100%;
  top: 0%;
  display: block;
}

ul>li {
  position: relative;
  padding: .4em 0;
  background-color: white;
}

li>a {
  color: #660000;
  text-decoration: none;
  text-transform: capitalize;
  font-size: 150%;
  font-family: "Felix Titling Regular", Times, serif;
  background-color: white;
}

wiki

media

images

videos

best scenes

bloopers

home

facts

about

feedback

contact us

Here's my code on fiddle (https://jsfiddle.net/vwb6g740/1/)

A: This is true for block elements and inline elements, but not for inline-block elements.

What I know so far is that a parent with nothing but floated children has no height.

You have display:inline-block; set on that parent element.
I can't explain why, but I can reproduce that behavior.

p {
  display: inline-block;
  background: blue;
}

div {
  background: red;
}

span {
  background: green;
}

i {
  float: left;
}

test

test

test


text:
Q: Outlook not displaying a portion of HTML The Issue
I am writing a new form handler, every step of the process is automated, I manage what fields show on the form using a CMS and then that information will appear on the email when it is sent to the recipient.
Every step of this is working, except for actually sending the data collected in the form. This was working before when the data was static but now that it is dynamic the information doesn't appear on the email.
The weird thing about it is that the information is actually being sent, but just isn't displaying in Outlook, I assume some part of the HTML fails to render somehow but I've exhausted all of my thoughts and need some fresh ideas.
In case it is of any use I am using Outlook 2016.
What does the email look like in Outlook?
I've provided an image below, please note the blank area under 'Contact Information'.

How do I know the information is being sent?
When I view the email in a web-browser I can see all of the information on the email, this is what it looks like:

The HTML

{:formName:}

{:formIntro:}

Contact information:

        {:formData:}

{:formMessage:}

The PHP
$html = str_replace('{:formName:}', $form['name'], $html);
$html = str_replace('{:formIntro:}', $form['intro'], $html);
$html = str_replace('{:formData:}', $input_data, $html);
$html = str_replace('{:formMessage:}', $message_data, $html);

The Output

Contact

Lorem ipsum...

Contact information:

name	Mark Overton

email	test@test.com

title	Mr

phone	777777777

message	TEst

What I've tried

*

*Taking out portions of the template.

*Double-checking all of the generated HTML.

*Scanning through the HTML template for broken tags.

*Removing surrounding div's.

*Double-checked all of the CSS.

*Banging my head against a wall.

What do I need from you?
Ideas, anything that you think could be causing this issue.
I am happy to provide whatever information you think might be useful but at this stage I'm not sure what that is, I'm not sure if anyone has had a similar issue in the past and would be able to point me in the right direction.

A: Finally worked this out:
The reason it was hidden in Outlook was because of the following code in my template:


text:
Q: JqueryMobile 1.3 ICONS not appearing? I am creating a mobile application for android on Codio online IDE, and im using jquery mobile. I downloaded the latest Version: 1.3.0's .js  &  .css, but when I run it, all seems to work except JQM icons. NONE of the JQM icons appears, while the dark circles should host various white icons.
How to make JQM icons appears ?

Edit: Answer: search, download, and deploy to the correct place the Zip File: jquery.mobile-1.3.0.zip (JavaScript, CSS, and images). Available on http://jquerymobile.com/download/

A: you are missing the icons files. they are referenced in the CSS in your case it's the https://d.codio.com/hugolpz/Cat-in-migration/App/css/images/icons-18-white.png that is missing


text:
Q: Prove that this holomorphic function is constant Suppose $f$ is a non-vanishing continuous function on $\bar{\mathbb{D}}$ that is
holomorphic in $\mathbb{D}$. Prove that if
$$|f(z)|=1~~~\text{whenever}~~~|z|=1$$
then $f$ is constant.
I have proved this by showing that the function
$$F(z)=\left\{\begin{array}{cc}f(z)&\text{when}~~|z|\leq1\\ 1/\bar{f}(\bar{z})&\text{otherwise}\end{array}\right.$$
is bounded and entire.
Is there any other more elegant way to do this problem, because my method is turning out to be too gruesome for this beautiful problem.
Thanks in advance!

A: According the Maximum Modulus Principle we have $\vert f(0)\vert\leq 1$.
But since $f$ does not vanish, the function $z\mapsto1/f(z)$ satisfies the same conditions as $f$ and consequently we have also $\left\vert \frac{1}{f(0)}\right\vert\leq 1$, or equivalently $\vert f(0)\vert\geq 1$.
Combining these two inequalities we get $\vert f(0)\vert = 1$, and the Maximum Modulus Principle implies in this case that $f$ is constant since it attains its maximum inside $\Bbb{D}$.


text:
Q: Draw box with colored background and linebreaks which adjusts to the text width? I want to draw labels on a photograph. The labels will only contain 1..3 words, and sometimes there shall be a linebreak, e. g.
Big House \newline
(empty)

Is it possible to create a box which draws a white rectangle below this text and which adapts to the width of the text?
I could use \colorbox{white}{Big House \newline (empty)}, but it does not allow the linebreak.
If I use a \parbox{}, I have to define the width by hand.
Is there a box with a colored background, which can itself adapt its width to the longest text and contain linebreaks or paragraphs?

A: \newcommand{\overbox}[2][l]{%
  \colorbox{white}{\begin{tabular}{@{}#1@{}}#2\end{tabular}}%
}

\overbox{Big House \\ (empty)}

One can also say
\overbox[c]{Big House \\ (empty)}

to get lines centered with respect to one another.
Example

A: You could use the varwidth environment provided by the homonymous package; this environment is an analogue of minipage, but its resulting width is the natural width of its contents. A little example:
\documentclass{article}
\usepackage{varwidth}
\usepackage{xcolor}
\usepackage{lipsum}

\newcommand\MyCBox[1]{%
  \colorbox{red!60}{\begin{varwidth}{\dimexpr\linewidth-2\fboxsep}#1\end{varwidth}}}

\begin{document}

\noindent\MyCBox{Big House\\ (empty)}

\noindent\MyCBox{Big House and some more text\\ (empty)}

\noindent\MyCBox{Big\\ (empty)}

\noindent\MyCBox{\lipsum[1]}

\end{document}


text:
Q: Bootstrap Tabs how to tell which tab is the active one in jQuery? There's a similar thread about this, but it's in AngularJS. How do I tell which tab in the Bootstrap 3 Tabs as the "active" one in jQuery only?
thanks.

A: You can grab the active tab by doing:
$('.nav').find('li.active')

You can easily replace the .nav with the selector that will identify the UL tag surrounding your tabs.


text:
Q: I need help for slice puzzle game This is define the code for move number
def move(pos,empty,board):
        m = pos[0]//
        n = pos[1]
        if empty == (m-1,n) or empty == (m+1,n)or empty == (m,n-1) or empty == (m,n+1):
                 board[empty[0]][empty[1]] = num
                 board[m][n] = 0
                 empty = (m,n)
        else :
                print('can\'t move! try again.')

The result:
Traceback (most recent call last):
  File "<pyshell#3>", line 1, in <module>
    sliding_puzzle()
  File "C:\Users\sungod\Desktop\과제.py", line 57, in sliding_puzzle
    (empty,board)=move(pos,empty,board)
  File "C:\Users\sungod\Desktop\과제.py", line 35, in move
    m = pos[0]
TypeError: 'NoneType' object is not subscriptable

A: line 35, in move m = pos[0] TypeError: 'NoneType' object is not subscriptable

If an object is not subscriptable it does not have any of these forms:
string:  "foobar"[3] == "b"
tuple:   (1,2,3,4)[3] == 4
list:    [1,2,3,4][3] == 4
dict:    {"a":1, "b":2, "c":3}["c"] == 3

which means pos is not any of those. My best guess from what you actually provided here..


text:
Q: role="presentation" on H1 Using the following HTML
<!DOCTYPE html>

<title>Headings</title>

Heading 1

Heading 2

Not Heading 1

ChromeVOX announces "Not Heading 1" as a Heading 1
validator.w3.org Warns:
Warning: Consider using the h1 element as a top-level heading only (all h1 elements are treated as top-level headings by many screen readers and other tools).
From what I gather from http://www.w3.org/TR/aria-in-html/#presentation
I thought role="presentation" would remove the semantic value form the h1 element.
Is this the correct expectation from ChromeVox and validator.w3.org?

A: For elements with no required children (like h1, h2, etc..), any elements nested inside the element with role=presentation preserve their semantics.
However for elements with required children (such as ul or table) any required child elements nested inside the element with role=presentation also have their semantics removed.


text:
Q: Python: Renaming columns with pandas Why isn't my attempt to rename columns working? I could swear I am following the right syntax and I am not getting any errors... it's simply not doing it.
import numpy as np
import pandas as pd
header = list(range(17))
energy = pd.read_excel('Energy Indicators.xls',
                       usecols = [2, 3, 4, 5],
                       skiprows = list(range(17)),
                       skipfooter = 38)

energy.rename(columns={'Unnamed: 2': 'Country',
                       'Petajoules': 'Energy Supply',
                       'Gigajoules': 'Energy Supply per Capita',
                       '%': '% Renewable'})

A: What you are missing is inplace=True to rename and apply on the original dataframe object.
Note: inplace=True returns None inplace=False returns a copy of the object with the operation performed.
import pandas as pd

df_sorted = pd.DataFrame({'duration':[1,0,2,0],'Count':[23,23,2,1]})
df_sorted.rename(columns={'duration':'NewName'},inplace=True)
print(df_sorted)

A: You have two options. You can re-assign the output of energy.rename() by using energy=energy.rename() or you can add the optional argument inplace=True.
From the documentation for DataFrame.rename:

inplace : bool, default False
Whether to return a new DataFrame. If True then value of copy is ignored.

A: You have two options for rename

*

*Update with the result or here directly return it because you don't modify it then

energy = energy.rename(columns={'Unnamed: 2': 'Country', 'Petajoules': 'Energy Supply',
                                'Gigajoules': 'Energy Supply per Capita', '%' : '% Renewable'})

return energy.rename(columns={'Unnamed: 2': 'Country', 'Petajoules': 'Energy Supply',
                              'Gigajoules': 'Energy Supply per Capita', '%' : '% Renewable'})

*Change the current object

energy.rename(columns={'Unnamed: 2': 'Country', 'Petajoules': 'Energy Supply',
                       'Gigajoules': 'Energy Supply per Capita', '%': '% Renewable'},
              inplace=True)

A: You dont necessarily need inplace=True. you just have to save it back to your original df
energy = energy.rename(columns={'Unnamed: 2': 'Country',
                   'Petajoules': 'Energy Supply',
                   'Gigajoules': 'Energy Supply per Capita',
                   '%': '% Renewable'})


text:
Q: Как переставить элементы массива в указанном порядке? a1, an+1, a2, an+2, ... , an, a2n
Задан массив целых чисел a размером 2n. Как сделать перестановку в массиве таким образом?

A: Раз устраивает медленный O(N2) способ, то просто поочередно сдвигаем элементы в нужную позицию:
#include <vector>
#include <iostream>

using namespace std;

int main(int argc, char * argv[])
{
    const int N = 10;

    vector<int> a(2*N);
    for(int i = 0; i < 2*N; ++i) a[i] = i+1;

    for(int i = 0; i < 2*N; ++i) cout << a[i] << " "; cout << "\n";

    for(int i = N; i <= 2*N-2; ++i)
    {
        for(int j = 0, k = i; j < 2*N-i-1; ++j,--k)
        {
            swap(a[k],a[k-1]);
        }
    }

    for(int i = 0; i < 2*N; ++i) cout << a[i] << " "; cout << "\n";
}


text:
Q: Problem with congruence equation $893x \equiv 266 \pmod{2432}$ I'm trying to solve $893x \equiv 266 \pmod{2432}$.
Firstly, I find the $\operatorname{gcd}(893, 2432)$ using the extended Euclidean Algorithm. When I calculate this, I receive that the gcd is (correctly) $19$, and that $19 = 17(2432) -49(893)$. From this, I know that there are $19$ distinct solutions.
I then divide my above, initial congruence by the gcd, obtaining $47x \equiv 14 \pmod{128}$.
I know that $\operatorname{gcd}(129, 47) = 1$ and that $1 = 18(128) - 49(47)$.
Therefore $14 = 14(18)(128)  -14(49)(47)$.
This implies that a solution to the congruence $47x \equiv 14 \pmod{128}$ is $x = -14(49) = -686$.
$-686 ≡ 82 \pmod{128}$, so I substitute $x = -14(49)$ for $x = 82$.
From this, I gather then that the solution to the congruence is $82 + 128t$, where $t$ is one of $0,1,2,...,18$. However, I believe this is not correct.
Where did I go wrong, and how might I go about fixing this?
Thank you so much!

A:
Where did I go wrong ?

Nowhere.

How might I go about fixing this ?

There's nothing to fix.

However, I believe this is not correct.

Next time, have more faith in yourself. ;-$)$

A: $\textrm{After carrying Euclidean Algorithm on 893 and 2432, we get their H.C.F. 19, and then go backwards} \\ \textrm{step by step to get a particular solution.}$
$\therefore 893 ( - 49 ) + 2432 \times 18 = 19$
$\left. {\Rightarrow  893(- 49 \times 14 ) + 2432 ( 18 \times 14) = 19\times 14 } \right.$
$\therefore 893 ( - 49 \times 14 + 128 n ) + 2432 ( 18 \times 4 +47n)=266$
$\textrm{Hence }x= - 686 + 128 n,  \text{where }n\in Z.$
$\textrm{ i.e. }x= 82 + 128 n, \text{where }n\in Z.$


text:
Q: Is it safe to use length instead of ==""? Is it safe to use length property instead of =="" for empty string validation?
Is it valid on all bool operators?
It might be a very simple question and I am pretty sure that the answer is a yes/yes, but I am using it a lot recently and I am a bit worried about any possible pitfall.
For completeness, here is a simple example
var valid = name.length && (foo.length||bar.length);

A: It is always safe to use .length IF you know for sure that you have something in the variable that can have properties (like a string).
But, if the variable might be undefined or null, then .length will not be valid and will not do what you want and name === "" would be safer.
Many Javascript developers simply do:
if (name) {
    //
}

This checks for any truthy value in name.  So, the if will not be satisfied if name is undefined, null or even an empty string "" and, in some cases, protects your code a bit more than what you were doing.

Or, in your example, you could perhaps just do:
var valid = name && (foo || bar);

This will require name and either foo or bar to be truthy.  This won't protect against name, foo or bar being some type of data without a .length property like your original code would, but it would do a better job of protecting against any of these variables being undefined or null.
Remember that an empty string "" is a falsey value so you can use that to your advantage in boolean comparisons.


text:
Q: onStartTemporaryDetach() in View The android docs says

This is called when a container is going to temporarily detach a
  child, with ViewGroup.detachViewFromParent.

Now what is this "temporary detach" and "permanent detach". When exactly is this method called?
I am using TextureView and i found that this method gets called before onSurfaceTextureDestroyed on the TextureView when i open a new Activity(Activity 2) from the TextureView's screen(Activity 1) but it doesnt get called when i close the Activity 1 using the back button.


text:
Q: Android emulator doesn't load I am learning Android studio  right now, by following a tutorial series. I created a new project and just added (and formatted) a button in content_main.xml. I also created a new layout resource file named new_layout. I have not coded anything yet, but when I run the program in the emulator, the emulator is stuck on a screen with the google 'G' logo, loading infinitely. Even though the gradle build has finished, the Android emulator is not opening and just keeps loading. Please help.

A: Turns out the virtual device had some problem, so making a new virtual device in the AVD Manager fixed it.


text:
Q: Java OutofMemory Strange Error I have started my jar from command line using following command
java -Xms1200m -Xmx1500m -jar xxx.jar

and I am creating BufferedImage which is in size 12600 * 12600 means it requires
606 MB of memory in following code
TranscoderInput input = new TranscoderInput(sr);

            String pngFile = "Style-" + shoeViewer.getCurrentStyle() + "_"
                    + shoeViewer.getSelectedMetadata().getSizeLabel()
                    + "_400DPI" + ".png";

            File outputFile = new File(pngFile);

            FileOutputStream fo = new FileOutputStream(outputFile);

            TranscoderOutput output = new TranscoderOutput(fo);

            long now = System.currentTimeMillis();

            t.transcode(input, null);

when I am debugging memory usage before executing above lines , my Runtime shows
I need 606 MB of memory and 1100 MB is still free .
So when I run above codes after 34 mins it throws OutOfMemory Exception .
what is the problem  ? is it process problem or heap problem ? why it takes 34 minutes ??
My PC configuration is following
Windows 32bit XP Service Pack2 Home Edition
Amd Athlon (tm) 7750 Dual Core 2.71 GHz
2GB of DDR2 RAM
java version "1.7.0_17"
Java(TM) SE Runtime Environment (build 1.7.0_17-b02)
Java HotSpot(TM) Client VM (build 23.7-b01, mixed mode, sharing)

please, help me solve out this problem.
below is the exception stack tarce with debugging messages.
before running above code i changed VM argument to following
java -Xms900m -Xmx1024m -XX:MinHeapFreeRatio=40 -XX:MaxHeapFreeRatio=70 -jar myjar.jar

Building XML Document from SVG Reader....
 Build completed of XML Document from SVG Reader....
 Converting modified XML Document to String Writer....
 Conversion complete of modified XML Document to String Writer....
 claimedBytes 766 Avaialbel Bytes 900189232
 Memory Statastics------------------------
Total memory is bytes: 912326656         Total memory is megabytes: 870
Used memory is bytes: 9308384    Used memory is megabytes: 8
Freememory is bytes: 900189096   Free memory is megabytes: 858

transcoding started at :Sun Mar 24 11:09:59 IST 2013
Exception in thread "AWT-EventQueue-0" java.lang.OutOfMemoryError: Java heap spa
ce
        at java.awt.image.DataBufferInt.<init>(Unknown Source)
        at java.awt.image.SinglePixelPackedSampleModel.createDataBuffer(Unknown
Source)
        at java.awt.image.Raster.createWritableRaster(Unknown Source)
        at org.apache.batik.gvt.renderer.StaticRenderer.updateWorkingBuffers(Sta
ticRenderer.java:536)
        at org.apache.batik.gvt.renderer.StaticRenderer.repaint(StaticRenderer.j
ava:375)
        at org.apache.batik.gvt.renderer.StaticRenderer.repaint(StaticRenderer.j
ava:344)
        at org.apache.batik.transcoder.image.ImageTranscoder.transcode(ImageTran
scoder.java:111)
        at org.apache.batik.transcoder.XMLAbstractTranscoder.transcode(XMLAbstra
ctTranscoder.java:142)
        at org.apache.batik.transcoder.SVGAbstractTranscoder.transcode(SVGAbstra
ctTranscoder.java:156)
        at com.mmg.app.eventlistener.PlaceOrderActionListener.save(PlaceOrderAct
ionListener.java:302)
        at com.mmg.app.eventlistener.PlaceOrderActionListener.saveCanvas(PlaceOr
derActionListener.java:270)
        at com.mmg.app.eventlistener.PlaceOrderActionListener.actionPerformed(Pl
aceOrderActionListener.java:143)
        at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
        at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
        at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
        at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
        at javax.swing.plaf.basic.BasicButtonListener.mouseReleased(Unknown Sour
ce)
        at java.awt.Component.processMouseEvent(Unknown Source)
        at javax.swing.JComponent.processMouseEvent(Unknown Source)
        at java.awt.Component.processEvent(Unknown Source)
        at java.awt.Container.processEvent(Unknown Source)
        at java.awt.Component.dispatchEventImpl(Unknown Source)
        at java.awt.Container.dispatchEventImpl(Unknown Source)
        at java.awt.Component.dispatchEvent(Unknown Source)
        at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
        at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
        at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
        at java.awt.Container.dispatchEventImpl(Unknown Source)
        at java.awt.Window.dispatchEventImpl(Unknown Source)
        at java.awt.Component.dispatchEvent(Unknown Source)
        at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
        at java.awt.EventQueue.access$200(Unknown Source)

A: Even through the raw unencoded image would only fill around 600 MB, the internal representation in the encoder might need more memory depending on how it's implemented. The following example shows how much memory is used when scaling a simple svg file to 12600 x 12600 (32 bit).
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.OutputStream;

import org.apache.batik.transcoder.TranscoderInput;
import org.apache.batik.transcoder.TranscoderOutput;
import org.apache.batik.transcoder.image.PNGTranscoder;

public class Test {
    public static void main(String[] args) throws Exception {
        PNGTranscoder t = new PNGTranscoder();
        t.addTranscodingHint(PNGTranscoder.KEY_WIDTH, new Float(12600));
        t.addTranscodingHint(PNGTranscoder.KEY_HEIGHT, new Float(12600));
        FileInputStream fis = new FileInputStream("C:\\StackOverflow\\SVG-logo.svg");
        TranscoderInput input = new TranscoderInput(fis);
        OutputStream ostream = new FileOutputStream("C:\\StackOverflow\\res.png");
        TranscoderOutput output = new TranscoderOutput(ostream);

        System.out.println("AllocatedMemory: \t" + (Runtime.getRuntime().totalMemory() / 1024) + " Kb");
        t.transcode(input, output);
        System.out.println("AllocatedMemory: \t" + (Runtime.getRuntime().totalMemory() / 1024) + " Kb");

        ostream.flush();
        ostream.close();

    }
}

On my machine the output is:
AllocatedMemory:    4096 Kb
AllocatedMemory:    1677721 Kb

So here the program uses 1677 MB to transcode a simple SVG file to a 12600 * 12600 PNG file.


text:
Q: Apollo Graphql - Send query to multiple hosts serving same schema but subset of data I have 2 graphql services, each serving a subset of data with the same schema.
Service1 has a list of Users with ID 1-10,000
Service2 has a list of Users with ID 10,001-20,000

My User Type looks like
type User {
  id: ID!
  name: String!
}

Each service has a graphql query to resolve a user.
type Query {
  fetchUser(id: ID!): User
  fetchUsers: [User!]
}

Is there a way that apollo can query both services and merge the results,
So I dont have to query each service individually?


text:
Q: android Expandable ListView on ChildClick Listner is not working I have an ExpandableListView the List is working so well but i want to when i click on Childs a clock icon change color and do something and save that but when i click on child the first clock  first child do the work but when i scroll down a random child or maybe 2 o 3 of them will change the color too and it will be save if i close the app this os my adapter code
public class exTourListAdapter extends BaseExpandableListAdapter {

private Context context;
private ArrayList<GroupTour> groups;
private int count;
SharedPreferences preferences;
AppCompatTextView timeTour ,tvPrize ,tvGameMode,tvBuyIn,tvLateReg
,tvReBuy,tvDays;
RelativeLayout childToursLayout;

Clock clock ;
public exTourListAdapter(Context context , ArrayList<GroupTour> groups,int count) {
    this.context = context;
    this.groups = groups;
    this.count = count;
}

@Override
public ChildTour getChild(int groupPosition, int childPosition) {
    GroupTour group = groups.get(groupPosition);
    exChild exchild = group.getChildren().get(groupPosition);
    ChildTour child = exchild.getChildTours().get(childPosition);
    return child;
}

@Override
public long getChildId(int groupPosition, int childPosition) {
    ChildTour childTour= getChild(groupPosition,childPosition);
    int id= childTour.getTourId();
    return id;
}

@Override
public View getChildView(int groupPosition, int childPosition,
                         boolean isLastChild, View convertView, ViewGroup parent) {

    ChildTour child =  getChild(groupPosition,
            childPosition);
    if (convertView == null) {
        LayoutInflater infalInflater = (LayoutInflater) context
                .getSystemService(context.LAYOUT_INFLATER_SERVICE);
        convertView = infalInflater.inflate(R.layout.ex_list_tours_child, null);
    }
    preferences = context.getSharedPreferences("timeonoff",Context.MODE_PRIVATE);

    timeTour = (AppCompatTextView) convertView.findViewById(R.id.time_tour);
    tvPrize = (AppCompatTextView) convertView.findViewById(R.id.tour_prize);
    tvGameMode = (AppCompatTextView) convertView.findViewById(R.id.tour_gamemode);
    tvBuyIn = (AppCompatTextView) convertView.findViewById(R.id.tour_buy_in);
    tvLateReg = (AppCompatTextView) convertView.findViewById(R.id.tour_late_reg);
    tvReBuy = (AppCompatTextView) convertView.findViewById(R.id.tour_rebuy);
    tvDays = (AppCompatTextView) convertView.findViewById(R.id.tour_days);
    clock = (Clock) convertView.findViewById(R.id.clock_layour);
    tvDays.setTag(child.getTourId());
    clock.setHours(child.getHour());
    clock.setMinutes(child.getMin());

    tvLateReg.setText("Late Register: "+child.getLateReg()+" min");
    int id = (int) getChildId(groupPosition,childPosition);
    if (preferences.getBoolean("time"+id,false) == true){
        clock.setClockColor(R.color.material_green_500);
    }else if (preferences.getBoolean("time"+id,true)==false){
        clock.setClockColor(R.color.material_brown_700);
    }
    if (child.getReBuy().equals("")){
        tvReBuy.setText("Rebuy: ?");
    }else {
        tvReBuy.setText("Rebuy: "+child.getReBuy());
    }
    tvDays.setText(child.getDay());
    tvBuyIn.setText("BuyIn: "+child.getBuyIn());
    tvGameMode.setText(child.getGameMode());
    tvPrize.setText(child.getPrize());
    timeTour.setText(child.getTime());
    return convertView;

}

@Override
public int getChildrenCount(int groupPosition) {
   int number = groups.get(groupPosition).getChildren().get(groupPosition).getChildNumbers();

    return number;
}

@Override
public GroupTour getGroup(int groupPosition) {
    // TODO Auto-generated method stub
    return groups.get(groupPosition);
}

@Override
public int getGroupCount() {
    // TODO Auto-generated method stub
    return groups.size();
}

@Override
public long getGroupId(int groupPosition) {
    // TODO Auto-generated method stub
    return groupPosition;
}

@Override
public View getGroupView(int groupPosition, boolean isExpanded,
                         View convertView, ViewGroup parent) {
    GroupTour group =  getGroup(groupPosition);
    if (convertView == null) {
        LayoutInflater inf = (LayoutInflater) context
                .getSystemService(context.LAYOUT_INFLATER_SERVICE);
        convertView = inf.inflate(R.layout.list_header_groups_tours, null);
    }
    TextView tv = (TextView) convertView.findViewById(R.id.tours_site_name);
    tv.setText(group.getName());
    // TODO Auto-generated method stub
    return convertView;
}

@Override
public boolean hasStableIds() {
    // TODO Auto-generated method stub
    return true;
}

@Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
    // TODO Auto-generated method stub
    return true;
}
public void onClockClick(View view){
    clock.setClockColor(R.color.material_red_300);
}

and this is my fragment code and the Clock class is the Clock Icon
public class ListToursexFragment extends Fragment {
SwipeRefreshLayout refresh;
ExpandableListView listView;
SharedPreferences.Editor editor;
SharedPreferences pref;
@Nullable
@Override
public View onCreateView(LayoutInflater inflater,
                         @Nullable ViewGroup container,
                         @Nullable Bundle savedInstanceState) {
    View view= inflater.inflate(R.layout.activity_tours,container,false);
    pref= getActivity().getSharedPreferences("timeonoff", Context.MODE_PRIVATE);
    editor =pref.edit();
    refresh = (SwipeRefreshLayout) view.findViewById(R.id.refresh_tours);
    listView = (ExpandableListView) view.findViewById(R.id.list_tours);
    refresh.setColorSchemeColors(
            R.color.material_green_200,
            R.color.material_green_400,
            R.color.material_green_600,
            R.color.material_green_800
    );
    refresh.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
        @Override
        public void onRefresh() {
            prepareData(url,listView);
        }
    });
    prepareData(url,listView);
    return view;
}

private void prepareData(String url, final ExpandableListView listView) {
    JsonObjectRequest request = new JsonObjectRequest(Request.Method.GET, url, null, new Response.Listener<JSONObject>() {
        @Override
        public void onResponse(JSONObject response) {
            try {

                JSONArray array = response.getJSONArray("sites");
                int count = response.getInt("sitescount");
                exTourParser parser = new exTourParser();
                final ArrayList<GroupTour> items = parser.Parse(array);

                exTourListAdapter adapter = new exTourListAdapter(getContext(), items,count);
                listView.setAdapter(adapter);
                listView.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
                    @Override
                    public boolean onChildClick(ExpandableListView expandableListView, View view, int i, int i1, long id) {
                        Clock clock = (Clock) view.findViewById(R.id.clock_layour);
                        boolean b= pref.getBoolean("time"+id,false);
                        if (b ==true){
                            editor.putBoolean("time"+id,false);
                            editor.commit();
                            clock.setClockColor(R.color.material_brown_700);
                        }else if (b == false){
                            editor.putBoolean("time"+id,true);
                            editor.commit();
                            clock.setClockColor(R.color.material_green_700);
                        }
                        return false;

                    }
                });
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }
    }, new Response.ErrorListener() {
        @Override
        public void onErrorResponse(VolleyError error) {
            Toast.makeText(getContext(), "ridiok", Toast.LENGTH_SHORT).show();
        }
    });
    RequestQueue quew = Volley.newRequestQueue(getActivity().getApplicationContext());
    quew.add(request);
}

and this screen shots first second only click on the first child then scroll few times then this happend black is default color

A: While you are working inside getView Method of Adapter and you are using IF condition inside it then try to have "else" also.
In your case i can see 'if' and 'else if', while

else

is missing.
if (b ==true)
{
             editor.putBoolean("time"+id,false);
             editor.commit();
             clock.setClockColor(R.color.material_brown_700);
}
else if (b == false)
{
          editor.putBoolean("time"+id,true);
          editor.commit();
          clock.setClockColor(R.color.material_green_700);
}

Can be converted to
 if (b)
    {
                 editor.putBoolean("time"+id,false);
                 editor.commit();
                 clock.setClockColor(R.color.material_brown_700);
    }
    else
    {
              editor.putBoolean("time"+id,true);
              editor.commit();
              clock.setClockColor(R.color.material_green_700);
    }


text:
Q: Search A and replace B in A|B in shell scripting/SED/AWK I have a text file with layout as:
tableName1|counterVariable1
tableName2|counterVariable2

I want to replace the counterVariable1 with some other variable say counterVariableNew.
How can I accomplish this?
I have tried various SED/AWK approaches, closest one is mentioned below:
cat $fileName | grep -w $tableName | sed -i 's/$tableName\|counterVariable/$tableName\|counterVariableNew'

But all the 3 commands are not merging properly, please help!

A: Your script is an example of [ useless use of cat ]. But the key point here is to escape the pipe delimiter which has a special meaning(it stands for OR) when used with awk FS. So below script should do
# cat 42000479
tableName1|counterVariable1
tableName2|counterVariable2
tableName3|counterVariable2

# awk -F\| '$1=="tableName2"{$2="counterVariableNew"}1' 42000479
tableName1|counterVariable1
tableName2 counterVariableNew
tableName3|counterVariable2

An alternate way of doing the same stuff is below
# awk -v FS='|' '$1=="tableName2"{$2="counterVariableNew"}1' 42000479

Stuff inside the single quote will not be expanded.

A: awk -F'|' -v OFS='|' '/tableName1/ {$2="counterVariableNew"}1' file
tableName1|counterVariableNew
tableName2|counterVariable2

This will search for A (tableName1) and replace B (counterVariable1) to counterVariableNew.
Or by using sed :
sed -r '/tableName1/ s/(^.*\|)(.*)/\1counterVariableNew/g' file
tableName1|counterVariableNew
tableName2|counterVariable2

For word bounded search:  Enclose the pattern inside \< and \> .
sed -r '/\<tableName1\>/ s/(^.*\|)(.*)/\1counterVariableNew/g' file
awk -F'|' -v OFS='|' '/\<tableName1\>/ {$2="counterVariableNew"}1' file


text:
Q: Mysql Select Count For Every Date In Month Let's say I have a table like the following:
date_upload|url_upload|status_upload
2017-11-01 |www.com   |verified
2017-12-01 |www.com   |verified
2017-13-01 |www.com   |verified
2017-11-01 |www.com   |verified

and I want result from count like this:
date_upload |count_upload
2017-01-01  | 0
2017-02-01  | 0
..........  | 0
2017-11-01  | 2
2017-12-01  | 1
2017-13-01  | 1
2017-14-01  | 0
..........  | 0
2017-31-01  | 0

The result should return a count of every date in this month, although mine records just 4.

A: Use a calendar table:
SELECT t1.date, COUNT(t2.date_upload) AS count_upload
FROM
(
    SELECT '2017-01-01' AS date UNION ALL
    SELECT '2017-01-02' UNION ALL
    SELECT '2017-01-03' UNION ALL
    ...
    SELECT '2017-01-31'
) t1
LEFT JOIN yourTable t2
    ON t1.date = t2.date_upload
GROUP BY
    t1.date;

In practice, the subquery aliased as t1 can be replaced with a bona fide calendar table containing those dates.


text:
Q: OpenMP4 - Why does calling a function multiple times makes it faster So I'm currently learning openmp4.
What I experienced is that if I call a function a 2nd time it will get significantly faster.
The omp block is inside of this function.
In my example the 1st call takes 5 seconds and the 2nd only 0,3s.
I am using the intel-icc with an Intel Xeon Phi(60cores 240Threads).
Could someone please explain why this is happening?

A: I think that is due to the OpenMP threading initialization. The creation of the threading team, and initializing each thread, etc.. This in fact is an expensive procedure.
I don't know what your code looks like, but this can also be the effect of caching. During first time, the mic will start caching the needed data. The second time: the data will already be cached and ready. But I can't confirm this until I see the code.


text:
Q: Highlighting specific parts of a customize graph I want to highlight specific parts, like this, for my graph (see code below). But in my case the highlighting (from the link above) doesn't work. The specific customized graph elements come from here.
\documentclass[border=5pt, xcolor=dvipsnames]{standalone}
\usepackage[dvipsnames]{xcolor}
\usepackage[utf8x]{inputenc}
\usepackage{tikz}\usetikzlibrary{positioning,backgrounds,calc,trees,decorations.markings,automata,angles,quotes}

\tikzset{
    myneg/.style={
        decoration={
            markings,
            mark=at position 0.5 with
                {\draw (0,0) arc (0:180:#1) (0,0) arc (180:360:#1);}
        },
        postaction=decorate
    },
    myneg/.default=6pt,
    mynode/.style={
        draw,
        circle,
        minimum size=20pt
    }
}

\pgfdeclarelayer{background}
\pgfsetlayers{background,main}

\newcommand{\convexpath}[2]{
[
        create hullnodes/.code={
                \global\edef\namelist{#1}
                \foreach [count=\counter] \nodename in \namelist {
                        \global\edef\numberofnodes{\counter}
                        \node at (\nodename) [draw=none,name=hullnode\counter] {};
                }
                \node at (hullnode\numberofnodes) [name=hullnode0,draw=none] {};
                \pgfmathtruncatemacro\lastnumber{\numberofnodes+1}
                \node at (hullnode1) [name=hullnode\lastnumber,draw=none] {};
        },
        create hullnodes
]
($(hullnode1)!#2!-90:(hullnode0)$)
\foreach [
        evaluate=\currentnode as \previousnode using \currentnode-1,
        evaluate=\currentnode as \nextnode using \currentnode+1
        ] \currentnode in {1,...,\numberofnodes} {
-- ($(hullnode\currentnode)!#2!-90:(hullnode\previousnode)$)
    let \p1 = ($(hullnode\currentnode)!#2!-90:(hullnode\previousnode) - (hullnode\currentnode)$),
        \n1 = {atan2(\x1,\y1)},
        \p2 = ($(hullnode\currentnode)!#2!90:(hullnode\nextnode) - (hullnode\currentnode)$),
        \n2 = {atan2(\x2,\y2)},
        \n{delta} = {-Mod(\n1-\n2,360)}
    in
        {arc [start angle=\n1, delta angle=\n{delta}, radius=#2]}
}
-- cycle
}

\begin{document}
\begin{tikzpicture}[node distance=1cm and 2cm]
\node[mynode, color=MidnightBlue] (b) at (0,0) {$U_3$};
\node[mynode,above=of b,color=MidnightBlue] (a) {$U_2$};
\node[mynode, above=of a,color=MidnightBlue] (h) {$U_1$};
\node[mynode,below=of b,color=MidnightBlue] (c) {$U_4$};
\node[mynode,right=of b] (d) {$$};
\node[mynode,right=of d,color=BrickRed] (e) {$W_2$};
\node[mynode,below=of e,color=BrickRed] (f) {$W_3$};
\node[mynode,above =of e, color=BrickRed] (j) {$W_1$};
\coordinate (aux) at (d.west);
\foreach \Value in {a,b,c}
    \draw (\Value) -- (aux);
\path
    pic[draw,angle radius=35pt,"\raisebox{20pt}{$\lor$}",
        angle eccentricity=1.25]
    {angle=a--aux--c};

\node[above left= -0.3 cm and  1 cm  of j,font=\scshape] {$\land$};

\draw
    (h) -- (j);
\draw[]
    (d) -- (e);
\draw[myneg]
    (c) -- (f);
\draw[myneg]
    (a) -- (j);
\fill[red,opacity=0.3] \convexpath{h,a,j}{40pt};
\end{tikzpicture}
\end{document}

Below there is the code just for the graph, in which I want to highlight specific parts:
    \documentclass[border=5pt, xcolor=dvipsnames]{standalone}
\usepackage[dvipsnames]{xcolor}
\usepackage[utf8x]{inputenc}

\usepackage{tikz}
\usetikzlibrary{positioning,decorations.markings,automata,angles,quotes}

\tikzset{
    myneg/.style={
        decoration={
            markings,
            mark=at position 0.5 with
                {\draw (0,0) arc (0:180:#1) (0,0) arc (180:360:#1);}
        },
        postaction=decorate
    },
    myneg/.default=6pt,
    mynode/.style={
        draw,
        circle,
        minimum size=20pt
    }
}

\begin{document}

\begin{tikzpicture}[node distance=1cm and 2cm]
\node[mynode, color=MidnightBlue] (b) at (0,0) {$U_3$};
\node[mynode,above=of b,color=MidnightBlue] (a) {$U_2$};
\node[mynode, above=of a,color=MidnightBlue] (h) {$U_1$};
\node[mynode,below=of b,color=MidnightBlue] (c) {$U_4$};
\node[mynode,right=of b] (d) {$$};
\node[mynode,right=0cm and 4.5cm of b,color=BrickRed] (e) {$W_2$};
\node[mynode,right= 0cm and 4.5cm of c,color=BrickRed] (f) {$W_3$};
\node[mynode,right =0cm and 4.5cm of a, color=BrickRed] (j) {$W_1$};
\coordinate (aux) at (d.west);
\foreach \Value in {a,b,c}
    \draw (\Value) -- (aux);
\path
    pic[draw,angle radius=35pt,"\raisebox{20pt}{$\lor$}",
        angle eccentricity=1.25]
    {angle=a--aux--c};

\node[above left= -0.3 cm and  1 cm  of j,font=\scshape] {$\land$};

\draw
    (h) -- (j);

\draw[]
    (d) -- (e);
\draw[myneg]
    (c) -- (f);
\draw[myneg]
    (a) -- (j);

\end{tikzpicture}

\end{document}


text:
Q: Normal and tangential components of acceleration I was asked to solve the following problem on a test:
A motorist is moving at 70 km/hour on a circular path of radius 500 meter. Determine the normal and tangential components of acceleration.
All I know from high school physics knowledge - centripetal acceleration in uniform circular motion is $\frac{v^2}{r}$. I am not sure whether this is the normal or tangential component of acceleration or none. If this is one of those two, then how to calculate the other one? What are ways to distinguish them?

A: If the speed is constant there is only normal acceleration (from the motorist to the center of the circunference).
To get both accelerations you can make:
1) Get your position vector in polar coordinates:
$$
\vec{r} = x\vec{i}+y\vec{j} =r \cos \theta \; \hat{i} + r \sin \theta \; \hat{j} = r \hat{r}.
$$
Now you can get the speed vector making the derivative with respect to time:
$$
\vec{v} = \dfrac{d\vec{r}}{dt}=\omega r \left( - \sin \theta \; \hat{i} + \cos \theta \; \hat{j}\right) = \omega r \hat{v},
$$
wehre
$$
\omega = \dfrac{d\theta}{dt}.
$$
Finally you get the acceleration
$$
\vec{a}=\dfrac{d\vec{v}}{dt}=
\omega^2 r
\left(
-\cos \theta \; \hat{i} - \sin \theta \; \hat{j}
\right)
+
r\alpha
\left( - \sin \theta \; \hat{i} + \cos \theta \; \hat{j}\right),
$$
where
$$
\alpha = \dfrac{d\omega}{dt}.
$$
Now notice that you can rewrite the acceleration in terms of the position and speed vectors:
$$
\vec{a}=
-\omega^2 r \hat{r}
+
r\alpha
\hat{v},
$$
and that's it. One of it is the normal acceleration and the other is the tangential. Who to rembember it? Easy: position vector goes from the center of the circle, so
$
-\omega^2 r \hat{r}
$
is an acceleration that goes to the center of the circle: we call it normal or radial acceleration $a_n=\omega ^2 r $. The other acceleration goes in the speed vector, and the speed is alway tangential to the circle in circular motion. Then we call ir tangential acceleration $a_t = \alpha r$.
If you go back to the original coordinates, you get what you said:
$$
a_n = \dfrac{v^2}{r}, \qquad a_t = \dfrac{dv}{dt}.
$$
In your homework notice that you hace a 70 km/h speed with no acceleration. Then one of the circular accelerations is zero. Guess what? Notice also that in a circular motion theres is ALWAYS one acceleration that MUST be non-zero.

A: In uniform circular motion the acceleration is radial (normal) of modulus v^2/r.
The tangential component is zero.

A: Tangential acceleration is acceleration parallel to the circular path. Since the velocity (this velocity is also in tangential direction) of the motorist is constant, there is no tangential acceleration.
Normal acceleration is acceleration perpendicular to the path; here it is the centripetal acceleration.


text:
Q: I added a mail account to Outlook using imap and now want to sync the agenda to iphone, is this possible? Currently I have the mail account added to both Outlook and iphone using the same imap/smtp settings.
When I add and verify the account on iPhone in "Settings -> Mail, contacts, calendars" the only sync options it allows me to select are:
Mail
Notes
There's no option to sync an agenda like when you add an Exchange mail account.
Is it possible to do this at all? If so, how?

A: The Internet Message Access Protocol (IMAP) is an Internet standard protocol used by e-mail clients to retrieve e-mail messages from a mail server over a TCP/IP connection as defined by RFC 3501.
If you wish to sync contacts & calendar entries you need to use WebDAV (CalDAV, CardDAV).
So as you have only IMAP configured on the device it allows you only to select "mail".


text:
Q: Problem with control ACTIVEX and Arctoolbox (9.3.1) on windows 7 64 bit
Possible Duplicate:
Problem with ArcToolbox tools

"one or more activex controls could not be displayed
when ever you try to open any tools from Arctoolbox it display this errors.
then go to start run -->regedit--> HKEY_CURRENT_USER\Software\Microsoft\Windows\Curre ntVersion\Internet Settings\Zones\ and delete the pseudonumeric key(L) or Rectangle shape before zone 0.
restart the arcgis , and it works"
Did anyone have ever tested this command, to resolve the problem in object?
What happens to the others programs and to OS?
Is it secure operation?