text:
Q: How to handle authentication in PHP REST web service? I've read that a good way to write web services to be consumed from mobile apps is to avoid SOAP (too verbose) and to use REST. In many REST examples, I have seen it is better to avoid sessions due to the stateless nature of REST. But how can I assure security when invoking my web service? I would like to make a "login" call than pass a session_id/token to the next web service call. How can I do it?

A: The cleanest way would be using HTTP authentication.
While that wouldn't go by the login+sessionid way you mentioned it would be much cleaner and more straightforward (API calls do not related on other API calls and clients do not need to expect session timeouts etc.)

A: You can pass user token (and session, or any other auth data if you need it) in a json request like:
{"auth": {"session_id": "abc", "token":"123"},
 "data": "your request data"
}

If you are crazy about security you can generate a new token after each user login and even have life time for tokens.


text:
Q: Alerts don't show in captcha I have a Problem in Captcha Alert showing .
When I enter captcha code Incorrcet in Registration Page, The Alerts don't work .
My Captcha Code:

  <img src="captcha/captcha_code_file.php?rand=<?php  echo rand(); ?>" id='captchaimg'  style="border:1px solid #CCC;">

  <input id="6_letters_code" name="6_letters_code" type="text" style="width:200px;margin-top:-15px;" tabindex="7">

Error Alert code:
<?php
if( isset ($_REQUEST['register']) ) {

    if( empty($_SESSION['6_letters_code'] ) || strcasecmp($_SESSION['6_letters_code'], $_POST['6_letters_code']) != 0)
        {
            echo $msg .= '';
        }
}?>

where I should use this Alert Code ?? after captcha code or end of the my code ??

A: Looks like your IF session and strcasecmp section was messed up a bit. This should work as long as $_REQUEST['register'] and $msg are doing what I imagine you want them to do.
<?php

if(isset($_REQUEST['register'])) {

    if(
        (empty($_SESSION['6_letters_code']))
        ||
        (strcasecmp($_SESSION['6_letters_code'], $_POST['6_letters_code']) != 0)
    )
    {
        echo $msg .= '';
    }

}

?>

As for the alert, perhaps you need to use an auto-displaying JS alert like this (instead of using the "echo $msg .=" line...
echo '';

redpajama_set_name: RedPajamaStackExchange


text:
Q: Sequence is periodic $x_{n+2}=|x_{n+1}-x_{n-1}|$ How to show that the sequence $$x_n, n \geq 0, x_{n+2}=|x_{n+1}-x_{n-1}|, n \geq 1$$
with $x_0, x_1, x_2$ positive integers, not all null,  is periodic?
I tried to pick up the square but obtained equalities not helped.
Thanks so much for any suggestion.

A: Each number in the sequence is an integer in the range $[0,\max(x_0,x_1,x_2)]$.  As soon as you have three consecutive numbers appear in turn, that have previously appeared in that same order, then the sequence must repeat.  Now apply the pigeonhole principle.

A: Clearly
\begin{align}
&x_{n+2} =\lvert x_{n-1}-x_{n+1}\rvert\le \max\{x_{n-1}, x_{n+1}\}, \\
&x_{n+3} =\lvert x_n-x_{n+2}\rvert\le \max\{x_{n}, x_{n+2}\}, \\
\end{align}
and hence
$$
x_{n+3}\le \max\{x_{n+2},x_{n+3}\}\le\max\{x_{n-1},x_{n},x_{n+1},x_{n+2}\}
$$
and recursively
$$
x_n\le \max\{x_0,x_1,x_2,x_3\}=\max\{x_0,x_1,x_2\}=:N.
$$
This means that $x_n\in\{0,1,\ldots,N\}$, for all $n\in\mathbb N$.
In particular,
$$
(x_n,x_{n+1},x_{n+2})\in\{(i,j,k): 0\le i,j,k\le N\}=:S,
$$
and since $S$ is finite, then there are $k,m\in\mathbb N$, such that
$$
(x_\ell,x_{\ell+1},x_{\ell+2})=(x_{\ell+m},x_{\ell+m+1},x_{\ell+m+2}).
$$
But, using the recursive definition, this implies that $x_{\ell+3}=x_{\ell+m+3}$, and inductively we obtain that
$$
x_{\ell+j}=x_{\ell+m+j}, \quad \text{for all}\quad j\in\mathbb N.
$$
Thus the sequence $\{x_n\}_{n\in\mathbb N}$ is periodic with period $m$.

A: ALSO POSTED ON A DIFFERENT QUESTION.
The answers posted above don't complete the analysis to give the period, they only assert it exists - in fact the sequence need not be strictly periodic although the ultimate period is $7$ (I can't count and initially put $6$). The exception would be the null sequence (period $1$).
Note that the absolute value of the $x_r$ is at most the maximum of $x_{k-2}, x_{k-1}, x_k$  for any $k\lt r$ - we can't get a greater value than we've had already, so there is a point in the sequence where we hit the highest value.
Suppose $x_{n-1}$ is the highest possible value. We have $x_{n+2}=x_{n-1}$ only if $x_{n+1}=0$ and this is true only if $x_n=x_{n-2}$ so if the highest value $a$ is sustained we have $ \dots x_{n-2}, x_{n-1}, x_n, x_{n+1}, x_{n+2} \dots = \dots b, a, b, 0, a \dots$ with $a\ge b$.
The sequence then continues $\dots b,a,b,0,a,a-b,a-b,b \dots$, and unless $b=a$ or $b=0$ the maximum value within the tail of the sequence has decreased (since any three consecutive terms define the rest of the sequence, and we could consider the tail of the sequence as starting with $a-b, a-b, b$). Since we can't have an infinite decreasing sequence of non-negative numbers we must reach the situation where $a=b$ when the sequence goes:
$$\dots a,a,a,0,a,0,0,a,a,a \dots$$
When $b=0$ we get the same sequence shifted $$\dots 0,a,0,0,a,a,a,0,a,0 \dots$$
So the sequence starts off decreasing before becoming periodic. If it turns out that $a=0$ there is ultimate period $1$ (constant) otherwise ultimate period $7$.
The constant $a$ is the highest common factor of the three initial values.


text:
Q: JMX exporter & spark-on-k8s-operator I'm trying to submit a spark application using spark operator and to expose metrics using JMX exporter.
I'm using Spark 3.1.1 & spark operator v1beta2-1.3.3-3.1.1
Here is a snippet from the configuration.
monitoring:
    exposeDriverMetrics: true
    exposeExecutorMetrics: true
    prometheus:
      jmxExporterJar: "/opt/spark/jars/jmx_prometheus_javaagent-0.11.0.jar"
      port: 8090
      configFile: "/opt/spark/work-dir/prometheus/prometheus.yaml"
  driver:
    cores: 1
    coreLimit: "1200m"
    memory: "2g"
    javaOptions: "-Dconfig.file=/opt/spark/work-dir/conf/application_app.conf -Dlog4j.configuration=file:///opt/spark/work-dir/log/log4j_app.properties"
    labels:
      version: 3.1.1
    serviceAccount: spark-jobs-spark

The application doesn't expose any metrics from the driver.
below you can find prometheus yaml:
# These come from the application driver if it's a streaming application
      # Example: default/streaming.driver.com.example.ClassName.StreamingMetrics.streaming.lastCompletedBatch_schedulingDelay
      - pattern: metrics<name=(\S+)\.(\S+)\.driver\.(\S+)\.StreamingMetrics\.streaming\.(\S+)><>Value
        name: spark_streaming_driver_$4
        labels:
          app_namespace: "$1"
          app_id: "$2"
      - pattern: metrics<name=(\S+)\.(\S+)\.spark.streaming.(\S+)\.(\S+)><>Value
        name: streaming_query
        labels:
          job: "$1"
          instance: "$2"
          query: "$3"
          name: "$4"
      # These come from the application driver if it's a structured streaming application
      # Example: default/streaming.driver.spark.streaming.QueryName.inputRate-total
      - pattern: metrics<name=(\S+)\.(\S+)\.driver\.spark\.streaming\.(\S+)\.(\S+)><>Value
        name: spark_structured_streaming_driver_$4
        labels:
          app_namespace: "$1"
          app_id: "$2"
          query_name: "$3"
      # These come from the application executors
      # Example: default/spark-pi.0.executor.threadpool.activeTasks
      - pattern: metrics<name=(\S+)\.(\S+)\.(\S+)\.executor\.(\S+)><>Value
        name: spark_executor_$4
        type: GAUGE
        labels:
          app_namespace: "$1"
          app_id: "$2"
          executor_id: "$3"
      # These come from the application driver
      # Example: default/spark-pi.driver.DAGScheduler.stage.failedStages
      - pattern: metrics<name=(\S+)\.(\S+)\.driver\.(BlockManager|DAGScheduler|jvm)\.(\S+)><>Value
        name: spark_driver_$3_$4
        type: GAUGE
        labels:
          app_namespace: "$1"
          app_id: "$2"
      # These come from the application driver
      # Emulate timers for DAGScheduler like messagePRocessingTime
      - pattern: metrics<name=(\S+)\.(\S+)\.driver\.DAGScheduler\.(.*)><>Count
        name: spark_driver_DAGScheduler_$3_count
        type: COUNTER
        labels:

NOTE: Here is an interesting part. If I'm using spark-shell with javaagent defined with jmx exporter I'm able to find the metrics but not from spark-submit. What am I missing?
I tried to run a jmx exporter with spark-shell inside the pod and it worked. I have no idea why it's not working from spark-submit.


text:
Q: Integral with fourth, cube and square root We are seeking to evaluate this integral:
$$\mathrm{\int_{1}^{4}\left (\frac{1}{x^{2}+\sqrt{{3x\left ( x^{2}-9\sqrt[3]{\frac{1}{x-5}} \right )}}-\sqrt[4]{5x+7}}+x^{3}-6x^{2}+5x-3  \right )dx}$$
I have been trying to solve for hours, but I still can't find the solutions. Anyone has an idea?


text:
Q: What is the reasoning behind isNaN's implementation? Although the name of the function isNaN refers semantically to the value isNaN, the native implementation returns true for some non-NaN objects like undefined or {}.
isNaN(undefined);
=> true

I think, e.g., underscore's implementation is much more intuitive/logical:
_.isNaN(undefined);
=> false

Why did the ECMA standard specify such a counterintuitive behavior?
Why didn't they design isNaN to return true only if the value to test is
really isNaN and leave the burden to test for convertability-to-number on a separate isNumber function?
Doing it this way would have led to even more advantages like no double negative when testing for numbers:
if (isNumber(x)) { } // if x is a number

instead of
if (!isNaN(x)) { }   // if x is not not a number

Since they are going to introduce Number.isNaN() in ECMAScript 6 (which does exactly what you would expect from it), it looks like there are more people thinking like this.
So, why did they design isNaN the way it is in the first place? Was it just a wrong decision or was there a good reasoning to do so?


text:
Q: JavaFX Как в лайв режиме проврить checkbox на галочку Привет всем,
Я в JavaFX новечек и хотел бы узнать как сделать так, чтобы если допустим CheckBox был нажат то SplitMenuButton становилась в режим disable или наоборот.

A: Для этого необходимо использовать selectedProperty(). Необходимо повесить на него листенер, и в листенере уже делать свои вещи.
Пример :
checkBox.selectedProperty().addListener((observable, oldValue, newValue) - > {
    if (newValue && !oldValue) {
        //чекбокс был переведен с положение включено
    } else if (!newValue && oldValue) {
        //чекбокс был переведен с положение выключено
    }
});


text:
Q: is there anything like timestamp(9) in teradata I just encountered a scenario where I have to load data like :
'2014-12-24 13:59:10:060606066'
in a Teradata table have datatype as Timestamp
as you can see in millisecond format there are 9 digits , is there any way to load such data
or Teradata does'nt supports it at all.
for now i have removed last 3 digits made it like '2014-12-24 13:59:10:060606' and loaded in database but I may need to handle it in future.

A: Perhaps you can accomplish this by storing three fields in your table:

*

*Message_Queue_Timestamp TIMESTAMP(6) NOT NULL

*Message_Queue_Date DATE NOT NULL

*Message_Queue_Seconds_From_Midnight FLOAT NOT NULL
Using dnoeth's suggestion to convert the input using to_timestamp() to retain a DBA-friendly timestamp in the table. This is Message_Queue_Timestamp.
Then split the incoming timestamp into two fields: Message_Queue_Date and Message_Queue_Seconds_From_Midnight. I was originally going to suggest that the latter be stored as DECIMAL(14,9) but then realized as a FLOAT formatting/converting it to a TIME in Teradata is easier. These two fields allow you to retain the precision of the timestamp that was ingested by the database without having to store the data as a character string.
The conversion of the timestamp to seconds should be fairly straight forward in your ETL processing. Hope this helps.


text:
Q: Can't enter mysql root password on mac terminal I have downloaded and installed the appropriate version for my 2014 macbook and my server is running. I have done the bash code thing that I don't understand but the next step is
Mysql -u root -p
Enter password:

Now I have tried everything to do this. I know the mac terminal does not show the password as you type. That's not the problem I have also tried using
Mysql -u root -password ='temppassword'

But this time it tells me it's not safe to write passwords in the line and rejects me
The temporary password that the program gave me includes "+ and &" symbols. Is that the problem? How can I solve this? I can't even start my mysql Journey.


text:
Q: Service, handler, timer, runnable - which to use and how? I'm trying to make an Android app which contacts a webserver every 15 minutes to retrieve som kind of RSS. I know how to retrieve the RSS, but my problem is how I make the app contact the webserver periodically.
I've read about services, handlers, timers and runnables but I don't know which of them I should use, and how I should use them.
Thanks in advance.

A: Most things that need to perform a polling operation independent of any activities should use AlarmManager for the scheduling, with your own IntentService for the implementation of the actual polling logic. If you intend for the device to wake up out of sleep mode to do the work, you will need a _WAKEUP alarm with the AlarmManager and perhaps my WakefulIntentService.

A: Consider using the BuzzBox SDK: it perfectly fits your use case. There is also an RSS parser included in the library.
http://hub.buzzbox.com/android-sdk/
You can set up your Task to run every 15 minutes like this:
SchedulerManager.getInstance()
    .saveTask(this, "*/15 8-19 * * 1,2,3,4,5", YourTask.class);
SchedulerManager.getInstance()
    .restart(this, YourTask.class);

Notice the cron string: "*/15 8-19 * * 1,2,3,4,5" - your Task will run every 15 min, from 8am to 7pm, mon to fri.
The library takes care of the rest (rescheduling after reboot and after clock changes, error handling and retries...) and has some nice features: learn more: http://hub.buzzbox.com/android-sdk/scheduler


text:
Q: how to connect my java base desktop application with Quickbooks to fetch data? I am new for the QuickBooks. Can any one guide me what steps I required to load data from Buickbook in my local application and Do i required to make Webservice?

A: Take a look at the FAQs
http://docs.developer.intuit.com/0025_Intuit_Anywhere/0058_FAQ
This seems like a duplicate question as well.
thanks
Jarred


text:
Q: Kafka JDBC Connect (Source and Sink) and Informix is there any way to convert ":" to "." in a query constructed by jdbc connector?
"SELECT * FROM  database  :  user  :  table  WHERE  database  :  user  :  table "
connector configuration:
"name": "jdbc_source_connector",
"config": {
    "connector.class" : "io.confluent.connect.jdbc.JdbcSourceConnector",
    "connection.url" : "jdbc:informix-sqli://IP:PORT/databasa:informixserver=oninit;user=user;password=password",
    "topic.prefix" : "table-",
    "poll.interval.ms" : "100000",
    "mode" : "incrementing",
    "table.whitelist" : "table",
    "query.suffix" : ";",
    "incrementing.column.name" : "lp"

ERROR:
[2021-02-03 14:03:02,809] INFO Begin using SQL query: SELECT * FROM  database  :  user  :  table  WHERE  database  :  user  :  table : lp  > ? ORDER B
Y  database  :  user  :  table : lp  ASC ; (io.confluent.connect.jdbc.source.TableQuerier:164)
[2021-02-03 14:03:02,853] ERROR Failed to run query for table TimestampIncrementingTableQuerier{table="database "." user "." table", query='null', top
icPrefix='database-', incrementingColumn='lp', timestampColumns=[]}: {} (io.confluent.connect.jdbc.source.JdbcSourceTask:404)
java.sql.SQLSyntaxErrorException: A syntax error has occurred.

connector session:
informix database:/usr/informix$ onstat -g ses 544271

IBM Informix Dynamic Server Version 12.10.FC13 -- On-Line -- Up 60 days 18:26:06 -- 4985440 Kbytes

session           effective                                               #RSAM    total      used       dynamic
id       user     user      tty      pid      hostname                    threads  memory     memory     explain
544271   user      -         -        1266352  kafkahost                  1        172032     102672     off

Program :
Thread[id:175, name:task-thread-jdbc_source_connector_database, path:/app/kafka_2.13-2.7.0/plugins/kafka-connect-jdbc-10.0.1/lib/jdbc-4.50.4.1.jar]

tid      name     rstcb            flags    curstk   status
583042   sqlexec  7000000437451a8  Y--P---  6224     cond wait  netnorm   -

Memory pools    count 2
name         class addr              totalsize  freesize   #allocfrag #freefrag
544271       V     70000004f6c7040  167936     68592      113        35
544271*O0    V     700000065ad0040  4096       768        1          1

name           free       used           name           free       used
overhead       0          6656           scb            0          144
opentable      0          11352          filetable      0          1040
log            0          16536          temprec        0          22688
keys           0          816            gentcb         0          1592
ostcb          0          3472           sqscb          0          25128
hashfiletab    0          552            osenv          0          2056
sqtcb          0          9336           fragman        0          640
sapi           0          144            udr            0          520

sqscb info
scb              sqscb            optofc   pdqpriority optcompind  directives
7000000343d3360  700000039194028  0        0           0           1

Sess       SQL            Current            Iso Lock       SQL  ISAM F.E.
Id         Stmt type      Database           Lvl Mode       ERR  ERR  Vers  Explain
544271     -              database                CR  Not Wait   0    0    9.28  Off

Last parsed SQL statement :
  SELECT * FROM  database  :  user  :  table  WHERE  database  :  user  :  table :
    lp  > ? ORDER BY  database  :  user  :  table : lp  ASC

A: so, the only workaround is to add the query option to the connector configuration
config after modifications:
"name": "jdbc_source_connector",
"config": {
    "connector.class" : "io.confluent.connect.jdbc.JdbcSourceConnector",
    "connection.url" : "jdbc:informix-sqli://IP:PORT/databasa:informixserver=oninit;user=user;password=password",
    "topic.prefix" : "table-tablename",
    "poll.interval.ms" : "100000",
    "mode" : "incrementing",
    "query" : "select * from table ",
    "incrementing.column.name" : "lp"


text:
Q: How to make the unicode larger which is placed inside the button? I'm beginner class coder and I'm trying to create white circle inside the button using the unicode (Change to white color), but I really don't know how to increase the unicode size and place it center inside the button.
If you have any other options to put circle inside button, please help me out (It doesn't have to be unicode and putting unicode was the only way I can think of).
What I actually want to do is when the circle is aligned right, it is active status, but when the circle is aligned left, it will be changed to deactive status. I'm struggling with this.
Thank you.

.notification {
  display: flex;
}

.push-title {
  font-size: 1.15rem;
}

.push-active {
  margin-left: 20%;
  color: #8A8A8A;
}

.btn-active {
  margin-left: 3%;
  background: #FF512F;
  background-image: -webkit-linear-gradient(left top, #FF512F, #DD2476);
  background-image: -moz-linear-gradient(left top, #FF512F, #DD2476);
  background-image: -ms-linear-gradient(bottom right, #FF512F, #DD2476);
  background-image: -o-linear-gradient(bottom right, #FF512F, #DD2476);
  background-image: linear-gradient(bottom right, #FF512F, #DD2476);
  -webkit-border-radius: 60;
  -moz-border-radius: 60;
  border-radius: 60px;
  padding: 1px 24px 1px 24px;
  text-decoration: none;
}

Push Notifications

Active

          •

A: css
.notification {
  display: flex;
}

.push-title {
  font-size: 1.15rem;
}

.push-active {
  margin-left: 20%;
  color: #8A8A8A;
}

.btn-active {
  margin: 0 auto;
  background: #FF512F;
  background-image: -webkit-linear-gradient(left top, #FF512F, #DD2476);
  background-image: -moz-linear-gradient(left top, #FF512F, #DD2476);
  background-image: -ms-linear-gradient(bottom right, #FF512F, #DD2476);
  background-image: -o-linear-gradient(bottom right, #FF512F, #DD2476);
  background-image: linear-gradient(bottom right, #FF512F, #DD2476);
  -webkit-border-radius: 60;
  -moz-border-radius: 60;
  border-radius: 60px;
  padding: 1px 24px 1px 24px;
  text-decoration: none;
  color:white;
  height:30px;
  font-size:60px;
  line-height:28px;
}

HTML

Push Notifications

Active

   •

A: if you use bootstrap , i recommened this for you
http://bootsnipp.com/snippets/x8pBm

A: You can use a pseudo element on a checkbox and toggle the status based on whether it's selected or not.

input {
  display: none;
}
label {
  width: 1.5em;
  height: 1em;
  background: red;
  border-radius: .5em;
  display: inline-block;
  overflow: auto;
  position: relative;
  text-indent: 9999px;
  cursor: pointer;
}
label:after {
  content: '';
  width: .5em;
  height: .5em;
  background: black;
  border-radius: 50%;
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-100%,-50%);
  transition: transform .25s, background .15s;
}
input:checked + label:after {
  transform: translate(0%,-50%);
  background: white;
}
<input id="checkbox" type="checkbox">active

A: You could use a span or div and style it to be the circle. This can be done in many ways. Just a sample below. Hope it puts you in the right direction

.notification {
  display: flex;
}

.push-title {
  font-size: 1.15rem;
}

.push-active {
  margin-left: 20%;
  color: #8A8A8A;
}

.btn-active {
  margin-left: 3%;
  background: #FF512F;
  background-image: -webkit-linear-gradient(left top, #FF512F, #DD2476);
  background-image: -moz-linear-gradient(left top, #FF512F, #DD2476);
  background-image: -ms-linear-gradient(bottom right, #FF512F, #DD2476);
  background-image: -o-linear-gradient(bottom right, #FF512F, #DD2476);
  background-image: linear-gradient(bottom right, #FF512F, #DD2476);
  -webkit-border-radius: 60;
  -moz-border-radius: 60;
  border-radius: 60px;
  padding: 0 10px;
  text-decoration: none;
  display: flex;
  align-items: center;
    width: 38px;
    height: 22px;
    justify-content: flex-start;
}
.btn-active span {
  display: block;
  padding: 5px;
  background: green;
  border-radius: 50%;
}

Push Notifications

Active


text:
Q: Manually route a global keyboard shortcut to a specific application on Windows7? I have an application (last.fm 1.5.4) that doesn't use global keyboard shortcuts, i.e. its shortcuts only work when the application has focus.
Is there a way of manually defining a global shortcut in windows7 that will be routed to the application, even when it doesn't have focus?

A: Only to remark that AutoHotkey, suggested by Botond Balázs, started as a fork of AutoIt.
AutoIt has continued to evolve even more, and may be more pleasurable for writing scripts.

A: If we're all going the autohotkey route, let's give some scripting help!
This script was reccomended by Lifehacker, and looks pretty good to me. Never used last.fm, so that's all I've got :)
Looks like it's a little complex, but if you simply paste that script into the top of a .ahk file (basically a text file with the extension .ahk), then you can use things like:
#p::ControlLastFM("Toggle")

to play/pause on Winkey (# is the winkey modifier) and P (p is p, any key will do :))

A: You can use AutoHotKey to define a global shortcut, and bind it to a script that sends key presses to the window.


text:
Q: Docker terminology confusion When we do,
docker images

I see a list of images with their repository, tag, image id, created and virtual size.
I understand what image id and created are.
But what is the relationship between repository and tag?
And is the virtual size?
I went through the glossary on their website. But I couldn't find any information about this. The reason I ask is because when I do docker images I sometimes see the same image being listed more than once with the same image id but different tag.

A: Indeed, I found it confusing as well.
In a nutshell:

*

*an image is uniquely defined by its id (a docker image is analogous to a git commit)

*a given image may be tagged one or multiple times (just like git tags)

*a repository is a set of images, to quote the documentation: "a repository is a hosted collection of tagged images that together create the file system for a container."

The git analogy might be useful to grasp this.
About the size: "size" is the size of the commit (eg: of the image), while virtual size is the cumulative size of all "previous" images this image is based upon (eg: "all previous commits"). Some info here: https://github.com/dotcloud/docker/pull/594 and https://github.com/dotcloud/docker/issues/22
Does it help?


text:
Q: Will any modulo operation of relatively prime numbers be related to cyclic group of same order? I am engineer/applied mathematician who is quite new to most things number theory and also groups so please bear with me if this is obvious.
Consider the $b\times b$ matrix constructed by:
$$M_{ij} = \delta(j-(\text{mod }(a^i,b)))$$

*

*For which $a,b$ can we be sure $M$ is a permutation matrix.

*For which can we be sure $M$ will be a permutation matrix permutation-similar to cyclic matrix: $$P_{ij} = \delta(i,j+1) : P=QMQ^{-1}$$, where $Q$ permutation matrix.

A: I think I understand the question.
I assume that when you write $\mod(x,m)$ you mean what a mathematician would write as $x \pmod{m}$, the remainder when you divide $x$ by $m$.
Then you are asking when the powers of some number $a$ run through the possible remainders modulo $b$ once each with no repetition.
If that is the case then what you are looking for is a primitive root. That wikipedia page can get you started.
Every prime has a primitive root. For example, $a = 3$ is one for $b=7$, but $a=2$ is not. The other numbers that have primitive roots are the powers of primes and twice the powers of primes.
It's easy to count how many primitive roots there are, but very hard to find one.


text:
Q: Group query for months I have this table.
+------------------------+--------------------+-----+
| id                     |mydate              |value||
+------------------------+------+-----+-------------+
| 1                      |2018-06-18 18:34:09 |50   |
| 2                      |2018-06-18 12:34:09 |50   |
| 3                      |2018-08-18 13:34:09 |10   |
| 4                      |2018-08-18 14:34:09 |10   |
| 5                      |2018-09-18 16:34:09 |20   |
| 6                      |2018-09-18 17:34:09 |10   |
+------------------------+--------------------+-----+

I would like a Query to get something similar
Group for months
I would like a consultation to achieve this
|mydate   |value|
+---------------+
June      |100  |
August    |20   |
September |30   |

in case it is not possible with MySQL. (It could be in PHP)

A: You should use sum, group by, and MONTHNAME to get the result you need.
select sum(value), MONTHNAME(mydate) as month
from test
group by month

If you require the text version of the months you could swap that in PHP.
http://sqlfiddle.com/#!9/26b8fb/2

A: Here is an example:
SELECT MONTHNAME(mydate) as month, SUM(value) as value FROM myTable GROUP BY month


text:
Q: Port 8083: Failed to invoke the service. Possible causes: The service is offline or inaccessible I have a wcf service which is hosted in windows service and when run at 8083 port, the service method invocation from client throws below error. However if the service is started at another port number , then there is no error when the operation contract is invoked from the client . how can i resolve the error with port 8083
The HTTP service located at http://localhost:8083/WinService is unavailable.  This could be because the service is too busy or because no endpoint was found listening at the specified address. Please ensure that the address is correct and try accessing the service again later.
Server stack trace:
   at System.ServiceModel.Channels.HttpChannelUtilities.ProcessGetResponseWebException(WebException webException, HttpWebRequest request, HttpAbortReason abortReason)
   at System.ServiceModel.Channels.HttpChannelFactory`1.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan timeout)
   at System.ServiceModel.Channels.RequestChannel.Request(Message message, TimeSpan timeout)
   at System.ServiceModel.Dispatcher.RequestChannelBinder.Request(Message message, TimeSpan timeout)
   at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs, TimeSpan timeout)
   at System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage methodCall, ProxyOperationRuntime operation)
   at System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage message)
Exception rethrown at [0]:
   at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)
   at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)
   at IInterOpIntegrationWCFService.TestService(ClientIdentity objClientIdentity)
   at InterOpIntegrationWCFServiceClient.TestService(ClientIdentity objClientIdentity)
Inner Exception:
The remote server returned an error: (503) Server Unavailable.
   at System.Net.HttpWebRequest.GetResponse()
   at System.ServiceModel.Channels.HttpChannelFactory`1.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan timeout)

A: For this situation, a service endpoint WCF must always supply the ABC - Address, Binding, Contract. You only define the binding and contract in your config. I notice that there is nothing within the endpoint address property.
And you can refer to the following links for more information:
Why WCF cannot be invoked in wcftestclient?
https://social.msdn.microsoft.com/Forums/vstudio/en-US/4d900638-dbbd-4d88-a835-bc8565e83cbf/failed-to-invoke-the-service-possible-causes-the-service-is-offline-or-inaccessible-while-invoking?forum=wcf
Answered by
http://forums.asp.net/t/2016601.aspx?wcf+test+client+failed+to+invoke+the+service


text:
Q: SQL - select x entries within a timespan I'm creating a database (in MySQL) with a table of measurements. For each measurement I want to store the DateTime it came in. For showing plots within an app for different intervals (measurements of the day/week/month/year) I want sample the data points I have, so I can return e. g. 30 data points for the whole year as well as for the day/hour. This is the same as done with stock price graphs:
stock price plot for 1 day
vs
stock price plot for 1 month
As you can see, the amount of data points is the same in both pictures.
So how can I select x entries within a timespan in MySQL via SQL?
My data looks like this:
+====+====================+=============+==========+
| id | datetime           | temperature | humidity |
+====+====================+=============+==========+
| 1  | 1-15-2016 00:30:00 | 20          | 40       |
+----+--------------------+-------------+----------+
| 2  | 1-15-2016 00:35:00 | 19          | 41       |
+----+--------------------+-------------+----------+
| 3  | 1-15-2016 00:40:00 | 20          | 40       |
+----+--------------------+-------------+----------+
| 4  | 1-15-2016 00:45:00 | 20          | 42       |
+----+--------------------+-------------+----------+
| 5  | 1-15-2016 00:50:00 | 21          | 42       |
+----+--------------------+-------------+----------+
| 6  | 1-15-2016 00:55:00 | 20          | 43       |
+----+--------------------+-------------+----------+
| 7  | 1-15-2016 01:00:00 | 21          | 43       |
+====+====================+=============+==========+

Let's say, I always want two data points (in reality a lot more). So for the last half hour I want the database to return data point 1 and 4, for the last ten minutes I want it to return 6 and 7.
Thanks for helping!
PS: I'm sorry for any errors in my English

A: OK, assuming a very simple systematic approach, you can get the first and last entry for any defined period:
select *
from table
where mydatetime =
   (select
    max(mydatetime)
    from table
    where mydatetime between '2017-03-01' and '2017-03-15'
    )
OR mydatetime =
   (select
    min(mydatetime)
    from table
    where mydatetime between '2017-03-01' and '2017-03-15'
    )

A: I believe your answer can be found at the following location:
https://stackoverflow.com/a/1891796/7176046
If you are looking to filter out any items not within your date/time your query would use:
Select * from table where Date/Time is (What you want to sort by)


text:
Q: Format negative integers in two's complement representation I would like to represent an negative integer in bits, using two's complement representation. Using standard Python bit representation utilities doesn't help much:
>>> bin(-5)
'-0b101'
>>> format(-5, 'b')
'-101'

-5 in two's complement is represented as 1011. How do I do this?

A: Python's integers already use two's complement, but since they have arbitrary precision, the binary representation of negative numbers would have an infinite string of 1s at the start, much like positive numbers have an infinite string of 0s. Since this obviously can't be shown, it is represented with a minus sign instead.
If you want the binary representation for a specific width, you can just use modulo.
>>> bin(-5)
'-0b101'
>>> bin(-5 % (1<<32))
'0b11111111111111111111111111111011'


text:
Q: Webpack - CSS Minification and Bundle Almost three hours of research and here I am asking for community help.
I have an project with the following CSSs:

*

*The ones being used by every page (generics): buttons.css, tables.css, forms.css andlists.css

*The one being used only by a specific HTML page: page-custom-buttons.css.
For the ones being used by every page I want to bundle them and minify into a single file.
The one being used only by a specific page I just want to minify them.
From the many guides, questions and documentation I have walk though I found the following things:

*

*The extract-text-webpack-plugin is now deprecated and mini-css-extract-plugininstead.

*We can use mini-css-extract-plugin to bundle the CSSs.

*We can use optimize-css-assets-webpack-plugin to optimize it but it will require the installation of another package for dealing with js minifier (more about here)

The MiniCssExtractPlugin description says

This plugin extracts CSS into separate files. It creates a CSS file per JS file which contains CSS. It supports On-Demand-Loading of CSS and SourceMaps.

From the little I understand from the definition and the examples this shouldn't be used as a bundler but instead for giving the funcionallity of importing CSS from JS code like we do in react (import './styles.css').
The real questions are, don't webpack fit in this type of problems? Should I use other software? What does MiniCssExtractPlugin really do and what's the different between the css-loader. How can I do bundle myfiles and minifying them correctly?
I found a similiar unanswsered question: https://dev.to/shaijut/how-to-bundle-mutiple-js-and-css-files-into-single-bundle-2a70
Thank you for someone who might reply to this answer. Anyhing you know helpful!


text:
Q: Where is Kirk's home on Earth in "Search for Spock"? This would also have been his home in "Wrath of Khan"; because it seems to havethe same view out the window. I assume it is in the SF Bay Area but it kind of looks like it is looking back towards Sausalito and I want to know if I'm right.
However I can imagine that his home in the movies is somewhere other than it was in the original series since he is semi-retired.

A: His apartment is in Russian Hill.
The view from his apartment is looking north towards Marin County from the Russian Hill neighborhood in San Francisco.
According to FilmInAmerica.com,

This behind-the-scenes picture shows the translight used on stage to create the view out Captain Kirk's window. It appears as if the view is from Russian Hill since we can see the Marina and Presidio on the left, the Golden Gate Bridge next, and then Mount Tamalpais in the distance on the right. The Marin County lights, many of which were probably added by the effects crew, are coming from Fort Baker and Sausalito.

View looking northward toward Richardson Bay.

View looking more north-by-northwest, showing left view from Kirk's apartment.

Here is a picture of two artists creating the backdrop for Kirk's apartment.

A few oddities which you can check by comparing the image above to a Google Map of the region.

*

*Angel Island is missing. It is between Russian Hill and Marin County. It should be at the far right of the translight backdrop. (Unless the building lights at the shoreline are on Angel Island, which would be odd since Angel Island is a state park.)

*Lights from several cities are missing. There are no lights along Richardson Bay even though that currently has the cities of Sausalito, Marin City, Belvedere, Tiburon, and Strawberry.

*The Golden Gate Bridge is missing. It should be visible on the far left side of the translight backdrop. We know from subsequent movies, TNG episodes, and Deep Space 9 episodes that the iconic bridge survives until it was destroyed by surprise Breen attack during the Dominion War sometime around stardate 52,600.

A: I think it's on the Mare Island golf course looking inland.

A: According to the Memory Alpha article on apartments:

James T. Kirk's San Francisco apartment was the home of Admiral James
  T. Kirk in 2285. It was in a tall skyscraper in San Francisco and
  featured sweeping views of the city, the bay, Alcatraz, the Golden
  Gate Bridge and at least two other prominent 23rd century skyscrapers.

It dives a bit further into the backdrop itself:

The backdrop view of San Francisco from Kirk's apartment was
  previously used in the movie The Towering Inferno (1974). The backdrop
  in that movie was used for a 135th floor restaurant overlooking San
  Francisco. The metallic sculpture in Kirk's apartment near the
  fireplace bears a striking resemblance to the "Glass Tower" skyscraper
  in the movie.

A: I'm not sure there's anything within either The Wrath of Khan or The Search for Spock that explicitly says where Kirk's apartment is. The existence of both fast atmospheric shuttlecraft and transporters mean that it could actually be anywhere at all!
The simplest explanation, though, is that it is in fact in San Francisco or at least in the Bay Area. Presuming that he actually has a "day job" as an administrative admiral at Starfleet HQ, or as a teacher at the academy, or both, it would certainly be the most convenient location for him.

A: I was wondering the same thing after watching Star Trek: The Wrath of Khan on SyFy last night.
Here are a couple shots of Kirk's apartment on Memory Alpha. The windows look out onto the Bay, but I don't see the Golden Gate Bridge or Alcatraz. Does the ridge behind the bay look familiar to anyone? That could help pinpoint where in the Bay Area Kirk's home is located.


text:
Q: MDX Query aggregate combining crossjoin expression with non-crossjoin/comma-separated expression I have an issue while retrieving on columns with crossjoin(someMeasure1,someMeasure2) , someMeasure3. Details:
WITH MEMBER [Date].[Custom] AS
  'Aggregate({[Date].&[20220101]:[Date].&[20220810]})'
MEMBER [Measures].[Total YTD] AS
  '([Date].[Test1], [Measures].[Customer])'
SELECT
  crossjoin(
     {[Measures].[Customer Form], [Measures].[Customer]},
     [Date].[Monthly Key]
  ),
  [Measures].[Total YTD] on 0,
  nonempty(
    {[Hier Top].[Hier1].[city].members}
  ) on 1
FROM
  [WAREHOUSE]

It gives output:

How do combine someMeasure3 (ie [Measures].[Total YTD]) with the other crossjoined members? (I believe it's similar to SQL's aggregate functions, eg sum()/count()/max()/etc, with group by clause)
Best Wishes

A: Just realise there's Union() function there, or operator +. I can specify the second member of the tuple as Year key. Solution is
WITH MEMBER [Date].[Custom] AS
  'Aggregate({[Date].&[20220101]:[Date].&[20220810]})'
MEMBER [Measures].[Total YTD] AS
  '([Date].[Test1], [Measures].[Customer])'
SELECT
  crossjoin(
     {[Measures].[Customer Form], [Measures].[Customer]},
     [Date].[Monthly Key]
  )
  +
  ([Measures].[Total YTD], [Date].[Yearly Key]) on 0,

  nonempty(
    {[Hier Top].[Hier1].[city].members}
  ) on 1
FROM
  [WAREHOUSE]

Note that I am using op () not {} to specify the member dimensionality manually for [Measures].[Total YTD], [Date].[Monthly Key]
All good


text:
Q: Non-algebraic set of countably infinite set of points Algebraic subsets of affine space have the property $(*)$: that their intersection with a line $L$ is either finite or $L$ itself (so $L$ was a subset). I am building an example of a set with property $(*)$, but is not algebraic. I am allowed to use any field and any dimension to construct this counterexample. My original idea was to simply take the graph of $e^x$ in $\mathbb{R}^2$, or $\mathbb{A}_{\mathbb{R}}^2$ if you prefer. I think this graph clearly has the property. I had trouble showing that it wasn't an algebraic set. So, instead of forcing that route, I build a set that I imagine won't be algebraic out of points instead of arcs. The construction is as follows: Pick any two distinct points at least distance one from eachother in the plane. Pick another point by avoiding all lines connecting the previous points, and choose this point to be at least distance one from the other points. We can build a countable collection of isolated points in this way, call it $X$.
If $X$ doesn't intersect a line $L$, great. If it does in exactly one point, great. Suppose $L$ intersects $X$ in at least two points $x_i$ and $x_j$, and suppose $i<j$. In the construction of $X$, $x_j$ does not sit on a line which connects any two points of smaller index. Since $x_i$ is one point with smaller index, there can be no other points index less than $j$ on $L$. But each point after $x_j$ avoids the line containing $x_j$ and $x_i$. So $|L\cap X|=2$, and $X$ has property $(*)$.
Now I need to show that $X$ is not algebraic. My hope was that working with isolated singletons would make proving this more simple, but now I realize that there is more subtlety here than I originally thought. In any case, by way of contradiction, suppose $X$ is algebraic. Then $X$ decomposes uniquely as a non-trivial union of irreducible algebraic sets $X=U_1\cup,\dots,\cup U_n$. But each isolated point $X_i=\lbrace x_i\rbrace$ is algebraic and irreducible. Thus $X_i\subset X$ implies that each $X_i$ is a subset of some irreducible $U_j$. By countable pigeonhole, without loss of generality, suppose that $U_1$ contains countably infinitely many of our $x_i$'s. Now $U_1$ is an irreducible countably infinite set having property $(*)$. This at least tells us that $I(U_i)$ is a prime ideal.
Remark: I don't know if we need to take the $x_i$'s to be at least distance from one another, but I figured we should.

A: I think your original idea of using the graph of $e^x$ is a good one. Here's how I'd finish the proof of that statement:
Lemma: No polynomial vanishes on all points of the form $(x,e^x)$.
Proof: Plug in and take limits as $x\to\infty$. You'll have a sum of polynomials times exponential functions, and so by factoring out the maximal power of $e^x$, you can see that $0=e^{-x}(\cdots)+p(x)$ where $p(x)\neq 0$. Taking the limit as $x\to \infty$, we see that $p(x)$ must have limit $0$ at $\infty$, which is clearly nonsense.
This means that any algebraic curve in the plane can only intersect the exponential function in finitely many points. In particular, any line may intersect it at most twice.
An alternative proof is that any infinite discrete set in an affine space is not algebraic. It suffices to show this in $\Bbb A^1$, as we can reduce to this by projecting suitably. But we already know that $\Bbb A^1$ has the cofinite topology, so the claim is proven and you may wish to use this in your attempt by choosing individual points.


text:
Q: Why can't gdb evaulate functions when !=/== and &&/|| are combined in an expression? It may be that the difficulty I'm having in describing my problem is the reason I can't find anyone else with an instance of it. I am using gdb 7.4-2012.04.
It seems at the least that any expression involving both !=/== and &&/|| for vectors or vector iterators will fail to evaluate in gdb with the following error:
Cannot access memory at address 0x0
Here's a test case, followed by my compilation line and tests:
#include <stdio.h>
#include <iostream>
#include <stdint.h>
#include <vector>

using namespace std;

typedef char GUID[32];

int main(int argc, char **argv){
    vector<int> vec;
    for (int i=0; i<5; i++){
        vec.push_back(i);
    }
    for (vector<int>::iterator vecIter=vec.begin(); vecIter!=vec.end(); vecIter++){
        int i=0;//Just need a line gdb will recognize for a breakpoint.
    }
    cout << vec[0] << endl;//g++ needs to include operator[] in the binary for this to work.
    return 0;
}

Here's a snippet of the tests I performed:
user@comp$ g++ -g -O0 any_test.cpp
user@comp$ gdb a.out
(gdb) b 16
(gdb) r
Breakpoint 1, main (argc=1, argv=0x7fffffffe288) at any_test.cpp:16
16          int i=0;//Just need a line gdb will recognize for a breakpoint.
(gdb) p *vecIter == vec[1] or *vecIter == vec[2]
Cannot access memory at address 0x0

The original useful statement does not work. Let's reduce a bit and find the problem.
(gdb) p vec[1] or *vecIter == vec[2]
Cannot access memory at address 0x0
(gdb) p vec[1] or *vecIter
$1 = true
(gdb) p 1 or *vecIter == vec[2]
Cannot access memory at address 0x0

Looks like the problem is '==' after 'or'. Is this the same with other operators?
(gdb) p 1 and *vecIter == vec[2]
Cannot access memory at address 0x0
(gdb) p 1 and *vecIter != vec[2]
Cannot access memory at address 0x0

That's a resounding yes. What if I pull out all the functions for gdb? Just let it dereference and compare ints?
(gdb) p 1 or *vecIter._M_current == vec._M_impl._M_start[1]
$2 = true

Ok, let's check some combinations of derefs and functions to make sure it's not just one of these types that causes the problem:
(gdb) p 1 or *vecIter._M_current == *vecIter
Cannot access memory at address 0x0
(gdb) p 1 or vec._M_impl._M_start[1] == vec[1]
Cannot access memory at address 0x0

As you can see, the problem is not specifically the vector or its iterator. Any operator (function) called on either one will trigger this issue if inserted after &&/||, and on either side of an ==/!=.
EDIT: forgot a question again. My question is this:
Why do I get "Cannot access memory at address 0x0" in the line "p *vecIter == vec[1] or *vecIter == vec[2]"?

A: The problem is in functions that return references.  Here's a minimal example:
int& g() { static int i; return i; }
int main() {}

The same problem is exhibited (I'm using gdb 7.8.1):
(gdb) p 0 || +g()
Cannot access memory at address 0x0

A workaround is to convert the reference to a pointer and indirect it:
(gdb) p 0 || +*&g()
$1 = true

Filed a bug: https://sourceware.org/bugzilla/show_bug.cgi?id=17904

A: The order of evaluating "*vecIter == vec[1]" is evaluating *vecIter first, if true then skip evaluating vec[1] and the whole statement is true; and if false then evaluate vec[1]. The root cause here is that vecIter pointing to NULL memory, which is inaccessible, that *vecIter could not even be evaluated. Therefore gdb print out the "memory access" error.
same reason for other print statements of same error


text:
Q: SQL query like IN I have one table oc_product_option_value where is data:
product_id | option_value_id |
------------------------------
2262       |     78          |
2262       |     37          |
2263       |     70          |
2263       |     78          |
2264       |     37          |
2264       |     30          |

So, I want to get only just product_id = 2262, because it has option_value_id = 78 and 37. Another products don't match because they have only just one of this numbers.

A: Use HAVING with GROUP BY.
Query
select `product_id`
from `oc_product_option_value`
where `option_value_id` in (78,37)
group by `product_id`
having count(*) = 2;

A: You can use COUNT with DISTINCT if you have repeating entries with same option_vale_id e,g.:
SELECT product_id
FROM oc_product_option_value
WHERE option_value_id IN (37, 78)
GROUP BY product_id
HAVING COUNT(DISTINCT option_value_id) >= 2;


text:
Q: Can I support Stack Exchange sites propely by only asking right questions? Stack Exchange sites are about asking and answering. However, as I mentioned before I can't help by answering because most of the questions are about something I'm not good at. I mean, everywhere.
Though, I can help by asking questions which weren't asked before, related to the theme of the site where it's asked and either might be useful for someone in the future or provides useful and constructive answers.
Is it enough?

A: Asking good, well researched, clear questions is critical to getting good, well researched, clear answers. It's an essential part of stack exchange. As such you're certainly helping.
As such asking good questions counts under 'giving back' to the stack overflow community.
You can go further as a question asker by replying quickly and giving feedback on what helped you (by accepting solutions, upvoting good solutions and if an answer got you 95% of the way there commenting on how you got the last 5%).
Of course if you feel able to answer some questions go ahead, we love answers too, but it's certainly not mandatory.


text:
Q: Getting `NoClassDefFoundError` for classes `FutureCallback` and `LazyList` using Jetty Maven plugin 9.4.32.v20200930 on Java 11 I started a few months ago to maintain an old Spring project using the Jetty Maven plugin. I'm currently trying to port it to Java 11 but Jetty won't start the server and (silently) fails with MultiException[java.lang.NoClassDefFoundError: org/eclipse/jetty/util/FutureCallback, java.lang.NoClassDefFoundError: org/eclipse/jetty/util/LazyList].
This seems to be an old bug of the Jetty Maven plugin that I can reproduce on various 9.x versions.
It seems fixed in versions 10 and 11 and I would gladly use these versions but both are still in alpha, configuration has radically changed and documentation is not published yet.
maven.compiler.source and maven.compiler.target are both set to 11 in POM and nothing changes if I put dependencies providing org.eclipse.jetty.util.FutureCallback and org.eclipse.jetty.util.LazyList in the POM.
[WARNING] FAILED ServletHandler@4ba402b5{FAILED}: java.lang.NoClassDefFoundError: org/eclipse/jetty/util/LazyList
java.lang.NoClassDefFoundError: org/eclipse/jetty/util/LazyList
    at org.eclipse.jetty.servlet.ServletHandler.doStop (ServletHandler.java:277)
    at org.eclipse.jetty.util.component.AbstractLifeCycle.stop (AbstractLifeCycle.java:93)
    at org.eclipse.jetty.util.component.ContainerLifeCycle.stop (ContainerLifeCycle.java:180)
    at org.eclipse.jetty.util.component.ContainerLifeCycle.doStop (ContainerLifeCycle.java:201)
    at org.eclipse.jetty.server.handler.AbstractHandler.doStop (AbstractHandler.java:108)
    at org.eclipse.jetty.security.SecurityHandler.doStop (SecurityHandler.java:437)
    at org.eclipse.jetty.security.ConstraintSecurityHandler.doStop (ConstraintSecurityHandler.java:425)
    at org.eclipse.jetty.util.component.AbstractLifeCycle.stop (AbstractLifeCycle.java:93)
    at org.eclipse.jetty.util.component.ContainerLifeCycle.stop (ContainerLifeCycle.java:180)
    at org.eclipse.jetty.util.component.ContainerLifeCycle.doStop (ContainerLifeCycle.java:201)
    at org.eclipse.jetty.server.handler.AbstractHandler.doStop (AbstractHandler.java:108)
    at org.eclipse.jetty.server.session.SessionHandler.doStop (SessionHandler.java:519)
    at org.eclipse.jetty.util.component.AbstractLifeCycle.stop (AbstractLifeCycle.java:93)
    at org.eclipse.jetty.util.component.ContainerLifeCycle.stop (ContainerLifeCycle.java:180)
    at org.eclipse.jetty.util.component.ContainerLifeCycle.doStop (ContainerLifeCycle.java:201)
    at org.eclipse.jetty.server.handler.AbstractHandler.doStop (AbstractHandler.java:108)
    at org.eclipse.jetty.server.handler.ContextHandler.stopContext (ContextHandler.java:1061)
    at org.eclipse.jetty.servlet.ServletContextHandler.stopContext (ServletContextHandler.java:375)
    at org.eclipse.jetty.webapp.WebAppContext.stopWebapp (WebAppContext.java:1462)
    at org.eclipse.jetty.maven.plugin.JettyWebAppContext.stopWebapp (JettyWebAppContext.java:342)
    at org.eclipse.jetty.webapp.WebAppContext.stopContext (WebAppContext.java:1428)
    at org.eclipse.jetty.server.handler.ContextHandler.doStop (ContextHandler.java:1115)
    at org.eclipse.jetty.servlet.ServletContextHandler.doStop (ServletContextHandler.java:286)
    at org.eclipse.jetty.webapp.WebAppContext.doStop (WebAppContext.java:547)
    at org.eclipse.jetty.maven.plugin.JettyWebAppContext.doStop (JettyWebAppContext.java:433)

A: This is a interesting side-effect of interaction between maven and jetty.
What happens is that on jetty stop/shutdown the maven process yanks the classloader out from underneath the jetty threads leaving random errors in its wake, some even being unable to find classes that they need to perform a clean shutdown.
See https://github.com/eclipse/jetty.project/issues/4410
There is no workaround or fix for this that either Jetty or Maven has found.
If you find a solution please comment on the above issue (or file a new issue), and we'll document it.


text:
Q: Can we remove notes layer on Openstreetmap? Have a look at the following link :
A piece of OSM map
You can see many violet points which is added by people, I want to know if I can load only the road maps without these  violet points ( these points and related icons (such as shoes ,bicycle, climbing, ...) representing restaurants,banks,shops, ... and I do not need them. They make my map busy).
And maybe good to say that I dislike the style of humanitarian/transport/cycle map. Standard style is the best for my work.

A: This is not possible, because Openstreetmap provides only tiles to you and not the features itself. So an image is rendered on the OSM server and provided to you.
If you don't want certain features to be displayed you can either search for a map that is styled in a way you like it. The OSM Wiki provides a nice collection of tiled maps based on OSM data.
Another way is to create a map yourself. Mapbox Studio provides this service for example.


text:
Q: Creating a teamcity project from versioned controlled settings I have a git repository for a project with a .teamcity folder in it containing versioned teamcity settings. Assuming I have deleted this project from the teamcity server (by first disabling versioned settings and then deleting the project) how can I re-import it?
The use case here is being able to create a new project using a template generator, e.g. yeoman or dotnet new, and be able to import that easily into a parent TeamCity project.
Our current teamcity version is: TeamCity Enterprise 10.0.4 (build 42538), so things may have improved in later versions.

A: So I think I have figured this out, these are the steps that worked for me.

*

*Create a new project, making sure the Project ID is set correctly

*Add a VCS root pointing to your repo that contains your project

*Enable versioned settings making sure to select use settings from VCS and choosing the Kotlin settings format

*Select "Import settings from VCS" when prompted

In more detail...
Make sure the Project ID for your project matches what you have in your .teamcity file
For example if your .teamcity file contains .teamcity\MyAwesomeProject, then you need to make sure your Project ID in teamcity is set to MyAwesomeProject.
use settings from VCS
If you don't tell TeamCity to use the vcs settings by default then it will do what it usually does and start checking things into source control for you.


text:
Q: Illegal strings logcat at eclipse I have several devices. First (phone) worked correct. I see in eclipse tab logcat normal strings. On second device (Cube U30GT2), I don't know why, but see that logcat string divided on two: date/tag and messages.

How I can fix this?

A: This is no error. You're app eating recources and GC worked. It's normally. That's happens on Android 3+.

A: I think issue, that I use don't last ADT. Now we use in group 17 version. Try with another sdk (20), all ok.


text:
Q: Mysql 5.6 Replication Lag fluctuating between 0 and n I have one master and 7 slaves.
During high load on my master, I see replication lag and it keeps fluctuating between 0 and n (where n keeps increasing with time and I have seen n grow more than 1 hour). Fluctuations happen in a matter of seconds
i.e. sec:1 - Lag:0s, sec:2 - Lag:2000s, sec:3 - Lag:0s, sec:4 - Lag:2002s,

*

*When seconds_behind_master is 0; show slave status\G says: "Slave has read all relay log; waiting for the slave I/O thread to update it".

*When seconds_behind_master is n; show slave status\G says: either "Reading event from the relay log" or "System Lock".

On Master "show processlist" tells the replication thread has status "Sending binlog event to slave" always.
With the above points, I have figured that my SQL thread is not lagging and it's the IO thread which is the culprit. I read that network slowness can cause this issue, but network is not a bottleneck, as I have verified the bandwidth used between master and slaves is only 50%. When I turned on slave_compress_protocol, network usage went down but I was still seeing the replication lag grow in a fluctuating fashion.
I want to know what can be other causes apart from network which can cause this issue.
I have gone through: https://www.percona.com/blog/2013/09/16/possible-reasons-when-mysql-replication-lag-is-flapping-between-0-and-xxxxx/
and couldn't attribute my lag to any of the points mentioned in the post.
Also, when the load on master stops, replication lag stops fluctuating and starts decreasing steadily from n and finally catches up.
Thanks.
Edit:
Can it happen that due to heavy load on master (% CPU utilisation is hitting 100%), IO thread is waiting intermittently to read from the binlogs)?


text:
Q: Compatibility of ARC and Storyboard What's the compatibility of ARC and Storyboard considering devices and iOS?
Will ARC and Storyboard work on iPhone 3G, 3GS, 4 and 4S?
Will ARC and Storyboard work on iOS 4 and 5?

A: ARC runs with 5.0 or higher, Storyboard also needs iOS 5. Therefore, both are potentially available with the iPhone 3GS and above.
EDIT: Obviously, ARC is also compatible with iOS 4.0 and above, once you don't use weak. I briefly tested it, seems to work. That would mean that the iPhone 3G would also be compatible.


text:
Q: Writing stderr from one process to another process c++/unix I have one application where parent process launches jobs over distributed farm system like lsf/vnc .
Now what I want is whenever there is any error reported in thier respective log by any of the jobs launch , error should be redirected to main stdout screen of parent process. so that there is no need to monitor log of each job separately.
I have never used pipe/semaphores in my codes but I can learn that if needed.
Please suggest some efficient solution. I am working on Linux/Solaris platform.
Thanks

A: Depending on how you launch the subprocesses there are different mechanics how to set their standard handles.
In general, you'll have to set their stderr handle to be the same your stdout handle.
Keep in mind that this has nothing to do with the "logs" that you mention; it's about what your subject says (redirecting stderr).

A: If you want the stderr of the children to be the same as the stdout of the parent, then you may be able to simply launch the parent with its stderr tied to its stdout.  If cmd is the command to launch the parent, try:
$ cmd 2>&1

A: You probably should use dup2() library call in order to duplicate STDERR in the child process to desired file descriptor, for example to STDOUT of any other descriptor, which can be opened before by the parent process and inherited by the child process after fork().
Try to read manula page for "dup2" call.


text:
Q: How to add chapters into mp4/mkv file using ffmpeg? Currently i'm using MKVToolNix for my needs which is fine but i would prefer some CLI also.
As far as i know ffmpeg supports chapters management.

A: The ffmetadata format allows you to add chapters to a file.
Have a look at https://ffmpeg.org/ffmpeg-formats.html#Metadata-1 for an example.


text:
Q: How to Call function with onPress(on click) that is defined in useEffect hook I have Logout screen in which i defined Logout button, by pressing logout button I am removing token and want to redirect to login screen, when i do press it's removing token but not redirecting to login, it's redirect when I am closing or reopening or after refreshing.
to overcome this problem i am using useEffect hook for compnentDidUpdate or something like that like this.
useEffect(() => {
 const handleLogout = () => {
  // dispatch(logoutAction());
};
handleLogout();
}, [handleLogout]);

But when I am calling handleLogout on onPress, Error occur variable handleLogout not defined, because of scopes you cannot use variable outside its scope.
 <TouchableNativeFeedback onPress={handleLogout}>
    <View style={styles.logoutBtn}>
      <Text style={{color: '#FFFFFF'}}>Logout</Text>
    </View>
  </TouchableNativeFeedback>

A: just define this function outside of use effect, and only reference it and call it inside useEffect.
...
const handleLogout = () => {
  // dispatch(logoutAction());
};

useEffect(() => {
    handleLogout();
}, [handleLogout]);

return (
    <TouchableNativeFeedback onPress={handleLogout}>
    <View style={styles.logoutBtn}>
      <Text style={{color: '#FFFFFF'}}>Logout</Text>
    </View>
  </TouchableNativeFeedback>
)
...

But im not sure if this is 'good' practice, since this might cause useEffect triggers on renders, since you are passing a function as dependency. So it just looks weird from the get go in my opinion. What i would do , ditch the useEffect all together, and maybe try adding some extra function in dispatch. Something like
...
const navigation = useNavigation()

const handleLogout = () => {
  dispatch(logoutAction());
  navigation.navigate('YourInitialScreen')
};

return (
    <TouchableNativeFeedback onPress={handleLogout}>
    <View style={styles.logoutBtn}>
      <Text style={{color: '#FFFFFF'}}>Logout</Text>
    </View>
  </TouchableNativeFeedback>
)
...

Its somwhat hard to understand what exactly you are trying to do without not knowing what this dispatch really does. But maybe this helps in your brainstorming.

A: Move function definition outside useEffect:
const handleLogout = () => {
  // dispatch(logoutAction());
};

useEffect(() => {
  handleLogout();
}, [handleLogout]);


text:
Q: Rails 3.1 - Devise inserting address into subject line of confirmation email I'm using rails 3.1 with Devise.  When an account confirmation email goes out, it is received with the following subject line:
Subject:    [["test13@test.com"]]MySite Account Confirmation Instructions

I've modified the corresponding entry in config/locals/devise.en.yml like this:
mailer:
  confirmation_instructions:
    subject: 'MySite Account Confirmation Instructions'

I don't want the '[["test13@test.com"]] in the email subject line.  How can I get Devise to not put it there?  BTW I really don't want to have to create some custom mailer that overrides Devises' stock mailer...  Big extra bonus points for an answer that avoids anything to do with custom mailers.  But if that is the only way, I need to know that too...

A: My guess is that the [["test13@test.com"]] should actually only show up in development mode, since that's the format of ActionMailer's DevelopmentMailInterceptor (see the notes in RailsCast 206)
The email address between brackets indicates the address to which the email would have been sent on production. It instead sends it to you at an email specified in your DevelopmentMailInterceptor.

A: The mail subject is generated in Devise::Mailers::Helpers.headers_for (source code here), so the most straightforward way would be monkey-patching this method.

A: This was a strange one... Had to reboot my Mac, after which the problem was gone.


text:
Q: Magento Multistore possible for this? I want to make a multistore and already made the 3 different websites, stores and for every store 3 storeviews for languages.
the first shop is the german standard shop with 19% tax.
the second shop should be an austrian shop with 20% tax.
the third shop should be a swiss shop with CHF (Swiss Franks) as currency.
First of all, is this possible? And then how?

A: Short answer: yes it's possible.
Longer answer:
You can assign taxes per website so you can have a difference between DE an AT shops.
You can also have different currencies for websites.
And here you have 2 options.
You either enter the prices in EUR for your first 2 shops, enable CHF for the CH website and set an conversion rate.
Then for the CH website the prices will be automatically changed.
The second option is to change the price scope from system->configuration->catalog to Website and manage different prices for the CH website.
In this case you need to set the base currency for the CH website to CHF. You can do that from system->configuration->currency setup (I think).


text:
Q: missing method public function index()
Missing Method in BusinessController
  Error: The action index is not defined in controller BusinessController
  Error: Create BusinessController::index() in file: app/Controller/BusinessController.php.

If I add this method, it brings me to the homepage.  I want to go business_index.ctp
Here is my controller

App::uses('Controller', 'Controller');
  class BusinessController extends AppController {
     public $name = 'Business';
     public $components = array('Auth','RequestHandler','Cache');
     public $uses = array('User','CreditHistory');
     public function beforeFilter(){
         parent::beforeFilter();
     }
function Sync(){
         $this->layout = $this->autoRender = false;
     }
     //Admin Dashboard
     public function business_index(){
         $this->set('title','Dashboard');
         $uid = $this->Auth->User('id');
         $this->set('user_id',$uid);
     }

I have a view name business_index.ctp inside a folder name Business
Not sure what I am doing wrong.

A: You could either do redirect $ this-> redirect ('business_index'); in your index method or add router rule in config/routes.php. See http://book.cakephp.org/2.0/en/development/routing.html


text:
Q: Can't login after lock screen (black screen) After locking screen and monitor going into sleep mode, I can't get the login screen anymore, the monitor stays in sleep mode forever.
In previous Ubuntu versions after pressing any key or the mouse, the login screen showed up, but not anymore. I have to restart the computer.
How can I fix this issue?
Thanks.

A: I have already opened a bug report on Launchpad. Please comment there if you have the same problem.
https://bugs.launchpad.net/ubuntu/+source/unity/+bug/1617471

A: Ubuntu Gnome 16.04.1 + Nvidia graphic drivers: I have the same issue. At the moment a simple workaround is to manually recall the current X window by pressing Ctrl+Alt+F7.
Hope to find a permanent solution soon.

A: I have the same problem now, with Zorin OS 16 (final release), which is based on Ubuntu 20.1, if I'm not wrong.
I hope in'sha'Allah that I'll find a solution for this, or that these bugs would disappear after the next update. You can try installing xsrceensaver, as mentioned by benfischer on Launchpad:
sudo apt install xscreensaver

or you can try updating NVIDIA drivers (you can also remove them and reinstall them) as mentioned by System76.
First run:
sudo apt purge ~nnvidia
sudo apt autoremove
sudo apt clean

Then:
sudo apt update
sudo apt full-upgrade
sudo apt install system76-driver-nvidia

After the installation has been completed, run:
sudo systemctl reboot

Now, try logging in again.

A: Since this is a known bug that needs a patch from the developers, there is no official long-term solution that I know of (although calling dmesg and posting the time-synced results to question might help us to better help you. System boot logs are dmesg's specialty.)
The best I can offer is a workaround. It should work, although I obviously can't test it. It is my goto is situations such as yours, but every situation is unique.
The workaround:
From the black screen, hit [ctrl]+[alt]+[F5] to go to TTY. From there type sudo gnome-session or just gnome-session.
From there, let me know what you see. It should restart the session on TTY1. after that command is correctly entered, use [ctrl]+[alt]+[F1] to return to TTY1. There should be a login screen waiting for you.. no reboot required.

A: I have solved this issue for me by installing lightdm login manager. I have upgraded to Ubuntu 21.10 and after that I have started encountering the blank screen issue while system is locked.
The default Ubuntu login screen is called lightdm. Chances are it's already installed in your system, so you can just run sudo dpkg-reconfigure lightdm to re-select it. If it isn't installed, just run sudo apt-get install lightdm and then follow the commands in the wizard. If you want to uninstall the other login screen (really a display manager), write down the other choices that show up when you run the reconfigure command.
For me gdm3 was already installed, so the istallation wizard wanted to confirm which login manager to use by default, where I choose lightdm.
That's all.


text:
Q: Result "almost doubles" on Try It Online for Project Euler This code is for Project Euler Problem 1. It appears to work here, but on Try It Online (tio.run) the result appears to "almost double" (twice the expected result minus 1). It seems like every number is added twice. Is it possible to fix it?
`,`                              /-------\
`,`                            .->---{+}-~-$#&
`,`                     /------->-----^  |
`,`                    /*\     /*\    |  |
`,`                /---~-+\/---~-+\   |  |
`,`                |   ! |||   ! ||   |  |
`,` .-#1000->*-{-}-*#3[%]|\*#5[%]|\*#0/  |
`,`         |\#1/  \---/ | \---/ | |     |
`,`         |            \------->->-----*
`,`         \----------------------------/

Test case for smaller constant:
`,`                              /-------\
`,`                            .->---{+}-~-$#&
`,`                     /------->-----^  |
`,`                    /*\     /*\    |  |
`,`                /---~-+\/---~-+\   |  |
`,`                |   ! |||   ! ||   |  |
`,` .-#10--->*-{-}-*#3[%]|\*#5[%]|\*#0/  |
`,`         |\#1/  \---/ | \---/ | |     |
`,`         |            \------->->-----*
`,`         \----------------------------/

(Prints 23 on Aaron, and 45 on Try It Online)


text:
Q: How far to go with functional level increase? I'm running an AD environment with a virtual DC running 2008r2 on Hyper-V, a physical DC running 2008 at a remote location, and another physical DC collocated with the vitual DC, running 2003r2. This last DC is very old and the hardware is failing. I am transitioning roles off of it. The plan will be to put in a new DC running 2012. Forest is at 2000 and domain is at 2003. I have to raise the functional level of the forest to install the new server, to a minimum of 2003. Should I go through all the work of preparing for this transition only to stop at 2003, or should I just change both forest and domain to 2008? It's a very simple environment (7 policies in the whole thing and about 50 users). I'd rather raise it as far as possible- what are the risks? I know rolling back is a big deal, and the change will have to complete late Saturday night, so time is a factor. What is the likelihood of failure? None of our custom apps even use AD. Other considerations: we heavily use Citrix XenApp 5 as a terminal server, Exchange 2007, SQL Server 2005, 2008, 2008r2.
Thanks!

A: Updating to a 2008 functional-level should be just fine. Your environment is not old enough to run into any significant issues, and you're retiring the oldest thing there as part of this. Should be just fine.

A: Well you need a compelling reason to do so.  I haven't done this in my environment yet but think it's a pretty slick feature with a function level of 2008r2+.  Active Directory recycle bin....http://technet.microsoft.com/en-us/library/dd392261(v=ws.10).aspx


text:
Q: Using the tar command to display all files in a .tar archive to a file and to standard output Is it possible to direct that input from this command to a file and also to standard output?
tar -t all.tar
Also Is there a way to kill all processes running lets say an xclock?

A: you can use pipe the output of tar -t all.tar to the command tee
tar -t all.tar | tee output_file_name


text:
Q: How to check other user's input command or related command history log in Red hat 7.5 I find sometimes I can't see other user's input command when other user logins Linux system at same time:
Do you know how to see such input in below Red-hat 7.5 system?
Also does anyone know how to see such input command history for other users?
-------------- Related detail ------------------------
[appuser@ip-10-1-X-XX ~]$ w
 15:02:01 up  6:41,  2 users,  load average: 0.20, 0.07, 0.06
USER     TTY      FROM             LOGIN@   IDLE   JCPU   PCPU WHAT
rouser   pts/0    ip-10-1-1-XX.cn- 10:11    3:23m  0.00s  0.00s tail -f lykos-reports.log
appuser  pts/1    ip-10-1-1-XX.cn- 14:56    1.00s  0.00s  0.00s w
You have mail in /var/spool/mail/appuser

[appuser@ip-10-1-1-239 ~]$ cat /etc/redhat-release
Red Hat Enterprise Linux Server release 7.5 (Maipo)

Thanks


text:
Q: How to use view in 4-dimensional neural network I'm new to Neural Networks, so I hope u will forgive me if this is really basic stuff.
So far i managed to use view once in my first very simple project and now i tried to understand something more complex.
I found this code on github and I'm trying to understand it.
This is how network is built.
class Net(nn.Module):
    def __init__(self):
        super(Net, self).__init__()
        self.conv1 = nn.Conv2d(1, 32, 3, 1)
        self.conv2 = nn.Conv2d(32, 64, 3, 1)
        self.dropout1 = nn.Dropout(0.25)
        self.dropout2 = nn.Dropout(0.5)
        self.fc1 = nn.Linear(9216, 128)
        self.fc2 = nn.Linear(128, 10)

    def forward(self, x):
        x = self.conv1(x)
        x = F.relu(x)
        x = self.conv2(x)
        x = F.relu(x)
        x = F.max_pool2d(x, 2)
        x = self.dropout1(x)
        x = torch.flatten(x, 1)
        x = x.view(-1, 64 * 12 * 12)
        x = self.fc1(x)
        x = F.relu(x)
        x = self.dropout2(x)
        x = self.fc2(x)
        output = F.log_softmax(x, dim=1)
        return output

I'm trying to get the image of number network failed to recognize, yet I don't really know how to use view here.
def test(model, device, test_loader):
    model.eval()
    test_loss = 0
    correct = 0
    mistakes = 0
    images, labels = next(iter(test_loader))
    img = images[0].view(1, 784)

    with torch.no_grad():
        logps = model(img)
        for data, target in test_loader:
            data, target = data.to(device), target.to(device)
            output = model(data)
            test_loss += F.nll_loss(output, target, reduction='sum').item()
            pred = output.argmax(dim=1, keepdim=True)
            correct += pred.eq(target.view_as(pred)).sum().item()

    test_loss /= len(test_loader.dataset)
    print('\nTest set: Average loss: {:.4f}, Accuracy: {}/{} ({:.0f}%)\n'.format(
        test_loss, correct, len(test_loader.dataset),
        100. * correct / len(test_loader.dataset)))

I couldn't find usefull examples so I would be gratefull for any kind of hint.
Every time I modify it I get one of these two errors.
builtins.RuntimeError: Expected 4-dimensional input for 4-dimensional weight [32, 1, 3, 3], but got 2-dimensional input of size [1, 784] instead
builtins.RuntimeError: shape '[1, 784, 3, 3]' is invalid for input of size 784
Thanks in advance for any kind of help.

A: Go with this
Since  your dataloader already has data in 4D . No need to change it using .view()
And your CNN expects data in 4D
def test(model, device, test_loader):
    model.eval()
    test_loss = 0
    correct = 0
    mistakes = 0
    """  NO NEED OF THIS
    images, labels = next(iter(test_loader))
    img = images[0].view(1, 784)  # This makes your image to 1D
    """
    with torch.no_grad():
        #logps = model(img)
        for data, target in test_loader:
            data, target = data.to(device), target.to(device)
            output = model(data)
            test_loss += F.nll_loss(output, target, reduction='sum').item()
            pred = output.argmax(dim=1, keepdim=True)
            correct += pred.eq(target.view_as(pred)).sum().item()

    test_loss /= len(test_loader.dataset)
    print('\nTest set: Average loss: {:.4f}, Accuracy: {}/{} ({:.0f}%)\n'.format(
        test_loss, correct, len(test_loader.dataset),
        100. * correct / len(test_loader.dataset)))


text:
Q: Assembly languaje, base pointer i was reading an example in assembly languaje, and i have a little doubt. We were using assembly only on our programs, but the last unit on the semester it's to merge it with turbo c (in-line assembly), and reading the code, there's a part which i don't quite get it:
Here's the assembly part:
dosseg
.model small
.code
public _myputchar
_myputchar PROC
    push bp
    mov bp,sp
    mov dl,[bp+4]
    mov ah,2
    int 21h
    pop bp
    ret
_myputchar ENDP
END

And here's the C part:
#include<stdio.h>
extern void myputchar( char x );
char *str={"Hola Mundo\n"};
void main ( void )
{
    while(*str)
    myputchar(*str++);
    getchar();
}

So, it's pretty straight forward, and the program works, but, what i don't get, it's the assembly code. The problem is, Why the base pointer (bp) it's pointing to +4? (mov dl,[bp+4]), I would think that you only had to mov dl,bp but i don't get why +4. If someone can help we, that would be really apretiated!. (in the include section i put the "" Because the formating tools it's giving me such headech -_-!

A: The argument (x) is pushed onto the stack before calling the function. After this, the call instruction will push the return address (2 bytes in this case) onto the stack, and the push bp at the beginning of the function will push another 2 bytes onto the stack.
So by now you've pushed 2+2 == 4 more bytes onto the stack after the argument. Since the stack grows downward that means that to get the argument you have to offset the pointer by +4 bytes.

A: The starting address of the string you want to print is at [bp + 4]. The current stack pointer is [bp]. Remember, the stack grows down.


text:
Q: Get only current view focus In my case user should not click on any other view, while current view is active (image preview)
How do i set the focus only on current view?
Thanks

A: if you have view above another view you can simply give blank click to top view so that bottom view will not be accessed.
Simply give onClick to the parent layout of above view.
android:onClick="doNothing";

And then in actvity just define the method doNothing.
public void doNothing(View view)
{

}


text:
Q: Get a simple string representation of a struct field's type Using Go's ast package, I am looping over a struct's field list like so:
type Thing struct {
    Field1 string
    Field2 []int
    Field3 map[byte]float64
}

// typ is a *ast.StructType representing the above
for _, fld := range typ.Fields.List {
    // get fld.Type as string
}

…and would like to get a simple string representation of fld.Type, as it appears in the source code, e.g. []int or map[byte]float64.
The ast package field type Type property is an Expr, so I've found myself getting off into the weeds using type switches and handling every type specifically – when my only goal is to get out the plain string to the right of each field name, which seems like it should be simpler.
Is there a simple way?

A: You can use go/types ExprString
This works with complicated types like []string, []map[string]string, etc.
import (
    ...
    "go/types"
    ...
)

...

// typ is a *ast.StructType representing the above
for _, fld := range typ.Fields.List {
    ...
    typeExpr := fld.Type
    typeString := types.ExprString(typeExpr)
    ...
}

https://golang.org/src/go/types/exprstring.go

A: This is exactly what Fprint in the go/printer package is for. It takes any AST node as an argument and writes its string representation to a io.Writer.
You can use it in your example as follows:
package main

import (
    "bytes"
    "fmt"
    "go/ast"
    "go/parser"
    "go/printer"
    "go/token"
    "log"
)

func main() {
    src := `
        package foo

    type Thing struct {
    Field1 string
    Field2 []int
    Field3 map[byte]float64
  }`

    fset := token.NewFileSet()
    f, err := parser.ParseFile(fset, "", src, 0)

    if err != nil {
        panic(err)
    }
    typeDecl := f.Decls[0].(*ast.GenDecl)
    structDecl := typeDecl.Specs[0].(*ast.TypeSpec).Type.(*ast.StructType)

    for i, fld := range structDecl.Fields.List {
        // get fld.Type as string
        var typeNameBuf bytes.Buffer
        err := printer.Fprint(&typeNameBuf, fset, fld.Type)
        if err != nil {
            log.Fatalf("failed printing %s", err)
        }
        fmt.Printf("field %d has type %q\n", i, typeNameBuf.String())
    }
}

Output:
field 0 has type "string"
field 1 has type "[]int"
field 2 has type "map[byte]float64"

Try it in playground: https://play.golang.org/p/cyrCLt_JEzQ

A: There are two things you could be getting at here, one is the type of an expression as would ultimately be resolved during compilation and the other is the code which would determine that type.
Digging through the docs, I don't believe the first is at all available.  You can get at the later, however, by using End() and Pos() on Node.
Quick example program:
package main

import (
    "fmt"
    "go/ast"
    "go/parser"
    "go/token"
)

func main() {
    src := `
        package foo

    type Thing struct {
    Field1 string
    Field2 []int
    Field3 map[byte]float64
  }`

    fset := token.NewFileSet()
    f, err := parser.ParseFile(fset, "", src, 0)

    if err != nil {
        panic(err)
    }

    // hard coding looking these up
    typeDecl := f.Decls[0].(*ast.GenDecl)
    structDecl := typeDecl.Specs[0].(*ast.TypeSpec).Type.(*ast.StructType)
    fields := structDecl.Fields.List

    for _, field := range fields {
        typeExpr := field.Type

        start := typeExpr.Pos() - 1
        end := typeExpr.End() - 1

        // grab it in source
        typeInSource := src[start:end]

        fmt.Println(typeInSource)
    }

}

This prints:
string
[]int
map[byte]float64

I through this together in the golang playground, if you want to mess with it.

A: I found a way to do this without using the original source code as a reference for simple members (not slices, arrays or structs):
          for _, field := range fields {
                 switch field.Type.(type) {
                 case *ast.Ident:
                     stype := field.Type.(*ast.Ident).Name // The type as a string
                     tag = ""
                     if field.Tag != nil {
                         tag = field.Tag.Value //the tag as a string
                     }
                     name := field.Names[0].Name //name as a string
                     ...

For the non-simple members you just need another case statement (IE: case *ast.ArrayType:).


text:
Q: Unity 3D: JSON Error when deserializing : ArgumentException: JSON must represent an object type I am using the following:
[System.Serializable]
public class Choice
{
public string choice;
public int votes;
}

[System.Serializable]
public class RootObject
{
public string question;
public string published_at;
public List<Choice> choices;
}

To deserialize the following JSON:

[
      {
          "question": "Favourite programming language?",
          "published_at": "2015-08-05T08:40:51.620Z",
          "choices": [
              {
                  "choice": "Swift",
                  "votes": 2048
              }, {
                  "choice": "Python",
                  "votes": 1024
              }, {
                  "choice": "Objective-C",
                  "votes": 512
              }, {
                  "choice": "Ruby",
                  "votes": 256
              }
          ]
      }
  ]

And I am getting this Error message in console : ArgumentException: JSON must represent an object type. Please tell me what I am doing wrong.

A: Your json begins with an [ and ends with a ] this indicates that it is an array, and not an object.
As you are trying to deserialize it to the object rootobject, it fails, as it would expect an object annotation using { and }.
You can fix this by either changing the array to an object.
Or by deserializing it to an array instead.
You can find some samples, and more explanation over at this answer: Serialize and Deserialize Json and Json Array in Unity


text:
Q: Regex for match web extensions I want to check whether a url is a image, java script, pdf etc
String url = "www.something.com/script/sample.js?xyz=xyz;
Below regex works fine but only with out xyz=zyz

".*(mov|jpg|gif|pdf|js)$"

When i remove $ at the end to eliminate regex requirement for .js to be in end but then it gives false

A: .*(mov|jpg|gif|pdf|js).*$ allows you to have any optional text after the file extension. The capturing group captures the file extension. You can see this here.

A: Use the regex as below:
   .*\\.(mov|jpg|gif|pdf|js)\\?

This matches for dot(.) followed by your extension and terminated by ?
The first dot(.) is matching any character while second dot(.) prefixed by \\ match for dot(.) as literal just before your extension list.

A: Why not use java.net.URL to parse the url string, it could avoid lots of mismatching problems:
try {
  URL url = new URL(urlString);
  String filename = url.getFile();
  // now test if the filename ends with your desired extensions.
} catch (Exception e) {
  // This case the url cannot be parsed.
}

A: I'm not a big fan of this, but try:
.*\\.(mov|jpg|gif|pdf|js).*$

The problem is that it will accept things like "our.moving.day"
and post your code.  there is always more than one way to skin a cat and perhaps there is something wrong with your code, not the regex.
Also, try regex testers...theres a ton of them out there.  i'm a big fan of:
http://rubular.com/ and http://gskinner.com/RegExr/ (but they are mostly for php/ruby)