text:
Q: Rate of water temperature change Goal:
I have a pipe containing water.  Solving for $k$ in Newton's Law of Cooling, I want to detect whether or not fresh water is flowing through the pipe.  Assumption: The closer the empirical $k$ is to $\alpha = \frac{hA}{mc}$, the less flow present and vice versa.
Specs:
Pipe material: Iron
Length: 100 cm
$h \approx 20\:\mathrm{Wm^{-2}K^{-1}}$
$c_{water}=42000\:\mathrm{Jkg^{-1}K^{-1}}$
Sample 1
Outer diameter: 3.81 cm
Inner diameter: unknown
$A=\pi D L=0.12\:\mathrm{m^2}$
$m=\rho V=\rho \frac{\pi D^2}{4}L=1.14\:\mathrm{kg}$
With no fresh water flow, using $\alpha = \frac{hA}{mc}$ = .0005
Empirical Data: $T_1$ = 294.43, $T_2$ = 295.15, $T_{\infty}$ = 299.43, $t$ = 316 sec
$$k=\frac{1}{-t} \times \ln\Big(\frac{T_2 - T_{\infty}}{T_1 - T_{\infty}}\Big)$$
$$k = .0005$$
This is reaching ambient temperature as environmentally expected, indicating no fresh flow.
However, $T_1$ = 303.15, $T_2$ = 299.43, $T_{\infty}$ = 303.43, $t$ = 330 sec
$$k = -.0081$$
Indicating an external factor (i.e. fresh water flow) effecting the natural rate of temperature change.
Sample 2
Outer diameter: 5.08 cm
Inner diameter: unknown
$A=\pi D L=0.06\:\mathrm{m^2}$
$m=\rho V=\rho \frac{\pi D^2}{4}L=2.03\:\mathrm{kg}$
With no fresh water flow, using $\alpha = \frac{hA}{mc}$ = .0004
Empirical Data where fresh water is flowing: $T_1$ = 294.43, $T_2$ = 295.15, $T_{\infty}$ = 300.29, $t$ = 482 sec
$$k = .0003$$
Question
I am trying to understand how the resulting $k$ in sample 2 is so similar to the no-flow $k$ of .0004.

A:
We assume the pipe thickness to be negligible (as it is 'unknown') and no radial temperature gradients to exist. In addition plug flow is assumed.
We consider an infinitesimal element of length $dx$ and apply Newton's cooling law:
$$\frac{dQ}{dt}=hdA[T(x)-T_{\infty}]=\pi Dh[T(x)-T_{\infty}]dx$$
If the infinitesimal element changes temperature then:
$$dQ=-dmcdT(x)$$
So:
$$\frac{dQ}{dt}=-\frac{dm}{dt}cdT(x)$$
$$\frac{dQ}{dt}=-\dot{m}cdT(x)$$
Where $\dot{m}=\frac{dm}{dt}$ is the mass throughput flowing through the pipe.
This gives us the identity:
$$-\dot{m}cdT(x)=\pi Dh[T(x)-T_{\infty}]dx$$
$$\frac{dT(x)}{T(x)-T_{\infty}}=-\frac{\pi Dh}{\dot{m}c}dx$$
Call:
$$k=\frac{\pi Dh}{\dot{m}c}$$
$$\int_{T_1}^{T_2}\frac{dT(x)}{T(x)-T_{\infty}}=-k\int_0^Ldx$$
$$\ln\Big[\frac{T_2-T_{\infty}}{T_1-T_{\infty}}\Big]=-kL$$
$$\large{T_2=T_{\infty}+[T_1-T_{\infty}]e^{-kL}}$$

I am trying to understand how the resulting $k$ in sample 2 is so similar to the no-flow $k$ of .0004.

One cannot treat the problem the same way when there's no water flow. For $\dot{m}=0 \implies k \to +\infty$! That is of course not allowed.
The cases with and without water flow must be treated differently.


text:
Q: How to pass multiple 2d array as input to tensorflow serving api? I have a tensorflow model which takes two 2d arrays as input.
This is how I trained the model.
x.shape == (100, 250)
y.shape == (100, 10)

model.fit([x,y], y_train)

Now I'm using tensorflow serving API for deploying into production. Now when I tried to make a api request for predictions I'm getting an error
"{'error': 'instances is a plain list, but expecting list of objects as multiple input tensors required as per tensorinfo_map'}"
data1 = json.dumps({"signature_name": "serving_default",
                   "instances": [x.tolist(), y.tolist()]})
# both x and y are numpy 2d array

json_response = requests.post('http://44.287.13.8:9000/v1/models/context_model/versions/1:predict',
                               data=data1, headers=headers)

pred = json.loads(json_response.text)

print(pred)
{'error': 'instances is a plain list, but expecting list of objects as multiple input tensors required as per tensorinfo_map'}

A: I had a quite similar problem. I wanted to test my saved model in combination with the serving API. First I wrote the following POST command to get the prediction: curl -g -d "{""instances""":" [[[158, 194, 8102, 5294, 15.404460999999998, 47.241882000000004, 1]]]}" -X POST http://localhost:8501/v1/models/my_model:predict. With this input I got the same error as you. As mentioned here https://www.tensorflow.org/tfx/serving/api_rest#predict_api, you have to serve the input data in the following way: curl -d "{"""instances""": [{"""NAME1W1""": [158], """NAME1W2""": [194], """ZIP""": [""8102""], """STREETW""": [5294], """LONGITUDE""": 15.404460999999998, """LATITUDE""": 47.241882000000004,"""ASG""": [1] }]}" -X POST http://localhost:8501/v1/models/my_model:predict. Don't get confused of the """, I had to use them because I am using curl on Windows and not on Linux.

A: When you have multiple inputs, you need to know the names of inputs from GraphDef and pass a list of dict to tensorflow serving
First, make sure that you have correct input names by running this command in terminal
saved_model_cli show --dir /home/your_user_name/path/to/your/saved_model/1 --all

In my case, I get the following as part of the output. What is important is that the names of the inputs are input_1 and input_2, again in my case.

signature_def['serving_default']:   The given SavedModel SignatureDef
contains the following input(s):
inputs['input_1'] tensor_info:
dtype: DT_FLOAT
shape: (-1, 2)
name: serving_default_input_1:0
inputs['input_2'] tensor_info:
dtype: DT_FLOAT
shape: (-1, 2)
name: serving_default_input_2:0

Also, as you can see, each input takes 2 fields, respectively.
Finally, I can send an http request for a prediction with input_1 of [1.,0.] and input_2 of [0.36708057, 0.66139287]
import requests
import json

data = json.dumps({"signature_name":"serving_default","instances":[{'input_1':[1., 0.],'input_2':[0.36708057, 0.66139287]}]})
headers = {"content-type":"application/json"}
json_response = requests.post('http://localhost:8501/v1/models/test:predict',data=data,headers=headers)
print(json.loads(json_response.text))

The output was {'predictions':[[0.315578]]}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Best way to implement a "console shell" with bottom edit line, status bar and scrolling history? This is quite a complex question, but I'm hoping there may be a library to quickly accomplish what I'm looking to do.
The best way for me to start to explain this is with an example of desired output:
+------------------------------------------------+
| TESTAPP v0.1 (C) Test Company          Running |
| ---------------------------------------------- |
| info: This is a logged message.                |
| input: user typed "hello"                      |
| info: This is a logged message.                |
| debug: option 1 code 2 value 3                 |
| info: The debug line was just printed.         |
| --Status: [Opts 1] [Codes 5] [Values 11]    -- |
| > about to press enter...                      |
+------------------------------------------------+

Parts:
+------------------------------------------------+
| TITLE BAR -- TITLE BAR -- TITLE BAR -- TITLE   |
| ...                                            |
| ...                                            |
| ...scrolling log area...                       |
| ...                                            |
| ...                                            |
| ...                                            |
| STATUS BAR -- STATUS BAR -- STATUS BAR --      |
| > INPUT LINE -- INPUT LINE -- INPUT LINE     < |
+------------------------------------------------+

Here's the key points:

*

*A Python program that will go full-screen after launch.

*The topmost line will be a title bar, that might contain some updateable areas.

*The line right below the title bar could be a separator (Not necessarily required)

*The bottommost line will be an input line.

*The line directly above the input line will be a status line, which would be updated frequently.

*A line above the status line may be used as a separator, but not necessarily required.

*The remaining lines in the center of the screen would be a scrolling history view. The application will write lines to this area, and after the area is full the earliest lines will scroll off-screen.

*A scroll-back buffer would be nice, but is not absolutely essential.

*Color output would be desirable for the status and title bars, but simple inversion would be acceptable.

*The input line should support readline-style history and so on.

*Also, it needs to push and scroll to the left rather than wrapping, so the whole UI doesn't get pushed off-screen if the user types too much text.

Example:
| info: The debug line was just printed.         |
| --Status: [Opts 1] [Codes 5] [Values 11]    -- |
| > ...men to come to the aid of their country._ |
+------------------------------------------------+

Basically, I'm writing a server that I want to be controllable at the console. The simple method of simply putting the server on a thread and starting a raw_input loop means that output from the server to the console easily interrupts the input of text.
For an even more concise example, think irssi or epicII.
I could in theory code all of this myself using the curses library and a LOT of work, but it feels to me that there may be some sort of library, or at least some shortcut, to accomplishing this. I'm not too familiar with the curses library to begin with. Unless there's a really good concise quick-start guide out there, I feel like I'd end up spending more time understanding curses that I have on writing the actual server code. :-)

A: Whats wrong with pycurses ? Its just a wrapper around ncurses.
Saves reinventing the wheel.
More than a few examples out there and additional widgets etc
e.g

*

*http://yannik520.github.io/pycurses_example.html

*pycurses widgets
In answer to your question there are more than a few libraries that can do that:

*

*pycurses make sure to check the [ncurses faq] (http://invisible-island.net/ncurses/ncurses.faq.html)

*blessings

*terminal.py

*npyscreen

*clint

*pyscreen
A few previous questions that may help:

*

*Dynamic terminal printing with python

*Text Progress Bar in the Console

*Python Progress Bar

*fish
If you can keep your display code in a separate class it should make it easier if you need to move to having a gui. You might want to look at tkinter as well.


text:
Q: How to retain whitespace for python in Intellij idea I want to retain a space character on only the blank lines between code segments of a single function. The reason is that when cut/paste into interpreter, it will break if no space there (says unexpected indentation).
So I want intellij to not strip out that space character. But I can not find setting to prevent the extra whitespace removal.
here is the use case:
def myfunc():
  print "something"

  def internal_Func_that_I_want_separated_by_newline():
    print "how to have a line above this one that includes a single space?"

  def anotherfunc():
    print "foobar"

  foobar()
  internal_Func_that_I_want_separated_by_newline()

thanks

A: You need to set Editor | Strip trailing spaces on save to None. Here is the screenshot of the option.


text:
Q: Faster index finding of flanking non-NA values This is a speed optimization question.
Here is my sample data. The real data has over 100k rows and >300 columns.
library(data.table)
dt <- data.table(ref=1:20, tgt1=11:30, tgt2=21:40)
dt[c(3,8,9,15,16,17), "tgt1"] = NA
dt[c(4,5,15,17), "tgt2"] = NA
dt

#>     ref tgt1 tgt2
#>  1:   1   11   21
#>  2:   2   12   22
#>  3:   3   NA   23
#>  4:   4   14   NA
#>  5:   5   15   NA
#>  6:   6   16   26
#>  7:   7   17   27
#>  8:   8   NA   28
#>  9:   9   NA   29
#> 10:  10   20   30
#> 11:  11   21   31
#> 12:  12   22   32
#> 13:  13   23   33
#> 14:  14   24   34
#> 15:  15   NA   NA
#> 16:  16   NA   36
#> 17:  17   NA   NA
#> 18:  18   28   38
#> 19:  19   29   39
#> 20:  20   30   40

Some columns have NA at some positions, and my goal is to get the positions of the nearest non-NA flanking values. For instance, for the second column tgt1, I am using the following code
tgt = dt[, tgt1]
tgt.na = which(is.na(tgt))
tgt.non.na = which(!is.na(tgt))
start = sapply(tgt.na, function(x) max(tgt.non.na[tgt.non.na < x]))
stop = sapply(tgt.na, function(x) min(tgt.non.na[tgt.non.na > x]))
data.frame(start, stop)

#>   start stop
#> 1     2    4
#> 2     7   10
#> 3     7   10
#> 4    14   18
#> 5    14   18
#> 6    14   18

Here for the tgt1 column, I get what I want. For example, for the NA at 3rd row, the closest flanking non-NA values are at 2 and 4, and so on for others. My issues is that the sapply are very slow. Imagine running this for >300 columns and 100k rows. In current form it takes over few hours to finish. Ultimately, when these positions are found, then they are used to index values from ref column to compute the missing values in tgt1 and so on columns. But that is the topic for another time.
Is there any way I can make it faster? Any data.table way solution for it.
Edit: All great solutions, here is my benchmark, and you can see all proposed methods worked lightning fast compared to my original sapply. I select lapply, not only because it is the fastest but also because it aligns well with my current code syntax.
Unit: milliseconds
           expr         min          lq        mean      median          uq         max neval
         sapply 3755.118949 3787.288609 3850.322669 3819.458269 3897.924530 3976.390790     3
 dt.thelatemail    9.145551    9.920238   10.242885   10.694925   10.791552   10.888180     3
  lapply.andrew    2.626525    3.038480    3.446682    3.450434    3.856760    4.263086     3
   zoo.chinsoon    6.457849    6.578099    6.629839    6.698349    6.715834    6.733318     3

A: You should be able to take advantage of rleid to calculate the prior value to a run of NAs and then match it up. E.g.:
dt[, a := rleid(is.na(tgt1))]
dt[, rev(ref)[match((a - 1)[is.na(tgt1)], rev(a))] ]
#[1]  2  7  7 14 14 14
dt[, ref[match((a + 1)[is.na(tgt1)], a)] ]
#[1]  4 10 10 18 18 18

Seems pretty quick to process 100k rows:
dt <- dt[rep(1:20,5e3),]
dt[, ref := 1:1e5]
system.time({
  dt[, a := rleid(is.na(tgt1))]
  dt[, rev(ref)[match((a-1)[is.na(tgt1)],rev(a))]]
  dt[, ref[match((a+1)[is.na(tgt1)],a)]]
})
#   user  system elapsed
#   0.02    0.00    0.02

A: Another possibility using zoo package:
library(zoo)
for (j in paste0("tgt", 1L:2L)) {
    print(dt[, {
        k <- is.na(get(j))
        x <- replace(ref, k, NA_integer_)
        .(start=na.locf0(x)[k],
          end=na.locf0(x, fromLast=TRUE)[k])
    }])
}

output:
   start end
1:     2   4
2:     7  10
3:     7  10
4:    14  18
5:    14  18
6:    14  18
   start end
1:     3   6
2:     3   6
3:    14  16
4:    16  18

timing code:
library(data.table)
library(zoo)
sz <- 100e3
nc <- 400
dt <- data.table(ref=1L:sz,
    as.data.table(matrix(sample(c(NA_integer_, 1L), sz*nc, replace=TRUE), ncol=nc)))

library(microbenchmark)
microbenchmark(
    mtd0=for (j in paste0("V", 1L:nc)) {
        k <- dt[,is.na(get(j))]
        dt[, a := rleid(k)][,
            .(start=rev(ref)[match((a-1)[k],rev(a))], end=ref[match((a+1)[k],a)])]
    },
    mtd1=for (j in paste0("V", 1L:nc)) {
        dt[, {
            k <- is.na(get(j))
            x <- replace(ref, k, NA_integer_)
            .(start=na.locf0(x)[k], end=na.locf0(x, fromLast=TRUE)[k])
        }]
    },
    times=3L)

timings:
Unit: seconds
 expr      min       lq     mean   median       uq      max neval cld
 mtd0 6.638253 6.698023 6.730352 6.757794 6.776402 6.795010     3   b
 mtd1 4.832264 4.835764 4.854799 4.839264 4.866066 4.892867     3  a

Not much diff in timings given the number of rows.

A: Here is a base R alternative using rle. I used lapply because I was not sure how you wanted to save all the output dataframes. Hope this helps!
dt <- data.table(ref=1:20, tgt1=11:30, tgt2=21:40)
dt[c(3,8,9,15,16,17), "tgt1"] = NA
dt[c(4,5,15,17), "tgt2"] = NA

lapply(dt[,-1], function(x) {
  na_loc <- which(is.na(x))
  rle_x <- rle(is.na(x))
  reps <- rle_x$lengths[rle_x$values == T]

  start <- na_loc - 1
  start <- start[!start %in% na_loc]
  end <- na_loc + 1
  end <- end[!end %in% na_loc]

  data.frame(start = rep(start, reps),
             end = rep(end, reps))
})

$tgt1
   start end
1:     2   4
2:     7  10
3:     7  10
4:    14  18
5:    14  18
6:    14  18

$tgt2
   start end
1:     3   6
2:     3   6
3:    14  16
4:    16  18

It also scales fairly well on my laptop for a sample dataframe w/ 300 columns:
df1 <- data.frame(ref = 1:1e5)
df1[paste0("tgt", 1:300)] <- replicate(300, sample(c(1:50, rep(NA, 5)), 1e5, replace = T))

microbenchmark::microbenchmark(
  base = {
    lapply(df1[,-1], function(x) {
      na_loc <- which(is.na(x))
      rle <- rle(is.na(x))
      reps <- rle$lengths[rle$values == T]

      start <- na_loc - 1
      start <- start[!start %in% na_loc]
      end <- na_loc + 1
      end <- end[!end %in% na_loc]

      data.frame(start = rep(start, reps),
                 end = rep(end, reps))
    }
  )},
  times = 5
)

Unit: seconds
 expr      min       lq     mean   median       uq      max neval
 base 1.863319 1.888617 1.897651 1.892166 1.898196 1.945954     5


text:
Q: UITextView as inputAccessoryView like iMessage I want to have the same kind of behaviour as iMessage has for its input. I don't know in what end I should start, so I'll describe what I want to do and you can (I hope) give me suggestions on how to do this. I code in Swift so I'd like it to be in Swift if you provide any code.
What I want
I want to have a button on my screen (not an UITextView or UITextField) which upon press shows the keyboard, and where the keyboard has a UIToolBar with an UITextView in it. When I type in the UITextView the ToolBar/TextView expands up until a certain point then it starts to scroll.
How on earth do I do this? I've been trying for an hour but I can't seem to trigger the keyboard unless I have a UITextView or UITextField to set as becomeFirstResponder(). Furthermore I don't understand how I'm supposed to attach a UITextView to the UIToolBar once I get the keyboard up. I have added the UIToolBar, but not the UITextField.
Cheers

A: This should do it for you: https://github.com/AlexLittlejohn/ALTextInputBar
It grows like you mentioned, and it's also at the bottom of screen, like an input accessory view.

*

*In your pods file copy paste
pod 'ALTextInputBar'

*Run your podfile

*Configure it like this
import ALTextInputBar

class ViewController: UIViewController {

    let textInputBar = ALTextInputBar()

    // The magic sauce
    // This is how we attach the input bar to the keyboard
    override var inputAccessoryView: UIView? {
        get {
            return textInputBar
        }
    }

    // Another ingredient in the magic sauce
    override func canBecomeFirstResponder() -> Bool {
        return true
    }
}


text:
Q: Partitioning in SQL I've been trying to find the median number of times an account (person) is seen (appt_id) by a provider (provider_code) in a given period. The attached SQL doesn't seen to be capturing all of the provider_codes and I can't figure out why. Desired outcome is that all provider_code are listed with a median number.
*I don't have access to MS SQL Server 2012 or Newer - yes we are way behind the times and yes it does make life much more difficult.

SELECT
   provider_code, office_location,
  CONVERT(INT, count(account)) AS Median

FROM
(
   SELECT
      office_location,provider_code,
   account,appt_date,dept_code,appt_status,appt_class,
      ROW_NUMBER( ) OVER (
         PARTITION BY office_location,provider_code
         ORDER BY account ASC) as RowAsc,

      ROW_NUMBER( ) OVER (
         PARTITION BY office_location,provider_code
         ORDER BY account DESC) as RowDesc

   FROM appointments_view WITH(NOLOCK)

WHERE account IS NOT NULL AND appt_date BETWEEN '1/1/17' /*24 month prior*/ AND '1/1/19'

 ) X

WHERE
   RowAsc IN (RowDesc, RowDesc - 1, RowDesc + 1)

GROUP BY office_location,provider_code
ORDER BY office_location,provider_code

A: For a median you could use the window function PERCENTILE_CONT or PERCENTILE_DISC
(MS Sql Server 2012+)
Example snippet:
declare @Appointments table (
 appt_id int primary key identity(4046100,1),
 appt_date date not null default GetDate(),
 account int not null,
 provider_code varchar(10) not null,
 office_location char(3) not null default 'REN',
 appt_class char(3) not null
 );

insert into @Appointments (appt_date, account, provider_code, appt_class) values
('2019-02-01',100001,'FOO1','IND'),('2019-02-01',100002,'FOO1','IND'),('2019-02-01',100002,'FOO1','PSY'),('2019-02-01',100002,'FOO1','IND'),
('2019-02-01',100002,'FOO1','IND'),('2019-02-01',100003,'FOO1','IND'),('2019-02-01',100003,'FOO1','IND'),('2019-02-01',100003,'FOO1','IND');

select provider_code, office_location, MAX(MedianContTotalAppointments) AS MedianApt
from
(
    select provider_code, office_location, account
    , count(appt_id) as TotalAppointments
    , PERCENTILE_CONT(0.5) WITHIN GROUP (ORDER BY count(appt_id)) OVER (PARTITION BY provider_code, office_location) AS MedianContTotalAppointments
    -- , PERCENTILE_DISC(0.5) WITHIN GROUP (ORDER BY count(*)) OVER (PARTITION BY provider_code, office_location) AS MedianDiscTotalAppointments
    from @Appointments
    where account IS NOT NULL
      and appt_date BETWEEN cast('2017-02-01' as date) AND cast('2019-02-01' as date)
    group by provider_code, office_location, account
) q
group by provider_code, office_location
order by provider_code, office_location;

Returns:
provider_code   office_location     MedianApt
FOO1            REN                 3

In a MS Sql Server version before 2012, then this example snippet might work:
declare @Appointments table (
 appt_id int primary key identity(4046100,1),
 appt_date date not null default GetDate(),
 account int not null,
 provider_code varchar(10) not null,
 office_location char(3) not null default 'REN',
 appt_class char(3) not null
 );

insert into @Appointments (appt_date, account, provider_code, appt_class) values
 ('2019-02-01',100001,'FOO1','IND'),('2019-02-01',100002,'FOO1','IND'),('2019-02-01',100002,'FOO1','PSY'),('2019-02-01',100002,'FOO1','IND')
,('2019-02-01',100002,'FOO1','IND'),('2019-02-01',100003,'FOO1','IND'),('2019-02-01',100003,'FOO1','IND'),('2019-02-01',100003,'FOO1','IND')
--,('2019-02-01',100004,'FOO1','IND'),('2019-02-01',100004,'FOO1','IND')
;

select provider_code, office_location, AVG(TotalAppointments) AS MedianApt
from
(
    select provider_code, office_location, account
    , COUNT(appt_id) as TotalAppointments
    , ROW_NUMBER() OVER (PARTITION BY provider_code, office_location ORDER BY COUNT(appt_id) ASC) AS rn
    , COUNT(*) OVER (PARTITION BY provider_code, office_location) AS cnt
    from @Appointments
    where account IS NOT NULL
      and appt_date BETWEEN cast('2017-02-01' as date) AND cast('2019-02-01' as date)
    group by provider_code, office_location, account
) q
where rn in (FLOOR((cnt+1)*0.5), CEILING((cnt+1)*0.5))
group by provider_code, office_location
order by provider_code, office_location;


text:
Q: Automated way to create multiple kubernetes Job manifests Cron template
kind: CronJob
metadata:
  name: some-example
  namespace: some-example
spec:
  schedule: "* 12 * * *"
  jobTemplate:
    spec:
      template:
        spec:
          containers:
          - name: some-example
            image: gcr.io/some-example/some-example
            imagePullPolicy: Always
            env:
             - name: REPO_URL
               value: https://example.com/12/some-example

I need to create multiple Job files with different URLs of REPO_URL over 100s save in a file. I am looking for a solution where I can set Job template and get the required key:value from another file.
so far I've tried https://kustomize.io/, https://ballerina.io/, and https://github.com/mikefarah/yq. But I am not able to find a great example to fit the scenario.

A: That would be pretty trivial with yq and a shell script. Assuming
your template is in cronjob.yml, we can write something like this:
let count=0
while read url; do
  yq -y '
    .metadata.name = "some-example-'"$count"'"|
    .spec.jobTemplate.spec.template.spec.containers[0].env[0].value = "'"$url"'"
  ' cronjob.yml
  echo '---'
  let count++
done < list_of_urls.txt | kubectl apply -f-

E.g., if my list_of_urls.txt contains:
https://google.com
https://stackoverflow.com

The above script will produce:
[...]
metadata:
  name: some-example-0
  namespace: some-example
spec:
  [...]
              env:
                - name: REPO_URL
                  value: https://google.com
---
[...]
metadata:
  name: some-example-1
  namespace: some-example
spec:
  [...]
              env:
                - name: REPO_URL
                  value: https://stackoverflow.com

You can drop the | kubectl apply -f- if you just want to see the
output instead of actually creating resources.

Or for more structured approach, we could use Ansible's k8s
module:
- hosts: localhost
  gather_facts: false
  tasks:
    - k8s:
        state: present
        definition:
          apiVersion: batch/v1beta1
          kind: CronJob
          metadata:
            name: "some-example-{{ count }}"
            namespace: some-example
          spec:
            schedule: "* 12 * * *"
            jobTemplate:
              spec:
                template:
                  spec:
                    containers:
                    - name: some-example
                      image: gcr.io/some-example/some-example
                      imagePullPolicy: Always
                      env:
                       - name: REPO_URL
                         value: "{{ item }}"
      loop:
        - https://google.com
        - https://stackoverflow.com
      loop_control:
        index_var: count

Assuming that the above is stored in playbook.yml, running this with
ansible-playbook playbook.yml would create the same resources as the
earlier shell script.


text:
Q: How to change Font type in a text area using a combobox I am doing a simple text editor and have a combo box filled with the font names. However I can't manage to make the program change the font of the text area when a new font is selected form the combo box. I was using this line of code to try and make it work.
txtArea.setFont(new Font("Serif", Font.ITALIC, 16));

I need to replace "Serif" with some kind of variable to change from the font from the selected font type from the combo box.
All help will be really appreciated.

A: OK, if your combo box is filled with available font names, you can try like this:
    fontComboBox.addItemListener(new ItemListener() {
        @Override
        public void itemStateChanged(ItemEvent e) {
            if (e.getStateChange() == ItemEvent.SELECTED) {
                txtArea.setFont(new Font((String) fontComboBox.getSelectedItem(), Font.ITALIC, 16));
            }
        }
    });


text:
Q: Postgresql Sequelize search with one to many join New to postgresql and I am using node and Sequelize. I have a database with tables vehicles and photos:
¦Vehicles:
¦
¦ id     99
¦ make   Nissan
¦ model  Micra

¦Photos:
¦
¦ id            1      2
¦ photoUrl    xxx    yyy
¦ photoOrder    1      2
¦ vehicleId    99     99

What I am hoping for, on a search by vehicle id, is an output like this:
[
    {
        "id":99,
        "make":"Nisan",
        "model":"Micra",
        "photos":[
            {
                "photoOrder":1,
                "photoUrl":"xxx"
            },
            {
                "photoOrder":2,
                "photoUrl":"yyy"
            }
        ]
    }
]

The associations that I have are:
db.photos.belongsTo(db.vehicles);
db.vehicles.hasMany(db.photos);

I can add vehicles and add photos. When I retrieve a vehicle(s) I get the vehicle info but no photos:
export function findAll(req, res) {
    Vehicle.findAll()
        .then(data => {
            res.send(data);
        })
        .catch(err => {
           ...
        });
}

Have I got my associations correct and how do I achieve my desired output?

A: You can access the photos via the getPhotos function on the vehicles. If you want to eagerly load them then you need to do something like
Vehicle.findAll({
  include: Photos
})

Documentation here .. https://sequelize.org/master/manual/assocs.html#eager-loading-example


text:
Q: What is a white socket and how does it work? I'm familiar with red, green, and blue sockets. I've read about white sockets but never seen one. How does it work? How do you make them?

A: White sockets allow you to put any gem in it. The only current way to get a white socket is to use one of the Vaal currency on an item be warned though once you do this it is corrupted and you can not use any other currency on it. I'm sorry I don't remember exactly what it's called but it gives random effects.

A: Beside Descent of Champion races, which give you two white socket items, the Tabula Rasa is the only item in the game with white sockets.
You can put any color gem into a white socket.


text:
Q: Is there any application/tool for quick translations of a selected word? I'm looking for a simple application or tool that enables me to quickly translate a selected word (for example when reading a pdf or document).
I know there are several applications that offer translations but I'm rather looking for just a small tool that completely runs in the background and uses the notification system for a quick translation of a selected word when a certain hotkey is pressed.
Especially German - English, English - German would be great.
Thank you very much for your help!
Lots of greetings

A: Checkout Stardict

You may find German dictionary from the main site. Or from this http://cihar.com/software/slovnik/
To install stardict, you may install from software center or running this command:
sudo apt-get install stardict

After you install stardict and dictionary click on the setting icon on the bottom and define selection key like the screenshot shows:

Selection translation looks like this on pdf:

A: I found that the hotkey function in Stardict works quite unreliably in Ubuntu 14.04
An alternative is GoldenDict. To install goldendict in all currently supported versions of Ubuntu open the terminal and type:
sudo apt install goldendict

Select word -> Ctrl + C + C
 (it should be enabled by default, otherwise check "Preferences")


text:
Q: Git stopped working on Android studio I had everything set up on Android Studio but recently it stopped working. The last time I pushed onto Git was as recent as five days ago!
When I press VCS->Enable Version Control Integration: I get a dialog box on the right corner saying:
Can't start Git: /usr/local/bin/git
Probably the path to git executable is not valid: Fix it

When I press "fix it" it takes me to preferences, I tried testing the connection but, it said no such file or directory!
So I looked at the directories and there wasn't a "git" file in the location, when I searched further I found a "git" file in "/usr/local/git"! So I changed it to that location in preferences, to which I got another dialog box saying:
Cannot run program "/usr/local/git": error=13, Permission denied

Does anyone know how to fix this?

A: In my case this problem happened because I updated my Xcode and I had to agree the license.
So the solutions for me was go to terminal and type:
sudo /usr/bin/git

and type 'agree' to the terms of the software license agreements.

A: Generally, /usr/local/git/ is a folder.
In the preferences, you should put /usr/local/git/bin/git

A: Had to do both:
sudo /usr/bin/git AND
figure out that git was installed in /usr/local/git/current/bin/git


text:
Q: Create a table for Phalcon model I am a beginner in Phalcon PHP Framework.
I've created a model. Like this:
class User extends Phalcon\Mvc\Model
{

    /**
     * @Primary
     * @Identity
     * @Column(type="integer", nullable=false)
     */
    public $id;

    /**
     * @Column(type="string", nullable=false)
     */
    public $username;

    /**
     * @Column(type="string", nullable=false)
     */
    public $email;

    /**
     * @Column(type="string", nullable=false)
     */
    public $first_name;

    /**
     * @Column(type="string", nullable=false)
     */
    public $last_name;

    /**
     * @Column(type="string", nullable=false)
     */
    public $password;

    public function getSource()
    {
        return "users";
    }
}

So now I want to do some ORM operations.
User::count(array('email = :email:', 'email' => $email)) == 0;

And I getting this error:
SQLSTATE[42S02]: Base table or view not found: 1146 Table 'dbname.users' doesn't exist
The table is really not exists, so how I should create it? Manually via SQL Query or using a specific tool in Phalcon Framework?

A: After a brief review of the phalcon docs i suppose that you are looking for something like this => Phalcon PHP creating tables
Sample of usage:
<?php
use \Phalcon\Db\Column as Column;

$connection->createTable(
    "robots",
    null,
    array(
       "columns" => array(
            new Column("id",
                array(
                    "type"          => Column::TYPE_INTEGER,
                    "size"          => 10,
                    "notNull"       => true,
                    "autoIncrement" => true,
                )
            ),
            new Column("name",
                array(
                    "type"    => Column::TYPE_VARCHAR,
                    "size"    => 70,
                    "notNull" => true,
                )
            ),
            new Column("year",
                array(
                    "type"    => Column::TYPE_INTEGER,
                    "size"    => 11,
                    "notNull" => true,
                )
            )
        )
    )
);

Howto setup a migration : Source

By default Phalcon Developer Tools use the app/migrations directory to
  dump the migration files. You can change the location by setting one
  of the parameters on the generation script. Each table in the database
  has its respective class generated in a separated file under a
  directory referring its version:

Each file contains a unique class that extends the
  Phalcon\Mvc\Model\Migration These classes normally have two methods:
  up() and down(). Up() performs the migration, while down() rolls it
  back.
Up() also contains the magic method morphTable(). The magic comes when
  it recognizes the changes needed to synchronize the actual table in
  the database to the description given.

<?php

use Phalcon\Db\Column as Column;
use Phalcon\Db\Index as Index;
use Phalcon\Db\Reference as Reference;

class ProductsMigration_100 extends \Phalcon\Mvc\Model\Migration
{

    public function up()
    {
        $this->morphTable(
            "products",
            array(
                "columns" => array(
                    new Column(
                        "id",
                        array(
                            "type"          => Column::TYPE_INTEGER,
                            "size"          => 10,
                            "unsigned"      => true,
                            "notNull"       => true,
                            "autoIncrement" => true,
                            "first"         => true,
                        )
                    ),
                    new Column(
                        "product_types_id",
                        array(
                            "type"     => Column::TYPE_INTEGER,
                            "size"     => 10,
                            "unsigned" => true,
                            "notNull"  => true,
                            "after"    => "id",
                        )
                    ),
                    new Column(
                        "name",
                        array(
                            "type"    => Column::TYPE_VARCHAR,
                            "size"    => 70,
                            "notNull" => true,
                            "after"   => "product_types_id",
                        )
                    ),
                    new Column(
                        "price",
                        array(
                            "type"    => Column::TYPE_DECIMAL,
                            "size"    => 16,
                            "scale"   => 2,
                            "notNull" => true,
                            "after"   => "name",
                        )
                    ),
                ),
                "indexes" => array(
                    new Index(
                        "PRIMARY",
                        array("id")
                    ),
                    new Index(
                        "product_types_id",
                        array("product_types_id")
                    )
                ),
                "references" => array(
                    new Reference(
                        "products_ibfk_1",
                        array(
                            "referencedSchema"  => "invo",
                            "referencedTable"   => "product_types",
                            "columns"           => array("product_types_id"),
                            "referencedColumns" => array("id"),
                        )
                    )
                ),
                "options" => array(
                    "TABLE_TYPE"      => "BASE TABLE",
                    "ENGINE"          => "InnoDB",
                    "TABLE_COLLATION" => "utf8_general_ci",
                )
            )
        );
        // insert some products
        self::$_connection->insert(
            "products",
            array("Malabar spinach", 14.50),
            array("name", "price")
        );
    }
}

Once the generated migrations are uploaded on the target server, you
  can easily run them as shown in the following example:


text:
Q: simple false position with matlab I'm trying to do a simple False Position code following my teachers model but can't get it to actually work.  Not sure if my if-else is correct or what as it only says Method Failed but I know there should be an answer of P=3.0571 and i=16. Totally new to programming and matlab so any help would be greatly valued. Thanks
%False Position
%(x^2-4x+4-lnx=0 for 2<=x<=4)

p0=2; p1=4; TOL=10^-6; N=100;

q0=p0^2-4*p0+4-log(p0);
q1=p1^2-4*p1+4-log(p1);

i=2;
while i<=N
    p=p1-q1*(p1-p0)/(q1-q0);

    if abs(p-p1)<TOL
        disp('False Position')
        p
        i
        break
    end

    i=i+1;
    q=p^2-4*p+4-log(p);

    if q*q1<0
        p0=p1;
        q0=q1;
    else
        p1=p;
        q1=q;
    end
end

   if i>=N disp('Method Failed')
   end

A: I am not really familiar with the false position method, but it seems you are trying to find the zero of some function by shrinking some interval at every step by setting either the left or right edge to some intermediate value based on some condition. I think there is a bug in your if: in case q*q1<0, you set the left edge to the same values as the right edge. You probably need to change it to:
if q*q1<0
    p0=p;q0=q;
else
    p1=p;q1=q;
end

Note that I only changed p1 to p and q1 to q.
For the rest your code looks OK, but I would suggest some small changes to make it more readable: change all p and q to x and y, and maybe define your function as a function handle (type help function_handle). Right now, you are defining your function in 3 different places. If you want to change your function in the future, you would have to make the exact same change in all those places, or you would have a bug. It is better to not repeat yourself and define your function only once as fun = @(x) x^2-4*x+4-log(x);, and then later use it as y0 = fun(x0) and y1 = fun(x1) etc.


text:
Q: ERROR: Index was out of range. Must be non-negative and less than the size of the collection: sumList[i]=(sumList[i] + formula3[j]); C# I tried doing sumlist.Add(sumlist[i] + formula3[j]) but I got the same error. I need a way to update the sum in every row. Thank you

A: The first time the program executes to the statement:
sumList[i]=(sumList[i] + formula3[j]);

The sumList is empty, and access to any element by index is forbidden at this time.
If the length is fixed, use Array instead of List<T> will work.
Because Array will initialize the elements.
I make some changes to your code and added some NOTE: as shown below.
Hope it works :)
    private List<List<double>> Formula3(List<List<double>> formula2MatrixResult, List<double> criteriaWeights)
    {
        List<List<double>> formula3List = new List<List<double>>();
        int combinations = 3;
        for (int i = 0; i < CriteriaWeights.Count; i++) //rows
        {
            List<double> formula3 = new List<double>();

            // NOTE: use an array of double instead of List<double>
            // and initialzie the length as fixed CriteriaWeights.Count
            double[] sumList = new double[CriteriaWeights.Count];

            for (int j = 0; j < combinations; j++) //col
            {
                if (formula2MatrixResult[i][j] < 0)
                    formula3.Add(0);
                else
                    formula3.Add(formula2MatrixResult[i][j] * criteriaWeights[i]);

                formula3List.Add(formula3);

                // NOTE: the List<T> count is dynamical,
                // so access element by invalid index is forbidden.
                sumList[i] = (sumList[i] + formula3[j]);
            }

            // NOTE: if you want to use List<T> finally,
            // you can call 'sumList.ToList();' to convert T[] to List<T>.
        }
        return formula3List;
    }

The difference between List<T> and Array is here:
Array versus List<T>: When to use which?


text:
Q: How should I use Executor insteand of AsyncTask or IntentService for queueing task on Android?
*

*Is it a good solution or not?

*How to implement?

*When should I shutdown properly? I shutdown it onDestroy() in the Activity, then relaunch my app as soon as possible. It causes a java.util.concurrent.RejectedExecutionException, why? Does anyone know its lifecycle?
Any idea? Thanks.

A: I just figure out the AsyncYask already implemented the Java's concurrency executor with core_pool_size 5 and max_pool_size 128. That's great!

A:
*

*Yes, I think so. AsyncTask is used for those tasks which will update UI. Sorry I am not familiar with IntentService.

*Create an Application object which implements android.app.Application interface. Create Executor in the onCreate method. You can get your Application object using following statement:

MyApplication app = (MyApplication) context.getApplicationContext();

*I am not sure what you mean by "app destory". I think you can shutdown Executor in Application's onTerminate method and onLowMemory method.


text: Q: Creating DOM objects using plain JavaScript In Raphael each and every thing you draw is considered as a DOM element, so you can directly call events on them.How can i implement the same thing if i use raw/plain JavaScript and not use any of the JavaScript libraries?


text:
Q: how to get IndexPath in iphone application.
I'm trying to get indexPath.row value to do something  on the basis of  row selected in programmatically created tableview.
Can someone please tell me  why is  the indexPath.row value is not coming correct. It's some thing like  21487...3?
NSUInteger nSections = [myTableView numberOfSections];
NSUInteger nRows = [myTableView numberOfRowsInSection:nSections];
NSIndexPath *indexPath = [NSIndexPath indexPathForRow: nRows inSection:nSections];
NSLog(@"No of sections in my table view %d",nSections);
NSLog(@"No of rows in my table view %d",nRows);
NSLog(@"Value of selected indexPath Row %d", indexPath.row);

Thanks,
Aaryan

A: The rows and sections of an NSIndexPath are arrays, and so start at 0 rather than 1. Therefore, the number of rows (or sections) in an NSIndexPath is actually 1 greater than the index of the last one.
Try
NSInteger lastSection = nSections - 1;
NSInteger lastRow = nRows - 1;
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:lastRow inSection:lastSection];


text:
Q: That's not ... is it? or is that? That's not nice, is it?
or
That's not nice, is that?
Thanks guys. Tried googling, didn't work. Can't figure out a good way to search on this topic.

A: This type of question is called a tag question (question tag in the UK). The most common form is a negated verb and a personal pronoun for positive statements and the reverse for negative ones.

You're John Smith, aren't you?
That's not John Smith, is it?

Using a demonstrative pronoun such as "this" or "that" in this construction instead of a personal pronoun would be highly non-idiomatic (i.e., wrong).


text:
Q: Como importar arquivos utilizando REGEX? Boa Tarde Pessoal, Tudo bem?
Estou com uma dúvida em regex em python.
Desejo criar um script para abrir arquivos sem informar seu formato podendo ser
pdf, txt, jpg, png, entre outros... Porém, desejo apenas especificar o nome da imagem, sem informar seu formato(informando o formato dentro do regex). Alguma dica de solução?

A: Você pode criar um pattern com o nome desejado, e as extensões possíveis.
Supondo que você deseja buscar por imagem.png, ou imagem.jpg ou imagem.gif dentro de c:/teste
import re
import os
padrao = r'imagem\.(png|jpg|gif)'
base_dir = 'c:/teste/'
for arquivo in os.listdir():
    if re.match(padrao, arquivo):
        with open(base_dir + arquivo) as reader:
            print(reader.read())


text:
Q: Appropriate language for scripting gathering server information tasks? I have a fairly unique problem, and I'd like to gather some input on it.
I'm responsible for creating a script of some sort that can do the following things:

*

*Run on any Windows Server 2008 R2 server

*Set up and run Perfmon Counters

*Log these counters to a log file

*Roll the log file when it gets too large

The script needs to be able to have the following properties:

*

*Compatible with WPF or Winforms (I need to create a GUI for it)

*Can be run by a local administrator on any Windows Server 2008 R2 server

*Is portable (as in, it can be easily packaged and put on a thumb drive, etc., with minimal (or no) installer overhead)

*Can be run by a user with little/no technical expertise (this goes back to the need to have a GUI)

So far I've gone down the road of Powershell, because it seems to fulfill most of the requirements. However, with how Powershell's security is set up I either need to have the script force an unrestricted script policy, or I need to figure out a way to create a self-signed certificate on any machine that might use it.
It's that last bit that causes problems, because makecert.exe requires that the user put in a password/key for the certificate (thus confusing a non-technical user) and isn't guaranteed to exist in a production Windows Server 2008 environment (thus forcing the user to install the Windows SDK or Visual Studio).
So I wanted to see if there was another language out there that could fulfill the requirements above, to make sure I'm using the right tool for the job.
NOTE: I'm not planning on using the scripting language itself to create the GUI, that can be done via VB or C# or something else. The script just needs to be called by a winform or WPF. Those are being used because I am most used to using Visual Studio rather than any other IDE.

A: I think you are on the right track and this should take care of your last concern.
I have quoted relevant lines from the powershell help file on about_Execution_Policies

You can set an execution policy for the local computer, for the current
      user, or for a particular session.
The execution policy for a particular session
      is stored only in memory and is lost when the session is closed.

You don't need to sign your scripts to make your powershell scripts portable. The execution policy for a powershell session can be set by using -ExecutionPolicy parameter when calling powershell.exe. This does not effect or change the execution policy that is already set on the computer.
For example, your GUI can call the script Install-Perfmon.ps1 using the commandline:
powershell.exe -ExecutionPolicy Unrestricted -File Install-Permon.ps1

This will work even the computer has a stricter execution policy already set.


text:
Q: Probability of a specific event when rolling a 6 sided die five times I am stuck on computing probability problem that goes as follows:
I am rolling a 6 sided die 5 times in total. What is the probability that I roll at least one 3, but no 1 or 2 at all (= probability of rolling at least 3 but at least one dice has to be 3).
Examples that satisfy my condition:

*

*35456

*33454

*45366

*...

Examples that do not satisfy my condition:

*

*45445 (satisfy at least 3, but does not satisfy at least one dice has to be 3)

*32653 (does not satisfy at least 3, satisfy one dice has to be 3)

*...

The part of rolling at least one 3, as far as I know, should be opposite event to no 3 at all: $$1 - \left(\frac56\right)^5 = 0.5981.$$
I am stuck on the second part.

A: Let,
$\\ A = Event \space all \space dice \space > \space 2  \\ B = Event \space a \space 3 \space is \space rolled\\$
We are interested in computing $P(A \cap B) = P(A) \space P(B \space | \space A)$
$P(A) = (\frac{2}{3})^{5} = 0.1316872 $
$P(B \space | \space A) = 1 - (\frac{3}{4})^{5} = 0.7626953$
Then,
$P(A \cap B) = P(A) \space P(B \space | \space A) = (0.1316872) \space (0.7626953) = 0.1004372$
We can simulate this with R to convince ourselves of the result:
> set.seed(0x12345678)
> hits <- 0
> runs <- 1000000
> for (i in 1:runs) {
+   s <- sample(1:6, 5, replace=TRUE)
+   if ( 3 %in% s & !(2 %in% s) & !(1 %in% s)) {
+     hits <- hits + 1
+   }
+ }
> hits / runs
[1] 0.10021

A: As suggested by @Dougal, I post my answer here:
The probability of obtaining at least one 3 and all values bigger than 2 in a six sided dice is equal to the probability of obtaining all values over 2 except the combinations in which all values are bigger than 3.
$$P(5\text{ rolls}>2)-P(5\text{ rolls}>3)=\left(\frac{4}{6}\right)^5-\left(\frac{3}{6}\right)^5\approx0.1004  $$
The problem can also be solved as the probability of obtaining all values over 2 and getting at least a 3 in those 5 rolls. This can be expressed as:
$$P(5\text{ rolls}>2)\cdot P(\text{at least a }3|5\text{ rolls}>2)= \left(\frac{4}{6}\right)^5\cdot\sum_{i=1}^{5}\binom{5}{i}\left(\frac{1}{4}\right)^i\cdot\left(\frac{3}{4}\right)^{5-i} $$
I believe the first solution is easier to understand, but, both provide the same result.


text:
Q: Google map: "click to see this area on google maps" - how to keep the markers My website has a map with a marker on it (pointing to a specific business address)
At the bottom left corner of the map is a Google sign which says:
"Click to see this area on Google maps"
When I click the Google sign, it opens a larger map in a new window.
However, the marker is not there.  (it doesn't make sense!)
Is there any way to keep the marker when clicking to view on a larger map ?
Many thanks!!

A: It is quite obvious - why would maps.google.com show markers in your application? They just say: "click to see this area" - so it just to see that area on a different map..
If you need a direct link to maps.google.com which will create the markers, look here: URL for multiple markers in Google Maps


text:
Q: JavaScript Empty Setter Method Error Given this code:
let person = {
_name: 'Lu Xun',
_age: 137
}

Need to add new setter method to change the person's age. I'm trying to add an empty age setter method, but get an error message Unexpected identifier or "Must have at least one parameter", though it asks for an empty method, to begin with.

A: let person = {
_name: 'Lu Xun',
_age: 137,
set age(ageIn){

}
};

I got stuck on this too. It's looking for you to name the new variable, which is not explained well in the question.


text:
Q: What does underscore variable followed by range mean in bash: $_{0..10} According to tldp.org, bash underscore variable is:

The underscore variable is set at shell startup and contains the absolute file name of the shell or script being executed as passed in the argument list. Subsequently, it expands to the last argument to the previous command, after expansion. It is also set to the full pathname of each command executed and placed in the environment exported to that command. When checking mail, this parameter holds the name of the mail file.

But this answer to How can I repeat a character in Bash? makes an strange use of it:
# exactly the same as perl -E 'say "=" x 100'.
echo -e ''$_{1..100}'\b='

Playing around with this variable I can't make anything out of it's semantics, so the question is what does

*

*An string.

*Followed by $_.

*Followed by range expansion.

*Followed by another string

mean in bash?
Sample:
$ echo $_{0..10}         ; echo $_{0..10} | wc

      1       0       1

$ echo ''$_{0..10}''     ; echo ''$_{0..10}'' | wc

      1       0      11

$ echo ''$_{0..10}'x'    ; echo ''$_{0..10}'x' | wc
x x x x x x x x x x x
      1      11      22

$ echo 'x'$_{0..10}''    ; echo 'x'$_{0..10}'' | wc
x x x x x x x x x x x
      1      11      22

$ echo 'ab'$_{0..10}'cd' ; echo 'ab'$_{0..10}'cd' | wc
abcd abcd abcd abcd abcd abcd abcd abcd abcd abcd abcd
      1      11      55

A:
echo $_{0..10}

The braces are expanded to:
echo $_0 $_1 $_2 $_3 $_4 $_5 $_6 $_7 $_8 $_9 $_10

It prints the values of eleven strangely-named variables named _0, _1, _2, and so on. They're not set—which is why you don't see anything—but if they were, you would:
$ _0=zero _1=one _2=two _3=three _4=four _5=five _6=six _7=seven _8=eight _9=nine _10=ten
$ echo $_{0..10}
zero one two three four five six seven eight nine ten

$ echo ''$_{0..10}'x'

Same thing, but now there's an x after each variable name. It's not part of the variable name. It's a separate, literal character x, as if you'd written:
echo ${_0}x ${_1}x ${_2}x ${_3}x ${_4}x ${_5}x ${_6}x ${_7}x ${_8}x ${_9}x ${_10}x

Now the output when the variables have values is:
$ _0=zero _1=one _2=two _3=three _4=four _5=five _6=six _7=seven _8=eight _9=nine _10=ten
$ echo ''$_{0..10}'x'
zerox onex twox threex fourx fivex sixx sevenx eightx ninex tenx

This should be enough to understand the other examples in your question.
It also shows that the linked answer is a poor way to repeat a string. It relies on these variables being unset. Not recommended.

A: That is brace expansion.
Read
info bash -n "Brace Expansion"
This expands the last command, stored in $_, with the given numbers.


text:
Q: error while Twitter integration in android Am trying to integrate twitter with my application to share message and image on my twitter wall. But displaying following exception:
05-17 01:06:28.151: D/Twitter Update Error(22720): 401:Authentication credentials (https://dev.twitter.com/pages/auth) were missing or incorrect. Ensure that you have set valid consumer key/secret, access token/secret, and the system clock is in sync.
05-17 01:06:28.151: D/Twitter Update Error(22720): {"request":"\/1.1\/statuses\/update.json","error":"Read-only application cannot POST."}
05-17 01:06:28.161: W/System.err(22720): 401:Authentication credentials (https://dev.twitter.com/pages/auth) were missing or incorrect. Ensure that you have set valid consumer key/secret, access token/secret, and the system clock is in sync.
05-17 01:06:28.161: W/System.err(22720): {"request":"\/1.1\/statuses\/update.json","error":"Read-only application cannot POST."}
05-17 01:06:28.161: W/System.err(22720): Relevant discussions can be found on the Internet at:
05-17 01:06:28.161: W/System.err(22720):    http://www.google.co.jp/search?q=2fc5b7cb or
05-17 01:06:28.161: W/System.err(22720):    http://www.google.co.jp/search?q=11613e08
05-17 01:06:28.161: W/System.err(22720): TwitterException{exceptionCode=[2fc5b7cb-11613e08], statusCode=401, message=null, code=-1, retryAfter=-1, rateLimitStatus=null, version=4.0.1}
05-17 01:06:28.161: W/System.err(22720):    at twitter4j.HttpClientImpl.handleRequest(HttpClientImpl.java:164)
05-17 01:06:28.161: W/System.err(22720):    at twitter4j.HttpClientBase.request(HttpClientBase.java:53)
05-17 01:06:28.161: W/System.err(22720):    at twitter4j.HttpClientBase.post(HttpClientBase.java:82)
05-17 01:06:28.166: W/System.err(22720):    at twitter4j.TwitterImpl.post(TwitterImpl.java:2004)
05-17 01:06:28.166: W/System.err(22720):    at twitter4j.TwitterImpl.updateStatus(TwitterImpl.java:251)
05-17 01:06:28.166: W/System.err(22720):    at com.android.twitterapi.Item$updateTwitterStatus.doInBackground(Item.java:64)
05-17 01:06:28.171: W/System.err(22720):    at com.android.twitterapi.Item$updateTwitterStatus.doInBackground(Item.java:1)
05-17 01:06:28.171: W/System.err(22720):    at android.os.AsyncTask$2.call(AsyncTask.java:288)
05-17 01:06:28.171: W/System.err(22720):    at java.util.concurrent.FutureTask.run(FutureTask.java:237)
05-17 01:06:28.176: W/System.err(22720):    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
05-17 01:06:28.176: W/System.err(22720):    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
05-17 01:06:28.176: W/System.err(22720):    at java.lang.Thread.run(Thread.java:841)

Can anyone please help me?
Following is my code:
MainActivity:
package com.android.twitterapi;

import me.grantland.twitter.Twitter;
import me.grantland.twitter.Twitter.DialogListener;
import me.grantland.twitter.TwitterError;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends Activity implements OnClickListener {

public static final String CONSUMER_KEY    = "fZRZJcNrFbg55dmr4rLVA";
public static final String CONSUMER_SECRET = "Xbxmn2hlT91mzydcmbnGRqOIYg8Ohipd9F8HfQYhHg";

private Twitter mTwitter;

private Button mTwitterButton;

 String access_token ;
 // Access Token Secret
 String access_token_secret ;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.login);

    mTwitter = new Twitter(CONSUMER_KEY, CONSUMER_SECRET);

    mTwitterButton = (Button)findViewById(R.id.twitter_login);
    mTwitterButton.setOnClickListener(this);
}

@Override
public void onClick(View v) {
    if (v.equals(mTwitterButton)) {
        mTwitter.authorize(this, new DialogListener() {
            @Override
            public void onComplete(String accessKey, String accessSecret) {
                access_token = accessKey;
                access_token_secret = accessSecret;
                AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                builder.setTitle("Success")
                       .setMessage("access_key: " + accessKey
                            + "\naccess_secret: " + accessSecret)
                       .setPositiveButton("Ok", null);
                AlertDialog alert = builder.create();
                alert.show();

                new Item(MainActivity.this, accessKey, accessSecret);
            }
            @Override
            public void onCancel() {
                AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                builder.setTitle("Canceled")
                       .setMessage("Twitter Login Canceled")
                       .setPositiveButton("Ok", null);
                AlertDialog alert = builder.create();
                alert.show();
            }

            @Override
            public void onError(TwitterError error) {
                AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
                builder.setTitle("Error")
                       .setMessage(error.getMessage())
                       .setPositiveButton("Ok", null);
                AlertDialog alert = builder.create();
                alert.show();
            }
        });
    }
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    // Twitter Auth Callback
    mTwitter.authorizeCallback(requestCode, resultCode, data);
}

}

Item.java:
package com.android.twitterapi;

import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
import twitter4j.api.TweetsResources;
import twitter4j.auth.AccessToken;
import twitter4j.conf.ConfigurationBuilder;
import android.app.Activity;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.util.Log;
import android.widget.Toast;

public class Item {

Activity mActivity;
String access_token;
String access_token_secret;
public Item(Activity activity, String key, String secret ) {

    mActivity  = activity;
    access_token = key;
    access_token_secret = secret;

     new updateTwitterStatus().execute("Om Sri Sri Sri Veerabhadra Swamy");
}
 /**
 * Function to update status
 * */
class updateTwitterStatus extends AsyncTask<String, String, String> {
     ProgressDialog pDialog;
    /**
     * Before starting background thread Show Progress Dialog
     * */
    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        pDialog = new ProgressDialog(mActivity);
        pDialog.setMessage("Updating to twitter...");
        pDialog.setIndeterminate(false);
        pDialog.setCancelable(false);
        pDialog.show();
    }

    /**
     * getting Places JSON
     * */
    protected String doInBackground(String... args) {
        Log.d("Tweet Text", "> " + args[0]);
        String status = args[0];
        try {
            ConfigurationBuilder builder = new ConfigurationBuilder();
            builder.setOAuthConsumerKey(MainActivity.CONSUMER_KEY);
            builder.setOAuthConsumerSecret(MainActivity.CONSUMER_SECRET);

            // Access Token

            AccessToken accessToken = new AccessToken(access_token, access_token_secret);
           Twitter twitter =  new TwitterFactory(builder.build()).getInstance(accessToken);

            // Update status
            twitter4j.Status response = ((TweetsResources) twitter).updateStatus(status);

            Log.d("Status", "> " + response.getText());
        } catch (TwitterException e) {
            // Error in updating status
            Log.d("Twitter Update Error", e.getMessage());
            e.printStackTrace();
        }
        return null;
    }

    /**
     * After completing background task Dismiss the progress dialog and show
     * the data in UI Always use runOnUiThread(new Runnable()) to update UI
     * from background thread, otherwise you will get error
     * **/
    protected void onPostExecute(String file_url) {
        // dismiss the dialog after getting all products
        pDialog.dismiss();
//            // updating UI from Background Thread
//            runOnUiThread(new Runnable() {
//                @Override
//                public void run() {
                Toast.makeText(mActivity,
                        "Status tweeted successfully", Toast.LENGTH_SHORT)
                        .show();
                // Clearing EditText field
////                    txtUpdate.setText("");
//                }
//            });
    }

}
}

Twitter.java:
package me.grantland.twitter;

import oauth.signpost.OAuthConsumer;
import oauth.signpost.commonshttp.CommonsHttpOAuthConsumer;
import android.app.Activity;
import android.content.Intent;
import android.util.Log;

/**
 * @author Grantland Chew
 */
public class Twitter {
public static final String TAG = "me.grantland.twitter";
public static final boolean DEBUG = false;

public static final String REQUEST_TOKEN = "https://twitter.com/oauth/request_token";
public static final String ACCESS_TOKEN = "https://twitter.com/oauth/access_token";
public static final String AUTHORIZE = "https://twitter.com/oauth/authorize";
public static final String DENIED = "denied";
public static final String CALLBACK_SCHEME = "gc";
public static final String CALLBACK_URI = CALLBACK_SCHEME + "://twitt";

public static final String EXTRA_ERROR = "error";
public static final String EXTRA_CONSUMER = "consumer";
public static final String EXTRA_AUTHORIZE_PARAMS = "params";
public static final String EXTRA_ACCESS_KEY = "access_key";
public static final String EXTRA_ACCESS_SECRET = "access_secret";

// Used as default activityCode by authorize(). See authorize() below.
public static final int DEFAULT_AUTH_ACTIVITY_CODE = 4242;

private OAuthConsumer mConsumer = null;

private int mRequestCode;
private DialogListener mListener = null;

public Twitter(String consumerKey, String consumerSecret) {
    if (consumerKey == null || consumerSecret == null) {
        throw new IllegalArgumentException(
                "You must specify your consumer key and secret when instantiating " +
                "a Twitter object. See README for details.");
    }
    mConsumer = new CommonsHttpOAuthConsumer(consumerKey, consumerSecret);
}

/**
 * Short authorize method that uses default settings.
 *
 * Starts either an activity or dialog that a user will use to enter their credentials
 * to authorize your application with Twitter.
 *
 * @param activity
 *          The Activity to display the authorization window on.
 * @param listener
 *          The callback for Twitter authentication responses.
 * @return
 */
public boolean authorize(Activity activity, final DialogListener listener) {
    return authorize(activity, false, null, DEFAULT_AUTH_ACTIVITY_CODE, listener);
}

/**
 * Short authorize method that uses the default activityCode.
 *
 * Starts either an activity or dialog that a user will use to enter their credentials
 * to authorize your application with Twitter.
 *
 * @param activity
 *          The Activity to display the authorization window on.
 * @param forceLogin
 *          Forces the user to enter their credentials to ensure the correct users account
 *          is authorized.
 * @param screenName
 *          Prefills the username input box of the OAuth login screen with the given value.
 * @param listener
 *          The callback for Twitter authentication responses.
 * @return
 */
public boolean authorize(Activity activity, boolean forceLogin, String screenName, DialogListener listener) {
    return authorize(activity, forceLogin, screenName, DEFAULT_AUTH_ACTIVITY_CODE, listener);
}

/**
 * Full authorize method.
 *
 * Starts either an activity or dialog that a user will use to enter their credentials
 * to authorize your application with Twitter.
 *
 * @param activity
 *          The Activity to display the authorization window on.
 * @param forceLogin
 *          Forces the user to enter their credentials to ensure the correct users account
 *          is authorized.
 * @param screenName
 *          Prefills the username input box of the OAuth login screen with the given value.
 * @param activityCode
 *          The requestCode used in Activity#onActivityResult. Can be changed if the default
 *          conflicts with another Activity in your application.
 * @param listener
 *          The callback for Twitter authentication responses.
 * @return
 */
public boolean authorize(Activity activity, boolean forceLogin, String screenName, int activityCode, DialogListener listener) {

    // Optional params
    String authorizeParams = "";
    if (forceLogin) {
        authorizeParams += "?force_login=" + forceLogin;
    }
    if (screenName != null) {
        authorizeParams += (authorizeParams.length() == 0 ? "&" : "?") + "screen_name=" + screenName;
    }
    if (DEBUG) Log.d(TAG, "authorize params: " + authorizeParams);

    // We could check if the activity exists in the manifest and fallback on
    // the dialog, but if a user wants to use the dialog they can.
    if (activityCode > 0) {
        startTwitterActivity(activity, authorizeParams, activityCode, listener);
    } else {
        startTwitterDialog(activity, authorizeParams, listener);
    }

    return true;
}

private boolean startTwitterActivity(Activity activity, String authorizeParams, int activityCode, DialogListener listener) {
    mRequestCode = activityCode;
    mListener = listener;

    Intent intent = new Intent(activity, TwitterActivity.class);
    intent.putExtra(EXTRA_CONSUMER, mConsumer);
    intent.putExtra(EXTRA_AUTHORIZE_PARAMS, authorizeParams);
    activity.startActivityForResult(intent, DEFAULT_AUTH_ACTIVITY_CODE);

    return true;
}

private boolean startTwitterDialog(Activity activity, String authorizeParams, final DialogListener listener) {
    TwitterDialog dialog = new TwitterDialog(activity, mConsumer, authorizeParams, new DialogListener() {
        @Override
        public void onComplete(String token, String secret) {
            if (DEBUG) Log.d(TAG, "access_key: " + token);
            if (DEBUG) Log.d(TAG, "access_secret: " + secret);

            mConsumer.setTokenWithSecret(token, secret);

            listener.onComplete(token, token);
        }

        @Override
        public void onError(TwitterError error) {
            listener.onError(error);
        }

        @Override
        public void onCancel() {
            listener.onCancel();
        }
    });
    dialog.show();

    return true;
}

/**
 * Callback for Twitter authorize. Should be called in any Activity that calls
 * Twitter#authorize.
 *
 * @param requestCode
 *          The integer request code originally supplied to
 *          startActivityForResult(), allowing you to identify who this
 *          result came from.
 * @param resultCode
 *          The integer result code returned by the child activity
 *          through its setResult().
 * @param data
 *          An Intent, which can return result data to the caller
 *          (various data can be attached to Intent "extras").
 */
public void authorizeCallback(int requestCode, int resultCode, Intent data) {
    if (mRequestCode != requestCode) {
        return;
    }

    String accessKey, accessSecret;

    if (Activity.RESULT_OK == resultCode) {
        String error = data.getStringExtra(EXTRA_ERROR);
        if (error != null) {
            mListener.onError(new TwitterError(error));
        } else {
            accessKey = data.getStringExtra(EXTRA_ACCESS_KEY);
            accessSecret = data.getStringExtra(EXTRA_ACCESS_SECRET);

            if (DEBUG) Log.d(TAG, "access_key: " + accessKey);
            if (DEBUG) Log.d(TAG, "access_secret: " + accessSecret);

            mConsumer.setTokenWithSecret(accessKey, accessSecret);

            if (mListener != null) {
                mListener.onComplete(accessKey, accessSecret);
                return;
            }
        }
    } else if (Activity.RESULT_CANCELED == resultCode) {
        if (mListener != null) {
            mListener.onCancel();
        }
    }
}

//==============================================================================================
// Properties
//==============================================================================================

/**
 * @return boolean - whether this object has an non-expired session token.
 */
public boolean isSessionValid() {
    return mConsumer != null && (getAccessToken() != null && getAccessTokenSecret() != null);
}

/**
 * @return String - the consumer_key.
 */
public String getConsumerKey() {
    return mConsumer.getConsumerKey();
}

/**
 * @return String - the consumer_secret.
 */
public String getConsumerSecret() {
    return mConsumer.getConsumerSecret();
}

/**
 * Sets the consumer_key and consumer_secret.
 * @param consumerKey
 * @param consumerSecret
 */
public void setConsumerKeyAndSecret(String consumerKey, String consumerSecret) {
    mConsumer = new CommonsHttpOAuthConsumer(consumerKey, consumerSecret);
}

/**
 * @return String - the access_token.
 */
public String getAccessToken() {
    return mConsumer.getToken();
}

/**
 * @return String - the access_token_secret.
 */
public String getAccessTokenSecret() {
    return mConsumer.getTokenSecret();
}

/**
 * Sets the access_token and access_token_secret.
 * @param token
 * @param secret
 */
public void setTokenWithSecret(String token, String secret) {
    mConsumer.setTokenWithSecret(token, secret);
}

/**
 * Callback interface for dialog requests.
 */
public static interface DialogListener {

    /**
     * Called when a dialog completes.
     *
     * Executed by the thread that initiated the dialog.
     *
     * @param values
     *            Key-value string pairs extracted from the response.
     */
    public void onComplete(String accessKey, String accessSecret);

    /**
     * Called when a dialog has an error.
     *
     * Executed by the thread that initiated the dialog.
     */
    public void onError(TwitterError error);

    /**
     * Called when a dialog is canceled by the user.
     *
     * Executed by the thread that initiated the dialog.
     */
    public void onCancel();

}
}

TwitterActivity.java:
package me.grantland.twitter;

import oauth.signpost.OAuth;
import oauth.signpost.OAuthConsumer;
import oauth.signpost.OAuthProvider;
import oauth.signpost.commonshttp.CommonsHttpOAuthProvider;
import oauth.signpost.exception.OAuthException;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.Window;
import android.webkit.WebView;
import android.webkit.WebViewClient;

import com.android.twitterapi.R;

public class TwitterActivity extends Activity {
private static final String TAG = Twitter.TAG;
private static final boolean DEBUG = Twitter.DEBUG;

private static final int RETRIEVE_REQUEST_TOKEN = 1;
private static final int RETRIEVE_ACCESS_TOKEN = 2;

private static final String KEY_URL = "url";

private H mMainThreadHandler;

private OAuthConsumer mConsumer;
private OAuthProvider mProvider;

private ProgressDialog mSpinner;
private WebView mWebView;

/**
 * Handler to run shit on the UI thread
 *
 * @author Grantland Chew
 */
private class H extends Handler {
    @Override
    public void handleMessage (Message msg) {
        Bundle data = msg.getData();

        switch (msg.what) {
            case RETRIEVE_REQUEST_TOKEN: {
                mWebView.loadUrl(data.getString(KEY_URL));
            } break;
            case RETRIEVE_ACCESS_TOKEN: {

            } break;
            default: {

            }
        }
    }
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.twitter_layout);

    Intent intent = getIntent();
    mConsumer = (OAuthConsumer)intent.getSerializableExtra(Twitter.EXTRA_CONSUMER);
    String authorizeParams = intent.getStringExtra(Twitter.EXTRA_AUTHORIZE_PARAMS);

    mMainThreadHandler = new H();

    mProvider = new CommonsHttpOAuthProvider(
            Twitter.REQUEST_TOKEN,
            Twitter.ACCESS_TOKEN,
            Twitter.AUTHORIZE + authorizeParams);
    mProvider.setOAuth10a(true);

    mSpinner = new ProgressDialog(this);
    mSpinner.setMessage(getResources().getString(R.string.loading_loading));
    mSpinner.setOnCancelListener(new OnCancelListener() {
        @Override public void onCancel(DialogInterface dialog) {
            cancel();
        }
    });

    mWebView = (WebView)findViewById(R.id.twitter_webview);
    mWebView.getSettings().setJavaScriptEnabled(true);
    mWebView.getSettings().setSaveFormData(false);
    mWebView.getSettings().setSavePassword(false);
    mWebView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
    mWebView.setWebViewClient(new TwitterWebViewClient());

    // Retrieve request_token on background thread
    Thread thread = new Thread() {
        @Override
        public void run() {
            try {
                Message msg = new Message();
                msg.what = RETRIEVE_REQUEST_TOKEN;

                Bundle bundle = new Bundle();
                bundle.putString(KEY_URL, mProvider.retrieveRequestToken(mConsumer, Twitter.CALLBACK_URI));
                msg.setData(bundle);

                if (DEBUG) Log.d(TAG, "url: " + bundle.getString(KEY_URL));
                mMainThreadHandler.sendMessage(msg);
            } catch (OAuthException e) {
                error(e);
            }
        }
    };
    thread.start();
}

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (KeyEvent.KEYCODE_BACK == keyCode) {
        cancel();
        return true; // consume event
    }

    return false; // don't consume event
}

private void error(Throwable error) {
    Intent intent = this.getIntent();
    intent.putExtra(Twitter.EXTRA_ERROR, error.getMessage());
    this.setResult(RESULT_OK, intent);
    finish();
}

private void cancel() {
    Intent intent = this.getIntent();
    this.setResult(RESULT_CANCELED, intent);
    finish();
}

private void complete(String accessKey, String accessSecret) {
    Intent intent = this.getIntent();
    intent.putExtra(Twitter.EXTRA_ACCESS_KEY, accessKey);
    intent.putExtra(Twitter.EXTRA_ACCESS_SECRET, accessSecret);
    this.setResult(RESULT_OK, intent);
    finish();
}

private void retrieveAccessToken(final Uri uri) {
    Thread thread = new Thread() {
        @Override
        public void run() {
            try {
                if (DEBUG) Log.d(TAG, uri.toString());
                String oauth_token = uri.getQueryParameter(OAuth.OAUTH_TOKEN);
                String verifier = uri.getQueryParameter(OAuth.OAUTH_VERIFIER);
                if (DEBUG) Log.d(TAG, oauth_token);
                if (DEBUG) Log.d(TAG, verifier);

                mConsumer.setTokenWithSecret(oauth_token, mConsumer.getConsumerSecret());
                mProvider.retrieveAccessToken(mConsumer, verifier);

                complete(mConsumer.getToken(), mConsumer.getTokenSecret());
            } catch (OAuthException e) {
                error(e);
            }
        }
    };
    thread.start();
}

private class TwitterWebViewClient extends WebViewClient {
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        if (DEBUG) Log.d(TAG, url);
        Uri uri = Uri.parse(url);
        if (uri != null && Twitter.CALLBACK_SCHEME.equals(uri.getScheme())) {
            String denied = uri.getQueryParameter(Twitter.DENIED);

            if (denied != null) {
                cancel();
            } else {
                retrieveAccessToken(uri);
            }

            return true;
        }
        return false;
    }

    @Override
    public void onPageStarted(WebView view, String url, Bitmap favicon) {
        super.onPageStarted(view, url, favicon);
        if (DEBUG) Log.d(TAG, "Webview loading URL: " + url);
        if (view.getVisibility() != View.INVISIBLE && !mSpinner.isShowing()) {
            mSpinner.show();
        }
    }

    @Override
    public void onPageFinished(WebView view, String url) {
        mSpinner.dismiss();
        view.setVisibility(View.VISIBLE);
    }

    @Override
    public void onReceivedError(WebView view, int errorCode,
            String description, String failingUrl) {
        super.onReceivedError(view, errorCode, description, failingUrl);
        error(new TwitterError(description, errorCode, failingUrl));
    }
};
}

A: I recommend you use this library. This library as explained in the book "Learning Android, 2nd Edition": It has been stripped down to the bare essentials, making it easy for you to peek at it's source code and see it's inner workings, if you care to do so. It also supports Twitter's older API that allows for simple authentication (username and password) versus the new OAuth authentication. is much simpler to integrate and use than the one you are using. Again it depends what you want to actually do. if your purpose is to learn and you are new to Java and Android this is recommended due to focus on learning the concept rather than library and API.

A: I can recommend you this library - https://github.com/antonkrasov/AndroidSocialNetworks
But your issue in permission of your app.
Open your app settings and go to permissions tab:

Then select Read and Write and save:

Now all should work.


text:
Q: Is there such a construction as "to send hello" or "to send hi"? Is there such a construction as "to send hello" or "to send hi"?
Or something close?
Or which is better?

A: I've stumbled upon such strucure several times: Andrew sends his hello's so looks like it could be used, even though to the majority of native English speakers it obviously doesn't sound normal. Andrew gives/sends his regards , probably, would be a better choice.
Google Books results for "sends his hello"

A: On Xmas cards, I often write "'Hi' to all!" (Verb implied - no need to sweat it.)

A: "Say Hi to (name) from me" works fine in English too. Probably the most common way to say it.


text:
Q: Call request/reply method of duplex service freeze client until timeout occur I have create a duplex WCF service tha return data from an external device to the client and allow also request/reply calls.
My problem is that the request/reply calls sometime freeze the client until timeout occurs.
These are the interfaces:
[ServiceContract(CallbackContract = typeof(ITimerServiceCallback), SessionMode = SessionMode.Required)]
public interface ITimerService
{
    [OperationContract]
    void StartTimer();

    [OperationContract]
    void StopTimer();

    [OperationContract]
    void DoOp();
}

public interface ITimerServiceCallback
{
    [OperationContract(IsOneWay = true)]
    void ReportTick(string now);
}

This is the implementation:
[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerSession)]
    public class TimerService : ITimerService
    {
        public TimerService()
        {
            _timer = new System.Timers.Timer() { Interval = 500 };
            _timer.Elapsed += Timer_Elapsed;
        }

        private void Timer_Elapsed(object sender, ElapsedEventArgs e)
        {
            _context.GetCallbackChannel<ITimerServiceCallback>().ReportTick(DateTime.Now.ToString());
        }

        private readonly System.Timers.Timer _timer;
        private OperationContext _context;

        public void StartTimer()
        {
            _context = OperationContext.Current;
            _timer.Start();
        }

        public void StopTimer()
        {
            _timer.Stop();
        }

        public void DoOp()
        {
            System.Threading.Thread.Sleep(200);
        }
    }

Step to reproduce the problem:
    * call StartTimer
    * call DoOp (one or more time until the client freeze)
After one minute I have an timeout exception.

A: If I use the async/await from the client side all work fine.
ex: the DoOp method is called in this way:
private async void _btnDoOp_Click(object sender, EventArgs e)
{
    _btnNoOp.Enabled = false;
    try {
        Task task = Task.Run(() => _client.DoOperation());
        await task;
    } catch (Exception ex) {
        MessageBox.Show(ex.Message);
    } finally {
        _btnNoOp.Enabled = true;
    }
}


text:
Q: How to design a performance test for e-commerce application with Jmeter where 10% of users make orders I am conducting a performance test for an e-commerce demo application with Jmeter. I have managed to record the pages which a user navigates more but I want that 10% of total users which navigates the website to make orders.
I am aware that Jmeter interface is simplified and there is no way to play with these parameters.
Is this even do-able?
Thanks all!
I
I was expecting to find more on this topic

A: JMeter provides Throughput Controller which allows to execute its children with the defined percentage from total number of requests.

Also there is Weighted Switch Controller plugin which is a little bit more flexible and convenient.


text:
Q: Detecting key release with crossterm with rust I'm trying to detect key releasing instead of pressing using crossterm.
I'm using the basic example named event-stream-tokio. I need tokio runtime for the project.
Link to the example code: https://github.com/crossterm-rs/crossterm/blob/master/examples/event-stream-tokio.rs
Anyway, when I'm trying to amend the example to catch key release and not press - I'm not able to do so. Only the press kind is detected.
Does anybody know how to make it work?
Here is my changed function in that example:
async fn print_events() {
    let mut reader = EventStream::new();

    loop {
        let mut delay = Delay::new(Duration::from_millis(1_000)).fuse();
        let mut event = reader.next().fuse();

        select! {
            _ = delay => { println!(".\r"); },
            maybe_event = event => {
                match maybe_event {
                    Some(Ok(event)) => {
                        println!("Event::{:?}\r", event);

                        if event == Event::Key(
                            // Here I changed the example
                            KeyEvent::new_with_kind(
                                KeyCode::Char('c'),
                                KeyModifiers::NONE,
                                KeyEventKind::Release
                            )) {
                            println!("c key was released!. position is: {:?}\r", position());
                        }

                        if event == Event::Key(KeyCode::Esc.into()) {
                            break;
                        }
                    }
                    Some(Err(e)) => println!("Error: {:?}\r", e),
                    None => break,
                }
            }
        };
    }
}

Printing the position of the cursor is not important. It's only part of their example.
Thanks!

A: The default behavior of terminals is that what you get is not a stream of key state events but a stream of text — of characters typed. There is no concept of key-up.
However, the kitty keyboard protocol is a set of extensions which some terminals support to allow reporting key-up events, and that is what crossterm's KeyEventKind is about. You have to enable the features by using PushKeyboardEnhancementFlags, and you have to be using a terminal that implements that extension. Otherwise you will never see a release event.


text:
Q: Visual studio unicode issue when using nmake command I use Visual studio 6 to build dll from .rc file using nmake command and it works fine with English, Arabic and French but when trying to generate dll for Russian language it generated with a garbage data not Russian I think this problem is due to vs 6 unicoding and I changed the region(non - unicode) to Russian  I googled this problem to find any help about this issue but no answer if anyone can help?
I tried changing the region and add Russian language for windows
this the call for nmake command
nmake -a -f mlobject.mak
I expect the generated dll to show me Russian characters when include and use it in the application but the result is garbage characters.

A: I have solved it the bug is that when I'm trying to read string or resource value from dll in gupta(programming language like c++ and c#) it convert the string and read it as garbage data so when reading from dll I convert the string into binary then convert it to string again.


text:
Q: Bibtex does not find .aux files of chapters included with \include in output folder I recently split my thesis in several files each containing one chapter which is included with \include in the main Latex-file.
I call pdflatex with -output-directory=output to keep the source directory clean.
The problem is that bibtex does not find the axuliary files for the included subfiles. I call it with bibtex ./output/%.aux and it finds the main.aux but not any of the sub-aux.files such as chapter1.aux, chapter2.aux, etc.
The problem seems to be that the path to the output folder is not included in the main.aux. When I change the path there manually for example from \@input{1_intro.aux} to \@input{output/1_intro.aux} everything compiles fine.
Is there any way to make pdflatex write the proper paths into the main.aux?
I am using TexStudio on a Linux machine. Thanks a lot!

A: It's late, I leave this for future generations...
Do you need to use \include or may you use \input? If you use the latter, a unique .aux file is created (instead of one for each .tex file), and you get away with calling bibtex from the main directory like you already do:bibtex ./output/%.aux
(not my idea, credits to https://tex.stackexchange.com/a/518934)


text:
Q: Why is git slow on my windows machine? Just typing git at the command prompt (of powershell), takes 2.5 seconds until it returns with the help message.
I'm using the git for windows release, installed in C:\Program Files (x86)\Git. When I use cygwin (via babun), I get an error: Hint: your prompt is very slow. Check the installed 'BLODA' software. Maybe this is related? If it is, I'm using a corporate laptop, so can't uninstall antivirus or driver software, are there other options?

A: For me the reason seemed to be the "Inject ConEmuHk" setting in cmder under which I ran git. I've opened a bug https://github.com/bliker/cmder/issues/592

A: Try and see if the issue persists with the latest 2.4+ git for Windows release.
There is a bug related to the git bash startup time which is actively addressed.


text:
Q: Extract json values into columns if certain id exists I have some db that stores json array of objects in a column. I need to make columns out of these objects keys if object's id has certain value
My documents table is simple:
id |   name    | percent_split
1  | some name | [ {id: 59, share:22, value: 55},{id:58, share:40, value:33}]

I've tried some variants of the following to get the data, not mentioning making columns out of object keys:
SELECT
id, name,
(SELECT FROM documents
    WHERE (
    CASE WHEN JSON_VALID(percent_split) THEN
    json_search(percent_split, 'one', '{"id":"59"}')
    ELSE null
    END)
) AS result_for_59
FROM documents

I would like to get additional columns in the result of my query
id, name, 59_share, 59_value, NN_share, NN_value

Please help :)
I could go with any language easily, but in this case I'm limited to use only MySql technology.

A: We made a function in mysql which has two arguments: the column_value and the value we search for:
RETURN JSON_EXTRACT(value, JSON_UNQUOTE(
    REPLACE(
        JSON_SEARCH(
            ,'one',column_value
        ),'.id','.share'
    ))
)

Then we call it inside select part of query, for every value we need:
if(json_valid(percent_split),get_share(39, percent_split),NULL) AS share39