text:
Q: Task "Regarding" field not populating from subgrid in CRM 2013 I am using CRM 2013 on-premise with UR1 installed
I have a custom entity with a subgrid on it looking at related "tasks" which looks like this:

Whenever I create a task from the subgrid using the "+" button in the top right hand corner of the subgrid; the "Regarding" field of the newly created task remains blank. When it should be populated by a lookup to the record it was created from.

I have javascript on the task entity which checks the "Regarding" field to check what kind of entity it was created from (if it was created from one) and gets certain field values from the calling entity to populate fields on the task.
Since the "Regarding" field is never filled the Javascript never fires - and the fields do not populate.
When the record is saved, if the regarding field is blank (I have not manually filled it in) - it will eventually be populated by the correct record about 10 - 15 seconds later if you refresh the page. Then the correct fields will be populated and the user is able to edit the option set values and save again. This is not ideal for the user as they would like it to be one fluid action.
Is there any way around this problem?
EDIT for future browsers of this question:
Found a partial work around. If you use an "Activity" subgrid rather than a "Task" subgrid the field will populate. This has a drawback though as you cannot edit the "Activity" subgrid's view to show "Task" specific fields.

A: Ran into this same issue. The way I got around it was to add a look-up to the custom entity on the form (we put this on a hidden tab). When the Task gets created from the custom entity the look-up will be populated. You can then use that look-up to grab the values that you need to populate, including the regarding field. Not the most elegant, but it works.

A: I also ran into this problem and went with a pure JS approach to resolving.  On load of the task form, call populateRegarding().
This works because even though the regarding lookup doesn't populate by default, the query string parameters include _CreateFromType and _CreateFromId values.
This works in 2015, didn't test on earlier versions.  Note that it is unsupported.

function populateRegarding() {
  var regarding = Xrm.Page.getAttribute("regardingobjectid"),
    createFromType = Xrm.Page.context.getQueryStringParameters()._CreateFromType,
    createFromId = Xrm.Page.context.getQueryStringParameters()._CreateFromId;

  if (!createFromId || !createFromType ||
      !regarding || regarding.getValue() !== null) {
    return;
  }

  var entityLogicalName = getEntityLogicalNameFromObjectTypeCode(createFromType);

  regarding.setValue([{
    id: createFromId,
    entityType: entityLogicalName,
    name: "Hardcoded Name" // TODO: retrieve name dynamically
  }]);
}

// This method uses an undocumented object and is therefore unsupported.
// You could implement a supported version of this function by querying for
// metadata, but that would be very expensive.
function getEntityLogicalNameFromObjectTypeCode(otc) {
  var map = Mscrm.EntityPropUtil.EntityTypeName2CodeMap,
    logicalName;

  otc = Number(otc); // convert string to number

  for (logicalName in map) {
    if (!map.hasOwnProperty(logicalName)) { continue; }

    if (map[logicalName] === otc) {
      return logicalName;
    }
  }
}


text:
Q: Using iloc with list comprehension to set value I'm attempting to use list comprehension to iterate through a dataframe and set a new value to the location with iloc.  I have confirmed it is iterating through correctly.
import pandas as pd
import numpy as np

df = pd.DataFrame([np.arange(10)]*10)

#working
for i in range(10):
    for j in range(10):
        df.iloc[i,j] = 0+i

#not working
[df.iloc[i,j] = 5 for i in range(10) for j in range(10)]

Can someone explain why above won't work? or what will?

A: This won't work because a list comprehension requires a Python expression in its leftmost position.
[df.iloc[i,j] = 5 for i in range(10) for j in range(10)]
 ^^^^^^^^^^^^^^^^
# This is a statement, not an expression.

This is a consequence of the Python language grammar, which is formally specified here:  Python 3 Full Grammar specification
You could rewrite this to use advanced indexing, I think.  Using different dimensions for rows and columns, for clarity:
import pandas
import numpy

df = pandas.DataFrame([numpy.arange(4)]*7)

After which df is:
   0  1  2  3
0  0  1  2  3
1  0  1  2  3
2  0  1  2  3
3  0  1  2  3
4  0  1  2  3
5  0  1  2  3
6  0  1  2  3

You can assign with "fancy indexing", i.e. providing indices in a list:
df.iloc[[0, 2, 4], [2]] = 100
df.iloc[list(range(6)), list(range(2))] = 125

After which df is:
     0    1    2  3
0  125  125  100  3
1  125  125    2  3
2  125  125  100  3
3  125  125    2  3
4  125  125  100  3
5  125  125    2  3
6    0    1    2  3

A: You do assignment statement df.iloc[i,j] = 5 inside listcomp, so it doesn't work.  df.iloc[i,j] = 5 doesn't return anything for listcomp to create a list and listcomp doesn't allow statements. You need assigment statement outside listcomp. Your listcomp may change to this
df[:] = [[5 for j in range(10)] for i in range(10)]

Out[17]:
   0  1  2  3  4  5  6  7  8  9
0  5  5  5  5  5  5  5  5  5  5
1  5  5  5  5  5  5  5  5  5  5
2  5  5  5  5  5  5  5  5  5  5
3  5  5  5  5  5  5  5  5  5  5
4  5  5  5  5  5  5  5  5  5  5
5  5  5  5  5  5  5  5  5  5  5
6  5  5  5  5  5  5  5  5  5  5
7  5  5  5  5  5  5  5  5  5  5
8  5  5  5  5  5  5  5  5  5  5
9  5  5  5  5  5  5  5  5  5  5

However, I guess this is just an example you use to show the issue because there is better way to create such dataframe .

redpajama_set_name: RedPajamaStackExchange


text:
Q: What is the difference between dataframe.series and dataframe['series']? I just tried sorting my dataframe and used the following function:
df[df.count >= df.count.quantile(.95)]

It returned the error:
AttributeError: 'function' object has no attribute 'quantile'

But bracketing the series works fine:
df[df['count'] >= df['count'].quantile(.95)]

It's not the first time I've gotten different results based on this distinction, but it also usually doesn't happen, and I always thought that these were two identical objects.
Why does this happen?

A: Because count is one of data frame's built in method, when you use . it is recognized as the method instead of the column count, i.e, . prioritize built-in method over columns:
df = pd.DataFrame({
    'A':[1,2,3],
    'B':[2,3,4],
    'count': [4,5,6]
})

df.count()
#A        3
#B        3
#count    3
#dtype: int64

df.count
#              V V V V V V V V
#<bound method DataFrame.count of    A  B  count
#0  1  2      4
#1  2  3      5
#2  3  4      6>

Another distinction between dot and bracket is, you can not use dot to create a new column. i.e. if the column doesn't exist, df.column = ... won't work, you have to use bracket in this case. as df[column] = ..., using the above dummy data frame:
# original data frame
df
#   A   B   count
#0  1   2   4
#1  2   3   5
#2  3   4   6

Using dot to create a new column won't work, C is set as an attribute instead of a column:
df.C = 2
df
#   A   B   count
#0  1   2       4
#1  2   3       5
#2  3   4       6

While bracket is the standard way to add a new column to the data frame:
df['C'] = 2
df
#   A   B   count   C
#0  1   2       4   2
#1  2   3       5   2
#2  3   4       6   2

If a column already exists, it's valid to modify it with dot assuming the data frame doesn't have an attribute with the same name (as is the case of the count above):
df.B = 3
df
#   A   B   count   C
#0  1   3       4   2
#1  2   3       5   2
#2  3   3       6   2


text:
Q: executing file contents as commands under R from Linux terminal I've written a text file containing script for R. I've gotten it to run under Windows from a .bat file running a .txt file under R with CMD BATCH.
I'm trying to replicate that (minus the clickability) in the Terminal
I've  changed the permissions for program execution, I've set the file  to have the shebang, and have tried rewriting for it a few different programmes such as
#!/usr/bin/R

library(rvest)

library(plyr)

which returns an error "Syntax error near unexpected symbol 'rvest'
and
#!/home/robert/Téléchargements/R-3.2.3/src/unix/Rscript.c

library(rvest)

library(plyr)

which also returns an error "Syntax error near unexpected symbol 'rvest'
Separately, on both of these I changed the file extension from nothing to .R
In one case it gave the same error, in the other it started a session of R but didn't execute the commands.
I realise it's a messy question, but I'm having difficulty getting these ducks in a row.

A: Ultimately, this was what worked:
R < /home/robert/R/scraper1.R --no-save

But here's the rest of my answer in case that doesn't work for someone else:

I'm not sure if you've seen any of these, but here's some stuff to try:
Dupe?
The top answer from a very similar post: I'm going to assume you googled your question before posting it, so I'm sure you've already seen this, but it's not referenced in your question, so here it is [Source]:
Content of script.r:
#!/usr/bin/Rscript

cat("Hello")

Invocation from command line:
./script.r

?Rscript
?Rscript allows you to run R scripts in a Unix-esque system [Source]:
    ## example #! script for a Unix-alike

    #! /path/to/Rscript --vanilla --default-packages=utils
    args <- commandArgs(TRUE)
    res <- try(install.packages(args))
    if(inherits(res, "try-error")) q(status=1) else q()

Batch
Here's something from an old R mail pipe [Source]:

*

*Place the line: R --vanilla < foo.txt  foo.results into a file named foo.batch.  No other text should be in the file.

*Make this file executable via chmod 755 foo.batch

*At the command line try at -f foo.batch now or perhaps, batch -f foo.batch.

*If this does not work, ask your system administrator how to set up a batch process.
The advantage of the batch process is 1. you need not be logged in, 2.
your job will take a lower priority than interactive jobs.

R -e
Loading two libraries and running an R command [Source]
R -e 'library("rmarkdown");library("knitr");rmarkdown::render("NormalDevconJuly.Rmd")'

R -e 'library("markdown");rpubsUpload("normalDev","NormalDevconJuly.html")'

Other

*

*R < scriptname.R --no-save [Source]

*$ source("scriptname.R") [Source]


text:
Q: java.lang.NoSuchMethodError: org.hibernate.engine.spi.SessionFactoryImplementor.getProperties()Ljava/util/Map Please help to resolve my problem, I am getting below error when I try to run my program on Apache Tomcat. I am using hibernate Core (5.2.9.Final) and Hibernate commons Annotations (5.0.1.Final) in struts2.
Logs information are below:
INFO: Server startup in 41821 ms
25240 [http-nio-8080-exec-7] INFO  org.hibernate.Version  - HHH000412: Hibernate Core {5.2.9.Final}
25247 [http-nio-8080-exec-7] INFO  org.hibernate.cfg.Environment  - HHH000206: hibernate.properties not found
25352 [http-nio-8080-exec-7] WARN  org.hibernate.orm.deprecation  - HHH90000012: Recognized obsolete hibernate namespace http://hibernate.sourceforge.net/hibernate-configuration. Use namespace http://www.hibernate.org/dtd/hibernate-configuration instead.  Support for obsolete DTD/XSD namespaces may be removed at any time.
Hibernate Annotation Configuration loaded
Hibernate Annotation serviceRegistry created
26171 [http-nio-8080-exec-7] INFO  org.hibernate.annotations.common.Version  - HCANN000001: Hibernate Commons Annotations {5.0.1.Final}
26964 [http-nio-8080-exec-7] WARN  org.hibernate.orm.connections.pooling  - HHH10001002: Using Hibernate built-in connection pool (not for production use!)
26988 [http-nio-8080-exec-7] INFO  org.hibernate.orm.connections.pooling  - HHH10001005: using driver [com.mysql.cj.jdbc.Driver] at URL [jdbc:mysql://localhost:3306/scale_report?serverTimezone=UTC]
26989 [http-nio-8080-exec-7] INFO  org.hibernate.orm.connections.pooling  - HHH10001001: Connection properties: {user=root, password=****}
26989 [http-nio-8080-exec-7] INFO  org.hibernate.orm.connections.pooling  - HHH10001003: Autocommit mode: false
27023 [http-nio-8080-exec-7] INFO  org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl  - HHH000115: Hibernate connection pool size: 1 (min=1)
28642 [http-nio-8080-exec-7] INFO  org.hibernate.dialect.Dialect  - HHH000400: Using dialect: org.hibernate.dialect.MySQLDialect
Initial SessionFactory creation failed.java.lang.NoSuchMethodError: org.hibernate.engine.spi.SessionFactoryImplementor.getProperties()Ljava/util/Map;

I use following jar files:
antlr-2.7.7

classmate-1.3.0

dom4j-1.6.1

hibernate-commons-annotations-5.0.1.Final

hibernate-core-5.2.9.Final

hibernate-jpa-2.1-api-1.0.0.Final

hibernate-entitymanager-4.2.21.Final

jandex-2.0.3.Final

javassist-3.20.0-GA

jboss-logging-3.3.0.Final

jboss-transaction-api_1.2_spec-1.0.1.Final

com.azalea.ufl.barcode.1.0

commons-collections-3.1

commons-configuration-1.2

commons-fileupload-1.2.1

commons-lang-2.1

commons-logging

cvom

CrystalCommon2

CrystalReportsRuntime

DatabaseConnectors

derby

ejb3-persistence

freemarker-2.3.13

icu4j

jai_imageio

JDBInterface

jrcerom

jstl-1.2

jta-1.1

keycodeDecoder

log4j-1.2.15

logging

mssql-jdbc-7.0.0.jre8

mysql-connector-java-8.0.15

ognl-2.6.11

pfjgraphics

QueryBuilder

sap.com~tc~sec~csi

slf4j-api-1.5.8

slf4j-log4j12-1.5.8

struts2-convention-plugin-2.1.6

struts2-core-2.1.6

webreporting

webreporting-jsf

xmlbeans-2.3.0

xpp3

Xtreme

xwork-2.1.2

A: Exceptions like this will be thrown usually when there is a problem on the clean-build-deploy process, try manually delete previous compiled code, if in Apache tomcat, go to the folder with deployments and manually delete any past residuals.
EDIT:
For future references the specific Exception:
java.lang.NoSuchMethodError: org.hibernate.engine.spi.SessionFactoryImplementor.getProperties()Ljava/util/Map

Is thrown by Hibernate when there's a conflict of libraries, (usually javax.persistence)

the approach suggested is to make sure that the libraries
  sub-dependencies (the dependencies used by these libraries) are not
  conflicted, the suggestion given is that itf it is possible to you,
  eliminate suspected libraries and check when the message reappears and
  then try to look for a compatible version.


text:
Q: Slickgrid Loader and Datagrid issue Having trouble getting slick grid to show the ajax loading spinner while the data is loading. Code below, Any help appreciated. This code may be missing a few bracked but you gett the idea. I'm trying to put the ajax spinner into the page for when the data loads however I have a couple other controls that are conflicting so not sure if I'm implementing this correctly....
var loadingIndicator = null;
                                    dataView = new Slick.Data.DataView();
                                    grid = new Slick.Grid("#_data", dataView, columns, options);
                                    pager = new Slick.Controls.Pager(dataView, grid, $("#pager"));

                                     grid.onViewportChanged.subscribe(function (e, args) {
                                         var vp = grid.getViewport();
                                         loader.ensureData(vp.top, vp.bottom);
                                       });

                                    function comparer(a, b) {
                                        var x = a[sortcol],
                                            y = b[sortcol];
                                        return (x == y ? 0 : (x > y ? 1 : -1));
                                    }
                                    grid.onSort.subscribe(function (e, args) {
                                        sortdir = args.sortAsc ? 1 : -1;
                                        sortcol = args.sortCol.field;
                                        dataView.sort(comparer, args.sortAsc);
                                    });

                                     loader.onDataLoading.subscribe(function () {
                                         if (!loadingIndicator) {
                                          loadingIndicator = $("Buffering...").appendTo(document.body);
                                           var $g = $("#_data");

                                           loadingIndicator
                                               .css("position", "absolute")
                                               .css("top", $g.position().top + $g.height() / 2 - loadingIndicator.height() / 2)
                                               .css("left", $g.position().left + $g.width() / 2 - loadingIndicator.width() / 2);
                                         }

                                         loadingIndicator.show();
                                       });

                                       loader.onDataLoaded.subscribe(function (e, args) {
                                         for (var i = args.from; i <= args.to; i++) {
                                           grid.invalidateRow(i);
                                         }

                                        grid.updateRowCount();
                                        grid.render();

                                         loadingIndicator.fadeOut();
                                       });

                                      //  loadingIndicator.fadeOut();

                                    dataView.beginUpdate();
                                    $("#_data").show();
                                    dataView.onRowCountChanged.subscribe(function (e, args) {
                                        grid.updateRowCount();
                                        grid.render();
                                    });

                                    dataView.onRowsChanged.subscribe(function (e, args) {
                                        grid.invalidateRows(args.rows);
                                        grid.render();
                                    });

                                    dataView.onPagingInfoChanged.subscribe(function (e, pagingInfo) {
                                        var isLastPage = pagingInfo.pageNum == pagingInfo.totalPages - 1;
                                        var enableAddRow = isLastPage || pagingInfo.pageSize == 0;
                                        var options = grid.getOptions();

                                        if (options.enableAddRow != enableAddRow) {
                                            grid.setOptions({
                                                enableAddRow: enableAddRow
                                            });
                                        }
                                    });
                                    dataView.beginUpdate();
                                    dataView.setItems(data);
                                    dataView.endUpdate();

                                 // load the first page
                                    grid.onViewportChanged.notify();

                                })
                            }
                        })
                            .fail(function (t) {
                                alert("didn't work.");
                            });
                    }

A: This loading thing is not working this way as far as I have also tried. I tried solving this issue by initializing the "loadingIndicator" in the "loadTable" section.
var loadingIndicator = $("Loading...").appendTo(document.body);
loadingIndicator.css("position", "absolute");

and then after you are done updating the grid after endUpdate() I used
loadingIndicator.css("display", "none");

This helped me get the loading indicator when grid is loading the data in the table.
This might not be the best way, but did worked for me, you may want to try once. Improvise according to your project requirement.
Rest of the css part remains the same.

A: You forgot to write the px ..
Try this code..
.css("top", $g.position().top + $g.height() / 2 - loadingIndicator.height() / 2 + "px")
.css("left", $g.position().left + $g.width() / 2 - loadingIndicator.width() / 2 + "px");


text:
Q: Batch WMIC redirecting output and wrapping into variable I'm trying to use WMIC to remove some old printers on our older print servers
if I use the below syntax from the command line it works
WMIC PRINTER WHERE "SERVERNAME LIKE '%%OLDSERVERNAME%%'" DELETE
I was asked to see if I could make it replace the printers or update them to spare the helpdesk from getting "how do I add my printer" calls
I tried some variation with SET to set the properties for SERVERNAME, it appear to process, but nothing changes and doing a GET shows the old value still.
so I figured I could do a FOR /F loop, wrap the name of the printer (sharename) in a variable and then use another command to recreate the printers, after the offending printers have been deleted.
here's my script
@ECHO

ECHO Gathering Installed Printer Information...

FOR /F "tokens=1 skip=1" %%A IN ('WMIC PRINTER WHERE "Servername like "%%printaz1%%"" get sharename') DO SET PRINTERNAME=%%A

ECHO %PRINTERNAME%

so you would think you'd get the value all wrapped up in a nice variable to do with as you wish but no, I turned echo on and it appears that the variable gets set back to null as soon as it's captured
my output looks like this...
FOR /F "tokens=1 skip=1" %%A IN ('WMIC PRINTER WHERE "Servername like "%%printaz1%%"" get sharename') DO SET PRINTERNAME=%%A

SET PRINTERNAME=nameofprinter

SET PRINTERNAME=

ECHO

ECHO is on.

would love some thoughts on why it seems to be dumping the string.
Powershell and VBScript aren't out of the option either, I'm familar with both, just this seemed possible, and I really don't want to start over.

A: WMIC is returning two lines, one with the printername, and one empty.
The solution to this is to test for empty lines.
ECHO Gathering Installed Printer Information...
FOR /F "tokens=1 skip=1" %%A IN ('WMIC PRINTER WHERE "Servername like "%%printaz1%%"" get sharename') DO if not "%%A"=="" SET PRINTERNAME=%%A
ECHO %PRINTERNAME%

A: what you are looking for is this:
for /f "skip=2 tokens=2 delims=," %%A in ('WMIC PRINTER WHERE "Servername like "%%printaz1%%"" get sharename /format:csv') DO SET PRINTERNAME=%%A
ECHO %PRINTERNAME%

Explanation:
The unicode output of wmic includes a carriage return which is captured by the FOR /F which is what you do not want, as it means the 'enter' becomes part of your variable (%%A) and it also contains an empty line, which again will be outputted to %%A.
My example does the following:
/format:cvs -- will output a comma seperated output so we can capture using the delimiter ,
skip=2 -- will skip the empty line at the beginning and skip the header row of the csv.
tokens=2 -- the csv output contains the name,value as output, but you only want value, which is the second token.
by the way, because we no longer include space as a seperate it should even work with spaces in the value. give it a try.

A: I got around the UNICODE carriage return (which is really the problem here) like this:
@echo off
FOR /F "usebackq tokens=1,2 delims==" %%A IN (`wmic %* /VALUE ^| findstr "="`) DO (call :OUTPUT %%A "%%B")
exit /b

:OUTPUT
echo %1=%2

Save that as "wmi.bat"
and execute your query like this:
wmi.bat printer where 'name like "HP%"' get name

My output looks like this:
Name="HP1C0BCA (HP Officejet Pro 276dw MFP)"
Name="HP Officejet Pro L7500 Series"
Name="HP Officejet Pro 276dw MFP PCL 6"

You can imagine how you can play with this.
the "%%B" portion puts all of the output of /VALUE (including spaces) into the %2
%%A captures the object id, which becomes %1 which is handy if you use this to log all sorts of information from WMI. You don't have to worry about the Unicode carriage return anymore.
The big advantage of this approach is that you have a clever batch file which overcomes the limitations that wmic gives you when using it inside a script, and you can use it for anything.
you can use the STDOUT of the batch file as the parameter for anything else, even as input to wmic!

A: The most secure and general variant is to nest another for /F loop, like this:
for /F "skip=1 usebackq delims=" %%A in (`
    wmic Printer where 'Servername like "%%printaz1%%"' get ShareName
`) do for /F "delims=" %%B in ("%%A") do set "PRINTERNAME=%%A"

The problem is the Unicode output of the wmic command and the poor conversion to ANSI text by for /F, which leaves some orphaned carriage-return characters, which in turn lets appear some additional lines as non-empty. The second for /F loop gets rid of these conversion artefacts.
I also replaced the tokens=1 option by delims= in order not to truncate the returned item at the first white-space.
Take also a look at the following related answers by user dbenham:

*

*Why is the FOR /f loop in this batch script evaluating a blank line?

*For /F with wmic unwanted output

A: @ECHO

ECHO Gathering Installed Printer Information...

FOR /F "tokens=1 skip=1" %%A IN ('WMIC PRINTER WHERE "Servername like "%%printaz1%%"" get sharename') DO (
  SET PRINTERNAME=%%A
  goto end
)
:end
ECHO %PRINTERNAME%


text:
Q: Python - How to fill out a web form then download the file that is generated I'm trying to use use python to go to this page, https://comtrade.un.org/data/, fill in the form, and "click" the download button. Then get the csv file that is generated.
Anyone have some sample code for automating the download in python?
Thx.

A: You might be interested in trying out pywinauto. I have not had too much experience, but I do believe it could do the job.
Good luck!

A: The site you are accessing has an exposed API and you can use that form to generate the API URL and simply call that to return a JSON or CSV response. To get this with Python you can use requests and the core JSON module to parse the data if you want to use the data inside Python:

CSV File
import requests

api_url = 'https://comtrade.un.org/api/get?max=500&type=C&freq=A&px=HS&ps=2017&r=all&p=0&rg=all&cc=TOTAL&fmt=csv'
response = requests.get(api_url)
data = response.content

with open('output.csv', 'wb') as output:
    output.write(data)

Note the fmt=csv property in the URL.

Python Dictionary
import requests, json

api_url = 'https://comtrade.un.org/api/get?max=500&type=C&freq=A&px=HS&ps=2017&r=all&p=0&rg=all&cc=TOTAL'
response = requests.get(api_url)
data = json.loads(response.content)

print(data)

Note that the API URL in the example came from submitting the default form and clicking 'View API Call'. Under the generated table.


text: Q: ServerSocket.setSoTimeout() не выбрасывает exception на чтении у потока Открываю серверный сокет. ставлю ему таймуат 5000 мс. На accept() - валится SocketTimeoutException, что ожидаемо, если нет подключения в течении указ. времени. Но когда принимаю клиентское соединение, на операциях чтения из потока висит мертво никаких исключений не кидает. Так и должно быть? Каким образом можно закрывать клиентские соединения по таймату?


text:
Q: Sequencing in RxJS results in "out of memory" error I need to process 1 million lines of record, transform each one of them, and save them to multiple files (binned by the hour; 1 file for each hour -- I'm thinking of splitting them by "filter").
For some reason I need those lines to be processed strictly sequentially. Meaning, if line #450000 takes longer to process and to save (this is the tricky part because fs is async with callback), the processing wouldn't jump to #450001... It will wait until 450000 is finished. That random sleeping in the code is to simulate that scenario.
Previously (with simple Promise, no RxJs), I would create N promises, one for each line, keep them in an array, and do the chaining by reduce op, as explained here: https://github.com/kriskowal/q
But I don't want to create 1 million instances of Promises. So, I looked into ReactiveX, hoping that it will be like "pass the buck"; meaning it wouldn't wait, the processing would take place as soon as an event pops-up, and the resource used by the processing (thinking that the processing block is basically a promise behind the scene) will be released as soon as possible.
I tried to verify that with this code:
import Rx from 'rxjs-es6/Rx';
import Q from 'q';

let subject = new Rx.Subject();
let processEventJsons = function(observable) {
  observable.concatMap(eventJson => {
    let deferred = Q.defer();

    setTimeout(() => {
      eventJson.procDatetime = new Date().toISOString();
      deferred.resolve(eventJson);
    }, Math.random() * 5000);

    return Rx.Observable.fromPromise(deferred.promise)
  })
  .subscribe({
    next: enrichedEventJson => {
      console.log(JSON.stringify(enrichedEventJson));
    },
    error: err => console.error('something wrong occurred: ' + err),
    complete: () => console.log('done'),
  });
}

processEventJsons(
  subject.filter(dataJson => dataJson.type === "interview").map(dataJson => {
    return {event: "intv", datetime: dataJson.datetime}
  })
)

processEventJsons(
  subject.filter(dataJson => dataJson.type === "checkin").map(dataJson => {
    return {event: "chki", datetime: dataJson.datetime}
  })
)

for (let i = 0; i < 1000000; i++) {
  if (Math.random() < 0.5) {
    subject.next({id: i, type: "interview", datetime: new Date().toISOString()});
  } else {
    subject.next({id: i, type: "checkin", datetime: new Date().toISOString()});
  }
}
subject.complete();

But... I kept getting:

FATAL ERROR: CALL_AND_RETRY_LAST Allocation failed - JavaScript heap out of memory.

The console.log(JSON.stringify(enrichedEventJson)); doesn't get printed until the "for-loop" (at the end of the code) is completed.
This makes me think that switching to RxJS hasn't really improved the situation; it still queues-up promises behind the scene.
Or am I using the API wrongly? Can you help me point out what's wrong?
UPDATE UPDATE:
False Flag. Figured out the problem is not the in the use of RxJS, but in the for-loop (it's too tight). SO I changed it to:
for (let i = 0; i < 1000000; i++) {
  if (Math.random() < 0.5) {
    setTimeout(() => {
      subject.next({id: i, type: "interview", datetime: new Date().toISOString()});
    });
  } else {
    setTimeout(() => {
      subject.next({id: i, type: "checkin", datetime: new Date().toISOString()});
    });
  }
}

A:
I would create N promises, one for each line, keep them in an array, and do the chaining by reduce op

That's the simple but memory-hungry approach. It uses a million promises that need to exist at the same time. Instead, you can use a recursive approach to process your lines sequentially in constant memory:
function getInput(i) {
  return {id: i, type: Math.random() < 0.5 ? "interview" : "checkin", datetime: new Date().toISOString()};
}
function process(eventJson) {
  let deferred = Q.defer();
  setTimeout(() => {
    eventJson.procDatetime = new Date().toISOString();
    deferred.resolve(eventJson);
  }, Math.random() * 5000);
  return deferred.promise;
}
function filteredProcess({type, datetime}) {
  if (type === "interview")
    return process({event: "intv", datetime});
  if (type === "checkin")
    return process({event: "chki", datetime});
}
function log(enrichedEventJson) {
  console.log(JSON.stringify(enrichedEventJson));
}

function loop(i) {
  if (i < 1000000)
    return getInput(i)
    .then(filteredProcess)
    .then(log)
    .then(() => loop(i+1));
  else
    return Q("done")
}

loop().then(console.log, err => console.error('something wrong occurred: ' + err));


text:
Q: XML error on line 1 at column 1: Document is empty I'm trying to import from MySQL to PHP and paste in XML and this is giving this error.
function get_info(){
    global $conn;
     $sql ="SELECT * FROM auto ORDER BY evento_id DESC LIMIT 1";
     $result = $conn->query($sql);

     $xml = new DOMDocument();
     $xml->formatOutput = true;
     $r = $xml->createElement( "events" );
     $xml->appendChild( $r );

     while ($row = $result->fetch_assoc()) {

        $b = $xml->createElement( "event" );
             $evento_id = $xml->createElement( "evento_id" );
             $evento_id->appendChild($xml->createTextNode( $row['evento_id']));
             $b->appendChild( $evento_id );
          $r->appendChild( $b );
        }

        mysqli_free_result($result);
        $conn->close();

        header('Content-Type: text/xml');
        print $xml->saveXML();

        return 0;
}


text:
Q: I'm looking for better Google Slides Animation Settings - API or other I want to get a partial arch to an animation so that my image stays reasonably horizontal on the stage as it travels from right to left.
Currently, the spin animation sets a full spin of 360 deg on any object and its slow speed is way too fast for my needs.
Is there a way to get access to the animation settings via the API or any other way?
I want to also slow the travel speed across the screen. The size of my image should not change to make this happen either.
Any ideas on how to achieve this.


text:
Q: ¿Cómo limitar las opciones de un campo en filterView? Django Estoy haciendo una búsqueda de expedientes de un paciente y quiero filtrar por clinicas.
Para realizar la búsqueda utilizo una librería de Django llamada django-filter en la que te da una lista de todas las opciones posibles de los campos foreignkey.
Quiero filtrar los resultados del campo fisio con los fisios que pertenezcan al Usuario del grupo Clínica con el que estoy logeado ahora mismo.
Este es mi filtro:
class ExpedienteFilter(django_filters.FilterSet):

    paciente__nombre= django_filters.CharFilter(lookup_expr='icontains')
    paciente__apellidos = django_filters.CharFilter(lookup_expr='icontains')
    STATUS_CHOICES = (
        (0, 'Abierto'),
        (1, 'Cerrado'),
    )

    class Meta:
        model = Expediente
        fields = ['fisio', 'estado', 'paciente__nombre', 'paciente__apellidos']

Modelo Expediente
class Expediente(models.Model):
    paciente = models.ForeignKey(Paciente,on_delete=models.CASCADE)
    fisio = models.ForeignKey(User, models.SET_NULL, blank=True, null=True)
    patologia = models.TextField(blank=True, null=True)
    f_apert = models.DateTimeField(auto_now_add=True)
    f_cierre = models.DateTimeField(blank=True, null=True)
    estado = models.BooleanField(default=False)

    class Meta:
        ordering = ["-f_apert"]
    def __str__(self):
        return '%s' % (self.paciente)

El tema es que quiero que aparezcan solo los fisios que pertenecen a la clínica con la que estoy logueado ahora mismo pero me aparecen todas los fisios que existen.
Ejemplo:
Clinica 1 tiene fisio 1 y fisio 2 y clinica 2 tiene fisio 2 y fisio 3. Al entrar al expediente de un paciente de la clinica 1 quiero que en el select del filter me aparezcan solo fisio 1 y fisio 2.


text:
Q: How to use model on view in Orchard for TextBoxFor? I have model ReservationViewModel for use on view. There are set validation information etc. How to use it on view in methods like TextBoxFor(m => m.FirstName)? Exist any options how to declare model on OrchardCMS view(not in editorTempates but in client side)? If I understand good, orchard use in display method some contentshapes not model.
Thanks for some information.

A: Shapes are view models, only, they're dynamic objects. The strongly-typed, Lambda-based Html helpers don't work with dynamic objects, which are not strongly-typed. Use the weakly-typed Html helpers. In your example, that would be Textbox("FirstName").
Strongly-typed view models however are perfectly fine in Orchard. In order to determine how to use them in your particular use case, I'd need to know whether you're creating the view model in a controller action or in a driver.


text:
Q: Rails 5 display current users contacts I am trying to show only the current_user contacts via the rails current_user method:
def index
    if params[:category_id] && !params[:category_id].empty?
      category_find = Category.find(params[:category_id])
      @contacts = category_find.current_user.contacts.search(params[:term]).order(created_at: :desc).page params[:page]
    else
      @contacts = Contact.current_user.search(params[:term]).order(created_at: :desc).page params[:page]
    end
  end

contacts model:
   scope :search, -> (term) do
    where('LOWER(name) LIKE :term or LOWER(email) LIKE :term or LOWER(country) LIKE :term', term: "%#{term.downcase}%") if term.present?
  end

But it returns unfined method current_user.
what am I doing here that prevents me from showing the contacts only for the current user?
EDIT:
Here's the user contact:
class Contact < ApplicationRecord
  belongs_to :category
  has_one_attached :contact_avatar
  belongs_to :user

  validates :name, :email, presence: true
  validates_length_of :name, minimum: 3
  validates_length_of :mobile, minimum: 7, maximum: 15, allow_blank: true
  validates_length_of :phone, minimum: 7, maximum: 15, allow_blank: true

  scope :search, -> (term) do
    where('LOWER(name) LIKE :term or LOWER(email) LIKE :term or LOWER(country) LIKE :term', term: "%#{term.downcase}%") if term.present?
  end

end

Here's the User model.
class User < ApplicationRecord
  has_many :contacts
  has_many :categories

  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable, :trackable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :validatable

  has_one_attached :user_avatar
end

Here's the category model:
class Category < ApplicationRecord
    has_many :contacts
    belongs_to :user
end

Note I am using devise gem for authentication.

A: You have User#contacts and User#categories associations, just use them:
def index
  if params[:category_id] && !params[:category_id].empty?
    category = Category.find(params[:category_id])
    @contacts = current_user.contacts.where(category: category)
  else
    @contacts = current_user.contacts
  end
  @contacts = @contacts.search(params[:term]).order(created_at: :desc)
end

or maybe even better (with some refactoring):
@contacts = current_user.contacts.search(params[:term]).order(created_at: :desc)
if params[:category_id].present?
  category = Category.find(params[:category_id])
  @contacts = @contacts.where(category: category)
end

A: If you really wanted to make this chainable you should write it as:
class Contact < ApplicationRecord
  # ...

  # don't use scope for anything except oneliners
  def self.search(term)
    return self unless term.present? # prevents nil error
    where(
      'LOWER(name) LIKE :term or LOWER(email) LIKE :term or LOWER(country) LIKE :term',
      term: "%#{term.downcase}%"
    )
  end

  def self.by_category(category_id)
    category_id.present? ? where(category_id: category_id) : self
  end
end

The key is that your "scopes" (which are really just class methods) must always return a ActiveRecord::Relation or self which prevents nil errors.
def index
   @contacts = current_user.contacts
                             .search(params[:term])
                             .by_category(params[:category_id])
                             .order(created_at: :desc)
                             .page(params[:page])
end

A: This will work for you.
  def index
    if params[:category_id].present?
        category = Category.find(params[:category_id])
        @contacts = category.current_user.contacts
    else
        @contacts = current_user.contacts
    end
    @contacts = @contacts.search(params[:term]).order(created_at: :desc).page params[:page]
  end

You can use safe navigator also, If you get any nil error.
Better way to get pagination object first and then filter record on the basis of incoming params like below.
def index
  // Here we are trying to fetch all contacts of current user, order and paginate also.
  @contacts = current_user.contacts.order(created_at: :desc).page(params[:page])
  // Here we are filtering current user all contact for particular category if category_id is present.
  @contacts = @contacts.where(category_id: params[:category_id]) if params[:category_id].present?
  // Here we are filtering records with search term
  @contacts = @contacts.search(params[:term]) if params[:term].present?
end


text:
Q: How to create bounding boxes that are not orientated to the north? I want to create bounding boxes around polygons, the bounding boxes will then be used in a ST_Hausdorffdistance to determain the squarness of every polygon. My first choice is using the ST_Envelope function but the problem with this is that all the envelopes are orientated to the north.
The result is the following image.

The following image is how I would like it to look.

This is created with the Minimum bounding geometry tool in ArcGIS. Is there any possibilty to do this in PostGIS?
I tried doing it with the Box2D function in PostGIS, but I can't seem to find the way to save the geometry to the geom column?


text:
Q: How to place image over image without position absolute I want to create a HTML Email template, some of the css style properties are not allowed by Email Providers like Gmail, Outlook, is one such property is position:absolute. I want to place image over image, using div's and position:absolute I'm able to do it as this. How can we achieve this using tables without using position:absolute. I had searched over internet but have not found any related articles which gives solution.
Following are JSFiddle Links: With Div's: Link,
With Tables: Link.
Edit: At least is it possible or not I want to know ?

A: you could use negative margins and vertical-align:

https://jsfiddle.net/vhkssL0q/10/


text:
Q: Use cookies from CookieContainer in WebBrowser Is there any way that I can actually use the cookies from a cookie container (taken from a WebRequest previously) and use them in a WebBrowser control? If so, how would I do this? This is for a Winforms application in C#.

A: Here's an example oh how this could be achieved:
private class CookieAwareWebClient : WebClient
{
    public CookieAwareWebClient()
    {
        CookieContainer = new CookieContainer();
    }

    public CookieContainer CookieContainer { get; private set; }

    protected override WebRequest GetWebRequest(Uri address)
    {
        var request = base.GetWebRequest(address);
        var httpRequest = request as HttpWebRequest;
        if (httpRequest != null)
        {
            httpRequest.CookieContainer = CookieContainer;
        }
        return request;
    }
}

private void Form1_Load(object sender, EventArgs e)
{
    using (var client = new CookieAwareWebClient())
    {
        client.Proxy.Credentials = CredentialCache.DefaultNetworkCredentials;
        client.DownloadData("http://www.google.com");
        var cookies = client.CookieContainer.GetCookies(new Uri("http://www.google.com"));
        var prefCookie = cookies["PREF"];
        webBrowser1.Navigate("http://www.google.com", "", null, "Cookie: " + prefCookie.Value + Environment.NewLine);
    }
}

A: You need to make use of InternetSetCookie. Here is a sample...
public partial class WebBrowserControl : Form
{
     private String url;

     [DllImport("wininet.dll", CharSet = CharSet.Auto, SetLastError = true)]
     public static extern bool InternetSetCookie(string lpszUrlName, string    lbszCookieName, string lpszCookieData);

     public WebBrowserControl(String path)
     {
          this.url = path;
          InitializeComponent();

          // set cookie
          InternetSetCookie(url, "JSESSIONID", Globals.ThisDocument.sessionID);

          // navigate
          webBrowser.Navigate(url);
     }
}

A: Try to first use "client" CookedWebClient for the first navitation and get all the cookies from server. Then you can take the CookedContainer from CookedWebClient, or some other source like WebRequest, and use them in WebBrowser as shown below:
namespace ExampleWebBrowser
{
    public partial class Form1 : Form
    {
         [DllImport("wininet.dll", CharSet = CharSet.Auto, SetLastError = true)]
         public static extern bool InternetSetCookie(string lpszUrlName, string lbszCookieName, string lpszCookieData);

         CookedWebClient client = new CookedWebClient();

         ..
         ..
         ..

         private void usingWebBrowserWithWebClientCookies(string url)
         {
            CookieCollection cookies = client.Cookies.GetCookies(url);
            for (int i = 0; i < cookies.Count; i++)
            {
               Cookie c = cookies[i];
               InternetSetCookie(url, c.Name, c.Value);
            }
            webBrowser1.Navigate(url);
         }
     }

     public class CookedWebClient : WebClient
     {
        CookieContainer cookies = new CookieContainer();
        public CookieContainer Cookies { get { return cookies; } }
        protected override WebRequest GetWebRequest(Uri address)
        {
           WebRequest request = base.GetWebRequest(address);
           if (request.GetType() == typeof(HttpWebRequest))
              ((HttpWebRequest)request).CookieContainer = cookies;
           return request;
        }
     }
}


text:
Q: Textarea и Contenteditable - в чем разница? И почему selectionStart, selectionEnd не работают со вторым? Пытаюсь сделать личный HTML-редактор. С textarea всё работает как надо:
(CodePen-1)
Если ничего не выделено - теги добавляются просто в конце напечатанного текста. А если выделить текст - при клике на кнопку, текст помещается внутри тегов.
<button title="division" class="tag" onclick="tag('
','
');">div</button>
<textarea id="form"></textarea>

JS:
function tag(a,b){
  var x = document.getElementById('form');
  x.focus();
      var value = $("#form").val();
      var start=x.selectionStart;
      var end=x.selectionEnd;
      var selected = a + value.substr(start,end-start) + b;
  $("#form").val(  value.substr(0,start) + selected + value.substr(end)  );
}

Но внутренности Textarea невозможно покрасить или как-то выделить, поэтому есть необходимость сделать редактируемый div, в котором уже можно выделять ключевые слова или теги. Но selectionStart и selectionEnd не работают тут (CodePen-2):
<button title="division" class="tag" onclick="tag('
','
');">div</button>

JS:
function tag(a,b){
         var x = document.getElementById('form');
             var value = $("#form").text();
             var start = x.selectionStart;
             var end = x.selectionEnd;
                 var selected = a + value.substr(start,end-start) + b;
   $('#form').text(  value.substr(0,start) + selected + value.substr(end)  );
   x.focus();
}

Метод тыка не сработал и не понятно, что делаю не так. Видимо нужно просто знать...

A: Свойства selectionStart и selectionEnd объявлены непосредственно в элементах HTMLTextAreaElement и HTMLInputElement.
Так как в случае contenteditable элементом является div - эти свойства у него отсутствуют.
Для получения выделенного текста можно воспользоваться функцией getSelection

function tag(a, b) {
  var x = document.getElementById('form');
  var value = $("#form").text();
  var selection = window.getSelection().getRangeAt(0);
  var start = selection.startOffset;
  var end = selection.endOffset;
  var selected = a + value.substr(start, end - start) + b;
  $('#form').text(value.substr(0, start) + selected + value.substr(end));
  x.focus();
}
.tag {
  width: 90px;
  border: 3px solid #800;
  color: #800;
  background-color: white;
  margin: 0 0 10px 0;
  padding: 5px;
}

#form {
  width: 800px;
  height: 150px;
  background: rgb(255, 222, 159);
  font-size: 18px;
  border: 2px solid #800
}

<button title="division" class="tag" onclick="tag('
','
');">div</button>


text:
Q: How to update existing fields of a document in Firestore with the REST API I have a project with Cloud Firestore as database. Now I want to update the data in one document using the fetch method. My Cloud Firestore stucture is the following:
Logging (Collection)
   [userID] (Document)
       Notifications (Collection)
          [notificationID] (Document)
              active: "true"
              type: "T1"

And I use the fetch call below:
fetch("https://firestore.googleapis.com/v1/projects/[ID]/databases/(default)/documents/Logging/[userID]
       +"/Notifications/[notificationID]?updateMask.fieldPaths=active", {
          method: 'PATCH',
          body: JSON.stringify({
            "active": "false"
          }),
          headers: {
            Authorization: 'Bearer ' + idToken,
            'Content-Type': 'application/json'
          }
        }).then( function(response){
          console.log(response);
          response.json().then(function(data){
            console.log(data);
          });
        }).catch(error => {
          console.log(error);
        });

Executing the fetch method I'm running in an error with message

"Invalid JSON payload received. Unknown name "active" at 'document': Cannot find field."

How can I update the existing fields of a document of Firestore with the REST API? Can anyone help me out? I've tried a lot of different "urls" and methods, but nothing works for me.

A: As explained in the Firestore REST API doc, You need to pass an object of type Document in the body, as follows:
    {
      method: 'PATCH',
      body: JSON.stringify({
        fields: {
          active: {
            stringValue: 'false',
          },
        },
      }),
    }

I made the assumption that your active field is of type String (since you do "active": "false"). If it is of type Boolean, you need to use a booleanValue property instead, as follows. See this doc for more details.
    {
      method: 'PATCH',
      body: JSON.stringify({
        fields: {
          active: {
            booleanValue: false,
          },
        },
      }),
    }


text:
Q: How do I rotate the Y of this object according to the Y of the camera? I want to rotate the Y of my gameobject "Person" according to the Y rotation of "Person/Camero". I thought this would work but it doesn't, why doesn't this work? How could I fix it?
Also, this script is in "Person".
transform.rotation.y = GameObject.Find("Person/Camero").transform.rotation.y;

A: There are two problems with your code:
1.You are modifying transform.rotation.y directly. You can't do this and will get the compile-time error like below:

Cannot modify the return value of 'Transform.rotation' because it is
  not a variable

You have to get transform.rotation which is Quaternion, modify the y then assign that modified Quaternion back to transform.rotation.
Something like this should compile
//Get rotation
Quaternion tempRot = transform.rotation;
//Modify the Y
tempRot.y = GameObject.Find("Person/Camero").transform.rotation.y;
//Assign back to transform.rotation
transform.rotation = tempRot;

but will not run properly. See #2 below for reason.
2. The transform.rotation.y field is returned in a Quaternion form so as the GameObject.Find("Person/Camero").transform.rotation.y. Modifying just one axis will not give you what you actually expect since it's a Quaternion. You have to do this with angles instead.
This is done with the transform.localEulerAngles or transform.eulerAngles properties instead of transform.rotation. Use transform.localEulerAngles  if the object has a parent Object.
This is what should compile and work as exepected:
//Get rotation in Angle deg
Vector3 tempAngle = transform.localEulerAngles;

//Modify the Y axis
tempAngle.y = GameObject.Find("Person/Camero").transform.localEulerAngles.y;

//Assign back to transform.eulerAngles
transform.localEulerAngles = tempAngle;

A: You should never trie to rotate something by Hand. Instead finde the delta and use the Rotate function.
Try this:
var toRotate = GameObject.Find("Person/Camero").transform.rotation.ToAngleAxis() - transform.rotation.ToAngleAxis();
toRotate.x = 0;
toRotate.z = 0;
transform.Rotate(toRotate);

if he looks towards instead of away from the Camera add this line;
toRotate.y += 180;

Good Luck :)


text:
Q: Run time of algorithm I am trying to figure out the run time of the following algorithm.
I argue it is O(n) because the inner loop does not depend on the outer loop.
So we could have O(n) + O(n) = O(2n) which equals O(n)
Is this correct? I'm not sure my logic is correct and I cannot figure out how to analyze is correctly.
The algorithm is finding the largest elements to the left of a list of elements.
Thanks!
public static void main(String[] args){
    int[] a = {4,3,2,10,4,8,9,1};
    int[] p = new int[a.length];
    ArrayDeque<Integer> previousIndex = new ArrayDeque<Integer>();
    for(int i = 0; i < a.length ; i++){
        while (!previousIndex.isEmpty() && a[previousIndex.peek()] <= a[i]){
            previousIndex.pop();
        }
        if (previousIndex.isEmpty()) {
          p[i] = 0;
        } else {
          p[i] = previousIndex.peek();
        }
        previousIndex.push(i);
    }
    for(int i = 0; i < p.length ; i++){
        System.out.println(p[i]);
    }
  }
}

A: This is O(N) for though you have a loop within a loop, the total number of times the inner loop will be executed can never be more than the total number of times that
previousIndex.push(i);

is called, which is a.length (or N)

A: To work out the order really you are looking at the worst case. You are correct that the nested loop is the cause for concern here:
for(int i = 0; i < a.length ; i++){

This is immediately order N
    while (!previousIndex.isEmpty() && a[previousIndex.peek()] <= a[i]){

This could potentially also go nearly N times.
So the final order is N*N or N^2
You do have to keep in mind the usual case though. If it is likely that the while loop will in fact exit after only a couple of iterations you could get back down to O(N).

A: In fact, you are fine and have an O(N) algorithm - but it's harder to prove than most. This assumes, though, that .isEmpty(), .peek() etc. on the ArrayDeque are all constant-time operations. Consult the documentation to be sure.
The key is that your processing of the deque in the inner loop is destructive:
while (!previousIndex.isEmpty() && a[previousIndex.peek()] <= a[i]){
    previousIndex.pop();
}

This removes an element from previousIndex each time, and can only run when there is one to remove. Therefore, the total number of times the while loop could run, across all indices, is the number of times that something is .pushed into deque. And since this only happens at one point - at the end of the first for loop - we can see that the number of items pushed is O(N).


text:
Q: compare a element and next element in a list, if they are same then add corresponding index elements value in second list There are two lists. One has elements 1,1,0,0,0,1 and the second list as elements 200,300,100,200,100,350. I have to compare the list1 element at index with the next index element. if they are same then add elements at same indexes in list 2 and save in some other list.
input list1 -> 1,1,0,0,0,1
input list2 -> 200,300,100,200,100,350

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            List<int> signalTrans = new List<int>();
            List<double> time = new List<double>();

            List<double> timeSorted = new List<double>();
            List<int> signalTransSorted = new List<int>();

            signalTrans.Add(1);
            signalTrans.Add(1);
            signalTrans.Add(0);
            signalTrans.Add(0);
            signalTrans.Add(0);
            signalTrans.Add(1);

            time.Add(200);
            time.Add(300);
            time.Add(100);
            time.Add(200);
            time.Add(100);
            time.Add(350);

            int i;
            double k;

            for (i = 0; i < signalTrans.Count(); i++)
            {
                if ((i + 1) < signalTrans.Count())
                {
                    if (signalTrans[i + 1] == signalTrans[i])
                    {
                        k = time[i + 1] + time[i];
                        signalTransSorted.Add(signalTrans[i]);
                        timeSorted.Add(k);
                    }
                    else
                    {
                        continue;
                    }

                }

            }
        }
    }
}

output list1 -> 1,0,1
output list2 -> 500,400,350

A: If you are willing to use MoreLinq, I'd suggest starting with:
var result = signalTrans.Zip(time, (signalEntry, timeEntry) => new { signalEntry, timeEntry })
    .GroupAdjacent(z => z.signalEntry)
    .Select(z => new { signal = z.Key, totalTime = z.Sum(y => y.timeEntry) });

var indexes = result.Select(z => z.signal).ToList();
var totalTimes = result.Select(z => z.totalTime).ToList();

Zipis used to zip together the two lists together - so you have an IEnumerable of an anonymous type containing data from both lists.
GroupAdjacent then groups together adjacent entries from signalTrans.
Sum then adds up the time entries.
This results in the output you specify in your question:

output list1 -> 1,0,1
output list2 -> 500,400,350


text:
Q: Average function google sheets i am trying to build an average-function in this sheet.
How can i get the average for merchant a in CW6 ([CW34+CW35+CW36]/3), without a reference to the cellnumber.
So i need in E12 the average of the "merchant a" in the range of C:E.
I tried with match,index,averageif.. but havent got a solution.

A: Your match function is on the right lines (except that you need a zero to specify an exact match), then you need to add an INDEX function to get the correct row from C2:E4 and AVERAGE to get the average:-
=AVERAGE(INDEX($C$2:$E$4,MATCH(A12,$A$2:$A$4,0),0))


text:
Q: dust.js: Using paths in scoped sections This question is about using the dust.js templating system with paths to data in sub-contexts. My intention is to support i18n using a map of keys to strings.
Given data like this:
{i18n : { firstname : "First Name" },
 people : [
    {"name" : "Moe"},
    {"name" : "Curly"}
 ]}

In dust you can use sections to list each person:
{#people}
    {name}
{/people}

And you can use a path to get access to the firstname i18n string:
{i18n.firstname}

But the following does not work:
{#people}
    {i18n.firstname}: {name}
{/people}

In fact, the documentation specifically says:

To avoid brittle and confusing references, paths never backtrack up
  the context stack. If you need to drill into a key available within
  the parent context, pass the key as a parameter.

So I try and pass the key as a parameter:
{#people i18n=i18n}
    {i18n.firstname}: {name}
{/people}

But this doesn't work. When I experiment with this on the dust homepage, I see the compiled template has this code:
"i18n": ctx.get("i18n")

Which makes me think the above example should work fine.
So what gives? How can I make this work?
Note: The following does work:
{#people firstname=i18n.firstname}
    {firstname}: {name}
{/people}

But this doesn't work well if you need to access a lot of i18n keys within the people context.

A: Paths can be used in keys and in sections to specify where you want Dust to look for keys. To understand how and when to use paths, you should first understand how Dust looks for keys when there are no paths. You might want to sit down.
When searching for keys, Dust first looks in the current context, then looks in each parent context until there are no more parents to search in. If no key is found, Dust does nothing (unless you are using an Exists or Not Exists Section). If Dust finds the key, it stops searching and uses the given value. That's not too foreign, right? That's how JavaScript looks for variables in execution environments.
However, instead of looking up the tree toward root, when a path is used, Dust only looks at children. This is best illustrated with an example.
JSON:

{
  "i18n": {
    "firstname": "First Name"
  },
  "name": "My Dust Template",
  "firstname": "Surprise!",
  "people": [
    {
      "name": {
        "firstname": "Moe",
        "lastname": "Howard"
      }
    },
    {
      "name": {
        "firstname": "Curly",
        "lastname": "Howard"
      }
    }
  ]
}

And the Dust:
Dust Template:

{! Show the name of the template !}
{name}{~n}
{#people}

  {!
     As you noted, the following will not work, because
     when using a path, Dust only searches
     deeper into the JSON. The output will be:
     ": Surprise!"
  !}
  {i18n.firstname}: {firstname}{~n}

  {!
     To get your i18n string, you need to look up the
     stack instead of down. This can be done by using a
     section without a path, as follows. The output will be:
     "First Name: Moe"
     "First Name: Curly"
  !}
  {#i18n}{firstname}{/i18n}: {name.firstname}{~n}

  {!
     Note that we successfully used the path to
     get the firstname of each of the people.
  !}
{/people}

[EDIT]: For more info, check out this wiki page from the LinkedIn fork of Dust: https://github.com/linkedin/dustjs/wiki/Where-else-does-Dust-search-if-the-value-is-not-defined%3F-A.K.A.-Dust-Scoping

A: if this is your template:
{#people i18n=i18n}
  {i18n.firstname}: {name}
{/people}

here's how your context stack looks like as it iterates through your 'name' array
{ your original context}
i18n -> firstname: "First Name"
name -> "Moe"

what happens is, when you define a parameter, dust pushes into the context stack all the parameters you defined. then when it finds an array in your context, dust pushes into the stack, one at a time, all the items in the array.
so now when you define a path context within the section, even though you've passed i18n in as a parameter, the i18n context is still up in the context stack, and when you try to access i18n with a path, like {i18n.firstname}, dust wouldn't find it, coz it has to backtrack to find it, and getPath doesn't do backtracks. the get method, on the other hand does backtrack, so that's why, when you do this:
{#people firstname=i18n.firstname}
  {firstname}: {name}
{/people}

it works, because it's accessing the firstname within the section with a get method. hope you understand what i'm trying to say.
what i'd do is define a helper method that takes in a section like so:
{#people}
  {#i18n}{firstname}{/i18n}: {name}{~n}
{/people}

and define the method in your context (or push it to your global context [defined with makeBase] to make it a global helper) like so:
i18n: function(chunk, context, bodies, params){
  var trans = context.get(translation); //or whatever name you give to your i18n list
  chunk.render(bodies.block, context.push(trans));
  return chunk;
}

tested this on the dust website and it works. the advantage to this approach is you can now format your i18n output within the confines of the section. also, it would be good to define both the helper and the i18n list in your global context, so do use makeBase for that. all the best.


text:
Q: How to generate an array I want to generate an array in python numpy based on equation; 1/x for x = 1,2,3,...10 and I wrote; But I wasn't getting any output, please help
def Number(x):
  for x in range (1,11):
    y = 1/x
return y
y = Number(10)
print y

A: If you want to return an list, you need to actually make a list and append to it (or use a list comprehension). You just create a variable and assign to it. Instead do:
def Number(x):
    y = []
    for x in range (1,11):
        y.append(1./x)
    return y
y = Number(10)
print y

Now if you want to, you could use a list comprehension. This is a pythonic way to generate a list in a single line. It would look something like this.
def Number(x):
    y = [1./x for x in range(1,11)]
    return y
y = Number(10)
print y

Another way to do this is to use the map builtin, which is different in python 3, but you are using 2.7, so we are good.
def Number(x):
    y = map(lambda x: 1./x, range(1,11))
    return y
y = Number(10)
print y

The map function is applies the function to the specified list. In this case, I use an anonymous lambda function lambda x:1./x which is a simple way of writing a function with x as an argument and returns 1/x. The map function applies the lambda function to each element in the list.

A: This can be done as follow
def Number(n):
    return np.array([1/i for i in range(1, n)])

now you can do that
y = Number(10)


text:
Q: Is there a way to chain Javascript functions without creating a new object? Imagine we have a Button element
const ourButton = document.getElementById("#theButton");

And we want a fluent API to change the styles of this button without creating a new object, so chain a function like this:
style(ourButton).property("padding").value("32px");

Is this possible? I can't seem to figure out how to create this behaviour. I tried building a Fluent API "the conventional way" by creating a constructor function like this:
var FStyle = function(node) {
  this.node = node;
}

FStyle.prototype.property = function(property) {
  this.property = property;
  return this;
}

FStyle.prototype.value = function(value) {
  this.value = value;
  this.node.style[this.property] = this.value;
  return this;
}

and using it by constructing a new object:
const ourButtonStyle = new FStyle(ourButton);
ourButtonStyle.property("padding").value("64px");

Which works, once. If I would like to add a new style I have to create a whole new object. Why is this?
TL;DR: For learning purposes I'm trying to chain functions but don't understand it fully enough to understand the above behaviour. Returning this in a normal function to chain other functions to it won't do the job either. In the end I would like to "pipe" the result of a function to an other function.

A: Although not easily seen, the issue here is the namings!
You are creating a prototype function called property and then essentially you overwrite this function with the value you got from the function call. Check the comments in the code below.
FStyle.prototype.property = function(property) {
  // at this point "ourButtonStyle.property" is a function
  this.property = property;
  // here "ourButtonStyle.property" is a string
  return this;
}

An easy fix would be to rename these with something slightly deifferent
var FStyle = function(node) {
  this.node = node;
}

FStyle.prototype.property = function(prop) {
  this.prop = prop;
  return this;
}

FStyle.prototype.value = function(val) {
  this.val = val;
  this.node.style[this.prop] = this.val;
  return this;
}


text:
Q: sending Email with current path of asp file I want to create a asp file that once its opened it will send an Email to me with its Current location in Server, I am really new to ASP and I searched the internet on how to do so but I failed, also there is no Mail server on the server, any Ideas ?

A: Just replace example data with yours.
I assume that by "Current location in Server" your mean reqest path.
public partial class Index : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        var mail = new MailMessage();
        mail.Subject = "Subject";
        mail.Body = string.Format("<p>{0}</p>", Request.Path);
        mail.IsBodyHtml = true;
        mail.From = new MailAddress("sender@exampledomain.com");
        mail.To.Add("recipient@exampledomain.com");

        var smtp = new SmtpClient();
        smtp.Host = "mail.exampledomain.com";
        smtp.Credentials = new NetworkCredential("sender@exampledomain.com", "{sender_password_here}");
        smtp.Send(mail);
    }
}


text:
Q: Angular JS Bound HTML Functions Not Recognized I'm writing an app that draws data and displays it in the form of a table.  Angular JS is used for sorting and pagination.  The pagination div I have is injected using a function in Angular that builds a string a sets it to the $scope.pagination variable.  The problem is that the ng-click functions within the injected HTML are not recognized when they are clicked.  I'm assuming it is due to the fact that they are not there when the page is rendered.

  var listingsApp = angular.module('listingsApp', []);

  listingsApp.controller('pageController', function($scope, $sce, $filter, $http) {
    $scope.BuildPaginationHtml = function(showPage) {
      pageString = " " + i + " ";
      $scope.pagination = pageString;
    }
  }

Here clicking the span does not go to the GoToPage function.  I have a console log to verify it.  All the other click events on the page work.

A: For dynamic HTML, you have to use $compile
listingsApp.controller('pageController', function ($scope, $sce, $filter, $http, $compile) {
    $scope.BuildPaginationHtml = function(showPage) {
        pageString = $compile(" " + i + " ")($scope);
        $scope.pagination = pageString;
    }
});


text:
Q: Ruby On Rails - Can we use varchar column for saving serialized data Need to store a serialized hash into mysql. Since the size of hash is going to be very small, i decided to use a varchar for saving the serialized data instead of text column. I am using mysql with rails 3.
Model:
class User < ActiveRecord::Base
  serialize :monday
end

When I do the following,
u = User.new
u.monday = {:from => "10:00", :to => "04:00"}
u.save

I get following error "TypeError: class or module required". Shouldn't we use varchar for serialized data?

A: You need a :text database datatype to use the serialize option.


text:
Q: JSON, cellForRowAtIndexPath bug Struggling to find where fault is with my code. On first view load, everything works and loads fine as it should, but when i revisit that view, it seems that the first two cells are empty. I logged the dictionary (dict) in viewWillAppear: and it logs the data fine, so error has to be in cellForRow method. Take a look at my method, and see where i'm going wrong, the third cell populate third piece of data, so i'm totally stumped, but the first two cells are completely blank, no data.
http://pastebin.com/Va84MG5g

A: First of all, why are you doing all of that insane UITableViewCell customization inside of your tableView:cellForRowAtIndexPath: method? Create a custom UITableViewCell subclass and do the set up there.
In the class's initWithStyle: method, add all of your subviews with a frame of CGRectZero, because at initialization, the table view cell doesn't know how big it is. You can set text alignments, colors, etc. here as well. Then, in layoutSubviews, go ahead and set all the frames. Override prepareForReuse and set things like your UIImageViews to nil. This will help with performance for reused cells.
As for why you're not seeing your data in your first two cells, my initial thought is that it has something to do with the way you're setting up your cells for reuse. You're asking your tableView to dequeue a regular UITableViewCell and only creating all of these subviews if the returned cell is nil. So what happens when it returns a UITableViewCell? You skip the part where you alloc/init all these subviews, and so you're basically adding nothing to the cell. I feel if you create a custom subclass and ask your UITableView to dequeue that instead, you'll get the result you're looking for.
NOTE: If you're targeting at least iOS 5, you can create your UITableViewCell's layout in a nib and register the nib with the table view. Doing so will guarantee that you always get a dequeued cell, and you never have to do your if (cell == nil) check. If you're targeting iOS 6, you can register a UITableViewCell subclass.


text:
Q: (High school) How to become an expert on integration? It is very hard for me sometimes to find a right method to do an integration, for example, whether to use by parts method or substitution. I always find the questions I was given on an exam very hard to do without spending much time experimenting on it (I have to skip otherwise I will run out of time). An example question would be to integrate an arcsin(x).
So I wonder if there's any site that provides solutions for all different kinds of integration or something that will help me to recall instantly the method I need to use to integrate an equation? or any advice would be appreciate!!

A: 1) You need to know the tables of derivatives/primitives of elementary functions by heart, flawlessly. (Recall that powers yield powers, polynomials yield polynomials, exponential and $\sin/\cos$ yield themselves.)
2) Recognize factors of the integrand that you can integrate, i.e. write $f$ as $u'.v$.
2a) In some cases, $v$ can be expressed as a function of $u$. For example, $x.e^{x^2}=(x^2)'.e^{x^2}$ hints the substitution $u=x^2$. (Unessential constant omitted.)
2b) In other cases, it may appear that $u.v'$ would be somewhat simpler to integrate: try integration by parts. For example, in $x.\cos x$, you can integrate both $x$ or $\cos x$. Deriving the other factor will give $\sin x$ and $1$ respectively, resulting in integrands $x^2.\sin x$ (worse than before) or $\sin x$ (immediate).
2c) If you can't find an integrable factor, try this trick: $\int f(x)dx=\int x'f(x)dx=xf(x)-\int xf'(x)dx$.
In the case of $\arcsin x$, you won't find a suitable primitive in the tables (but note that the derivative is $\frac1{\sqrt{1-x^2}}$). You don't see an integrable factor either. Then observe that by using rule 2c, you will get rid of the $\arcsin$ !
Now you have to solve $\int \frac x{\sqrt{1-x^2}}dx$. You can integrate $x$ as $x^2$, a candidate for the $u$ function. But an even better $u$ candidate is $1-x^2$, as appearing under the radical, also having $x$ for derivative. It will yield $\int \frac{dx}{\sqrt x}$, found in the tables.
For this case, another strategy can be attempted: get rid of the annoying $\arcsin$ function from the beginning by subsitituting $x$ with $\sin x$. You integrand will turn to the form $\arcsin(\sin x).\cos x=x.\cos x$.


text:
Q: rationale behind the evaluation in tensorflow's tutorial code cifar10_eval.py In TF's official tutorial code 'cifar10', there is an evaluation snippet:
def evaluate():
with tf.Graph().as_default() as g:
            # Get images and labels for CIFAR-10.
            eval_data = FLAGS.eval_data == 'test'
            images, labels = cifar10.inputs(eval_data=eval_data)

            # Build a Graph that computes the logits predictions from the
            # inference model.
            logits = cifar10.inference(images)

            # Calculate predictions.
            top_k_op = tf.nn.in_top_k(logits, labels, 1)

            # Restore the moving average version of the learned variables for eval.
            variable_averages = tf.train.ExponentialMovingAverage(
                cifar10.MOVING_AVERAGE_DECAY)
            variables_to_restore = variable_averages.variables_to_restore()
            saver = tf.train.Saver(variables_to_restore)

            # Build the summary operation based on the TF collection of Summaries.
            summary_op = tf.summary.merge_all()

            summary_writer = tf.summary.FileWriter(FLAGS.eval_dir, g)

            while True:
                eval_once(saver, summary_writer, top_k_op, summary_op)
                if FLAGS.run_once:
                    break
                time.sleep(FLAGS.eval_interval_secs)

At runtime, it evaluates one batch of test samples and prints out 'precision' in the console every other eval_interval_secs, my questions are:

*

*each time eval_once() is executed, one batch of samples (128) are dequeued from the data queue, but why I didn't see the evaluation stop after enough batches, 10000/128 + 1 = 79 batches? I thought it should stop after 79 batches.

*Are batches from the first 79 sampling mutually exclusive? I'd assume so but want to double-check this.

*If each batch is indeed dequeued from the data queue, what are the samples after 79 times of sampling? some random sampling from the entire duplicate data queue again?

*since in_top_k() is taking in some unnormalized logit values and output a string of booleans, this masks the internal conversions of softmax() + thresholding. Is there a TF op for such explicit computations? Ideally, it'd be useful to be able to tune the threshold and see different classification results.
Please help.
Thanks!

A: *

*You can see the following line in "inputs" def of cifar10_input.py
filename_queue = tf.train.string_input_producer(filenames)

More about  tf.train.string_input_producer :
string_input_producer(
    string_tensor,
    num_epochs=None,
    shuffle=True,
    seed=None,
    capacity=32,
    shared_name=None,
    name=None,
    cancel_op=None
 )

num_epochs : produces each string from string_tensor num_epochs times before generating an OutOfRange error. If not specified, string_input_producer can cycle through the strings in string_tensor an unlimited number of times.
In our case, num_epochs is not specified. That's why it does not stop after few batches. It can run unlimited times.

*By default, shuffle option is set to True in tf.train.string_input_producer.  So, it shuffles the data first and copies that shuffled 10K filenames again and again.
Therefore, it's mutually exclusive. You can print filenames to see this.

*As explained in 1, they are repeated samples. (not any random data)

*You could avoid using tf.nn.in_top_k. Use tf.nn.softmax and tf.greater_equal to obtain boolean tensor that has softmax value above the specific threshold.
I hope this helps. Please comment if there is any misunderstanding.


text:
Q: ANR for my IntentService I have an IntentService that creates a new thread and runs a long operation.
    @Override
    protected void onHandleIntent(Intent intent) {
        Log.d(TAG, "onHandleIntent at " + Calendar.getInstance().getTime());
        new Thread() {
            public void run() {
                Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND);
                            << A VERY LONG OPERATION == NETWORK + FILESYSTEM etc >>
                };
        }.start();
    }

Even though it is an IntentService, I see ANRs because of this service. According to my understanding IntentService runs on its own thread right?
06-28 02:18:36.751 I/ActivityManager( 1109): START {cmp=x.y.z/.MainActivity} from pid 466
06-28 02:19:56.861 W/ActivityManager( 1109): Timeout executing service: ServiceRecord{41767d48 x.y.z/x.y.a.RefreshService}
06-28 02:19:58.001 E/ActivityManager( 1109): ANR in x.y.z
06-28 02:19:58.001 E/ActivityManager( 1109): Reason: Executing service x.y.z/x.y.a.RefreshService
06-28 02:19:58.001 E/ActivityManager( 1109): Load: 8.5 / 8.16 / 7.52
06-28 02:19:58.001 E/ActivityManager( 1109): CPU usage from 14986ms to 0ms ago:
06-28 02:19:58.001 E/ActivityManager( 1109):   117% 2317/mediaserver: 45% user + 71% kernel
06-28 02:19:58.001 E/ActivityManager( 1109):   57% 2316/debuggerd: 47% user + 10% kernel
06-28 02:19:58.001 E/ActivityManager( 1109):   9.5% 1030/PE_Single_CPU: 3.2% user + 6.3% kernel
06-28 02:19:58.001 E/ActivityManager( 1109):   0.6% 1109/system_server: 0% user + 0.6% kernel / faults: 1783 minor
06-28 02:19:58.001 E/ActivityManager( 1109):   0.2% 904/yaffs-bg-1: 0% user + 0.2% kernel
06-28 02:19:58.001 E/ActivityManager( 1109):   0.1% 901/yaffs-bg-1: 0% user + 0.1% kernel
06-28 02:19:58.001 E/ActivityManager( 1109):   0% 1//init: 0% user + 0% kernel
06-28 02:19:58.001 E/ActivityManager( 1109):   0% 249/sync_supers: 0% user + 0% kernel
06-28 02:19:58.001 E/ActivityManager( 1109):   0% 923/virtualSensors: 0% user + 0% kernel
06-28 02:19:58.001 E/ActivityManager( 1109):   0% 1480/com.google.android.gm: 0% user + 0% kernel
06-28 02:19:58.001 E/ActivityManager( 1109):   0% 1545/com.updater: 0% user + 0% kernel
06-28 02:19:58.001 E/ActivityManager( 1109):  +0% 786/logcat: 0% user + 0% kernel
06-28 02:19:58.001 E/ActivityManager( 1109): 98% TOTAL: 53% user + 43% kernel + 0.9% softirq
06-28 02:19:58.001 E/ActivityManager( 1109): CPU usage from 551ms to 1089ms later:
06-28 02:19:58.001 E/ActivityManager( 1109):   110% 2317/mediaserver: 41% user + 69% kernel
06-28 02:19:58.001 E/ActivityManager( 1109):     56% 2451/MRVLFFPlayer: 23% user + 32% kernel
06-28 02:19:58.001 E/ActivityManager( 1109):     54% 1286/MRVLFFPlayer: 18% user + 36% kernel
06-28 02:19:58.001 E/ActivityManager( 1109):   67% 2316/debuggerd: 56% user + 10% kernel
06-28 02:19:58.001 E/ActivityManager( 1109):   7.4% 1030/PE_Single_CPU: 3.7% user + 3.7% kernel
06-28 02:19:58.001 E/ActivityManager( 1109):     3.7% 1065/AOUT_HAL_ISR_Ta: 1.8% user + 1.8% kernel
06-28 02:19:58.001 E/ActivityManager( 1109):     1.8% 1049/TSPMgr_MainTask: 1.8% user + 0% kernel
06-28 02:19:58.001 E/ActivityManager( 1109):     1.8% 1050/VPP_ISR_Task: 1.8% user + 0% kernel
06-28 02:19:58.001 E/ActivityManager( 1109):     1.8% 1072/gfxmgr_main_thr: 0% user + 1.8% kernel
06-28 02:19:58.001 E/ActivityManager( 1109):   5.5% 1109/system_server: 0% user + 5.5% kernel
06-28 02:19:58.001 E/ActivityManager( 1109):     5.5% 1136/ActivityManager: 0% user + 5.5% kernel
06-28 02:19:58.001 E/ActivityManager( 1109):   1% 497/kworker/1:1: 0% user + 1% kernel
06-28 02:19:58.001 E/ActivityManager( 1109):   1.8% 786/logcat: 0% user + 1.8% kernel / faults: 37 minor
06-28 02:19:58.001 E/ActivityManager( 1109): 96% TOTAL: 50% user + 45% kernel + 0.9% softirq
06-28 02:20:36.101 W/ActivityManager( 1109):   Force finishing activity x.y.z/.MainActivity
06-28 02:20:36.141 I/ActivityManager( 1109): Killing ProcessRecord{41623b60 466:x.y.z/10031}: user's request
06-28 02:20:36.551 I/WindowManager( 1109): WIN DEATH: Window{41551c38 x.y.z/x.y.z.MainActivity paused=true}
06-28 02:20:36.551 I/ActivityManager( 1109): Process x.y.z (pid 466) has died.
06-28 02:20:36.551 W/ActivityManager( 1109): Scheduling restart of crashed service x.y.z/x.y.a.RefreshService in 119400ms

Also, the trace file at /data/anr/traces.txt does not show any thread stack for this service. I can only see the main thread's stack(which is playing videos) and other AsyncTask threads.
By anychance, will main thread being busy in setting datasource create the background threads to ANR?
Any guidance is welcome.
Here is the stack trace for main thread and refresh thread:
Stack trace:
DALVIK THREADS:
(mutexes: tll=0 tsl=0 tscl=0 ghl=0)
"main" prio=5 tid=1 NATIVE
  | group="main" sCount=1 dsCount=0 obj=0x40b06460 self=0x12958
  | sysTid=1248 nice=0 sched=0/0 cgrp=default handle=1074144680
  | schedstat=( 0 0 0 ) utm=100 stm=30 core=0
  at android.media.MediaPlayer._setDataSource(Native Method)
  at android.media.MediaPlayer.setDataSource(MediaPlayer.java:884)
  at android.media.MediaPlayer.setDataSource(MediaPlayer.java:846)
  at android.widget.VideoView.openVideo(VideoView.java:275)
  at android.widget.VideoView.access$2100(VideoView.java:49)
  at android.widget.VideoView$6.surfaceCreated(VideoView.java:520)
  at android.view.SurfaceView.updateWindow(SurfaceView.java:597)
  at android.view.SurfaceView.access$000(SurfaceView.java:86)
  at android.view.SurfaceView$3.onPreDraw(SurfaceView.java:174)
  at android.view.ViewTreeObserver.dispatchOnPreDraw(ViewTreeObserver.java:590)
  at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1617)
  at android.view.ViewRootImpl.handleMessage(ViewRootImpl.java:2442)
  at android.os.Handler.dispatchMessage(Handler.java:99)
  at android.os.Looper.loop(Looper.java:137)
  at android.app.ActivityThread.main(ActivityThread.java:4424)
  at java.lang.reflect.Method.invokeNative(Native Method)
  at java.lang.reflect.Method.invoke(Method.java:511)
  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)
  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
  at dalvik.system.NativeStart.main(Native Method)

"Thread-158" prio=5 tid=20 NATIVE
  | group="main" sCount=1 dsCount=0 obj=0x411a38a8 self=0x25af28
  | sysTid=1301 nice=0 sched=0/0 cgrp=default handle=1661840
  | schedstat=( 0 0 0 ) utm=1 stm=3 core=0
  at libcore.io.Posix.recvfromBytes(Native Method)
  at libcore.io.Posix.recvfrom(Posix.java:131)
  at libcore.io.BlockGuardOs.recvfrom(BlockGuardOs.java:164)
  at libcore.io.IoBridge.recvfrom(IoBridge.java:503)
  at java.net.PlainSocketImpl.read(PlainSocketImpl.java:488)
  at java.net.PlainSocketImpl.access$000(PlainSocketImpl.java:46)
  at java.net.PlainSocketImpl$PlainSocketInputStream.read(PlainSocketImpl.java:240)
  at org.apache.http.impl.io.AbstractSessionInputBuffer.fillBuffer(AbstractSessionInputBuffer.java:103)
  at org.apache.http.impl.io.AbstractSessionInputBuffer.readLine(AbstractSessionInputBuffer.java:191)
  at org.apache.http.impl.conn.DefaultResponseParser.parseHead(DefaultResponseParser.java:82)
  at org.apache.http.impl.io.AbstractMessageParser.parse(AbstractMessageParser.java:174)
  at org.apache.http.impl.AbstractHttpClientConnection.receiveResponseHeader(AbstractHttpClientConnection.java:180)
  at org.apache.http.impl.conn.DefaultClientConnection.receiveResponseHeader(DefaultClientConnection.java:235)
  at org.apache.http.impl.conn.AbstractClientConnAdapter.receiveResponseHeader(AbstractClientConnAdapter.java:259)
  at org.apache.http.protocol.HttpRequestExecutor.doReceiveResponse(HttpRequestExecutor.java:279)
  at org.apache.http.protocol.HttpRequestExecutor.execute(HttpRequestExecutor.java:121)
  at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:428)
  at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:555)
  at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:487)
  at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:465)
  at x.y.z.c.a.b(SourceFile:597)
  at x.y.z.c.a.a(SourceFile:529)
  at x.y.z.c.a.a(SourceFile:214)
  at x.y.z.c.i.e(SourceFile:290)
  at x.y.z.services.a.run(SourceFile:43)

A: I have manipulated the same with While(true),its working fine,
From the logs starting the service is having some problem, try to share the other code details.

A: Do you bind an Activity to your Service?
If so, make sure you only bind to it once.
If you bind to it more than once, it will not stop when finishing its job, which may cause your ANR:
See:http://developer.android.com/reference/android/content/Context.html#stopService(android.content.Intent)


text:
Q: Show the menu at the center of the data toggle I have this code:
<button type="button" class="btn btn-success open">

        About the Library

Library Hours

Board of Visitors

Department and Staff

Direction Maps

Equipment

Floor Plans

Information and Policies

Mission and Vision

</button>

Here's my only CSS Code:
.dropdown-menu li > a:hover,
.dropdown-menu li > a:focus,
.dropdown-submenu:hover > a
{
    background-image: none;
    background-color: #0C6A13;
}

Here's what it looks like:

I have a button with a label "About the Library" as my data toggle. When I click my data toggle, the menu always show in the left side. I want it to be displayed in the center. How will I do it? Any help would be very much appreciated.

A: Here is a way but you've to specify a width:
Bootply : http://www.bootply.com/79wWifpDzR
Css:
.dropdown-menu li > a:hover,
.dropdown-menu li > a:focus,
.dropdown-submenu:hover > a
{
    background-image: none;
    background-color: #0C6A13;
}

.dropdown-menu{
 left:0 !important;
 right:0 !important;
    text-align:center;
    margin-left: auto !important;
    margin-right: auto !important;
    width: 200px;
  }

HTML:
<button type="button" class="btn btn-success open dropdown">

        About the Library

Library Hours

Board of Visitors

Department and Staff

Direction Maps

Equipment

Floor Plans

Information and Policies

Mission and Vision

</button>

A: try this for the css,
.dropdown-menu li > a:hover,
.dropdown-menu li > a:focus,
.dropdown-submenu:hover > a
{
background-image: none;
background-color: #0C6A13;
margin-left:auto;
margin-right:auto;
width:250px;

}

else replace auto; with a value for example margin-left:50px;
let me know how it goes :)


text:
Q: How to get the firs row from each group-by object of pandas also for columns containing strings? I have a pandas data frame with the following columns: "user", "text1", "text2", and "time". I would like to group by user and for each user take the text corresponding to the largest time. I try to achieve this by the following code (using first):
import pandas

df = pandas.DataFrame({'user':['f','f','s'], 'text1':['111','222','333'], 'text2':[11,22,33], 'time':[1,2,3]}, columns=['user', 'text1', 'text2', 'time'])

print df
print '----------------'

df = df.sort('time', ascending = False)

gr = df.groupby('user', as_index=False).first()
print gr

As a result I get the following:
  user text1  text2  time
0    f   111     11     1
1    f   222     22     2
2    s   333     33     3
----------------
  user  text2  time
0    f     22     2
1    s     33     3

As we can see it works for the text2 contains integer numbers but not for the text1 column that contains strings. Why does it happen and how one can resolve this problem?


text:
Q: OnsenUI 2 carousel automatically scrolls to first items on page scroll event I am developing a website in Angular 2 and have used Onsen UI carousel (Horizontal direction) in it. It is set to have multiple items by using item-width attribute.
This works as expected on desktop browsers.
On mobile devices (Android / iPhone), however, we noticed that if we scroll the page down and move up, then carousel list is automatically scrolled left to first item.
I have tried to search over documentation of OnsenUI but have not been able to find solution for it. Please recommend.


text:
Q: Finding the minimum cost I am currently trying to formulate a formula for this problem using Multivariable Calculus.
There is a job of shipping $V$ cubic feet of old steel shavings across the river by barge.
To do this, you'll make a box to put the shavings in for the barge shipment.
Define:
$x = \textrm{length of the box in feet},$
$y = \textrm{width of the box in feet}, \textrm{and}$
$z = \textrm{height of the box in feet}.$
The material for the box consists of five rectangular pieces.
The bottom has area $x \cdot y$; the material for it costs $a$ per square foot. So in dollars,
bottom cost $= a \cdot y.$
Another two pieces (the sides) have area $x \cdot z$ each; these cost $b$ per square foot. So in dollars
side cost $= 2 b \cdot z.$
And the other two pieces (the ends) have area $y \cdot z$; these cost $c$ per square foot. So in dollars,
end cost $= 2 c \cdot y \cdot z.$
The tugboat captain tells us that she will charge $d$ dollars for each trip. You have $V$ cubic feet of shavings;
so you'll need $\frac{V}{x y z}$ trips.
So in dollars,
transportation cost = $\frac{d \cdot V}{x y z}.$
The bottom line is
overall cost = bottom cost + side cost + end cost + transportation cost.
What should the ratios
bottom cost : side cost : end cost : transportation cost
be if the overall cost is at a minimum?
I was trying to use Lagrange multipliers but no constraint equation is given. How can i go about obtaining the ratios for obtaining the formula for minimum cost?

A: Suppose there are $n$ trips. For minimum cost, the box must be full on every trip (otherwise you could have made the same number of trips with a smaller box). So volume of box = $xyz = V/n$. By the inequality for arithmetic and geometric means,
$$(axy + 2bxz + 2cyz)/3 \ge (axy\cdot2bxz\cdot2cyz)^{1/3} = (4abcV^2/n^2)^{1/3}.$$
The cost of the box is minimized if AM = GM, which happens if and only if $axy = 2bxz = 2cyz.$ From this you can work out the ratios of the sides of the box. The total cost of the $n$ trips is
$$dn + 3(4abcV^2)^{1/3}n^{-2/3}.$$
If $n$ were a continuous variable, elementary calculus shows that the cost would be a minimum when $n = 2(abcV^2/d^3)^{1/5}.$ Since in practice $n$ has to be an integer, I think you would have to take the integers on each side of the theoretical minimum and see which gives the smaller cost.


text:
Q: sklearn.metrics.confusion_matrix - TypeError: 'numpy.ndarray' object is not callable I seem to be getting an error when calling confusion_matrix, please see below. How can I get this to work?
from sklearn.metrics import confusion_matrix
confusion_matrix = confusion_matrix(normalisedArr_y5,predicted5)

A: Both normalisedArr_y5 and predicted5 should be np.arrays or lists. Apparently one or both are not. You could try:
confusion_matrix = confusion_matrix(normalisedArr_y5.tolist(),predicted5.tolist())

A: 1 Be sure that both values are np arrays or lists as specified by @Roelant
2 do not assign to your variable's name the same name as the function name
from sklearn.metrics import confusion_matrix
cfm = confusion_matrix(normalisedArr_y5,predicted5)
print(cfm)

A: In my case, I was defining
normalisedArr_x5 = df.iloc[:,:-1]

and
normalisedArr_y5 = data.iloc[:,-1:]

and this Error was coming.
So just check if both the dataframe variables are the same (here df) and perform the steps again @Garch2017