text:
Q: How to refocus the camera on button click during record of video with Camera 2 Android? I create a camera Android app using googlesample. I need that camera will refocus on start of recording of video and each time the user presses on focus button during recording a video. Where can I find an example how to implement it?
This is my Camera2VideoFragment and it's parent class

A: you need to add capture call back to add focus control to your camera session.
private boolean firstCaptureDone = false;
private CameraCaptureSession.CaptureCallback captureCallback = null;

captureCallback = new CameraCaptureSession.CaptureCallback() {

            @Override
            public void onCaptureCompleted(CameraCaptureSession session, CaptureRequest request, TotalCaptureResult result) {
                super.onCaptureCompleted(session, request, result);

            boolean cameraFocussed = false;

            private void process(CaptureResult result) {
                int afState = result.get(CaptureResult.CONTROL_AF_STATE);
                if (CaptureResult.CONTROL_AF_TRIGGER_START == afState) {
                    if (cameraFocussed) {
                        if (firstCaptureDone) {
                            firstCaptureDone = true;
                            Log.d(TAG, "firstCapture Done with focus");
                        }
                    }
                }
                if (CaptureResult.CONTROL_AF_STATE_PASSIVE_FOCUSED == afState) {
                    cameraFocussed = true;
                } else {
                    cameraFocussed = false;
                }
            }

        };

mPreviewSession.setRepeatingRequest(mPreviewBuilder.build(), captureCallback, mBackgroundHandler);


text:
Q: Download sample data from stream input In developing/debugging a Stream Analytics job Query, I can either upload sample data, or capture a sample from the incoming stream.
When capturing, I remember there was an option to download the captured data and save it to my local machine. Now I do not see that option. I thought it was simply clicking on the document icon next to the ellipsis, but this does not work.
Is this still possible?
If not, what is the alternative technique to save/inspect the incoming data to a job?
Thanks
-John

A: Found it. This is likely the "new way", and I missed the memo.
Opening the stream job's Inputs, clicking on the desired input. Within the "Input Details" blade, there is a "Sample Data" button at the top. Clicking that starts a sampling, with option to download the sampled data when complete.
So the capability was removed from the context of the query, and added to the context of the input.
Hope this saves someone else some head scratching time.
-John

A: In addition to sampling from the input via the portal, you can tap into the hub for the input via Service Bus Exporer. Despite the name, you can use it for IoT Hub, Event Hub or Service Bus. It allows you to save the output. I use this often for realtime monitoring of both the inputs and outputs while working on ASA jobs.

redpajama_set_name: RedPajamaStackExchange


text:
Q: right border gradient I am trying to make right border of an
 element to be linear gradient.
I have tried following but with no success:
-webkit-border-image: -webkit-linear-gradient(top, #FE2EF7, #4AC0F2) 0 0 5px;

I am using Chrome.
Many thanks

A: There is a solution for that but I'm not sure you can adjust the border width: http://jsfiddle.net/u2ZE4/1/
-webkit-border-image: -webkit-gradient(linear, left top, left bottom, from(#e00), to(#fff))0 100% 0 0 stretch;

A: If anybody is interested, this is how I applied a right border gradient on a div where the top and bottom ends fade out. Seems like it took forever to figure out... This is only for Safari as doing the same thing in Firefox is a lot easier...
http://jsfiddle.net/fkFec/1102/

bla

.g {
    border-right-width:1px;
    -webkit-border-image: -webkit-gradient(linear, 0 0, 0 100%, color-stop(0, transparent), color-stop(0.5, grey), color-stop(0.5, grey), color-stop(1, transparent)) 0 100%;
    border-right-width: 1px;
    border-left-width: 0px;
    border-top-width: 0px;
    border-bottom-width: 0px;
    padding: 2px;
    width: 400px;
    height: 150px;
    margin: 10px auto;
}

A: Both above options were not working for me, but the following code worked:
For right border:
.right-gradient-bdr{
    border-width: 1px;
    border-style: solid;
    border-left:0;
    border-image:
    linear-gradient(rgba(0,0,0,0), rgba(0,0,0,1), rgba(0,0,0,0)) 0 100%;
}

For bottom border:
.bottom-gradient-bdr{
    border: 0px;
    border-bottom: 1px solid;
    border-image: linear-gradient(to right, rgba(0, 0, 0, 0), rgba(0, 0, 0, 1), rgba(0, 0, 0, 0));
    border-image-slice: 1;
}


text:
Q: Which Exceptions require a throws statement for the method? In Java, there are some kinds of exceptions which require a throws statement:
public void myMethod() throws IOException {
  throw new IOException("Error!");
}

while others don't:
public void myOtherMethod() {
  throw new IllegalArgumentException("Error!");
}

public void myThirdMethod() {
  throw new Error("Error!");
}

The first method wont compile wthout the throws statement.
What is the criteria for determining if an Exception/Error requires a throws statement?

A: Exception checked and complained by the compiler are called Checked Exceptions  in java.

At compile time, the java compiler checks that a program contains
  handlers for checked exceptions. Java compiler analyzes by which
  checked exceptions can result from execution of a method or
  constructor.For each checked exception which is a possible result, the
  throws clause for the method or constructor must mention the class or
  its superclasses of that exception.

Read more from JLS: http://docs.oracle.com/javase/specs/jls/se5.0/html/exceptions.html
IOException is a checked exception and hence java compiler asks you to either catch it or throw it. While IllegalArgumentException is a run time exception and is not checked or complained by the compiler.

A: Exceptions derived from RuntimeException do not need to be declared, others do.


text:
Q: How to use Dynamic Regression models in R to forecast future sales I want to forecast the sales having 2 independent variables, x1 and x2. I want to choose between different combinations and lags, e.g:
sales ~ x1
sales ~ lag(x1,-1)
sales ~ lag(x1,-1) + lag(x2,-1)
etc ...
I use the function auto.arima(sales, xreg=c(x1,x2)) in R.
My questions are:
i) What is the best way to choose the most appropriate model for forecasting purposes?
ii) I want to forecast sales, lets say, for the whole 2018. Do I have to separately forecast x1 and x2 and use these forecasts as inputs to the regression model? Is this the correct approach?
Does this process of forecasting the predictors and then using the forecasts as inputs to the regression model have a specific name?

A: 1. What is the best way to choose the most appropriate model for forecasting purposes?
One approach is to 1.) set up lagged predictors, 2.) fit auto.arima 3.) compare aicc
The below is untested code, but hopefully useful
my_x1 <- cbind(
    Lag0 = df[,"x1"],
    Lag1 = stats::lag(df[,"x1"],-1),
    Lag2 = stats::lag(df[,"x1"],-2),
    Lag3 = stats::lag(df[,"x1"],-3)) %>%
  head(NROW(df))

my_x2 <- cbind(
    Lag0 = df[,"x2"],
    Lag1 = stats::lag(df[,"x2"],-1),
    Lag2 = stats::lag(df[,"x2"],-2),
    Lag3 = stats::lag(df[,"x2"],-3)) %>%
  head(NROW(df))

# Restrict data so models use same fitting period
fit1 <- auto.arima(df[4:40,1], xreg=c(my_x1[4:40,1], my_x2[4:40,1]),
  stationary=TRUE)
fit2 <- auto.arima(df[4:40,1], xreg=c(my_x1[4:40,1:2], my_x2[4:40,1:2]),
  stationary=TRUE)
fit3 <- auto.arima(df[4:40,1], xreg=c(my_x1[4:40,1:3], my_x2[4:40,1:3]),
  stationary=TRUE)
fit4 <- auto.arima(df[4:40,1], xreg=c(my_x1[4:40,1:4], my_x2[4:40,1:4]),
  stationary=TRUE)

c(fit1[["aicc"]],fit2[["aicc"]],fit3[["aicc"]],fit4[["aicc"]])

read more here
2. I want to forecast sales, lets say, for the whole 2018. Do I have to separately forecast x1 and x2 and use these forecasts as inputs to the regression model? Is this the correct approach?
It may be that your best option here is to setup some scenario forecasting. For example, if x1 went up by 5% then the forecast would be sales_y. To forecast your predictors then use those forecasts to forecast sales introduces additional potential for error.
read more here
3. Does this process of forecasting the predictors and then using the forecasts as inputs to the regression model have a specific name?
Unless you are doing "scenario forecasting" as described above, I think that some forecasters would call the processes of building forecasts off of forecasts not recommended, but maybe there are others on this forum who can provide more insight into this approach.

A: This is an advanced class response to your question where dynamic regression structure is identified and error diagnostics are incorporated to refine tentative models.

*

*Follow http://www.math.cts.nthu.edu.tw/download.php?filename=569_fe0ff1a2.pdf&dir=publish&title=Ruey+S.+Tsay-Lec1 and https://web.archive.org/web/20160216193539/https://onlinecourses.science.psu.edu/stat510/node/75/ to form a Transfer Function.

*Follow http://docplayer.net/12080848-Outliers-level-shifts-and-variance-changes-in-time-series.html to possibly identify anomalies (pulses,level shiifts, seasonal pulses) and possible  deterministic error variance change.

*Review Transfer function in forecasting models - interpretation and http://svds.com/avoiding-common-mistakes-with-time-series/ to find out why ols methods to identify a tf are to be studiously avoided

*study http://www.autobox.com/cms/index.php/afs-university/autobox-examples/modeling-with-autobox/ paaticularly section 4 and the flow diagram

*Finally when you predict use monte carlo methods enabling possible future anomalies in order to obtain meaningful prediction intervals.


text:
Q: Basic Logic/ Predicate Proof help I'm having difficulty writing with these proofs. If you could write these statements as correct predicate logic statements and explain briefly how I would prove each one, I'd really appreciate it.
1) For any real number, there is a number larger than x and x^2.
2) Given any two unequal real numbers, there's a number between them.
3) There is no largest real number.
4) There is no largest negative real number.

A: 1) For any $x\in\mathbb{R}$, we know that $x\leq|x|$, that $0\leq|x|$ and that $0\leq x^2$. So $x\leq|x|+x^2+1$ and also $x^2\leq|x|+x^2+1$. This number, $x\leq|x|+x^2+1$, is an example of a number that is larger than both $x$ and $x^2$.
2) If $x,y\in\mathbb{R}$ and $x\neq y$, assume without loss of generality that $x<y$, then $\frac{x+y}{2}$ is different than both, and $x<\frac{x+y}{2}<y$.
3) For any $x\in\mathbb{R}$, $x+1>x$. So you can always find a number that is larger than any number you can think of. Which means, if you had a maximum real number, you would always be able to find a larger real number, and so it wouldn't be a maximum.
4) Given any negative real number $x<0$, there is a number between it and 0 (this is the point number 2 we just proved), and this number is smaller than 0, so also negative. If there was a largest negative real number, we would be able to find a number also negative larger than it, so it wouldn't be a maximum.


text:
Q: Is it possible to create a dynamic page accesible from "/example" path without creating folders? I know its posible to get different results by using GET and a path like this:
www.example.com/user?name=a

I have been looking for some sites (based on the same theme as me) where they use paths like:
/username/Jonh

Since there will be 100+ 'usernames' I think its ridiculous to create manually 100 folders for this.
I'm just wondering if its posible to create a dynamic page accesible by paths like:
www.example.com/user/a
www.example.com/user/b

A: Yes it is, there is something called mod_rewrite, if you are using Apache. You can read about it here: mod_rewrite.
For other webservers, there are similar modules.


text:
Q: Make a new array I am writing a program that parses sequence alleles. I have written code that reads a file and creates a header array and a sequence array. Here is an example of a file:
>DQB1*04:02:01
------------------------------------------------------------
--ATGTCTTGGAAGAAGGCTTTGCGGAT-------CCCTGGAGGCCTTCGGGTAGCAACT
GTGACCTT----GATGCTGGCGATGCTGAGCACCCCGGTGGCTGAGGGCAGAGACTCTCC
CGAGGATTTCGTGTTCCAGTTTAAGGGCATGTGCTACTTCACCAACGGGACCGAGCGCGT
GTTGGAGCTCCGCACGACCTTGCAGCGGCGA-----------------------------
---GTGGAGCCCACAGTGACCATCTCCCCATCCAGGACAGAGGCCCTCAACCACCACAAC
CTGCTGGTCTGCTCAGTGACAG----CATTGGAGGCTTCGTGCTGGGGCTGATCTTCCTC
GGGCTGGGCCTTATTATC--------------CATCACAGGAGTCAGAAAGGGCTCCTGC
ACTGA-------------------------------------------------------
>OMIXON_CONSENSUS_M_155_09_4890_DQB1*04:02:01
-------------------ATCAGGTCCAAGCTGTGTTGACTACCACTACTTTTCCCTTC
GTCTCAATTATGTCTTGGAAGAAGGCTTTGCGGATCCCTGGAGGCCTTCGGGTAGCAACT
GTGACCTTGATGCTGGCGATGCTGAGCACCCCGGTGGCTGAGGGCAGAGACTCTCCCGGT
AAGTGCAGGGCCACTGCTCTCCAGAGCCGCCACTCTGGGAACAGGCTCTCCTTGGGCTGG
GGTAGGGGGATGGTGATCTCCATGATCTCGGACACAATCTTTCATCAACATTTCCTCTCT
TTGGGGAAAGAGAACGATGTTGCATTCCCATTTATCTTT---------------------
>GENDX_CONSENSUS_M_155_09_4890_DQB1*04:02:01
TGCCAGGTACATCAGATCCATCAGGTCCAAGCTGTGTTGACTACCACTACTTTTCCCTTC
GTCTCAATTATGTCTTGGAAGAAGGCTTTGCGGATCCCTGGAGGCCTTCGGGTAGCAACT
GTGACCTTGATGCTGGCGATGCTGAGCACCCCGGTGGCTGAGGGCAGAGACTCTCCCGGT
AAGTGCAGGGCCACTGCTCTCCAGAGCCGCCACTCTGGGAACAGGCTCTCCTTGGGCTGG
GGTAGGGGGATGGTGATCTCCATGATCTCGGACACAATCTTTCATCAACATTTCCTCTCT

The headers are ('>DQB1', '>GENDX', and '>OMIXON') and the three sequences are the other three strings as seen above.
The next part of my code detects if the allele sequence is complete or incomplete. An allele is determined as "incomplete" if there are more than 4 breaks within the >DQB1 sequence. (A break is signified by a '-'). For example, the above sequence is broken because there are five breaks.
I am trying to write code where if there is an incomplete allele detected, the program creates a new array with only the >GENDX and the >OMIXON headers and sequences.
How can I make an array that does not include >DQB1?
Here is my code as is:
import sys, re

max_num_breaks=4
filename=sys.argv[1]
f=open(filename,"r")
header=[]
header2=[]
sequence=[]
sequence2=[]
string=""
for line in f:
    if ">" in line and string=="":
        header.append(line[:-1])
    elif ">" in line and string!="":
        sequence.append(string)
        header.append(line[:-1])
        string=""
    else:
        string=string+line[:-1]
sequence.append(string)
s1=sequence[0]
breaks=sum(1 for m in re.finditer("-+",''.join(s1.splitlines())))
if breaks>max_num_breaks:
    print "Incomplete Reference Allele Detected"
    for m in range(len(header)):
        if re.finditer(header[m], 'OMIXON') or re.finditer(header[m], 'GENDX'):
            header2.append(header[m])
            sequence2.append(sequence[m])
    print header2

The problem with the above code is that whenever I print header2 it still includes the DQB1.

A: Why do you want to use re.finditer?
What about
if header[m].find('OMIXON') > -1 or header[m].find('GENDX') > -1:

A: You can do this very easily using Biopython, assuming your sequences are saved in a FASTA file.
from Bio import SeqIO

headers = [record.id for record in SeqIO.parse("myfile.fasta", "fasta")][1:]

and you're done.
If you want to get the sequence part from the parse() object, just use record.seq.

A: The re.finditer function does not do what you think it does. For an example, see here.
I would recommend using this instead:
if header[m][1:7] == 'OMIXON' or header[m][1:6]=='GENDX':


text:
Q: Replacing anchor href value with regex I am trying to replace all the href values of the anchor elements in a web page by adding  url of my website before the href value.
Before you suggest XML/HTML parser, please know that I tried bunch of them, and they do great job, however all of them return HTML that is simply messed up for some of the websites that I'm trying to parse. That has to do probably with broken html that is written in the first place, but as I don't have control over that, regex is the only way here. So I came up with this code:
$response = '
Link
';
$pattern = "/(<a .*?href=\"|')([^\"'#]+)(.*?<\/a>)/i";
$response = preg_replace_callback($pattern, 'html_href',  $response);
function html_href($matches) {
    return  $matches[1] . "http://example.com/" . $matches[2] .  $matches[3];
}

and it actually changes $response into:

Link

Thats great. But later I found out that this regex somehow matches also this:
$response = "var href = $(this).attr('rel'); $(this).replaceWith('' + anchor+ '');";
$pattern = "/(<a .*?href=\"|')([^\"'#]+)(.*?<\/a>)/i";
$response = preg_replace_callback($pattern, 'html_href',  $response);
function html_href($matches) {
        return  $matches[1] . "http://example.com/" . $matches[2] .  $matches[3];
 }

and here $response becomes:
var href = $(this).attr('http://example.com/rel'); $(this).replaceWith('' + anchor+ '');

I don't really get, how come this inside attr() method is matched and replaced? Isn't this regex pattern supposed to match only parts of a string that start with <a ? I would like to avoid matching things inside javascript...

A: Just a few common approaches:

*

*Prefer <a\s+ instead of <a␣

*Use [^<>]* thereafter instead of .*? for in-tag attribute skipping. (This is probably the main reason it supuriosly matched JavaScript elsewhere.)

*When you want to allow " or ' use a character class [\"\'] just like you did in the middle.

*Match the href= contents more strictly with ([^<\"\'>]+) for example.

*Then ensure another [\"\'] comes thereafter.

*And assert the end of the <a tag with [^<>]*> (that might be the other main culprit for not matching the desired tags/links).
Use [^<>]+ again for the link text, if that coherently suits your input html.
Protip: write such regex patterns in a lofty /x notation whenever you can.

A: try this
PHP
$re = "/(<a.*href=)[\"'](.*)[\"']/m";
$str = "
Link
2014-54-22 22:23";
$subst = "\1\"http://example.com/\2\"";

$result = preg_replace($re, $subst, $str);

live demo


text:
Q: Wordpress - Equivalent function to gettext filter I'm struggling on a custom plugin I'm making on WP, in order to translate some static strings. The problem is I can't get the strings to translate. My goal is to catch all strings in an array, then process some checkings, translate some and put in the DB. Unfortunately the gettext filter was not designed to achieve this. This is why I'm searching an equivalent function to this filter, so I could load all strings and then process it the way I want. A function I could use on the translation page. Even better : a function that would load all strings directly in an array. I googled a lot to find it but I was unlucky.
Have a great day :)
Edit: The translation plugin I use stores translations in DB. There is no language file to load (that would be easy otherwise).


text:
Q: Is $\mathbb{Z}_p \times \mathbb{Z}_p$ a field when $p$ is prime? Initially I thought that it is but in  a solution to a problem, it was said that $\mathbb{Z}_7 \times \mathbb{Z}_7$ is not a field, because it is not an integral domain due to the fact that:
$(7,7) \cdot (1,1)=(0,0)$, which seems wrong to me because $(7,7)=(0,0)$.

A: It is not an integral domain, since $(1,0).(0,1)=(0,0)$.

A: The direct product of a field $K$, $L=K\times K = \{(a,b)\mid a,b\in K\}$ with component-wise operations (addition and multiplication), is generally not a field, since $(a,0)\cdot (0,b) = (0,0)$ and so the ring $L$ contains zero-divisors.

A: Whenever you have two integral domains, their product is not an integral domain anymore by the argument of José (For me the zero ring is not an integral domain). That is also why many classes of rings are not closed under products as we often want them to be integral domains.

A: So, the cross-product of fields isn't a field again, because of the zero divisors $(a,0)$ and $(0,b)$, for $a,b\neq0$.
But the reason you gave was incorrect,  as (as you noted) $(7,7)=(0,0)\in\Bbb Z_7×\Bbb Z_7$.  You have to take two nonzero elements whose product is zero.   $(1,0)$ and $(0,1)$, for instance.
A field is an integral domain,  since $ab=0$ implies one of $a$ and $b$ isn't a unit (hence is zero).
In other words, the category of fields, $\bf{Field}$, does not have products.


text:
Q: remove unused/bad index to speed up response from table Hi I have table with stat below
Rows :       4,639,162
Reserved :   7,183,216 KB
Data :       5,978,536 KB
Index Size : 1,199,840 KB
Unused :         4,840 KB

I have used sp_spaceused 'TableName' for this stat.
And table information is like below
index_name                         index_description                                   index_keys
IX_tbl_tablename_1                 nonclustered located on PRIMARY                     lng_clientid, str_facility_mims, str_group, str_eq_circ_id, int_tml_no
IX_tbl_tablename_fullreport        nonclustered located on PRIMARY                     str_eq_circ_id, str_facility, str_group
IX_tbl_tablename_lng_clientid      nonclustered located on PRIMARY                     lng_clientid
PK_tbl_tablename_1                 clustered, unique, primary key located on PRIMARY   lng_id, lng_clientid

I am not expert on index but does these index seems okay ??
EDIT : I am Concerned about different Index created and having some common columns. Eg : Clustered Index is created with lngid and clientid , but there is non-clustered index too with only clientid. So is okay ??


text:
Q: Angularjs ui grid issue with small set of data (very few rows) but containing huge text for some columns I am using ui grid in Modal but I am facing problem in representing data with large text. I have only maximum up to 5 rows in my data set. But some of the columns in the rows have huge text. So I would like to have to fixed width for each column and I should  be able to provide horizontal and vertical scroll bars at individual cell level if that particular cell exceeds certain text length ( > 1000). Is it possible to provide horizontal and vertical scroll bars at cell level? Is there any reference code for that?
In the attached image,  under Log Field I have nearly ten thousand words like that I will get up to maximum 5 rows. In each row I will have log field containing nearly 10 to 20 thousand words.


text:
Q: Clean, safe way to auto restart (and monitor) daemons/services At the moment I am using init.d-scripts for starting services like TeamSpeak or MineCraft. Sometimes a server application stops because of some failure or it is auto-stopped, because of some plugin.
So, what is a clean way to check (like every minute for example) if a service is running and if not, restarting via its init.d-script?
Easy monitoring of services would also be nice.

A: An external utility like monit may be useful. You can have it monitor processes and restart them if they go down. You can also configure alerts if certain thresholds are surpassed. And it's available as an Ubuntu package!


text:
Q: How do I randomly select 1 row out of rows with partial match in 2 columns in pyspark I'm using pyspark 3.0.1. I have a student data frame df. The dataframe looks like
MathsMarks HistoryMarks id   class   TotalMarks
  80          75         1     9        300
  90          78         1     9        350
  65          70         7     8        250
  58          55         7     8        200
  75          72         7     8        260
  85          82         9     9        400
  82          85         15    8        410

I need to select randomly one record from the data if id & class combination is repeated more than one time.
For example, my outcome might look like
MathsMarks HistoryMarks id   class   TotalMarks
  80          75         1     9        300
  58          55         7     8        200
  85          82         9     9        400
  82          85         15    8        410

Can you suggest me how to do that?
After implementing @mck's step I'm getting duplicate while they are not in consecutive rows. For example
 Group MathsMarks HistoryMarks id   class   TotalMarks
   A      80          75         1     9        300
   A      90          78         1     null     350
   A      70          78         1     9        320

   B      65          70         7     8        250
   B      58          55         8     null     240
   B      65          70         7     8        250
   B      58          55         8     null     200
   C      85          82         9     9        400
   D      82          85         15    8        410

I want this in below way
 Group MathsMarks HistoryMarks id   class   TotalMarks
   A      80          75         1     9        300
   A      90          78         1     null     350

   B      65          70         7     8        250
   B      58          55         8     null     240
   C      85          82         9     9        400
   D      82          85         15    8        410

A: You can use row_number():
from pyspark.sql import functions as F, Window

df1 = df.withColumn(
    "rn",
    F.row_number().over(Window.partitionBy("id", "class").orderBy(F.lit(None)))
).filter("rn = 1").drop("rn")

df1.show()
#+----------+------------+---+-----+----------+
#|MathsMarks|HistoryMarks| id|class|TotalMarks|
#+----------+------------+---+-----+----------+
#|        65|          70|  7|    8|       250|
#|        82|          85| 15|    8|       410|
#|        85|          82|  9|    9|       400|
#|        80|          75|  1|    9|       300|
#+----------+------------+---+-----+----------+

A: A simple dropDuplicates will do the job:
df.dropDuplicates(['id', 'class']).show()
+----------+------------+---+-----+----------+
|MathsMarks|HistoryMarks| id|class|TotalMarks|
+----------+------------+---+-----+----------+
|        82|          85| 15|    8|       410|
|        85|          82|  9|    9|       400|
|        80|          75|  1|    9|       300|
|        65|          70|  7|    8|       250|
+----------+------------+---+-----+----------+


text:
Q: How to uninstall a rpm that I checkinstalled? I just built vim with checkinstall running:
[root@localhost vim]# checkinstall -R -y --fstrans=no
I see there is a rpm created there :
[root@localhost vim]# ls /root/rpmbuild/RPMS/x86_64/
checkinstall-20141012-1.x86_64.rpm  vim-20141012-1.x86_64.rpm

vim works fine...
:version
VIM - Vi IMproved 7.4 (2013 Aug 10, compiled Oct 12 2014 16:19:20)
Included patches: 1-475
Compiled by statquant
Huge version with GTK2 GUI.  Features included (+) or not (-):
+acl             +clipboard       +cursorshape     +extra_search    -hangul_input    +listcmds        -mouse_gpm       -mzscheme        +python3/dyn     +startuptime     +termresponse    +viminfo         +xsmp_interact
+arabic          +cmdline_compl   +dialog_con_gui  +farsi           +iconv           +localmap        -mouse_jsbterm   +netbeans_intg   +quickfix        +statusline      +textobjects     +vreplace        +xterm_clipboard
+autocmd         +cmdline_hist    +diff            +file_in_path    +insert_expand   +lua             +mouse_netterm   +path_extra      +reltime         -sun_workshop    +title           +wildignore      -xterm_save
+balloon_eval    +cmdline_info    +digraphs        +find_in_path    +jumplist        +menu            +mouse_sgr       +perl            +rightleft       +syntax          +toolbar         +wildmenu        +xpm
+browse          +comments        +dnd             +float           +keymap          +mksession       -mouse_sysmouse  +persistent_undo +ruby            +tag_binary      +user_commands   +windows
++builtin_terms  +conceal         -ebcdic          +folding         +langmap         +modify_fname    +mouse_urxvt     +postscript      +scrollbind      +tag_old_static  +vertsplit       +writebackup
+byte_offset     +cryptv          +emacs_tags      -footer          +libcall         +mouse           +mouse_xterm     +printer         +signs           -tag_any_white   +virtualedit     +X11
+cindent         +cscope          +eval            +fork()          +linebreak       +mouseshape      +multi_byte      +profile         +smartindent     +tcl             +visual          -xfontset
+clientserver    +cursorbind      +ex_extra        +gettext         +lispindent      +mouse_dec       +multi_lang      +python/dyn      -sniff           +terminfo        +visualextra     +xim

For some reason I cannot uninstall it...
[root@localhost vim]# rpm -e /root/rpmbuild/RPMS/x86_64/vim-20141012-1.x86_64.rpm
error: package /root/rpmbuild/RPMS/x86_64/vim-20141012-1.x86_64.rpm is not installed
[root@localhost vim]# rpm -e vim-20141012-1.x86_64
error: package vim-20141012-1.x86_64 is not installed
[root@localhost vim]# rpm -e vim
error: package vim is not installed

How can I do this?

A: rpm -e doesn't take a fullpath as an argument, just the package name:
rpm -e vim-20141012-1.x86_64

Or even:
rpm -e vim

A: Install it again (using rpm) and uninstall it again the same way.


text:
Q: MySql - Abysmal Performance I am trying to run a relatively simple query on a table that has half a million rows. It's just a small fragment I'm using to test the values I get back are correct. The problem is this query takes over 20 minutes to complete, which seems unusually slow even for 500,000 records.
DROP VIEW IF EXISTS view_temp_sortie_stats;
CREATE VIEW view_temp_sortie_stats AS
SELECT server_id, session_id, ucid, role, sortie_id,
    (
        SELECT COUNT(sortie_id)
        FROM raw_gameevents_log
        WHERE sortie_id = l.sortie_id AND server_id = l.server_id AND session_id = l.session_id AND target_player_ucid = l.ucid AND event = "HIT"
    ) AS HitsReceived
FROM raw_gameevents_log l
WHERE ucid IS NOT NULL AND sortie_id IS NOT NULL
GROUP BY server_id, session_id, ucid, role, sortie_id;

SELECT * FROM view_temp_sortie_stats;

Here is my table:

Next I tried to add indexes for server_id, session_id, sortie_id to see if it would improve - this took more than 10 minutes to apply and timed out. So I could not add them.
This seems abnormally slow, it shouldn't take this much time to add indexes, or perform this query.
My innodb_buffer_pool_size is 5GB, yet the mysqld process only consumes 300mb of memory when these queries are run.
I am running on Windows Server 2012 R2 Standard with 12 GB Ram, 2x Intel Haswell CPU, so I should be seeing much better performance than this from mysql.
There is no one else connected to this instance of MySql and no other operations are occurring.
EDIT - Here is the query explained

Does someone know what might be wrong?
EDIT2 - Partial Fix
After some googling I found out why the add index was taking forever - the original query was still running in the background for over 2hrs. Once I Killed the query the add index took about 30 seconds.
Now when I run the above query it takes 27 seconds - which is a drastic improvement for sure, but that still seems pretty slow for 500,000 records. Here is the new query explain plan:

A: Your subquery is:
    SELECT COUNT(sortie_id)
    FROM raw_gameevents_log
    WHERE sortie_id = l.sortie_id AND server_id = l.server_id
    AND session_id = l.session_id AND target_player_ucid = l.ucid
    AND event = "HIT"

and the main query is:
SELECT server_id, session_id, ucid, role, sortie_id, [...]
FROM raw_gameevents_log l
WHERE ucid IS NOT NULL AND sortie_id IS NOT NULL
GROUP BY server_id, session_id, ucid, role, sortie_id;

Let's start from the subquery. The COUNT can count on whatever, so we don't bother with the select fields. The WHERE fields:
    WHERE sortie_id = l.sortie_id AND server_id = l.server_id
    AND session_id = l.session_id AND target_player_ucid = l.ucid
    AND event = "HIT"

You create an index beginning with the constant fields, then the others:
CREATE INDEX subqindex ON raw_gameevents_log(
    event,
    sortie_id, server_id, session_id, target_player_ucid
)

Then the main query:
WHERE ucid IS NOT NULL AND sortie_id IS NOT NULL
GROUP BY server_id, session_id, ucid, role, sortie_id;

Here you need an index on
ucid, sortie_id, server_id, session_id, role

Finally, you might try getting rid of the subquery (even if the optimizer probably already does a good work with that):
SELECT server_id, session_id, ucid, role, sortie_id,
COALESCE(hits, 0) AS hits
FROM raw_gameevents_log l
LEFT JOIN
(
    SELECT COUNT(1) AS hits FROM raw_gameevents_log
    WHERE event = 'HIT'
) AS h
ON (h.sortie_id = l.sortie_id, h.server_id = l.server_id, h.session_id = l.session_id, h.target_player_ucid = l.ucid)
WHERE l.ucid IS NOT NULL AND l.sortie_id IS NOT NULL
GROUP BY l.server_id, l.session_id, l.ucid, l.role, l.sortie_id;


text:
Q: Angular 2 service method calling - self.context.dummySer.foo is not a function I'm trying to call a service method from a component, but I keep getting this error: self.context.dummySer.foo is not a function
UPDATE:
Since the solutions worked for other components but not for this one and it just doesn't make any sense, I'll just copy paste the real "not working component" and service.
import { Component, OnInit, OnDestroy} from '@angular/core';
...stuff
import { UrlifyService } from '../services/urlify.service';

@Component({
  selector: 'app-editar-noticias',
  templateUrl: 'editar-noticias.component.html'
})

export class EditarNoticiasComponent implements OnInit, OnDestroy{
  ...stuff

  constructor(
    ...stuff
    public urlifySer: UrlifyService) {}

  ngOnInit(){
   ...stuff
  }
  ngOnDestroy(){
   ...stuff
  }

  ...other methods

  public urlify(titulo:string){
    this.urlifySer.urlify(titulo);
  }

}

View:
<input type="text" #titulo (blur)="urlify(titulo.value)">

Service:
import { Injectable } from '@angular/core';

@Injectable()
export class UrlifyService {

  urlified: string;

  constructor() { }

  urlify(str) {
    str = str.replace(/^\s+|\s+$/g, '');
    str = str.toLowerCase();

    let from = "àáäâèéëêìíïîòóöôùúüûñç·/_,:;";
    let to   = "aaaaeeeeiiiioooouuuunc------";
    for (let i=0, l=from.length ; i<l ; i++) {
      str = str.replace(new RegExp(from.charAt(i), 'g'), to.charAt(i));
    }

    str = str.replace(/[^a-z0-9 -]/g, '')
      .replace(/\s+/g, '-')
      .replace(/-+/g, '-');

    this.urlified = str;
  }

}

The method takes the title value and it builds a friendly url from it. As I said, calling the same method the same way from other components works... but for some reason, it just doesn't on this one.

A: It's considered a bad practice to directly call the service from your HTML binding, prefer using a method in your Component to handle this call. It will, by the way, fix your problem.
Your code would became:
@Component({
  selector: 'whatever',
  templateUrl: 'whatever.html'
})
export class whateverComponent {
    constructor(public dummySer: DummyService) {}

    public dummyMethod(text: string) {
        this.dummySer.foo(text);
    }
}

And in your html you would call the dummyMethod instead of your service.
Also, I noticed that they weren't any exported class in your component, did you just removed it to show us your code or was it the original code? The error could be there too.

A: As mentioned in Sakuto answer, defining the method in component will do your work.
Component:
constructor(private dummySer: DummyService) {}

foo(text) {
  this.dummySer.foo(text);
}

HTML:
<input type="text" #text (blur)="foo(text.value)">

Note: Mark your service private in constructor.


text:
Q: click to return false, click again to return true When someone clicks a button I want my function to return false and the keydown function will be disabled.
Then, if I click this same button a second time, it will return true and the keydown function will be enabled.
I did like this but it only returns false and keydown function disabled. I also need to enable this keydown function by clicking this button.
How can I do this?

var controlsEnabled = true;
$(".keyboard-btn").on('click', function() {
  controlsEnabled = false;
});

$(document).keydown(function(e) {
  if (controlsEnabled) {
    if (e.keyCode == 38) {
      verticalSlideDown();
      console.log("pressed key for Down : " + e.keyCode);
    }

    if (e.keyCode == 40) {
      verticalSlideUp();
      console.log("pressed key for Up: " + e.keyCode);
    }

    if (e.keyCode === 13) {
      var div = $(".scroll-inner-container");
      console.log("pressed key for stop : " + e.keyCode);
      div.stop();
    }
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button class="keyboard-btn">click here</button>

A: Your click even only ever sets controlEnabled to false. You need a way to toggle.
The quickest option is to write this
$(".keyboard-btn").on('click', function() {
  controlsEnabled = !controlsEnabled // will toggle false -> true or true -> false;
});

You could also use if statements to achieve the same thing.. like this
$(".keyboard-btn").on('click', function()
{
      if(controlsEnabled)
      {
          controlsEnabled = false;
      }
      else
      {
          controlsEnabled = true;
      }
});

This is more long-winded, but perfectly valid, and you could argue it's easier to read. You could also use a ternary operator like this
controlsEnabled = (controlsEnabled)? false : true;

But that wouldn't really give any advantage, being neither easier to read, or more elegant. But it's worth knowing the different ways to conditionally set a value based on itself. You never know when it might come in handy.

A: How about this?
$(".keyboard-btn").on('click', function() {
  controlsEnabled = !controlsEnabled;
});

A: This may helpful
$(".keyboard-btn").on('click', function () {

       controlsEnabled= controlsEnabled? false :true ; //  controlsEnabled = !controlsEnabled

});

A: Just replace first 4 lines with this code :
var controlsEnabled = true;
$(".keyboard-btn").on('click', function() {
  controlsEnabled = !controlsEnabled;
});

A: Firstly, your function doesn't return anything at the moment - you need to add the return keyword.
Secondly, your code isn't performing a boolean switch, it is merely assigning a boolean value. As true=1 and false=0, you can write:
controlsEnabled^=1;

which uses the XOR operator to switch from true to false and back again.


text:
Q: How do you get $(n-1)! \over n!$ from $1 \over n$ This is from problem 2.30 in Introduction to Probability, 2nd Edition by Bertsekas and Tsitsiklis.

How does the solution get $(n-1)! \over n!$ from $1 \over n$?
Similarly, how does the solution get $1 - e^{-1}$ from the final sequence?

A: Recall that by definition
$$\frac{(n-1)!}{  n!}=\frac{(n-1)(n-2)\ldots2\cdot 1}{  n(n-1)(n-2)\ldots2\cdot 1}$$
For your second question refer to Botond's answer.

A: It is $$n!=(n-1)!n$$ and this solves your problem

A: For your second question:
$$e^x=\sum\limits_{n \in \mathbb{N}} \frac{x^n}{n!}$$
And substitute in $x=-1$.


text:
Q: C# Schedule a window service I have a window service and i'm using System.Timers.Timer to schedule my service
protected override void OnStart(string[] args)
{
    timer_= new System.Timers.Timer(intervalTime * 1000);
    timer_.Elapsed += new System.Timers.ElapsedEventHandler(TimerEvent);
    timer_.Enabled = true;
}

private void TimerEvent(object sender, System.Timers.ElapsedEventArgs e)
{
    DoSth();
}

I find that, the Dosth() function doesn't run exactly when i start the service, but after intervalTimer seconds.I want it to run exactly after i start the service, so i call the function Dosth() before statment timer_.Enabled = true;. But i got another problem that. the distance of the 1st and the 2nd process is not exactly equal intervalTime, but base on processing time of DoSth() function. How can i solve this?


text:
Q: Unable to access ECR repository from separate account via `docker pull` I'm attempting to allow one AWS account (called "second" below) to pull an image in an ECR repository of another AWS account (called "first" below).
I'm following these documents:

*

*https://docs.aws.amazon.com/AmazonECR/latest/userguide/RepositoryPolicyExamples.html (to set the permissions)

*https://aws.amazon.com/premiumsupport/knowledge-center/secondary-account-access-ecr/ (to get the token)

I have added the following permissions to the ECR repository:
{
  "Version": "2008-10-17",
  "Statement": [
    {
      "Sid": "AllowCrossAccountPull",
      "Effect": "Allow",
      "Principal": {
        "AWS": "arn:aws:iam::<second>:root"
      },
      "Action": [
        "ecr:BatchCheckLayerAvailability",
        "ecr:BatchGetImage",
        "ecr:GetDownloadUrlForLayer"
      ]
    }
  ]
}

Then I run this command: eval "$(aws ecr get-login --no-include-email --region us-east-1 --profile second --registry-ids <second> <first>)"
And I get this result:
WARNING! Using --password via the CLI is insecure. Use --password-stdin.
WARNING! Your password will be stored unencrypted in /Users/libby/.docker/config.json.
Configure a credential helper to remove this warning. See
https://docs.docker.com/engine/reference/commandline/login/#credentials-store

Login Succeeded
WARNING! Using --password via the CLI is insecure. Use --password-stdin.
WARNING! Your password will be stored unencrypted in /Users/libby/.docker/config.json.
Configure a credential helper to remove this warning. See
https://docs.docker.com/engine/reference/commandline/login/#credentials-store

Login Succeeded

I changed the store to config.json temporarily just to make sure I could see that authentication was being added to the file as I expected, and it is:
{
        "auths": {
                "<second>.dkr.ecr.us-east-1.amazonaws.com": {
                        "auth": "<super long token>"
                },
                "<first>.dkr.ecr.us-east-1.amazonaws.com": {
                        "auth": "<super long token>"
                }
        },
        "HttpHeaders": {
                "User-Agent": "Docker-Client/18.09.0 (darwin)"
        },
        "stackOrchestrator": "swarm"
}

Finally I run: docker pull <first>.dkr.ecr.us-east-1.amazonaws.com/<repo>:<tag> and get this result:
Error response from daemon: pull access denied for <first>.dkr.ecr.us-east-1.amazonaws.com/<repo>, repository does not exist or may require 'docker login'

I've triple checked all the account numbers are correct, the repo is definitely there. I'm able to pull it if I login in with the same get-login command but --profile first.
I'm not sure what else to try so that I can pull this image!
Changing the Principal in the ECR permissions to "AWS": "arn:aws:iam::<second>:user/<user>" doesn't make any difference.

A: I figured it out -- the IAM user in the "second" account had a policy attached that limited its ECR access. The policy was:
    {
        "Sid": "ECRAccess",
        "Effect": "Allow",
        "Action": "ecr:*",
        "Resource": "arn:aws:ecr:us-east-1:<second>:repository/<unrelated-repo>"
    }

So even though the ECR repository in the "first" account had permissions allowing the user access, the user's own account restricted its access to a single unrelated repository.
When I added another section with the first account's repository ARN:
    {
        "Sid": "FirstAccountECRAccess",
        "Effect": "Allow",
        "Action": "ecr:*",
        "Resource": "arn:aws:ecr:us-east-1:<first>:repository/<repo>"
    }

Then docker pull worked!

A: Is your second account using an IAM user on your machine? Cuz in your policy you gave the root user on the second account access:
"Principal": {
        "AWS": "arn:aws:iam::<second>:root"
      },
consider changing this to in your policy:
"Principal": {
        "AWS": "arn:aws:iam::<second>:user/[nameofuser]"
      },


text:
Q: eclipse Luna + Java : 2 main files, compilation not proper Having strange problem for couple of days.
I have written 2 main files, so to test based on need.
 I have been facing following strange problems,

*

*The main fail stops executing after some statement. doesnt hang! after cleaning the build, and compiling again it  got executing!

*I updated few System.out.println statements, but i am cant see new statements.

*I excluded the unwanted main files and tried. even commented the whole unwanted main files and tried.

*I even tried changing the main file name that i am using.

I observe the eclipse is not compiling the main file i wanted or it is taking old class file some where residing?
I cant see the unwanted class anywhere in the workspace!!
anyone experienced similar problem?

A: Please try right-mouse click on the class in "Package Explorer", then
form the menu choose "Run As" -> "Java Application".
This will run (and compile if needed) the selected source code.

A: I copied a main file from other project, and that package got retained in that file. when i modify the code in copied main file, forgot to modify a constructor name which was pointing to earlier package.  I missed  to trace import statements and it was not expanded.  when i try to copy the file to post in stackflow, i found earlier package was included and found that was the culprit!!


text:
Q: Brother DCP-T510w prints, but don't scan, Ubuntu 20.04, How can I make xsane recognise it? I used my printer with ease back in Ubuntu 18.04, but I had to upgrade it. The System works fine and installed all drivers from DCP-T510w Brother's page. The Printer works fine, although sometimes I have to make some roundabout way to do it, but the scanner doesn't work. Document scanner and xsane doesn't recognize it.
I saw a dozen forums about similar problems, but they seemed complicated and without standard. None concerning Ubuntu 20.04.
Here are some information, I could gather about the drivers.
ScanImage and Brother drivers:

sane, find scan:

A: I have a Brother MFC and ran into the same problem.
It's seems like the 20.04 upgrade replaced /etc/sane.d/dll.conf with a default file.
The following fixed it for me:
sudo nano /etc/sane.d/dll.conf
I added a line with brother2 at the end of the file.
Judging from your recently added screenshots you should add a line brother4 if it's not already there.
If that doesn't fix it for you do a
diff /etc/sane.d/dll.conf /etc/sane.d/dll.conf.dpkg-old
Then you'll see the difference between the old and the new file to change it accordingly.


text:
Q: UICollectionViewDelegateFlowLayout Edge Insets not getting recognized by sizeForItemAt function? So as the title suggest, I seem to have run into a weird problem. All I am trying to do here is create a 2 column collectionview without hardcoding anything into my delegate methods. Upon debugging I found that insetForSectionAt is called after sizeForItemAt, hence the custom insets are not taken into consideration when calculating the size of every cell.
extension ViewController: UICollectionViewDelegateFlowLayout {

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    let flowLayout = collectionView.collectionViewLayout as! UICollectionViewFlowLayout
    print("left: ", flowLayout.sectionInset.left)   // Prints out 0.0
    print("right: ", flowLayout.sectionInset.right) // Prints out 0.0
    let marginsAndInsets = flowLayout.sectionInset.left + flowLayout.sectionInset.right + flowLayout.minimumInteritemSpacing * (cellsPerRow - 1)
    let itemWidth = (collectionView.bounds.size.width - marginsAndInsets) / cellsPerRow
    return CGSize(width: itemWidth, height: itemWidth)
}

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets {
    return UIEdgeInsets(top: 10, left: 10, bottom: 10, right: 10)
}
}

This problem can be solved very uglily by hard coding the values directly into the itemWidth variable as such, -20 because i know the values of left and right insets, 10 + 10
let itemWidth = (collectionView.bounds.size.width - marginsAndInsets - 20) / cellsPerRow

however, I have to believe that there is a better way of doing this, how can I call reloadData upon completion of the UIEdgeInset calculation so that my cells are properly sized?

A: So this is what I ended up doing, i just added the customizations directly when creating the sizes for the collectionView and its cells.
class PinController: UICollectionViewController {

fileprivate let pinCellId = "pinCellId"
fileprivate let cellsPerRow: CGFloat = 2.0
fileprivate let margin: CGFloat = 10.0
fileprivate let topMargin: CGFloat = 2.0
}

extension PinController: UICollectionViewDelegateFlowLayout {

func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    let flowLayout = customize(collectionViewLayout, margin: margin)
    let itemWidth = cellWidth(collectionView, layout: flowLayout, cellsPerRow: cellsPerRow)
    return CGSize(width: itemWidth, height: itemWidth * 1.1)
}

/*
 Customizes the layout of a collectionView with space to the left and right of each cell that is
 specified with the parameter margin
*/
private func customize(_ collectionViewLayout: UICollectionViewLayout, margin: CGFloat) -> UICollectionViewFlowLayout {
    let flowLayout = collectionViewLayout as! UICollectionViewFlowLayout
    // Interitem spacing affects the horrizontal spacing between cells
    flowLayout.minimumInteritemSpacing = margin
    // Line spacing affects the vertical space between cells
    flowLayout.minimumLineSpacing = margin
    // Section insets affect the entire container for the collectionView cells
    flowLayout.sectionInset = UIEdgeInsets(top: topMargin, left: margin, bottom: 0, right: margin)
    return flowLayout
}

/*
 Calculates the proper size of an individual cell with the specified number of cells in a row desired,
 along with the layout of the collectionView
 */
private func cellWidth(_ collectionView: UICollectionView, layout flowLayout: UICollectionViewFlowLayout, cellsPerRow: CGFloat) -> CGFloat {
    // Calculate the ammount of "horizontal space" that will be needed in a row
    let marginsAndInsets = flowLayout.sectionInset.left + flowLayout.sectionInset.right + flowLayout.minimumInteritemSpacing * (cellsPerRow - 1)
    let itemWidth = (collectionView.bounds.size.width - marginsAndInsets) / cellsPerRow
    return itemWidth
}
}


text:
Q: call function in dojo template widget from another dojo template widget I need to call a function in a dojo template widget from another dojo template widget.  The problem is I need to call this function as if it were a static function, without creating a new instance of the template -- is there anyway to do this?  In my app Template 1 is a datagrid, and Template 2 is a form opened by clicking the row in the datagrid.  I need to refresh the datagrid based on actions taken in the form
Thanks
   Start Page:

<!DOCTYPE html>

<meta name="viewport" content="initial-scale=1, maximum-scale=1,user-scalable=no"/>
    <link rel="stylesheet" href="http://js.arcgis.com/3.10/js/dojo/dijit/themes/claro/claro.css">
   <link rel="stylesheet" href="http://js.arcgis.com/3.10/js/esri/css/esri.css">

look here you

Template 1:
define(["Scripts/Mod2", "dojo/_base/declare", "dijit/_WidgetBase"],
 function (Mod2, declare, _WidgetBase) {
     return declare([_WidgetBase], {
         M1Method: function (msg) {
             alert(msg);
             M2 = new Mod2();
             M2.M2Method("call from Mod1"); //works great
             // Mod2.M2Method("call from Mod1"); //any way to make so this could work like static function?
         },
         M1Method2: function (msg) {
             alert(msg);
         }
     }
 )
 }
);

Template 2:
define(["require", "dojo/_base/declare", "dijit/_WidgetBase"],
 function (require, declare, _WidgetBase) {
     return declare([_WidgetBase], {
         M2Method: function (msg) {
             alert(msg);
             try {
                 require(["Scripts/Mod1"], function (Mod1) {
                     M1 = new Mod1();
                     M1.M1Method2("call from Mod2");
                     //Mod1.M1Method2("call from Mod2");//any way to make so this could work like static function?
                 });
             } catch (dohObj) {
                 alert(dohObj.message);
             }
         }
     }
 )
 }
);

A: I'm not entirely sure what you're actual question is, but if you want to create "static methods", then yes, it's possible. Just add them after the declare() statement, like this:
var M1 = declare([_WidgetBase], {
    /** Your code */
});
M1.M1Method = function(msg) {
    /** Your static method */
};
return M1;

However, please note that if you create a static method, it is not available when you create an instance, for example the following will work:
M1.M1Method("test");

But this won't work any longer:
var m = new M1();
m.M1Method("test");

If you want to create a method that is both available as part of the prototype AND as a "static method", then you can write something like this:
/** An object containing your "static methods" */
var statics = {
    static: function (msg) {
        console.log("Static:" + msg);
    }
};

/** Your actual prototype */
var M1 = declare([], lang.mixin({
    nonStatic: function (msg) {
        console.log("Non static:" + msg);
    }
}, statics));
/** Mixin the statics */
lang.mixin(M1, statics);
return M1;

So, we're using dojo/_base/lang::mixin() here to mix the static object twice, first we're using it to mix it into the prototype, so you can still access the method when you're having an instance and then we mix it into the result as well.
I've setup a basic example on JSFiddle: http://jsfiddle.net/g00glen00b/FE9Qz/


text:
Q: InvalidOperationException al publicar el Web Service hecho en WCF, Me muestra este error
[InvalidOperationException: Ya se asoció otra versión al URI de escucha 'http://xxx/SERVICES/WS_SOE.svc'. Si dos extremos desean compartir el mismo ListenUri, deben compartir también la misma instancia del objeto de enlace. Los dos extremos conflictivos se especificaron en llamadas AddServiceEndpoint(), en un archivo de configuración o en una combinación de ambos. ]

A: el servicio lo tenia en ambiente test y funcionaba bien, pero cuando lo subi al servidor de produccion fallaba con ese error que les muestro
Gracias por los que quisieron ayudarme
Al final lo resolvi agregandole estas etiquestas en el Web.Config
<services>
     <service behaviorConfiguration="SOEBehavior" name="WS_SOE.WS_SOE">
         <endpoint address="" binding="basicHttpBinding" bindingConfiguration=""
                  name="SOEBasicHttpEndPoint" contract="WS_SOE.IWS_SOE" />

     </service>
</services>

<behavior name="SOEBehavior">
       <serviceDebug includeExceptionDetailInFaults="true" />
       <serviceMetadata httpGetEnabled="true"/>
</behavior>

Espero y les sirva a otros.


text:
Q: React Native Web for web only project? I like the cleaness of react-native where everything is a <View/> component and am considering using it for web only project.
There are 3 concerns which make me hesitate

*

*probably there are much more web component for web environment. (so plain react might offer more library for web development)

*not sure if RN-web has any disadvantage over React on SEO?

*Would it be possible to mix in react.js code when needed? (just like we go out to android/ios native side when we can't do everything in RN side)

I'd like to hear from whoever tried using RN-web for web project.

*

*edit

The reason why I want RN-web is mostly because our RN code base is much bigger than web even though this project is web-only. (and I feel RN is much cleaner, I don't know why :()


text:
Q: MEF composition issue I can't solve what seems to be a basic MEF problem:
I have 2 "plugins" project (which we'll call P1 and P2), and a third project that is common to both plugins (which we'll call C). P1 and P2 both reference C.
When trying to import a component that lives in P1, it fails because this component has dependencies on components that live in C.
Here is the trace:

System.ComponentModel.Composition Warning: 1 : The ComposablePartDefinition 'MyCompany.Client.Pms.Plugin.InclusionList.ViewModel.InclusionListViewModel' has been rejected. The composition remains unchanged. The changes were rejected because of the following error(s): The composition produced multiple composition errors, with 4 root causes. The root causes are provided below. Review the CompositionException.Errors property for more detailed information.
1) No exports were found that match the constraint '((exportDefinition.ContractName = "MyCompany.Client.Plugins.Common.Controls.Selectors.PortfolioSelectors.ViewModel.ICalypsoBookSelectorViewModel") && (exportDefinition.Metadata.ContainsKey("ExportTypeIdentity") && "MyCompany.Client.Plugins.Common.Controls.Selectors.PortfolioSelectors.ViewModel.ICalypsoBookSelectorViewModel".Equals(exportDefinition.Metadata.get_Item("ExportTypeIdentity"))))'.
Resulting in: Cannot set import 'MyCompany.Client.Pms.Plugin.InclusionList.ViewModel.InclusionListViewModel.CalypsoBookSelectorViewModel (ContractName="MyCompany.Client.Plugins.Common.Controls.Selectors.PortfolioSelectors.ViewModel.ICalypsoBookSelectorViewModel")' on part 'MyCompany.Client.Pms.Plugin.InclusionList.ViewModel.InclusionListViewModel'.
  Element: MyCompany.Client.Pms.Plugin.InclusionList.ViewModel.InclusionListViewModel.CalypsoBookSelectorViewModel (ContractName="MyCompany.Client.Plugins.Common.Controls.Selectors.PortfolioSelectors.ViewModel.ICalypsoBookSelectorViewModel") -->  MyCompany.Client.Pms.Plugin.InclusionList.ViewModel.InclusionListViewModel -->  DirectoryCatalog (Path="C:\Work\mmtrader\dashboard\Code\Src\Dashboard\MM\Trader\bin\Debug\Plugins\Positions")

[...] (The 3 other problems are exactly the same, on different view models)
I have looked at the MEF catalog, and it turns out that MEF knows about those view models, so I don't know what's missing.
As requested by Dennis below, here are my import/export:
Export:
Export(typeof(ICalypsoBookSelectorViewModel))]
public class CalypsoBookSelectorViewModel : ScreenWithCleanupLifecycle, ICalypsoBookSelectorViewModel
{...}

Import:
[Import(typeof(ICalypsoBookSelectorViewModel))]
public ICalypsoBookSelectorViewModel CalypsoBookSelectorViewModel { get; set; }

And the catalog:

Thanks in advance for your help!

A: I finally found the problem, and it had nothing to do with the CalypsoBookSelectorViewModel that MEF was pointing the finger on.
Indeed, the ViewModel has dependencies on another component (a CalypsoBookSelectorModel), which in turn has a dependency on a IDispatcher component.
The problem was that this IDispatcher component, which was specified with a contract name (see below), was exported TWICE (once in each plugin), so MEF couldn't tell which one to use.
The real problem of course is that MEF should have told me that, instead of pointing the finger to a class two levels up the chain.
Thanks Dennis for looking at the problem, and I hope this will help other people who'll get the same problem.
The Dispatcher import:
[Import(DispatcherNames.BackgroundDispatcherName, typeof(IDispatcher))]
public IDispatcher Dispatcher { get; set; }

A: Your P1 imports something from C (more exactly, ICalypsoBookSelectorViewModel).
When MEF container tries to create P1, it also tries to resolve all imports, which P1 depends from. Hence, it performs search for export of ICalypsoBookSelectorViewModel type (indeed, contract name, but it doesn't matter in this case) in its own catalog and parent export providers.
If such export is not found (this is your case), MEF container remains composition unchanged.
To fix this, you should add [Export(typeof(ICalypsoBookSelectorViewModel))] to the corresponding type definition.
Of course, all this implies, that your catalog and export providers (if there are any) are initialized properly.
Note, that this export definitions are not equal:
public interface IA {}

[Export(typeof(IA))] // contract name is "IA"
public class A : IA {}

[Export] // contract name is "A"
public class A : IA {}

[Export]
public class Composed
{
    [Import] // MEF will search for exports like [Export(typeof(IA))]
    private IA field1;

    [Import] // MEF will search for exports like [Export]
    private A field1;
}

A: The error ocurr because he using [Import], for import more than one you should be use [ImportMany]

A: I have been searching for the solution to this problem after i got into it. I realized that i was using System.Composition instead of using System.ComponentModel.Composition on the exporting class.


text:
Q: MapKit overlays to add floor plans to map I am trying to add an overlay to iOS MapKit in order to show floor plans. However, I am unsure about the best way of doing this. If I add the floor plans by using an MKOverlay, will the floor plans be loaded lazily or do I need to find out which part of the map is being displayed and update overlays thereafter? I also looked at using MKTileOverlay, as it is using lazy loading, but I have the impression that it should be used for completely covering of the map and not only to add to the existing one. Is this correct?

A: Yes, you are right MKTileOverlay can cover whole map with tiles and Yes it is using lazy loading.
Use MKOverlay if you are not willing to replace native look and fill of map. You can also achieve lazy loading for MKOverlay too.
Note: MKTileOverlay will not remove your already existing MKAnnotations and MKOverlay.

A: MKOverlay is a protocol, not a class. You want MKTileOverlay as of iOS 7. Things are lazy loaded according to what portion of the map is currently shown.
You might find this useful as a reference on how the tiles are numbered and organized:
https://www.mapbox.com/foundations/how-web-maps-work/
As for covering Apple's map, this will happen by default, but you can also adjust the MKOverlayLevel used to place it between Apple's base map and labels layer, or you can use canReplaceMapContent = YES if you want to disable Apple's maps entirely.


text:
Q: undefined method `model_name' for NilClass:Class in Rails 3 I got this error referring to line 3 in the view when I used a form in new action to upload photos.I tried to get multiple photo uploaded. Photo is attached to the item and the item is added to the poll. The relavant codes are:
-# new view
%h1 Upload item pictures
= form_for(@poll, :html => {:multipart => true }) do |f|
  - @poll.errors.full_messages.each do |msg|
    %p = msg
  %fieldset
    = f.label :title
    = f.text_field :title
  %fieldset
    Pending Attachments: (Max of #{Item::Max_Attachments}) each under #{Item::Max_Attachment_Size/1.megabyte} MB)
    - if @poll.items.count >= Item::Max_Attachments
      <input id="newfile_data" type="file" disabled />
    - else
      %input{:id => "newfile_data", :type => "file"}
    #attachment_list
      %ul{:id => "pending_files"}
  %fieldset
    = f.submit "Create"

class PollsController < ApplicationController
  # POST /polls
  def create
    @poll = Poll.new(params[:poll])
    process_file_uploads(@poll)
    if @poll.save
      flash[:notice] = 'poll was successfully created.'
      redirect_to(@poll)
    else
      render :action => "new"
    end
  end
  private
  def process_file_uploads(poll)
    i = 0
    while params[:attachment]['file_'+i.to_s] != "" && !params[:attachment]['file_'+i.to_s].nil?
      poll.items.build(:photo => params[:attachment]['file_'+i.to_s])
      i += 1
    end
  end
end

class Poll < ActiveRecord::Base
  has_many :items, :dependent => :destroy
  accepts_nested_attributes_for :items
end

Are there anything wrong in my codes? Thanks!

A: I got it. Just need to define new in polls_controller like
def new
  @poll = Poll.new
end

And it works!


text:
Q: How do I evaluate a statement in a Snowflake Stored Procedure I have a need to create a calculation using a JSON document. Using a simple example like 10+10-3, I want to eval the statement but Snowflake javascript doesn't allow me to evaluate the statement, has anyone figured out how to evaluate a result of a json based calculation? I have been able to assign each input to a variable then execute a select statement to get the result, however it is fairly labor intensive.

A: The eval() function indeed gives the error: JavaScript execution error: Uncaught EvalError: Dynamic code evaluation disallowed.
One workaround is to inject the expression into a SELECT statement, like this:
create or replace procedure p(S varchar)
returns number
language javascript
as
$$
    const rs = snowflake.execute({ sqlText: `SELECT ${S}` })
    rs.next()
    return rs.getColumnValue(1)
$$;

call p('1+1');

But beware of SQL injection.  Or implement a simple javascript infix expression parser.


text:
Q: Office COM add-in, dialogs don't have the luna/aero theme (they look like Windows 98 classic look) I have an addin for Office 2007 which adds a toolbar with some buttons and handlers for their OnClick events. When the user clicks on the buttons, some dialogs show. But those dialogs have the dated Windows 98 look and feel with rectangular buttons, even on Windows 7.
I know that you need a manifest file to enable theming, but this addin is created with Visual Studio 2008 and it adds a manifest automatically which looks like this:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">
  <trustInfo xmlns="urn:schemas-microsoft-com:asm.v3">
    <security>
      <requestedPrivileges>
        <requestedExecutionLevel level="asInvoker" uiAccess="false"></requestedExecutionLevel>
      </requestedPrivileges>
    </security>
  </trustInfo>
  <dependency>
    <dependentAssembly>
      <assemblyIdentity type="win32" name="Microsoft.VC90.CRT" version="9.0.21022.8" processorArchitecture="x86" publicKeyToken="1fc8b3b9a1e18e3b"></assemblyIdentity>
    </dependentAssembly>
  </dependency>
</assembly>

What should I change to make my dialog use the current theme instead of Windows 98 look?
I've read about isolation awareness, but that didn't seem to work either.

A: As you've discovered, adding the manifest is only half of the battle. You also need to call the InitCommonControlsEx function when your add-in initializes, before any controls are created. This is necessary to register the window classes for the common controls you use.
And just in case you're skeptical of the documentation, Microsoft's Raymond Chen posted an article on his blog a while back addressing precisely this issue.
If you have any other issues, check this article: How to apply Windows XP themes to Office COM add-ins


text:
Q: Count specific word occurrence on page I have a webpage that has a table of usernames and scores, and it changes weekly based on scores. I just want to have a number of user's shown on my page. My table has multiple 's so using a script to count those will not work.
Every row does have something in common though, the word "Score". So I figured I could just count that word, and return the value. I cannot figure out how to just count that one word after the page is loaded completely.
Help?
Edit: fixed tag

A: Well that was easy, sorry for the bother.
I have $playerPicks listed in the table, so all I did was use:
echo count($playerPicks);

A: You can use simple Javascript - which is done on the clients machine, so it'll save server resources.
JSFiddle
var str = document.body.innerText;
var n = str.match(/Score/ig);

*

*The i flag means case insensitive search

*The g flag means to do a global match (match all occurrences, not just one)


text:
Q: Scrollable div fill available height iam currently trying to create a "split view" site with a scrollable navigation bar on the left side and a content area on the right.
The navigation area on the left contains a search field (with a submit button) and below there is a scrollable tree view similar to windows explorer.
I looked around and found solutions for scrollable divs and divs that fill the rest of the height in a window but combining those gives me some headache
Iam looking for a solution without absolute positioning because the created page will be embedded somewhere else where this would break things.
Here is a demo of what i tried so far: http://codepen.io/anon/pen/Aesgk/
As you can see, instead of 2 scrollbars as intended, i get a third one on the right because the navigation area's height.
Thanks in advance!

A: Try this CSS
height: 100%
overflow: scroll


text:
Q: I want records with clearence rate > 75. I can't use this in where clause, how should I do it? Select
suburb,round(100*count(case when result like 'Sold%' Then 1 else null end)/count(*))
AS clearence_rate
from sales
group by suburb
order by suburb;

A: If you want to filter the result of an aggregate expression you would do
Select suburb, <aggregate expression> AS clearence_rate
from sales
group by suburb
having  <aggregate expression> > 75
order by suburb;

A: There 2 opotion available.
First using CTE:
;WITH CTE AS (
Select
suburb,round(100*count(case when result like 'Sold%' Then 1 else null end)/count(*))   as [value]
AS clearence_rate
from sales
group by suburb
order by suburb
)
Select * from CTE Where [value] > 75

Second option using HAVING cluase:
Select
suburb,round(100*count(case when result like 'Sold%' Then 1 else null end)/count(*))   as [value]
AS clearence_rate
from sales
group by suburb
HAVING round(100*count(case when result like 'Sold%' Then 1 else null end)/count(*))   > 75


text:
Q: How to handle callbacks in Jetpack compose? I am migrating my multiple activity app to single activity app.
In the activity I am observing a live data from view model. When the observable triggers, I start a payment activity from a third party SDK as shown below.

onCreate() {
  viewmodel.orderCreation.observe {
    thirdpartysdk.startPaymentWithThisOrder(context)
  }
}

onActivityResult() {
  // use payment result
}

As I will be using a Composable now,
@Composable
fun PaymentScreen(onOrderCreated: () -> Unit) {
   val orderCreation by viewmodel.orderCreation.observeAsState()

   // How to use order creation once here to call onOrderCreated here only once as composable is called again and again
}

A: Here's my suggestion:
In your viewmodel, create a function to reset your orderCreation. And another field + function to store the payment result.
Something like:
fun resetOrderCreation() {
    _orderCreation.value = null
}

fun paymentResult(value: SomeType) {
    _paymentResult.value = value
}

Now, in your composable, you can do the following:
@Composable
fun PaymentScreen(onOrderCreated: () -> Unit) {
    // 1
    val orderCreation by viewmodel.orderCreation.observeAsState()
    var paymentResult by viewmodel.paymentResult.observeAsState()
    // 2
    val launcher = rememberLauncherForActivityResult(
        PaymentActivityResultContract()
    ) { result ->
        viewModel.paymentResult(result)
    }

    ...
    // 3
    LaunchedEffect(orderCreation) {
        if (orderCreation != null) {
            launcher.launch()
            viewModel.resetOrderCreation()
        }
    }
    // 4
    if (paymentStatus != null) {
        // Show some UI showing the payment status
    }
}

Explaining the code:

*

*I'm assuming that you're using LiveData. But I really suggest you move to StateFlow instead. See more here.

*You will probably need to write a ActivityResultContact to your third party lib. I wrote a post about (it's in Portuguese, but I think you can get the idea translating it to English).

*As soon the orderCreation has changed, the LaunchedEffect block will run, then you can start the third party activity using launcher.launch() (the parameters for this call are defined in your ActivityResultContract).

*Finally, when the payment status changed, you can show something different to the user.


text:
Q: Connect to MySQL with TCP I'm new to TCP world, so i'm trying many things.
How could I connect to a MySQL db with tcp/ip or UDP?
I dont' want to use a library, I want to do it by myself.

A: TCP. The protocols used are described in the "Client/Server Protocol" and "X Protocol" sections of the source-level documentation.
(The two protocols are an either/or choice. The X Protocol is newer and supports a wider range of features, but may be more difficult to implement than the "classic" client/server protocol.)


text:
Q: How to reset the vscode UI between tests? Is there is a way to reset the vscode user interface between tests, or at least before/after a full test run? Specifically to clear dialogs.
Background
I have a project created using the yeoman code generator recommended in the vscode extension development tutorials.
When I run the tests by launching "Extension Tests" from the Debug tab, a dedicated vscode window appears to host the running tests.
One of the tests triggers showing of a modal warning dialog, created by calling:
vscode.window.showWarningMessage(message, { modal: true })

However, these dialogs seem to persist between test-runs, unless I manually click to close them before the test window closes.
Worse, the dialog instances seem to aggregate - if I don't manually close a dialog at the end of one run, the same instance reappears the next time in addition to the new one added by the new run of the tests.
For the large majority of my tests I am stubbing UI interactions to avoid this issue. But I'd like solve this problem so I can have at least a few focused tests that drive the UI.
I have looked through the extension reference and some existing extensions but haven't spotted the solution yet.


text:
Q: Why am I getting a Mixin undefined error when compiling my LESS code? I am new to LESS and am trying to create a complex structure to my LESS files so I can separate the front end framework files from my platform files from my client specific changes.... So to that end I have a structure using @import "filename.less"; like this (all separated into sub folders....)
master.less > platform.less > bootstrap.less > variables.less
                                             > mixins.less
                                             > ............etc

                            > font-awesome.less > ........etc

                            > bootstrap-ui.less > ........etc

                            > platform-variables.less
                            > platform-mixins.less
                              ......... etc

            > site.less > site-variables.less
                          ...............etc..
                          random-page.less

OK so master.less has a import to platform.less and site.less etc....
My question how come I am able to use the mixins defined in mixins.less file.... in random-page.less but not able to use the mixins defined in my custom mixin file in random-page.less (platform-mixins.less) that is called from the platform.less file I'm very confused....   please advise.
The error that I receive is:
>> NameError: .no-padding is undefined in css/site/random-page.less on line 75, column 3:
>> 74   .footer-sidebar {
>> 75           .no-padding;
>> 76   }

Which is true because it does not exist in this file?
However the bootstrap standard mixin works as expected despite the  clear fix mixin/class not existing in this file...
.footer-sidebar {
    .clearfix;
}

A: To understand your structure, I created five files as follow:

*

*master.less:
.master {master:1;}
@import "site";
@import "platform";

*platform.less
.platform {platform:1;}
@import "platform-mixins.less";

*platform-mixins.less
.platform-mixins {platform-mixins:1;}
.platform-mixin() {color: red;}

*random-page.less
.random-page {
    .platform-mixin()
}

*site.less
.site {site:1;}
@import "random-page";

After that I run lessc master.less which outputs the following CSS code:
.master {
  master: 1;
}
.site {
  site: 1;
}
.random-page {
  color: red;
}
.platform {
  platform: 1;
}
.platform-mixins {
  platform-mixins: 1;
}

As expected, the .platform-mixin() from platform-mixins.less can be called without errors in random-page.less. So make sure that your mixin exists and that you really import the files you mention.


text:
Q: Form Sanitize using filter_var() and html entities() in PHP My input must be validated using  filter_var()  and  html_entities().
Heres my code which doesn't work:
session_start();

if(empty($_POST['add']) === false ) {

    $name =    filter_var(INPUT_POST, 'name', FILTER_SANITIZE_STRING);
    $email =   filter_var(INPUT_POST, 'email', FILTER_SANITIZE_EMAIL);
    $phone =   filter_var(INPUT_POST, 'phone', FILTER_SANITIZE_INT);
    $address = filter_var(INPUT_POST, 'address', FILTER_SANITIZE_STRING);

}
?>

When i do a test and put "Frost" into my Name input it comes out in bold but its not suppose to. After this is done It needs to write out to the $_SESSION['cart']. Im lost at this point

A: From the comments so far I can see:
If your $_GET variable contains that array, you are not posting the HTML form right. Use this for POST-ing a HTML <form>:
<form action="/path/to/script.php" method="post" enctype="multipart/form-data">

</form>
Also, like Peter van der Wal said, use the filter_input() function instead of filter_var() if you want to use INPUT_POST. Otherwise use filter_var($_POST['input_name'], FILTER_SANITIZE_STRING).
For more help post more HTML code
If you are new to coding/PHP I suggest you familiarize yourself with W3Schools and PHP Documentation. Quite useful if you understand these resources. Good way to start learning.

A: So at this point I need to submit the form to itself for testing purposes, now heres my code at this current time:
   <?php

 session_start();
 if(empty($_POST['add']) === false ) {

$name =    filter_var($_POST['name'], FILTER_SANITIZE_STRING);
$email =   filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);
$phone =   filter_var($_POST['phone'], FILTER_SANITIZE_INT);
$address = filter_var($_POST['address'], FILTER_SANITIZE_STRING);

}
?>
    <form method="post" action="cart.php" id="form1">

        Name:

        <input type="text" name="name">

        Email:

        <input type="email" name="email">

        Phone:

        <input type="tel" name="phone">

        Address:

        <input type="textarea" name="address">

            <input type="checkbox" value="remember">

            Remember Me

            <input type="submit" value="Submit">

    </form>

I also have a debug module on the page and now its in the $_POST array instead go GET which is good but when I put html entities inside the name input field they still aren't being sanitised/removed.
Debug Module:
$_POST contains:
Array
(
[name] => Frost
[email] =>
[phone] =>
[address] =>
)

*Frost shows in bold when I add the BOLD html tag into its input field but the whole point of this is to stop that from happening.


text:
Q: Classification of circle bundles over a 2-manifold with boundary I want to understand and try to give a proof of the following claim:
Let $B$ be a compact, connected topological $2$-manifold (surface) with nonempty boundary, then the $S^1$-bundles over $B$ with structure group $O(2)$ are in 1-1 correspondence with $\mathrm{Hom}(\pi_1(B), \mathbb{Z}_2)$.
I am familiar with the basic properties of bundles but not very familiar with how to classify them. It would be extremely helpful if you could help me prove this step by step so I can understand what is the idea here, so I am not completely lost when another similar thing comes up.


text:
Q: ios Ad-hoc install won't complete I have an iOS app that I want to test by doing an ad-hoc install through iTunes instead of through Xcode to make sure that it meets Apples guidelines. (It had a crash on the iPad when I submitted it the first time. I think I fixed it, but I want to test it this way to make sure)
It installed the first time, when I was verifying that I got the same crash that Apple got. When I fixed the bug and re-archived/exported the ipa file, imported it into iTunes and copied it to the iPad it started to install and then failed part way.
The app showed up on the screen, the install status circle appeared and started to fill, and then it just stopped, the circle went away, and now the icon is sitting there greyed out. According to iTunes it's still installing.
Not sure what to do with it now to finish it.

A: Sounds to me like you have a provisioning profile problem.
You need to make sure that your device (whatever the device you are using) has it's UUID first of all in the iOS Member Center, and secondly in the actual provisioning profile you are using for the Ad Hoc build.


text:
Q: How to find duplicates in one column and tag them in a new column depending on date order in a third column using R I have  a data frame that looks like this
idnr       date
a43        2011-12-19
a4945      2012-09-11
a43        2013-10-01
a231       2012-05-09
a231       2009-09-10
a6901      2015-06-12

I want (duplicates are defined only within idnr)

*

*the lower date of duplicates to be marked with 2 in newcolumn

*the higher date of duplicates to be marked with 1

*the non-duplicates to be marked with 2:

Again, duplicates are only defined within the idnr column.
   idnr       date          newcolumn
   a43        2011-12-19    2
   a4945      2012-09-11    2
   a43        2013-10-01    1
   a231       2012-05-09    1
   a231       2009-09-10    2
   a6901      2015-06-12    2

Or, if you like, I want the second reported duplicate to be tagged as 1 in newcolumn and the rest to be a 2.

A: library(dplyr)
Let's first create your table
table <- data.frame(indr = c('a43','a4945', 'a43', 'a231', 'a231', 'a6901'),
                date = c(as.Date('2011-12-19'), as.Date('2012-09-11'),  as.Date('2013-10-01'),
                as.Date('2012-05-09'), as.Date('2009-09-10'), as.Date('2015-06-12')))

Then we identify the duplicates
duplicates <- as.character(table$indr[duplicated(table$indr)])

Afterwards we assign a 2 to each unique value:
table$newcolumn[!table$indr %in% duplicates] <- 2

And finally you can use a for loop to assign the other values based on the max of the date
for(i in duplicates){
temp_table <- filter(table, indr == i)
high_date <- max(temp_table$date)
#now we assign the values
table$newcolumn[table$indr == i & table$date == high_date] <- 1
table$newcolumn[table$indr == i & table$date != high_date] <- 2
}

And that should do it


text:
Q: struts 2 Bean does not populate in action class I am using Struts 2-Spring framework in my assignment.
I have defined a bean in struts 2 action class
One interceptor for checking authorisation before executing every action.
The bean is used for defining controls like textfield, Radio button, etc on jsp page.
On submit of this page control goes properly to defined action class, but finds bean object as null in action class. Hence unable to perform futher operations.
Removing interceptors works fine.
Any pointer will be appreciated.

A: I haven't defined stack for interceptors defined in struts.xml.
After defining below stack in struts.xml its works fine:
<interceptors>
<interceptor-stack name="applicationStack">
    <interceptor-ref name="exception"/>
    <interceptor-ref name="alias"/>
    <interceptor-ref name="servletConfig"/>
    <interceptor-ref name="i18n"/>
    <interceptor-ref name="prepare"/>
    <interceptor-ref name="chain"/>
    <interceptor-ref name="scopedModelDriven"/>
    <interceptor-ref name="modelDriven"/>
    <interceptor-ref name="fileUpload"/>
    <interceptor-ref name="checkbox"/>
    <interceptor-ref name="multiselect"/>
    <interceptor-ref name="staticParams"/>
    <interceptor-ref name="actionMappingParams"/>
    <interceptor-ref name="params">
      <param name="excludeParams">dojo\..*,^struts\..*</param>
    </interceptor-ref>
    <interceptor-ref name="conversionError"/>
    <interceptor-ref name="validation">
        <param name="excludeMethods">input,back,cancel,browse</param>
    </interceptor-ref>
    <interceptor-ref name="workflow">
        <param name="excludeMethods">input,back,cancel,browse</param>
    </interceptor-ref>
    <interceptor-ref name="debugging"/>

    <!-- User defined interceptor -->
    <interceptor-ref name="contextSecurityInterceptor"/>
</interceptor-stack>


text:
Q: List.OrderByDescending results in duplicates This is my code
var peaks = FindPeaks(lfw, peakwidth);

var peaksordered = peaks.OrderByDescending(x => x.Value)
  .ThenBy(x => x.Frequency)
  .Distinct().ToList();

foreach (var mmm in peaksordered)
{
    Console.WriteLine(mmm.Frequency + ";" + mmm.Value);

}
return;

FindPeaks returns a List<FrequencyValue> which looks like this
public class FrequencyValue
{
    public double Frequency { get; set; }
    public double Value { get; set; }
}

When using the foreach with peaks, I get something like
12,3;0,4
14,5;0,7
...

As it should be. But if I use it the way mentioned I get only one result - or - if I omit the .Distinct() I get something like
12,3;0,4
12,3;0,4
12,3;0,4
12,3;0,4
12,3;0,4
12,3;0,4
12,3;0,4
12,3;0,4
12,3;0,4
....

Only duplicates. What do I need to change for ordering to work?
PS: Findpeaks:
    public static IEnumerable<FrequencyValue> FindPeaks(IEnumerable<FrequencyValue> lfw, int width)
    {
        FrequencyValue peak = new FrequencyValue();
        peak.Value = 0;
        int decay = 0;

        foreach (var value in lfw)
        {
            if (value.Value > peak.Value || decay > width / 2)
            {
                peak.Value = value.Value;
                peak.Frequency = value.Frequency;
                decay = 0;
            }
            else
                decay++;

            if (decay == width / 2)
                    yield return peak;
        }
    }

A: You've got two bugs cancelling each other out. This is very confusing.
Ordering is fine. Your Distinct is doing reference comparisons so it does not delete duplicates. Implement IEquatable<Frequenz_und_Wert> and override GetHashCode.
In addition, you are always returning the same object instance from FindPeaks. That's why Distinct appears to work (although not the way you need it). It just collapses the entire list to one item (to the only different item).
foreach happens to work for you because the printing happens between moments you do a yield return. The loop will always print from the same object, but the object is being modified in between iterations.
Move Frequenz_und_Wert peak = new Frequenz_und_Wert(); into the loop to create a new item for each iteration.

A: Your FindPeaks should look like this:
public static IEnumerable<Frequenz_und_Wert> FindPeaks(IEnumerable<Frequenz_und_Wert> lfw, int breite)
{
    int decay = 0;

    Frequenz_und_Wert peak = new Frequenz_und_Wert();
    peak.Wert = 0;
    foreach (var value in lfw)
    {
        if (value.Wert > peak.Wert || decay > breite / 2)
        {
            peak.Wert = value.Wert;
            peak.Frequenz = value.Frequenz;
            decay = 0;
        }
        else
            decay++;

        if (decay == breite / 2)
        {
                yield return peak;
                peak = new  Frequenz_und_Wert(){Wert = peak.Wert, Frequenz = peak.Frequenz};
        }
    }
}

The reason why the sorting is not working is that you keep overwriting the same instance, you need to return a new instance of Frequenz_und_Wert for every yield return.


text:
Q: High Surrogate Detection in Oracle Regular Expression I have a web service that pulls text from an NCLOB column and returns the data via XML. The NCLOB column is populated by extracting text from documents, so there are occasions where invalid XML characters are placed in the XML, causing the consuming system to fail.
As per the W3C, the range of valid characters is:
#x9 | #xA | #xD | [#x20-#xD7FF] | [#xE000-#xFFFD] | [#x10000-#x10FFFF]
/* any Unicode character, excluding the surrogate blocks, FFFE, and FFFF. */

We have tried a few different RegExp patterns, and we're close, but we're not completely there yet. Here is the closest we've come. All of the invalid characters are replaced except for the high surrogates (DB9B - DBFF).
REGEXP_REPLACE(
    TEXT,
    '[^[:print:]' || chr(13) || chr(10) || ']|[' || UNISTR('\FFFE-\FFFF') || ']',
    '*')

We have also tried this, but none of the surrogates (D800 - DFFE) are replaced.
REGEXP_REPLACE(REPLACE(TEXT, unistr('\0000'), ' '),
      '[' || unistr('\0001-\0008') || ']'
  || '|[' || unistr('\000B-\000C') || ']'
  || '|[' || unistr('\000E-\001F') || ']'
  || '|[' || unistr('\D800-\DFFF') || ']'
  || '|[' || unistr('\FFFE-\FFFF') || ']',' ')

How can we match the high surrogates? Any thoughts or guidance would be most appreciated.

A: You could write your own function since regex_replace does not seem to work for the high surrogates. Here's an example (tested on 9.2 and 11.2):
CREATE OR REPLACE FUNCTION replace_invalid(p_clob NCLOB) RETURN NCLOB IS
   l_result NCLOB;
   l_char   NVARCHAR2(1 char);
BEGIN
   FOR i IN 1 .. length(p_clob) LOOP
      l_char := substr(p_clob, i, 1);
      IF utl_raw.cast_to_binary_integer(utl_raw.cast_to_raw(l_char))
          BETWEEN to_number('DB9B', 'xxxx') AND to_number('DBFF', 'xxxx') THEN
         l_result := l_result || N'*';
      ELSE
         l_result := l_result || l_char;
      END IF;
   END LOOP;
   RETURN l_result;
END;

It should run with large NCLOB, here's an example with a clob > 32k characters:
SQL> DECLARE
  2     l_in  NCLOB;
  3     l_out NCLOB;
  4  BEGIN
  5     FOR i IN 1 .. to_number('DBFF', 'xxxx') LOOP
  6        l_in := l_in || nchr(i);
  7     END LOOP;
  8     dbms_output.put_line('l_in length:' || length(l_in));
  9     l_out := replace_invalid(l_in);
 10     dbms_output.put_line('l_out length:' || length(l_out));
 11     dbms_output.put_line('chars replaced:'
 12                        || (length(l_out) - length(REPLACE(l_out, '*', ''))));
 13  END;
 14  /

l_in length:56319
l_out length:56319
chars replaced:102

A: You can use series of calls TRANSLATE.
For example,
SELECT UNISTR('abc\00e5\00f1\00f6') Source FROM DUAL;
SELECT TRANSLATE(UNISTR('abc\00e5\00f1\00f6'), UNISTR('a\00e5\00f1'), 'a') Final FROM DUAL;

Source
------
abcåñö

Final
------
abcö

SQLFiddle


text:
Q: Simple selenium test failing when using AssertEqual function My whole script works until the last 2 lines where it fails.
    # Your shopping cart is empty banner
    emptyBanner = driver.find_element_by_xpath("/html/body/div/div[2]/div/div[3]/div/p").text
    self.assertEqual(emptyBanner, "Your shopping cart is empty.", "The basket is not empty")

when stepping through the code while debugging, I can see a variable 'emptyBanner' of type String is created and 'Your shopping cart is empty.' is stored within it.
Then on the last line comparing the variable and then the string, it fails.
On the exception error, the expected result is blank, I don't understand where the string stored in the variable went?
Ran 1 test in 14.127s

FAILED (failures=1)

The basket is not empty
Your shopping cart is empty. !=

Expected :
Actual   :Your shopping cart is empty.

I'm at a complete loss.
Here's the full code (im very new to coding/selenium):
from selenium import webdriver
from selenium.webdriver import ActionChains
import unittest

class Test(unittest.TestCase):
  def testShoppingCart(self):
    driver = webdriver.Chrome()
    driver.get("http://automationpractice.com/index.php")
    driver.maximize_window()

    actions = ActionChains(driver)

    # locators for Women and Summer Dresses in Nav Menu
    Women = driver.find_element_by_xpath("/html/body/div/div[1]/header/div[3]/div/div/div[6]/ul/li[1]/a")
    summerDresses = driver.find_element_by_xpath(
        "/html/body/div/div[1]/header/div[3]/div/div/div[6]/ul/li[1]/ul/li[2]/ul/li[3]/a")

    # select Summer Dresses from Nav Menu
    actions.move_to_element(Women).move_to_element(summerDresses).click().perform()
    driver.find_element_by_xpath("/html/body/div/div[2]/div/div[3]/div[2]/ul/li[1]").click() #click dress
    driver.find_element_by_id("add_to_cart").click() #add dress to cart
    driver.implicitly_wait(2)
    driver.find_element_by_xpath("/html/body/div/div[1]/header/div[3]/div/div/div[4]/div[1]/div[2]/div[4]/a").click() #click proceed to checkout button

    #checkout
    driver.find_element_by_xpath("/html/body/div/div[2]/div/div[3]/div/p").is_displayed() #check to see if dress is in checkout
    trashIcon = driver.find_element_by_class_name("icon-trash")
    trashIcon.is_displayed() #check to see if delete button is displayed
    trashIcon.click() #click delete icon

    # Your shopping cart is empty banner
    emptyBanner = driver.find_element_by_xpath("/html/body/div/div[2]/div/div[3]/div/p").text
    self.assertEqual(emptyBanner, "Your shopping cart is empty.", "The basket is not empty")

   if __name__ == '__main__':
       unittest.main()


text:
Q: How can I download IIS express by command?
*

*Can I use nuget tool getting latest version of IIS express? How if can?

*If nuget cannot do that, is there any way else that I can complete this task in one command line? Windows7

A: It seems you are searching for something like this:
Install-WindowsFeature -Name Web-Server -IncludeAllSubFeature -IncludeManagementTools -ComputerName Server1 -Credential contoso.com\johnj99

See Install-WindowsFeature for more details.


text:
Q: No indication of menu I imported a menu from my bootstrap to wordpress theme, at time of just static html, it showed and worked fine but when i used the wp_nav_menu, i don't have a 'text' or any indication to dropdown that menu, as its a dropdown menu. Am i missing something in the following code?
   wp_nav_menu( array(
        'menu'              => 'primary',
        'theme_location'    => 'primary',
        'depth'             => 3,
        'container'         => 'div',
        'container_class'   => 'collapse navbar-collapse',
        'container_id'      => 'bs-example-navbar-collapse-1',
        'menu_class'        => ' dropdown-menu',
      )
    );

as i would like to have a arrow to click to open dropdown.
Edit: I tried walker class, but i don't get a indicator of my dropdown and my styles in css just fails and i think walker class just overwrite it.


text:
Q: Show that the cosine of $\theta$ is $\frac{1 - t^2}{1 + t^2}$. Where am I going wrong? I've recently picked up the book Mathematics and it's History by John Stillwell due to a recent curiosity in the history of math.
I started doing one of the exercises in the book and got a little stumped (I'll admit, I'm quite rusty at math).

I'm asked to use this figure ...

... to show that $\cos \theta = \dfrac{1 - t^2}{1 + t^2}$.

I labeled the bottom side of the smaller triangle $a$, and the right side of the smaller triangle as $b$, which makes the bottom side of the bigger triangle $1 + a$.
In these terms, $\cos \theta = a$, since the hypotenuse of the smaller triangle is $1$.
I also came up with the following equations:
$$
a^2 + b^2 = 1
$$
$$
(a + 1)^2 + b^2 = t^2
$$
Solving the first equation for $b$ gives:
$$
b = \sqrt{1 - a^2}
$$
Substituting this equation into the second equation above gives:
$$
(a + 1)^2 + (\sqrt{1 - a^2})^2 = t^2
$$
$$
a^2 + 2a + 1 + 1 - a^2 = t^2
$$
$$
2a + 2 = t^2
$$
$$
a = \frac{t^2 - 2}{2}
$$
As you can tell, $\frac{t^2 - 2}{2}$ is not equal to the given $\frac{1 - t^2}{1 + t^2}$.
Where am I going wrong in my logic? Thanks!

A: You never say what $t$ is. I suppose that it is the slope of the line. Since it is a line passing through $(-1,0)$ and $(\cos\theta,\sin\theta)$, you have $t=\frac{\sin\theta}{1+\cos\theta}$. So,$$t^2=\frac{1-\cos^2\theta}{(1+\cos\theta)^2}$$and therefore\begin{align}\frac{1-t^2}{1+t^2}&=\frac{(1+\cos\theta)^2-1+\cos^2\theta}{(1+\cos\theta)^2+1-\cos^2\theta}\\&=\frac{2\cos^2\theta+2\cos\theta}{2+2\cos\theta}\\&=\cos\theta.\end{align}


text:
Q: swift playground can't find any type I'm new to swift playground, and I tried to create a instance of Type like Scene or Graphic. But every time I try it keep saying  cannot find 'Scene' in scope or cannot find 'Graphic' in scope.

What I am missing here?
Thanks

A: If you're using Xcode 12.5 beta, try to enable import App types from the right menu (you can open the right menu using the top right corner button). I think that should solve the problem, but i could be wrong.
Also read this answer by Vitali


text:
Q: Fetching timestamp from firestore Cloud Functions nodejs I am an interface where I have declared lastLogin as Date.
LastLogin looks like this:
export interface User {
 lastLogin: Date,
}

I am fetching this timestamp in my cloud function and I want it as a timestamp so that I can subtract it from the current Timestamp.
const mentor: User = mentorDoc.data() as User;
const login = mentor['lastLogin'];
const lastOpen  =  mentor['lastLogin'].valueOf();
const currentTime  = new Date().getTime();
const diffMs = (currentTime - lastOpen);
const diffHrs = Math.floor((diffMs % 86400000) / 3600000); // hours

Last open shows like this :
063740174400.000000000

And when I use to like this :
const lastOpen  = new Date (mentor['lastLogin'].valueOf());

Output:
undefined

A: Please change Date to firestore Timestamp both in the interface declaration as well as the collection field that holds the date in the firestore console
export interface User {
  lastLogin: firebase.firestore.Timestamp,
}

You can now retrieve the date and also update it, this time simply by passing a new Date object.
// Read currently saved Timestamp
const ref = db.collection<User>('users').doc(`${uid}`).get().toPromise()
const saved_date = ref?.data().lastLogin
const current_date = new Date()

// if you just want the Date difference in ms after retrieving the timestamp from firestore.
const diff = current_date.getMilliseconds() - (saved_date.toDate()).getMilliseconds() // Timestamp -> Date (ms)

// Update Timestamp using a Javascript Date object
 db.collection('..').doc('..').set({ lastLogin: current_date }, {merge:true})

// set creates the field while update works only if field already exists