text:
Q: Carregar chart com 2 store um para o axes e outro para series Crie um chart do tipo Line, para ele vou poder carregar um ou mais tipos de series dentro desse mesmo gráfico.
Mais nesse caso somente dois series como no link.
Fiz no listeners->painted para renderizar o gráfico.
A legenda consigo carregar dinamicamente de boa. mais as linhas não aparecem
Segue código da View, tem dois links com os dados em json.
prntscr.com/80vj9p ---- nesse eu carrego o graficoIndBIStore no caso seria as duas linhas do gráfico e as duas legendas
prntscr.com/80vkis  ---- nesse eu carrego os valores do gráfico mais, não carrega as linhas ficam no canto superior esquerdo
Imagem da view do gráfico prntscr.com/80vovv

Ext.define('Integrator.view.BI.Chart.Line', {
    extend: 'Ext.Panel',
    alias: 'widget.linechart',
    requires: ['Ext.chart.axis.Numeric', 'Ext.data.JsonStore', 'Ext.chart.CartesianChart'],

    config: {
        cls: 'card4',
        layout: 'fit',
        items: [
            {
                xtype: 'chart',
                id: 'chartBILine',
                store: {},
                background: 'white',
                animate: true,
                legend:{
                    position: 'bottom'
                }
            }
        ],
        listeners: {
            painted: function () {
                var indicadorStore = Ext.getStore('biChartsStore'),
                    graficoIndBIStore = Ext.getStore('GraficoIndBIStore'),
                    chart = Ext.getCmp('chartBILine'),
                    seriesArray = new Array(),
                    axesArray = new Array(),
                    fields = new Array(),
                    lineColors = ['#115fa6', '#94ae0a', '#a61120', '#006600', '#ff9900', '#ff9999', '#ffccff', '#66ff00', '#cc33ff'],
                    markerColors = ['#94ae0a', '#a61120', '#115fa6', '#003300', '#006600', '#0066ff', '#993300', '#66ff00', '#cc33ff'];

                graficoIndBIStore.each(function(rec, index){
                    seriesArray.push(
                        new Ext.chart.series.Line({
                            type: 'line',
                            xField: 'data',
                            yField: [rec.data.titulo_ind],
                            stacked: false,
                            style: {
                                smooth: true,
                                stroke: lineColors[index - 0],
                                lineWidth: 1,
                                shadowColor: 'rgba(0,0,0,0.7)',
                                shadowBlur: 10,
                                shadowOffsetX: 3,
                                shadowOffsetY: 3
                            },
                            marker: {
                                type: 'circle',
                                stroke: markerColors[index - 0],
                                fill: markerColors[index - 0],
                                lineWidth: 2,
                                radius: 4,
                                shadowColor: 'rgba(0,0,0,0.7)',
                                shadowBlur: 10,
                                shadowOffsetX: 3,
                                shadowOffsetY: 3,
                                fx: {
                                    duration: 300
                                }
                            }
                        })
                    );
                });

                indicadorStore.each(function(rec2, index2){
                    fields.push(rec2.data.valor);
                });

                axesArray.push(
                    new Ext.chart.axis.Numeric({
                        type: 'numeric',
                        position: 'left',
                        fields: fields,
                        title: 'Valor',
                        minorTickSteps: 1,
                        grid: {
                            odd: {
                                opacity: 1,
                                fill: '#ddd'
                            }
                        },
                        style: {
                            axisLine: false,
                            estStepSize: 20,
                            stroke: '#ddd',
                            'stroke-width': 0.5
                        }
                    })
                );

                axesArray.push(
                    new Ext.chart.axis.Category({
                        type: 'category',
                        position: 'bottom',
                        fields: ['data'],
                        title: {
                            text: 'Meses',
                            fontSize: !Ext.os.is.Phone ? 15 : 10
                        },
                        style: {
                            estStepSize: 1,
                            stroke: '#999'
                        },
                        label: {
                            rotate: { degrees: 65 }
                        }
                    })
                );

                var data = {"data": indicadorStore.getData().items};
                chart.setStore(data);

                chart.setAxes(axesArray);
                chart.setSeries(seriesArray);
            }
        }
    }
});


text:
Q: Why is $\vec u_x \cdot \vec u_\phi =-\sin\phi $? I am learning the coordinate transform between cylindrical and cartesian,and the picture is the teaching,and i don't understand why is  $\vec u_x \cdot \vec u_\phi =-\sin\phi $ ?
I guess the reason of  $\vec u_x \cdot \vec u_r =\cos\phi $ is $x=r\cos\phi$,but it can't explain why  $\vec u_x \cdot \vec u_\phi =-\sin\phi $,can anyone teach me?

A: $
\newcommand\PD[2]{\frac{\partial#1}{\partial#2}}
$
$\vec u_x$ is the vector telling you how a point $P(x, y, z)$ moves when you change $x$ a tiny bit; similarly for $\vec u_y$ and $\vec u_z$. Since the point at coordinates $(x, y, z)$ is
$$
  P(x, y, z) = x\vec u_x + y\vec u_y + z\vec u_z
$$
and $\vec u_x, \vec u_y, \vec u_z$ are constant, we see
$$
  \PD Px = \vec u_x,\quad \PD Py = \vec u_y,\quad \PD Pz = \vec u_z.
$$
The partial derivatives of $P$ capture the idea of moving a point a tiny bit and giving the resulting displacement vector. So now write $P$ in cylindrical coordinates:
$$
  P(r, \phi, z) = (r\cos\phi)\vec u_x + (r\sin\phi)\vec u_y + z\vec u_z.
$$
Then
$$
  \vec u_\phi = \PD p\phi = -(r\sin\phi)\vec u_x + (r\cos\phi)\vec u_y,
$$
so we see
$$
  \vec u_x\cdot\vec u_\phi = -(r\sin\phi)\vec u_x\cdot\vec u_x + (r\cos\phi)\vec u_x\cdot\vec u_y = -r\sin\phi.
$$

The coordinate basis $\vec u_r, \vec u_\phi, \vec u_z$ derived in this way does not have to consist of unit vectors, but it is often desirable to normalize and make them into unit vectors. In this particular case
$$
  |\vec u_\phi|
    = \sqrt{\vec u_\phi\cdot\vec u_\phi}
    = \sqrt{r^2\sin^2\phi + r^2\cos^2\phi}
    = \sqrt{r^2}
    = r,
$$
the last equality following since $r$ is usually assumed to be positive. Then
$$
  \hat u_\phi = \frac{\vec u_\phi}{|\vec u_\phi|} = -(\sin\phi)\vec u_x + (\cos\phi)\vec u_y
$$
and so
$$
  \vec u_x\cdot\hat u_\phi = -\sin\phi.
$$

A: Start by looking at the definition of $\hat a_r$ and $\hat a_\phi$. Those are vectors of length $1$, with $\hat a_r$ along the $r$, and $\hat a_\phi$ perpendicular to $\hat a_r$, in the horizontal plane. So now you need to write these in terms of the components along the axes. For $\hat a_r$, you have $$\hat a_r=\frac x{\sqrt{x^2+y^2}}\hat a_x+\frac y{\sqrt{x^2+y^2}}\hat a_y=\cos\phi\hat a_x+\sin\phi\hat a_y$$
You can easily see that the slope is $y/x$. The perpendicular to this will have the slope $-x/y$. Using the fact that it's normalized to $1$, you get $$\hat a_\phi=\pm\sin\phi\hat a_x\mp\cos\phi\hat a_y$$
The convention about the sign is given by the cross product:
$$\hat a_r\times\hat a_\phi=\hat a_z$$

redpajama_set_name: RedPajamaStackExchange


text:
Q: SQL Find max no of consecutive months over a period of last 12 Months I am trying to write a query in sql where I need to find the max no. of consecutive months over a period of last 12 months excluding June and July.
so for example I have an initial table as follows
+---------+--------------+-----------+------------+
|      id | Payment      |  amount   |    Date    |
+---------+--------------+-----------+------------+
|       1 | CJ1          |     70000 | 11/3/2020  |
|       1 | 1B4          |  36314000 | 12/1/2020  |
|       1 | I21          | 119439000 | 1/12/2021  |
|       1 | 0QO          |   9362100 | 2/2/2021   |
|       1 | 1G0          | 140431000 | 2/23/2021  |
|       1 | 1G           |   9362100 | 3/2/2021   |
|       1 | g5d          |   9362100 | 4/6/2021   |
|       1 | rt5s         |  13182500 | 4/13/2021  |
|       1 | fgs5         |     48598 | 5/18/2021  |
|       1 | sd8          |     42155 | 5/25/2021  |
|       1 | wqe8         |  47822355 | 7/20/2021  |
|       1 | cbg8         |   4589721 | 7/27/2021  |
|       1 | jlk8         |   4589721 | 8/3/2021   |
|       1 | cxn9         |   4589721 | 10/5/2021  |
|       1 | qwe          |  45897210 | 11/9/2021  |
|       1 | mmm          |  45897210 | 12/16/2021 |
+---------+--------------+-----------+------------+

I have written below query:
SELECT customer_number, year, month,
payment_month - lag(payment_month) OVER(partition by customer_number ORDER BY year, month) as previous_month_indicator,
FROM
(
    SELECT DISTINCT Month(date) as month, Year(date) as year, CUSTOMER_NUMBER
    FROM Table1
    WHERE Month(date) not in (6,7)
    and TO_DATE(date,'yyyy-MM-dd') >= DATE_SUB('2021-12-31', 425)
    and customer_number = 1
) As C

and I get this output
+-----------------+------+-------+--------------------------+
| customer_number | year | month | previous_month_indicator |
+-----------------+------+-------+--------------------------+
|               1 | 2020 |    11 | null                     |
|               1 | 2020 |    12 | 1                        |
|               1 | 2021 |     1 | -11                      |
|               1 | 2021 |     2 | 1                        |
|               1 | 2021 |     3 | 1                        |
|               1 | 2021 |     4 | 1                        |
|               1 | 2021 |     5 | 1                        |
|               1 | 2021 |     8 | 3                        |
|               1 | 2021 |    10 | 2                        |
|               1 | 2021 |    11 | 1                        |
+-----------------+------+-------+--------------------------+

What I want is to get a view like this
Expected output

+-----------------+------+-------+--------------------------+
| customer_number | year | month | previous_month_indicator |
+-----------------+------+-------+--------------------------+
|               1 | 2020 |    11 |                        1 |
|               1 | 2020 |    12 |                        1 |
|               1 | 2021 |     1 |                        1 |
|               1 | 2021 |     2 |                        1 |
|               1 | 2021 |     3 |                        1 |
|               1 | 2021 |     4 |                        1 |
|               1 | 2021 |     5 |                        1 |
|               1 | 2021 |     8 |                        1 |
|               1 | 2021 |     9 |                        0 |
|               1 | 2021 |    10 |                        1 |
|               1 | 2021 |    11 |                        1 |
+-----------------+------+-------+--------------------------+

As June/July does not matter, after May, August should be considered as consecutive month, and since in September there was no record it appears as 0 and breaks the consecutive months chain.
My final desired output is to get the max no of consecutive months in which transactions were made which in above case is 8 from Nov-2020 to Aug-2021
Final Desired Output:
+-----------------+-------------------------+
| customer_number | Max_consecutive_months |
+-----------------+-------------------------+
|               1 |                       8 |
+-----------------+-------------------------+

A: CTEs can break this down a little easier.  In the code below, the payment_streak CTE is the key bit; the start_of_streak field is first marking rows that count as the start of a streak, and then taking the maximum over all previous rows (to find the start of this streak).
The last SELECT is only comparing these two dates, computing how many months are between them (excluding June/July), and then finding the best streak per customer.
WITH payments_in_context AS (
  SELECT customer_number,
    date,
    lag(date) OVER (PARTITION BY customer_number ORDER BY date) AS prev_date
  FROM Table1
  WHERE EXTRACT(month FROM date) NOT IN (6,7)
),
payment_streak AS (
  SELECT
    customer_number,
    date,
    max(
    CASE WHEN (prev_date IS NULL)
           OR (EXTRACT(month FROM date) <> 8
                 AND (date - prev_date >= 62
                    OR MOD(12 + EXTRACT(month FROM date) - EXTRACT(month FROM prev_date),12)) > 1))
           OR (EXTRACT(month FROM date) = 8
                 AND (date - prev_date >= 123
                    OR EXTRACT(month FROM prev_date) NOT IN (5,8)))
         THEN date END
    ) OVER (PARTITION BY customer_number ORDER BY date ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)
    as start_of_streak
    FROM payments_in_context
)
SELECT customer_number,
  max( 1 +
    10*(EXTRACT(year FROM date) - EXTRACT(year FROM start_of_streak))
      + (EXTRACT(month FROM date) - EXTRACT(month FROM start_of_streak))
      + CASE WHEN (EXTRACT(month FROM date) > 7 AND EXTRACT(month FROM start_of_streak) < 6)
             THEN -2
             WHEN (EXTRACT(month FROM date) < 6 AND EXTRACT(month FROM start_of_streak) > 7)
             THEN 2
             ELSE 0 END
     ) AS max_consecutive_months
FROM payment_streak
GROUP BY 1;

A: You can use a recursive cte to generate all the dates in the twelve month timespan for each customer id, and then find the maximum number of consecutive dates excluding June and July in that interval:
with recursive cte(id, m, c) as (
   select cust_id, min(date), 1 from payments group by cust_id
   union all
   select c.id, c.m + interval 1 month, c.c+1 from cte c where c.c <= 12
),
dts(id, m, f) as (
   select c.id, c.m, c.c = 1 or exists
       (select 1 from payments p where p.cust_id = c.id and extract(month from p.date) = extract(month from (c.m - interval 1 month)) and extract(year from p.date) = extract(year from (c.m - interval 1 month)))
   from cte c where extract(month from c.m) not in (6,7)
),
result(id, f, c) as (
  select d.id, d.f, (select sum(d.id = d1.id and d1.m < d.m and d1.f = 0)+1 from dts d1)
  from dts d where d.f != 0
)
select r1.id, max(r1.s)-1 from (select r.id, r.c, sum(r.f) s from result r group by r.id, r.c) r1 group by r1.id


text:
Q: Leetcode Q9 Palindrome Number same code works in Java but not in C++ I tried solving this problem: https://leetcode.com/problems/palindrome-number/
using code:
class Solution {
public:
    bool isPalindrome(int x) {
        int rev = 0;
        int temp = x;
        while(temp != 0 && temp > 0){
            rev = rev* 10;
            rev = rev + temp%10;
            temp = temp/10;
        }
        if (rev == x){
            return true;
        }
        else{
            return false;
        }
    }
};

and got this error in C++:
Line 7: Char 22: runtime error: signed integer overflow: 998765432 * 10 cannot be represented in type 'int' (solution.cpp)
SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior prog_joined.cpp:16:22

The logically same code runs perfectly in Java though. Both java and c++ have int data type ranging from - 2^31 to 2^31-1
(Source:
https://www.tutorialspoint.com/cplusplus/cpp_data_types.htm,
https://docs.oracle.com/javase/tutorial/java/nutsandbolts/datatypes.html#:~:text=int%3A%20By%20default%2C%20the%20int,value%20of%20232%2D1.)
So Why is this error showing up and how can I fix it?
Thanks

A: You are getting this error because 9,987,654,320 is too big to fit in a 32-bit integer.
Solution: Use long long instead. That is:
long long rev = 0;
long long temp = x;

Also, I suggest clearly specify the type of parameter x.


text:
Q: How can I create Wordpress tags programmatically? The following snippet adds Wordpress categories programmatically. My question is how do you add tags programmatically?
//Define the category
$my_cat = array('cat_name' => 'My Category', 'category_description' => 'A Cool Category', 'category_nicename' => 'category-slug', 'category_parent' => '');

// Create the category
$my_cat_id = wp_insert_category($my_cat);

In this question, I'm talking about  adding the tags into database programmatically.
Say, I got 1000 tags to add to a fresh installation. And I don't want to go through the regular admin panel to add tags one by one manually. I'm looking for a programmatic solution. The snippet I posted takes care of the add of cats... thanks to the specific wp function wp_insert_category.... there is no function called wp_insert_tag though...
However, looking at the codex, I see the wp_insert_term function which may very well be the one to do the job - it seems.

A: Use wp_insert_term() to add categories, tags and other taxonomies, because wp_insert_category() fires a PHP error "Undefined function".
<?php wp_insert_term( $term, $taxonomy, $args = array() ); ?>

$term is the term to add or update.
Change the value of $taxonomy into post_tag if it's a tag and category if it's a category.
In $args array, you can specify values of inserted term (tag, category etc.)
Example:
wp_insert_term(
  'Apple', // the term
  'product', // the taxonomy
  array(
    'description'=> 'A yummy apple.',
    'slug' => 'apple',
    'parent'=> $parent_term['term_id']  // get numeric term id
  )
);


text:
Q: Save ggplot object as reactive object in Shiny I'm trying to create a linked zoom plot (via brushOpts) in Shiny and am following the example posted here.
In my code, I define a reactive data.frame that I use to create (what I think is) a reactive ggplot() object which is then sent to renderPlot:
# Reactive data.table
dat <- reactive({
    fpath <- paste(basepath, input$lab_name, input$experiment, sep = "/")

    # some files aren't read - based on the words dataset or eff in the file name
    file_no_suffix <- dir(fpath, full.names = T)[-grep("dataset|eff", dir(ll, full.names = T))]

    # readExpData used fread to read csv file and format it a certain way
    dt <- readExpData(file_no_suffix)

    return(dt)
  }

)

# Reactive ggplot object
plt <- reactive({ggplot(dat())})

# Drop down menu for x-axis of plot
output$dynchoices1 <- renderUI({
    selectInput(inputId = "mainplot_x", label = "Select X-axis", choices = colnames(dat()))
  })

# Drop down menu for y-axis of plot
output$dynchoices2 <- renderUI({
    selectInput(inputId = "mainplot_y", label = "Select Variable to Plot", choices = colnames(dat()))
  })

# Actual plot to display
output$mainplot <- renderPlot({
    mainplt <- plt + geom_point(aes_string(x = input$mainplot_x, y = input$mainplot_y),
                                color = "#003366")
return(mainplt)
})

The above code returns errors for both fread and ggplot in Rstudio console:
Warning: Error in fread: 'input' must be a single character string containing a file name,
a command, full path to a file, a URL starting 'http[s]://', 'ftp[s]://' or 'file://', or the input data itself
    102: fread
    101: readClabData [C:/Users/LT11231/Documents/R Directory/readExpData.R#52]
    100: <reactive:dat> [#10]
    ... rest truncated for brevity

Warning: Error in +: non-numeric argument to binary operator
Stack trace (innermost first):
    102: renderPlot [#25]
     92: <reactive:plotObj>
     81: plotOb
    ... rest truncated for brevity

Despir the error, it is clear that dat() is being created since colnames(dat() ) is being used to generate choices for two selectInput call that determine the x and y axes of the plot - I can see those in the App. The plot itself is missing:

If I don't define plt separately and write the entire expression as
output$mainplot <- renderPlot(ggplot(dat() +
                                     aes_string(x = input$mainplot_x, y = input$mainplot_y)) +
                              geom_point()

it works okay (still get the warnings for fread though).
I don't want to go this way since I expect to have several plots and I don't want to re-write this code for each such instance.


text:
Q: R : Find Column with highest value I want to find the MAX value in each column and generate info of which column that generate the highest value (Yelow cell in the pic).

Thanks for help.

A: Here is a base R solution
df <- cbind(df,
            do.call(rbind,
                    apply(df[-1], 1, function(v) data.frame(MAX = max(v),Top_Subject = names(v[which.max(v)])))))

such that
> df
    Name Math Physics History Chemistry Biology MAX Top_Subject
1   Jack    9       8       7         7       4   9        Math
2   Andy    6       8       6         5       5   8     Physics
3  Peter    7      10       7         6       8  10     Physics
4 Ashley    7       6       5         6       8   8     Biology

DATA
df <- structure(list(Name = c("Jack", "Andy", "Peter", "Ashley"), Math = c(9,
6, 7, 7), Physics = c(8, 8, 10, 6), History = c(7, 6, 7, 5),
    Chemistry = c(7, 5, 6, 6), Biology = c(4, 5, 8, 8)), class = "data.frame", row.names = c(NA,
-4L))

A: A base R solution (in future please c+p the output of dput(df) function in order to generate the example instead of a picture):
df2 <- transform(df, max_scores = apply(df[,sapply(df, is.numeric)], 1, max),
                top_sub_per_stud = names(df[,sapply(df, is.numeric)])[apply(df[,sapply(df, is.numeric)], 1, which.max)])

Data:
df <- structure(list(Name = c("Jack", "Andy", "Peter", "Ashley"), Math = c(9,
6, 7, 7), Physics = c(8, 8, 10, 6), History = c(7, 6, 7, 5),
    Chemistry = c(7, 5, 6, 6), Biology = c(4, 5, 8, 8)), class = "data.frame", row.names = c(NA,
-4L))


text:
Q: Python Web Scraping login with captcha I have to log-in on a web page using web scraping, but it requires to solve a captcha as well. I am able to solve the captcha. I am having problem persisting session.
session = requests.Session()
html = session.get(url).content
soup = bs(html, 'html.parser')
name = soup.find('input', attrs={'id':some_id1})
pass = soup.find('input', attrs={'id':some_id2})
captcha = soup.find('input', attrs={'id':some_id3})

After this I solve the captcha.
credentials = {
        some_id1 : username,
        some_id2 : password,
        some_id3 : captchatext,
    }

I don't know how to proceed further with the sessions, I came up with the below code but it does not work. I have also looked for various answers but none of them works.
session.post(url, data=credentials)
response = session.get(url).content
soup2 = bs(response, 'html.parser')

I need to fetch data from a URL which opens up after a successful log-in.

A: Use dev tools of your browser to inspect the requests done on that specific url. You will find a request url which you have to pass in the post method along with the payload i.e. Credentials. Then you will get correct response.


text:
Q: How to create additional parameters for IdentityServer3 grant_type:password I have IdentityServer3 spun up and working with AspNetIdentity and IdentityManager.  I've created a JS client based on the samples for resource owner flow.  My AspNetIdentity implementation is customized in a way as such the userstore has a foreign key to an organization table.  The Organization table acts as a Tenant table because our IdentityServer and WebApi will be multi-tenant.  When the user logs in, I need to pass into the request additional parameters that specify the user's tenant id.  Once I get the tenant id I'll override the AuthenticateLocalAsync to look up the tenant information for the user.
I'm stuck on passing the additional tenant id or other parameters on the grant_type:password.  I've tried to pass in the act_values array but I'm not sure I'm doing all this the correct way.
And any additional information on a good explanation of scopes, claims, roles, etc would be a big help because its all still fuzzy.
Here is the client on idsvr
            new Client
            {
                ClientId = "tleweb",
                ClientName = "TLE Web Client",
                ClientSecrets = new List<Secret>
                {
                    new Secret("secret".Sha256())
                },
                Enabled = true,
                Flow = Flows.ResourceOwner,
                RequireConsent = false,
                AllowRememberConsent = true,
                RedirectUris = new List<string>(){ "https://localhost:13048/account/signInCallback"},
                PostLogoutRedirectUris = new List<string>(){ "https://localhost:13048/"},
                AllowedScopes = new List<string>()
                {
                    Constants.StandardScopes.OpenId,
                    Constants.StandardScopes.Profile,
                    Constants.StandardScopes.Email,
                    "read",
                    "write",
                    "tenant_id"
                },
                AllowedCorsOrigins =  new List<string>
                {
                    "http://localhost:13048"
                },
                AccessTokenType=AccessTokenType.Jwt,
                AccessTokenLifetime = 3600,
                AbsoluteRefreshTokenLifetime = 86400,
                SlidingRefreshTokenLifetime = 43200,
                RefreshTokenUsage = TokenUsage.OneTimeOnly,
                RefreshTokenExpiration = TokenExpiration.Sliding

            }

Here is the js client code
        function getToken() {
        var uid = document.getElementById("username").value;
        var pwd = document.getElementById("password").value;

        var xhr = new XMLHttpRequest();
        xhr.onload = function (e) {
            console.log(xhr.status);
            console.log(xhr.response);

            var response_data = JSON.parse(xhr.response);
            if (xhr.status === 200 && response_data.access_token) {
                token = response_data.access_token;
            }

            showToken(response_data);
        }
        xhr.open("POST", tokenUrl);
        var data = {
            username: uid,
            password: pwd,
            acr_values: ["1"],

            grant_type: "password",
            scope: "openid profile read write tenant_id"
        };
        var body = "";
        for (var key in data) {
            if (body.length) {
                body += "&";
            }
            body += key + "=";
            body += encodeURIComponent(data[key]);
        }
        xhr.setRequestHeader("Authorization", "Basic " + btoa(client_id + ":" + client_secret));
        xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
        xhr.send(body);
    }

A: Found it! Use the acr_values parameter on the request
https://identityserver.github.io/Documentation/docsv2/endpoints/authorization.html


text:
Q: How do I go to a specific part of matlab code based on my menu choice? I have a matlab code to run an RRR Lego robot arm with EV3 brick and a mix of NXT &EV3 motors and sensors; RRR.m
It's further divided into the following:
RRR_connect//
RRR_goto_start_position//
RRR_new_pos//
RRR_goto_new_angle//
RRR_goto_new_coordinate//
RRR_return_to_start//
RRR_disconnect//
I have a GUImenu in 'RRR_new_pos' where the user would have 3 choices;
1.Enter joint angles
2.Enter end-effector coordinates
3.Quit
If the user chooses option 1, they get a form where they enter the desired angles for the 3 joints. The same with coordinates for option 2.
Now my question is, how do I go straight to 'RRR_goto_new_angle' If user enters joint angles, or go to 'RRR_goto_new_coordinate' if user enters end-effector coordinates or finally go to 'RRR_disconnect' if users clicks on Quit?
I'll upload the code if necessary. Please ask if there is a need for more clarification of the question.


text:
Q: Clash of Clans. What's the total time to train? all about clash of clans game.
I have total of 6 barracks. Two of them produces one barbarian each every 20 seconds, the another two barracks produces one archer each every 25 seconds, and the last two produces 1 minion each every 45 seconds. the capacity of army camp is 200.
all barracks train simultaneously.
one archer has an housing space of one.
one barbarian has an housing space of one.
one minion has an housing space of two.
so how much time will it take to full the 200 camp capacity?
http://snag.gy/7c22a.jpg I get this number of units at every full capacity.

A: To get a lower bound on the answer, let's oversimplify the problem at first.
(We can later correct the error that this introduces.)
Assume the first two barracks produce a continuous "flow" of barbarian-stuff
at the rate of $2$ barbarian-units every $20$ seconds,
which is to say, $\frac{1}{10}$ barbarian-unit per second.
Since one barbarian-unit fills one housing-unit, the rate at which
the first two barracks fill the camp is
$\frac{1}{10}$ housing-unit per second.
Similarly, the next two barracks produce archer-stuff at a rate of
$\frac{2}{25}$ archer-units per second,
filling $\frac{2}{25}$ housing-units per second.
The last two barracks produce minion-stuff at the rate
of $\frac{2}{25}$ minion-units per second,
filling $\frac{4}{45}$ housing-units per second.
The total flow of "stuff" into the camp is the sum of all three flows,
$$ \frac{1}{10} + \frac{2}{25} + \frac{4}{45}
=  \frac{45}{450} + \frac{36}{450} + \frac{40}{450}
= \frac{121}{450} $$
measured in housing-units per second.
The number of seconds this would take to fill $200$ housing units is
$$ \frac{200}{\left(\frac{121}{450}\right)} = 200 \times \frac{450}{121}
 \approx 743.8. $$
Clearly this is an oversimplification and has produced an error.
The camp cannot fill at some time like this; since barbarians, archers,
and minions are produced only at times that are multiples of $5$, the camp
must fill at a time that is a multiple of $5$.
In fact, in the first $743.8$ seconds the first two barracks will have
produced barbarians $37$ times (because $37 \times 20 = 740$),
the next two will have produced archers $29$ times
(because $29 \times 25 = 725$)
and the last two will have produced minions $16$ times
(because $16 \times 45 = 720$).
Taking into account the number of housing units occupied by each
barbarian/archer/minion produced, the number of housing units
that the barracks will have filled in this time is
$$ 37 \times 2 + 29 \times 2 + 16 \times 4 = 74 + 58 + 64 = 196. $$
So we just need to fill four more housing units.
The next barbarians will be produced at $760$ seconds,
the next archers at $750$ seconds, and
the next minions at $765$ seconds.
So the next event is at $750$ seconds; we get two archers, raising
the number of occupied housing units to $198$, and the next archers are
due at $775$ seconds. The next event after this is at $760$ seconds;
we get two barbarians, and the number of occupied housing units is now $200$,
broken down as follows:
\begin{array}{lll}
76 \text{ barbarians} & \times 1 \text{ unit/barbarian} & = 76 \text{ units}\\
60 \text{ archers}    & \times 1 \text{ unit/archer}    & = 60 \text{ units}\\
32 \text{ minions}    & \times 2 \text{ unit/minion}    & = 64 \text{ units}\\
\end{array}
and the process completes in $760$ seconds.
The numbers in your linked image ($76, 56, 34$)
would take (respectively) $760$ seconds, $700$ seconds, and $765$ seconds
to be produced at the rates stated in your question;
what happened to the archers that should have been produced
at $725$ seconds and $750$ seconds after the start?
Do the barracks start production at different times?
Or do they each produce their first batch of barbarians/archers/minions
instantly?
If the answer is that the first batch is produced instantly,
then at the very start we already have two barbarians, two archers,
and two minions, occupying $8$ housing units.
We therefore need to fill just $192$ more units;
in the oversimplified model, the number of seconds this would take is
$$ \frac{192}{\left(\frac{121}{450}\right)} = 192 \times \frac{450}{121}
 \approx 714.05. $$
At this time we would have $72$ barbarians (the two we started with,
plus $70$ more produced in the first $700$ seconds),
with the next ones due at $720$ seconds,
$58$ archers, with the next ones due at $725$ seconds,
and $32$ minions, with the next ones due at $720$ seconds.
So far, the number of housing units occupied is
$$ 72 + 58 + 32 \times 2 = 194. $$
The next event is at $720$ seconds: we get two barbarians and two minions,
occupying a total of $6$ housing units, so now the units occupied are
$$ 74 + 58 + 34 \times 2 = 200, $$
which (almost) agrees with the numbers in your image,
but now we have more archers and fewer barbarians.
So I suspect that after all there is some other discrepancy in "starting times"
among the six barracks.

A: Don't focus on the amount of each type of class in the army camp. Look instead at the time.
If it takes $20$ seconds to make 2 housing spaces, then it will take $20*100 = 2000$ seconds to fill it completely.
If it takes $25$ seconds to make 2 housing spaces, then it will take $25*100 = 2500$ seconds to fill it completely.
If it takes $45$ seconds to make 4 housing spaces, then it will take $45*50 = 2250$ seconds to fill it completely.
Now, think of these three events as three different people. They each have a separate time to complete one army camp.
Now, if they all work together, how long would it take? (which is essentially your question):
$$\frac{1}{2000} + \frac{1}{2500} + \frac{1}{2250} = \frac{1}{t}$$
We get that $t = 744$ seconds, or about $12.4$ minutes


text:
Q: LibGDX Sprite Screens not loading graphics, or loading up screens I have this issue in my LibGDX project, I essentially can't load up my gamescreen, I am following a YouTube tutorial (link to particular tutorial I'm on: https://www.youtube.com/watch?v=LSblkR4K1LU), and I have found that my sprite that is supposed to go on my screen, just it won't load up at all, it just opens, closes then pops this up: http://puu.sh/coxUv/d877d08a83.png, I will admit the only thing I have changed from the video was this:
@Override
public void render(float delta) {
    Gdx.gl.glClearColor(1F, 1F, 1F, 1F);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

    camera.update();

I changed GL10.GL_COLOR_BUFFER_BIT (that was in the video), to GL20.GL_COLOR_BUFFER_BIT, because it gave me an error: GL10 cannot be resolved to a variable, does anyone have an idea why, tell me if there is any needed information.
Thanks in advance.
EDIT:
Gamescreen Class:
package com.edac.unforgivingunderground;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Screen;
import com.badlogic.gdx.graphics.GL20;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;

public class GameScreen implements Screen{

UnforgivingUnderground game;
OrthographicCamera camera;
SpriteBatch batch;

public GameScreen(UnforgivingUnderground game){
    this.game = game;

    camera = new OrthographicCamera();
    camera.setToOrtho(false,1920,1080);

    batch = new SpriteBatch();

}

@Override
public void render(float delta) {
    Gdx.gl.glClearColor(1F, 1F, 1F, 1F);
    Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);

    camera.update();

}

@Override
public void resize(int width, int height) {
    // TODO Auto-generated method stub

}

@Override
public void show() {
    // TODO Auto-generated method stub

}

@Override
public void hide() {
    // TODO Auto-generated method stub

}

@Override
public void pause() {
    // TODO Auto-generated method stub

}

@Override
public void resume() {
    // TODO Auto-generated method stub

}

@Override
public void dispose() {
    // TODO Auto-generated method stub

}

Assets Class:
package com.edac.unforgivingunderground;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.graphics.Texture;
import com.badlogic.gdx.graphics.Texture.TextureFilter;
import com.badlogic.gdx.graphics.g2d.Sprite;

public class Assets {

public static Texture texture_back;
public static Sprite sprite_back;

public static void load(){

    texture_back = new Texture(Gdx.files.internal("logo"));
    texture_back.setFilter(TextureFilter.Linear, TextureFilter.Linear);
    sprite_back = new Sprite(texture_back);
    sprite_back.flip(false, true);
}

}
Desktop Launcher:
package com.edac.unforgivingunderground.desktop;

import com.badlogic.gdx.backends.lwjgl.LwjglApplication;
import com.badlogic.gdx.backends.lwjgl.LwjglApplicationConfiguration;
import com.edac.unforgivingunderground.UnforgivingUnderground;

public class DesktopLauncher {
public static void main (String[] arg) {
    LwjglApplicationConfiguration config = new LwjglApplicationConfiguration();

    new LwjglApplication(new UnforgivingUnderground(), config);
}

}
Main Class:
package com.edac.unforgivingunderground;

import com.badlogic.gdx.Game;

public class UnforgivingUnderground extends  Game{

public GameScreen game_screen;

@Override
public void create() {
    Assets.load();

    game_screen = new GameScreen(this);

    setScreen(game_screen);

}

A: Not sure why it crashed (you should post the stack dump) but possibly it's because this line: Gdx.files.internal("logo"). Maybe you mean logo.png or logo.jpg. Also make sure that the image file does really exist on your assets folder.
Also, I belive your render method is missing one line.:
@Override
public void render(float delta) {
    Gdx.gl.glClearColor(1F, 1F, 1F, 1F);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

    camera.update();

    Assets.sprite_back.draw(batch);
}

That way you'll render your sprite to the screen through the SpriteBatch. In your code you can see that you're not using it.


text:
Q: Deadlock while logging http requests into main UI C# In my WinForms app I want to see raw request/response data when it interacts with webApi. I need to show request/response in UI RichTextBoxes. To do this I set up my HttpClient as follows:
        private HttpClient client;
        private void CreateService()
        {
            client = new HttpClient(new LoggingHandler(new HttpClientHandler(), this))
            {
                BaseAddress = new Uri(this._URI)
            };
            client.DefaultRequestHeaders.Accept.Clear();
            client.DefaultRequestHeaders.Accept.Add(
                new MediaTypeWithQualityHeaderValue("application/json"));
        }

My Logging Handler:
    public class LoggingHandler : DelegatingHandler
    {
        private SimplySignRestClientAsync _client;

        public LoggingHandler(HttpMessageHandler innerHandler, SimplySignRestClientAsync client) : base(innerHandler)
        {
            this._client = client;
        }

        protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
        {
            string p_Request = "";
            if (_client._updateRequest != null)
            {
                p_Request = request.ToString();
                if (request.Content != null)
                {
                    p_Request += "\n\nContent:\n" + FormatJsonString(await request.Content.ReadAsStringAsync());
                }

                //_client._request.Text = p_Request; << this works but causes a cross-thread exception in debug only
                SetText(p_Request); << This deadlocks the UI
            }

            return response;
        }

        delegate void SetTextCallback(string text);

        private void SetText(string text)
        {
            if (_client._request.InvokeRequired)
            {
                SetTextCallback d = new SetTextCallback(SetText);
                _client._response.Invoke(d, new object[] { text });
            }
            else
            {
                _client._request.Text = text;
            }
        }
    }

If i try to access richtextbox directly it works  only when i execute app without debugging. But during debug it comes up with cross-thread exception.
This is how I call httpClient:
//This is how the original call gets initiated from UI
private void uiLogin_Click(object sender, EventArgs e)
{
   Agent resp = Client.Login(new Credentials(uiUsername.Text, uiPassword.Text));
   uiAuthToken.Text = Client.getAuthToken();
}

//this method has to stay synchronous, but it in turn calls an async method below
public Agent Login(Credentials loginInfo)
{
    var task = Task.Run(async () => await LoginAsync(loginInfo));
    return task.Result.Content;  <<< this is where the application stops if i hit pause during debug when deadlock happens
}

//
async public Task<RestResponse<Agent>> LoginAsync(Credentials loginInfo)
{
    HttpResponseMessage response = await client.PostAsJsonAsync(this._URI + "api/users/login", loginInfo);

    var content = await response.Content.ReadAsStringAsync();
    RestResponse<Agent> respAgent respAgent = JsonConvert.DeserializeObject<RestResponse<Agent>>(content);

    return respAgent;
}

as I understand my "return task.Result.Content" blocks the UI thread and "_client._response.Invoke(d, new object[] { text });" is waiting for that to unblock causing deadlock. But I'm not sure how to make invoke wait too.

A: If you want to do it using proper asynchronous constructs, you need to make the entry point (your Click event handler) asynchronous, and never block on asynchronous code as it causes the deadlock you are facing.
//This is how the original call gets initiated from UI
private async void uiLogin_Click(object sender, EventArgs e)
{
   Agent resp = await Client.Login(new Credentials(uiUsername.Text, uiPassword.Text));
   uiAuthToken.Text = Client.getAuthToken();
}

public async Task<Agent> Login(Credentials loginInfo)
{
    var result = await LoginAsync(loginInfo);
    return result.Content;
}


text:
Q: Regular expression to create multiple word fragments based off the same words Let's say I have the following string:
var str = "I like barbeque at dawn";

I want pairs of all words which are separated by a space. This can be achieved via the following regular expression:
  var regex = /[a-zA-Z]+ [a-zA-Z]+/g;
  str.match(regex);

This results in:
["I like", "barbeque at"]

But what if I want ALL permutations of the pairs? The regular expression fails, because it only matches any given word onces. For example, this is what I want:
["I like", "like barbeque", "barbeque at", "at dawn"]

I know I can use the recursive backtracking pattern to generate permutations. Do regular expressions have the power to create these types of pairs for me?

A: Use a lookahead with a capture, which allows overlapping matches:
(\w+)\s+(?=(\w+))

Demo
Alternative if you want to capture in one group vs two:
(?=(\b\w+\s+\b\w+))

Demo

A: This regex will do it:
(?=\b([a-zA-Z]+ [a-zA-Z]+))

See demo
Explanation:

*

*We use a look-ahead (?=...) in order not to test each position inside the input string. Thus, we'll still "move" through the whole string not consuming any characters

*\b will force the regex engine to find the borderline between the matches returned by the subsequent subpattern

*([a-zA-Z]+ [a-zA-Z]+) is the capturing group, that will collect 2-word phrases.

Sample code:
var re = /(?=\b([a-zA-Z]+ [a-zA-Z]+))/g;
var str = 'i like barbeque at dawn';

while ((m = re.exec(str)) !== null) {
    document.getElementById("res").innerHTML += m[1] + "<br/>";
}

A: You can do the following:
(\w+)\s+(?=(\w+))

and capture the pairs with ($1, $2)
See DEMO
Input: i like barbeque at dawn

Output: (i, like) (like, barbeque) (barbeque, at) (at, dawn)

A: You can use lookaheads for this:
var str = "i like barbeque at dawn";
var regex = /(?=\b([a-zA-Z]+ [a-zA-Z]+)\b)/g;
var matches= [];

while ((match = regex.exec(str)) != null) {
    if (match.index === regex.lastIndex)
       regex.lastIndex++;
    matches.push(match[1]);
}

console.log(matches);
//=> ["i like", "like barbeque", "barbeque at", "at dawn"]


text:
Q: PHP 2 Arrays Get Values From Both Arrays I dont want to merge or intersect or diff I just want to get both values from both arrays with matching keys regardless of values matching or not.
example data
array1 ( 0 => 'a', 1 => 'b' )
array2 ( 0 => 'a', 1 => 'c' )

foreach
echo "Key: ".$key." Value1: ".$v1." Value2: ".$v2."";

I would like this as the output
Key: 0 Value1: a Value2: a
Key: 1 Value1: b Value2: c

A: If both arrays have the exact same keys, you can iterate through one of them while printing values from both.
foreach ($array1 as $key => $val) {
   echo "Key: ".$key." Value1: ".$array1[$key]." Value2: ".$array2[$key];
}

A: $array1= array( 0 => 'a', 1 => 'b' );
$array2=array ( 0 => 'z', 1 => 'c' );
foreach ($array1 as $k=>$val){
   //safe in case of key does't exist in second array
   if(array_key_exists($k,$array2))
     echo $k . " Value1: ".$val ." Value2: ". $array2[$k].'<br>';
   else
     echo $k . " Value1: ".$val
}


text:
Q: Pegar foto de perfil do facebook e salvar no meu banco de dados? Já estou conseguindo fazer o login com facebook mas não pego a foto da pessoa, como fazer isso?
Vi algumas coisas como ''https://graph.facebook.com/ID_user/picture
Mas como posso utilizar isso?

A: Eu fiz da seguinte forma:
               FB.getLoginStatus(function(response){
                    if(response.status == 'connected') {
                        FB.ui(obj, callback);
                    }
                    else {
                        FB.login(function(response){
                            if(response.status == 'connected') {
                                //Depois do login chamo o callback
                                FB.ui(obj, callback);
                            }
                        });
                    }
                });
                //Função do callback
                function callback(response) {
                    if(response.error_code == 4201)
                    {

                    }
                    else
                    {
                        //Como no post_id retornado vem a {id}_{post_id}, eu dou um split e pego a ID.
                        var ids = response['post_id'].split('_');
                        //Como eu usei o angular, fiz os comandos abaixo, mas se quiser apenas a id -> ids[0];
                        var appElement = document.querySelector('[ng-controller=FbController]');
                        var $scope = angular.element(appElement).scope();
                        $scope.$apply(function() {
                            $scope.addJson(ids[0]);
                        });
                    }
                }

Para pegar a foto eu usei a API http://graph.facebook.com/v2.6/{{id}}/picture


text:
Q: Custom Taxonomy conditionals So I have setup a custom post type 'products' and custom taxonomies / categories 'defence' 'law & enforcement' and 'Commercial'.
I have using the following conditional to set some specific css and the correct banner for a product:
<?php if (has_term( 'defence', 'productcat', $post->ID )) { ?>

This works fantastic if the product is in one category.
Here's my problem - i have products in multiple categories so i would like a conditional to see how they got to my product page:
I have a menu down the left side on taxonomy landing page and on product page, as an example lets say i have product 1 in all 3 taxonomies; down the left hand side there will be the 3 parent taxonomies with the product underneath each one as a child.
What i would like to do is have a conditional to set my custom css / banner depending on where the product on the left menu is clicked; ie if product 1 under 'Defense' is click i would like to display the 'Defense' banner, same goes if it is clicked under the other 2 taxonomies.
Hope this makes sense.
In all honesty i don't think this is possible and products with multiple taxonomies will just have to have the default css and a rotating banner with all taxonomies which it belongs too.
Your time and help with this is appreciated
Edit
Just had a thought - if i can get the taxonomies to form part of my permalink ie domain.com/products/taxonomy/product i could use
$_SERVER['HTTP_HOST'] ==

A: Ok, to work around this and do what i need to do i installed a plugin (Custom Post Type Permalinks by Toto_unit) to add custom post types and custom taxonomies to my permalink structure.
For my conditionals i'm using $_SERVER['HTTP_HOST'] == to check the current url.
Hopefully this helps someone else.


text:
Q: What causes to auto br I have 3 CSS functions for sprites and I created a link with them. When an image is loaded, they are like that

Some of my code is below:
#twitterReply
{
  width:16px;
  height:16px;
  text-decoration:none;
  display:block;
  background-image:url('path');
  background-position:-0px -0px;

}
#twitterReply:hover,#twitterReply:active  { background-position:-16px -0px; }

#twitterRetweet
{
  width:16px;
  height:16px;
  text-decoration:none;
  display:block;
  background-image:url('path');
  background-position:-32px -0px;
}
#twitterRetweet:hover,#twitterRetweet:active  { background-position:-48px -0px; }

#twitterFavorite
{
  width:16px;
  height:16px;
  text-decoration:none;
  display:block;
  background-image:url('path');
  background-position:-64px -0px;
}
#twitterFavorite:hover,#twitterFavorite:active  { background-position:-80px -0px; }

How can I lay them together?

A: They all have display: block, that's why. Blocks occupy the full width of their parent element, thus a sequence of blocks looks like a stack.
Use display: inline-block instead.


text:
Q: Mediaelement.js 'loadedmetadata' event always returns duration 0 for Facebook videos For Facebook (and dailymotion) videos, the loadedmetadata event does not contain the duration of the video
...
success: function(me, node) {
  me.addEventListener('loadedmetadata', function _loaded_src(e) {
    console.log(me.duration)
  })
},
...

Duration is always 0
I have tried all other events listed in the documentation
I have tried calling play/pause then checking the duration but it still comes back 0
After some amount of time the duration is figured out, does anyone know  how I could wait for the duration to be available?


text:
Q: gtk3 css with GtkNotebook I'm using gtk3.0.12 and trying to create a notebook that has different tab background colors using css. I can set different properties for every thing but the background. How do I do this?
/*  Compile with:
*  gcc -Wall -o notebook1 `pkg-config --cflags --libs gtk+-3.0` notebook1.c
*/
#include <gtk/gtk.h>

int main(int argc, char *argv[] )
{
  GtkWidget *window;
  GtkWidget *mynotebook;
  GtkWidget *grid;

gtk_init (&argc, &argv);

GtkCssProvider *provider = gtk_css_provider_new ();
GdkDisplay *display = gdk_display_get_default ();
GdkScreen *screen = gdk_display_get_default_screen (display);
gtk_style_context_add_provider_for_screen (screen, GTK_STYLE_PROVIDER
         (provider), GTK_STYLE_PROVIDER_PRIORITY_APPLICATION);

gtk_css_provider_load_from_data (GTK_CSS_PROVIDER (provider),
                                 " GtkNotebook {\n"    // or  " .notebook {\n"
                                 "   -GtkWidget-focus-line-width: 0;\n"
                                 "}\n"
                                 " .notebook tab {\n"  // or  " * tab {\n"
                                 "   padding: 10 20 10 20;\n"
                                 "   border-radius: 8;\n"
                                 "   background-color: blue;\n"
                                 "}\n"
                                 " GtkNotebook tab GtkLabel#settings_tab {\n"
                                 "   color: white;\n"
                                 "   font: Serif 12;\n"
                                 "}\n"
                                 " .notebook tab GtkLabel#report_tab {\n"
                                 "   color: red;\n"
                                 "   font: Sans 12;\n"
                                 "}\n", -1, NULL);

g_object_unref (provider);

window = gtk_window_new (GTK_WINDOW_TOPLEVEL);
gtk_window_set_default_size(GTK_WINDOW(window), 800, 480);
g_signal_connect (GTK_WIDGET (window), "destroy",
                  G_CALLBACK (gtk_main_quit), NULL);
mynotebook = gtk_notebook_new ();
gtk_widget_set_name (GTK_WIDGET(mynotebook), "notebook");
gtk_notebook_set_tab_pos (GTK_NOTEBOOK (mynotebook), GTK_POS_TOP);

grid = gtk_grid_new();
GtkWidget *report_label = gtk_label_new ("Report");
gtk_widget_set_name (GTK_WIDGET(report_label), "report_tab");

gtk_container_add(GTK_CONTAINER(window),mynotebook);
gtk_container_add(GTK_CONTAINER(mynotebook),grid);
gtk_notebook_set_tab_label(GTK_NOTEBOOK(mynotebook), grid, report_label);

GtkWidget *grid2 = gtk_grid_new ();
GtkWidget *settings_label = gtk_label_new ("Settings");
gtk_widget_set_name (GTK_WIDGET(settings_label), "settings_tab");

gtk_notebook_insert_page (GTK_NOTEBOOK(mynotebook),  GTK_WIDGET(grid2),
             GTK_WIDGET(settings_label), -1);

gtk_widget_show_all(window);
gtk_main();
return(0);
}

A: Im having some difficulties with tabs to,
did you try something like:
background-color: shade (#000000, 0.90);

or
background-image: -gtk-gradient (linear, left top, left bottom,
                                     from (shade (#000000, 1.30)),
                                     to (shade (#ffffff, 1.05)));

only info I found for gtk3 is here
http://developer.gnome.org/gtk3/3.3/GtkCssProvider.html


text:
Q: Android phone as serial slave? Is there a way to connect an Android phone to a computer as serial port?
I've found several libraries etc. (this and this), but they all seem to really on Android 3.1 or higher (I have 2.3.4) and all seem to be a serial host.
So my question: Would it be possible to use my Android phone (2.3.4) as a serial slave?
Thanks in advance.


text:
Q: Floating imageview with text and buttons I am loading images from a db to listview and I want to create a floating window. Once one of them is clicked the floating window pic is attached.
I know how to handle onClick events from a list but I can't find a way to create the activity layout correctly

And this is what I came up so far -
<?xml version="1.0" encoding="UTF-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/image_dialog_root"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@android:color/transparent"
    android:gravity="center"
    android:paddingLeft="5dp"
    android:paddingRight="5dp" >

    <ImageView
        android:id="@+id/your_image"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:scaleType="centerInside"
        android:src="@drawable/ab" />

    <TextView
        android:id="@+id/image_desc"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:background="@android:color/background_light" />

    <RelativeLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" >

        <Button
            android:id="@+id/open_in_other_app"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true"
            android:layout_marginRight="5dp"
            android:text="button1" />

        <Button
            android:id="@+id/close_image_view"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true"
            android:layout_marginLeft="5dp"
            android:text="button2" >
        </Button>
    </RelativeLayout>

</FrameLayout>

A: With @twntee advice and some serach I got to this articale which solved my problem -
http://www.mkyong.com/android/android-custom-dialog-example/


text:
Q: What's the best way to migrate SELECT applications and data from an old Mac to a new one? I know I can make an easy transfer of everything using time machine, but I'm trying to transfer the minimum necessary to the new computer (applications I currently use, Aperture database, etc.) in order to keep the new machine as clean as possible, and avoid starting out with any legacy problems with permissions, etc.
Clearly, I can copy individual apps and databases to an external drive and then install them on the new machine, but I'm trying to find an easier way.

A: Have you looked at "Migration Assistant" in the Utilities directory (off Applications)? Note -- I haven't used it myself.
That utility should work over the network (so you don't need an external disk) and I think it gives you control over what gets transfered. It isn't whole disk but, like you want, user data and applications.
Note -- I tend to reinstall applications when moving to a new machine. Although a lot of applications for Mac OS X are self-contained (everything is in that application icon), there are some that install things in odd places on the hard drive and it can be a pain to track all those things down, or even to understand that something is missing (when all you get is a crash or weird error message).

A: Thanks for the ideas.  I would have voted the response up if I had enough points, even though it wasn't quite right for my needs:  I ran into the thing KeithB pointed out - I didn't want to transfer things wholesale.  Here's what I did - bunch of steps, but pretty painless, and faster than I thought it would be.
I got my new Macbook last night, linked it to my old one with ethernet, and just used file sharing over that mini-network to copy my data and libraries.  My goal was to install fresh versions everything  possible. It's all pretty obvious, but I was impressed with how easy it was to get all my data over with almost no "legacy" items that might someday be a corrupting influence on my young MBP.

*

*First, I had time machine run a
backup on the old machine, just in case

*I turned off airport on both machines
and connected the ethernet cable to
both.   (This is obvious to most, but
don't use wifi unless you have very
little data; it's MUCH slower.

*I enabled file sharing in the target
machine, (System Prefs, Sharing) and
set permissions to "Read and Write"
for "Everyone".  (It's important to
turn this off after you're done and
will be going back to "real"
networks, but it's harmless on the
two-mac ethernet ecosystem)

*This allowed me to see the new
computer in the left nav panel of the
old one, and to drag files into it.

*On the new computer, I set address
book and mail to sync with my google
account (in their respective prefs
panels)

*On the new computer, I set mobileme to sync my calendar,
keychain, and browser bookmarks (In
system prefs, then mobileme)

*On the old computer, I ran a repair of my aperture photo
library just in case, (open aperture while holding option and command,)  and then
copied the file and pasted it into the pictures folder
on the new mac.

*I installed a clean copy of aperture
using my existing license on the new
machine, and pointed it to the
library I'd just copied.

*I copied my entire itunes folder,
found in the music folder of the old
mac, to my new machine's desktop, and
then dragged it into iphoto on the
new machine, so it could "organize"
the files fresh.  NOTE - this won't retain playlists or ratings.  If you use either much, you may want a more traditional migration for your itunes library.

*If you have any imovie projects, you
can just drag the whole folder into
the "Movies" folder on the new
computer"

*I installed MS Office from the original disks on the new machine

*I copied the contents of my documents folder to the docs folder on the new machine.

*Just to be safe, I copied my entire
user folder (the one that looks like
a house) to my backup disk and to my
idisk in case I need them later.  If
you're storage space constrained,
consider removing the photo library,
imovie projects folder, and itunes
folder, since you already copied them
before you did this.

*I didn't have any apps that I still
wanted that I couldn't download new,
but if you did, you could obviously
jsut drag them to the new
Applications folder.  (I just
downloaded new copies of handbrake,
logmein, and things, and things
synced with my iphone to get my data.)

Not sure this is the best way, but it was easy, took under two hours, and on the off-chance I find something I overlooked and need, I can always get it off time machine or the copies of my user folder on the backup drive or idisk.
All in, it took me about an hour of "doing" and about an hour to transfer the data (I moved about 125GB, mostly pictures and music.)
Hopefully this is of some use to anyone else looking for a highly selective transfer.


text:
Q: Create heroku app from codeship's custom script I'm trying to create a heroku-application in Codeship's custom script but I can't understand how to login on heroku programmatically.
Is it possible to pass email and password to heroku login command?
Or maybe I can setup ssh-key to do this?
Something like heroku login -e email@email.com -p qwerty or heroku login -f ./ssh_key?

A: I've found the solution: an environment variable HEROKU_API_KEY do that for us.


text:
Q: Azure SQL Database: Full text index on certain emails does not work I have a full text index defined on user table's username column. When there is any character following + symbol in email in the search query there is no result. + is a valid symbol in email. Appreciate if you can explain why I see this behavior and any workaround for this.
/* returns result */
select * from AspNetUsers where contains(username, '"foo+77@gmail.com*"')
select * from AspNetUsers where contains(username, '"foo+*"')

/* does not return result */
select * from AspNetUsers where contains(username, '"foo+77*"')
select * from AspNetUsers where contains(username, '"foo+7*"')
select * from AspNetUsers where contains(username, '"foo+77@gmail*"')

A: Adding backslash before character 7 returns results.
Before adding backslash \ in the query:

After adding backslash \ in the query:
QUERY:
select * from AspNetUsers where contains(username, '"foo+\77*"')
select * from AspNetUsers where contains(username, '"foo+\7*"')
select * from AspNetUsers where contains(username, '"foo+\77@gmail*"')


text:
Q: Simple tuple in Python Would someone be able to explain in simple English why this happens when I try to index the below... I thought I should be getting back 45, 49, 52, 55 as my answer? I'm sure I am missing something here...
times = (43, 45, 49, 52, 55)
print(times[1:4])
(45, 49, 52)


text:
Q: What happend with find -exec mv command I just called
find -name '*.wmv' -exec '{}' ../other ';'

where one of the matched files contained spaces like
./blabla - Copy/blabla.wmv

It returned the message
find: `./blabla - Copy/blabla.wmv': No such file or directory

Now the source file is gone and in the target directory 'other' there's only a directory called 'blabla.wmv', but it's empty and I can't find the actual file.
I would have assumed that the command would expand to
mv './blabla - Copy/blabla.wmv' ../other

(with quotes around the source), but even if it expanded to
mv ./blabla - Copy/blabla.wmv ../other

neither of the files 'blabla', '-' nor 'Copy/blabla.wmv' existed
so that doesn't explain why the source file is gone and the directory 'blabla.wmv' was created. I'd like to know what really happened.
I don't really care about the file much but I want to be sure that it's not floating around somewhere it's not supposed to or overwrote something that's important.

A: There's no mv in your command.
Try:
find -name '*.wmv' -exec mv '{}' ../other ';'

Filenames with spaces are handled correctly by find.


text:
Q: Cannot access property from class //MigrationVC.h
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>

@interface MigrationVC : UIViewController

@end

//MigrationVC.m
#import "MigrationVC.h"

@interface MigrationVC()
@property (strong, nonatomic) IBOutlet UILabel *label;
@property (strong, nonatomic) IBOutlet UIProgressView *progressView;

@end

@implementation MigrationVC

@end

//CoreData
#import "CoreData.h"
#import "MigrationVC.h"

@interface CoreData()
@property (nonatomic,retain) MigrationVC *migrationVC;
@end

-(void)obsererForKeyPath:(NSString*)keyPath object:(id)object change:(NSDictionary*)change context:(void*)context
{
    if([keyPath isEqualToString:@"migrationProgress"])
    {
        dispatch_async(dispatch_get_main_queue(),^{
            float progress=[[change objectForKey:NSKeyValueChangeNewKey] floatValue];
            self.migrationVC.progress=progress;
        });
    }
}

I am trying to learn CoreData and migration right now but this is giving me a quite a headache.
I am trying to access the outlet properties from another classes but always gives red warning (Property 'label' not found on object of type MigrationVC*).
I tried adding a NSString property in .h file which was accessible but when i tried to change the outlet from .m to .h file i couldn't ctrl+drag the view in the .h file.
I never had this problem. I have accessed outlet from .m file many times in the past but it just gives me warning now.
How can i access the properties while outlet in .m file?

I cannot outlet the properties in .h file.

A: You have to transfer you outlet properties from .m file to .h file (copy and paste). If you want your properties to be public so they have to be declared in header file. If you want them to be private - declare them in implementation file.
//MigrationVC.h
#import <Foundation/Foundation.h>
#import <UIKit/UIKit.h>

@interface MigrationVC : UIViewController
@property (strong, nonatomic) IBOutlet UILabel *label;
@property (strong, nonatomic) IBOutlet UIProgressView *progressView;
@end

//MigrationVC.m
#import "MigrationVC.h"

@interface MigrationVC()

@end

@implementation MigrationVC

@end

A: As others have pointed out, you need to declare your properties in your header file if you want them to be accessible from other classes. You can, and you should. If you think you can't do that, explain why.
More important, though, is that you should not do what you are trying to do. You should not try to access a view controller's view objects from outside the view controller. That violates the principle of encapsulation, an important principle of object-oriented design. (It means that code outside of your view controller is dependent on the appearance of your view controller. If you later decide to make internal changes to your view controller, you are very likely to break outside code.) In addition to the somewhat abstract "It's bad design" reason for not doing it, it often doesn't work, because at the time to try to modify a view controller's views, they don't exist yet.
Instead, you should create DATA properties (like strings, or floating point progress values) in your view controller and expose those. Then have your view controller's viewWillAppear method install the data into it's views as appropriate. That way the data properties become part of the view controller's public contract without being tied to the internal details of the view controller.

A: You properties are declared in the private category so they are not visible for other classes. Only properties declared in a header file are visible.

A: In CoreData.m your MigrationVC is set as retain. I don't know if you can use it since with ARC.
@property (nonatomic,retain) MigrationVC *migrationVC;

It should be
@property (nonatomic,strong) MigrationVC *migrationVC;

And in MigrationVC your outlets should be weak not strong and in .h to be accesible from CoreData.m


text:
Q: Deploy a WPF user control in a Silverlight application I have developed a user control in WPF which draws some graphs.
Now i have to show this user control in a Silverlight application (to show on ASP.net webpage).
Is this possible to use a WPF user control in a Silverlight application?
I have searched on Google, but have not found a satisfactory answer.

A: No, it is not possible to show a WPF control in Silverlight. They use two different runtimes so are not directly substitutable with each other.
You have a few options though:

*

*use XBAP to show WPF within the browser

*rewrite your control so that you can compile a version for Silverlight or WPF (this is (was) quite a common way to do it)

Edit:
in response to your comment you seem to have some misunderstandings, I think you haven't understood the links I gave you. You may also have misunderstood what Silverlight is - just in case you have let me mention that Silverlight runs as a plugin within the web page, it isn't directly part of the HTML structure.
For the XBAP approach the WPF control/page is hosted inside a web page - just like a Silverlight control is. However you don't have direct access to the local filesystem or network filesystem (or databases running on the network) - Silverlight is the same, to access a database you really need to go via a WCF service.
With the second approach you have two versions (one for WPF, one for Silverlight) of your control and you use compile time targeting to dictate which control is built. You then use the appropriate control in the appropriate project.


text:
Q: Context is Missing when using Unobtrusive ajax in asp.net mvc-3
i have just shifted to unobtrusive ajax that ships with mvc-3 but it is breaking at one point.
Here is my link
<%:Ajax.ActionLink("Edit", "Home", "Edit", new{id = Model.SomeID}, new AjaxOptions{OnSuccess = "DoSomething"})%>

this is my js function that will be called on success
<script type="text/javascript">
function DoSomething(data)
{
    var clickedLinkID = this.id; // this line breaks it used to work with microsoft ajax
    //rest of code goes here
}
</script>

i found this article in which imran describes how to solve the problem. but it involves adding one line to jquery.unobtrusive-ajax.js. Does it have any side effects? should i be changing jquery files? if not how can i get id of the link that was clicked without changing jquery.unobtrusive-ajax.js file

A: Here is a complete copy of edited MS unobtrusive AJAX including a newly minified version. It contains the context (source element missing) fix plus another important fix whereby the documented "cancel" class was not honoured when applied to submit items (should prevent validation but doesn't).
jquery.unobtrusive-ajax
    /*!
    ** Unobtrusive Ajax support library for jQuery
    ** Copyright (C) Microsoft Corporation. All rights reserved.
    ** Fixed version (see full comments for details)
    */

    /*
        Fix for "validation ignores cancel class" applied from
        http://stackoverflow.com/questions/11561496/jquery-unobtrusive-validation-ignores-cancel-class-on-submit-button-if-used-in

        Line 144 changed to:
            // Fixed to pass class name (needed for other fixes and useful anyway)
            $(form).data(data_click, name ? [{ name: name, value: evt.target.value, className: evt.target.className }] : []);

        Line 154 changed to:
            // Fixed for "cancel" class not honoured (so correct documented behavior of non-validating/cancel buttons are restored)
            if (clickInfo.length > 0 && clickInfo[0].className.indexOf('cancel') < 0 && !validate(this)) {

    */

    /*
        Fix for "source element missing on post-back event handler" applied from
        http://forums.asp.net/t/1663285.aspx?How+to+get+source+Element+when+using+Unobtrusive+Ajax+in+ASP+NET+MVC+3

        Line 101 inserted:
            // Fixed to pass source element in context (so source element can be discovered in handlers)
            options.context = element;

    */

    /*jslint white: true, browser: true, onevar: true, undef: true, nomen: true, eqeqeq: true, plusplus: true, bitwise: true, regexp: true, newcap: true, immed: true, strict: false */
    /*global window: false, jQuery: false */

    (function ($) {
        var data_click = "unobtrusiveAjaxClick",
            data_validation = "unobtrusiveValidation";

        function getFunction(code, argNames) {
            var fn = window, parts = (code || "").split(".");
            while (fn && parts.length) {
                fn = fn[parts.shift()];
            }
            if (typeof (fn) === "function") {
                return fn;
            }
            argNames.push(code);
            return Function.constructor.apply(null, argNames);
        }

        function isMethodProxySafe(method) {
            return method === "GET" || method === "POST";
        }

        function asyncOnBeforeSend(xhr, method) {
            if (!isMethodProxySafe(method)) {
                xhr.setRequestHeader("X-HTTP-Method-Override", method);
            }
        }

        function asyncOnSuccess(element, data, contentType) {
            var mode;

            if (contentType.indexOf("application/x-javascript") !== -1) {  // jQuery already executes JavaScript for us
                return;
            }

            mode = (element.getAttribute("data-ajax-mode") || "").toUpperCase();
            $(element.getAttribute("data-ajax-update")).each(function (i, update) {
                var top;

                switch (mode) {
                case "BEFORE":
                    top = update.firstChild;
                    $("<div />").html(data).contents().each(function () {
                        update.insertBefore(this, top);
                    });
                    break;
                case "AFTER":
                    $("<div />").html(data).contents().each(function () {
                        update.appendChild(this);
                    });
                    break;
                default:
                    $(update).html(data);
                    break;
                }
            });
        }

        function asyncRequest(element, options) {
            var confirm, loading, method, duration;

            confirm = element.getAttribute("data-ajax-confirm");
            if (confirm && !window.confirm(confirm)) {
                return;
            }

            loading = $(element.getAttribute("data-ajax-loading"));
            duration = element.getAttribute("data-ajax-loading-duration") || 0;

            $.extend(options, {
                type: element.getAttribute("data-ajax-method") || undefined,
                url: element.getAttribute("data-ajax-url") || undefined,
                beforeSend: function (xhr) {
                    var result;
                    asyncOnBeforeSend(xhr, method);
                    result = getFunction(element.getAttribute("data-ajax-begin"), ["xhr"]).apply(this, arguments);
                    if (result !== false) {
                        loading.show(duration);
                    }
                    return result;
                },
                complete: function () {
                    loading.hide(duration);
                    getFunction(element.getAttribute("data-ajax-complete"), ["xhr", "status"]).apply(this, arguments);
                },
                success: function (data, status, xhr) {
                    asyncOnSuccess(element, data, xhr.getResponseHeader("Content-Type") || "text/html");
                    getFunction(element.getAttribute("data-ajax-success"), ["data", "status", "xhr"]).apply(this, arguments);
                },
                error: getFunction(element.getAttribute("data-ajax-failure"), ["xhr", "status", "error"])
            });

            options.data.push({ name: "X-Requested-With", value: "XMLHttpRequest" });

            // Fixed to pass source element in context (so source element can be discovered in handlers)
            options.context = element;

            method = options.type.toUpperCase();
            if (!isMethodProxySafe(method)) {
                options.type = "POST";
                options.data.push({ name: "X-HTTP-Method-Override", value: method });
            }

            $.ajax(options);
        }

        function validate(form) {
            var validationInfo = $(form).data(data_validation);
            return !validationInfo || !validationInfo.validate || validationInfo.validate();
        }

        $(document).on("click", "a[data-ajax=true]", function (evt) {
            evt.preventDefault();
            asyncRequest(this, {
                url: this.href,
                type: "GET",
                data: []
            });
        });

        $(document).on("click", "form[data-ajax=true] input[type=image]", function (evt) {
            var name = evt.target.name,
                $target = $(evt.target),
                form = $target.parents("form")[0],
                offset = $target.offset();

            $(form).data(data_click, [
                { name: name + ".x", value: Math.round(evt.pageX - offset.left) },
                { name: name + ".y", value: Math.round(evt.pageY - offset.top) }
            ]);

            setTimeout(function () {
                $(form).removeData(data_click);
            }, 0);
        });

        $(document).on("click", "form[data-ajax=true] :submit", function (evt) {
            var name = evt.target.name,
                form = $(evt.target).parents("form")[0];

            // Fixed to pass class name (needed for other fixes and useful anyway)
            $(form).data(data_click, name ? [{ name: name, value: evt.target.value, className: evt.target.className }] : []);

            setTimeout(function () {
                $(form).removeData(data_click);
            }, 0);
        });

        $(document).on("submit", "form[data-ajax=true]", function (evt) {
            var clickInfo = $(this).data(data_click) || [];
            evt.preventDefault();
            // Fixed for "cancel" class not honoured (so correct documented behavior of non-validating/cancel buttons are restored)
            if (clickInfo.length > 0 && clickInfo[0].className.indexOf('cancel') < 0 && !validate(this)) {
                return;
            }
            asyncRequest(this, {
                url: this.action,
                type: this.method || "GET",
                data: clickInfo.concat($(this).serializeArray())
            });
        });
    }(jQuery));

jquery.unobtrusive-ajax-fixed.min.js
    /*
    ** Unobtrusive Ajax support library for jQuery
    ** Copyright (C) Microsoft Corporation. All rights reserved.
    ** Fixed version (see full comments for details)
    */
    (function(a){var b="unobtrusiveAjaxClick",g="unobtrusiveValidation";function c(d,b){var a=window,c=(d||"").split(".");while(a&&c.length)a=a[c.shift()];if(typeof a==="function")return a;b.push(d);return Function.constructor.apply(null,b)}function d(a){return a==="GET"||a==="POST"}function f(b,a){!d(a)&&b.setRequestHeader("X-HTTP-Method-Override",a)}function h(c,b,e){var d;if(e.indexOf("application/x-javascript")!==-1)return;d=(c.getAttribute("data-ajax-mode")||"").toUpperCase();a(c.getAttribute("data-ajax-update")).each(function(f,c){var e;switch(d){case"BEFORE":e=c.firstChild;a("<div />").html(b).contents().each(function(){c.insertBefore(this,e)});break;case"AFTER":a("<div />").html(b).contents().each(function(){c.appendChild(this)});break;default:a(c).html(b)}})}function e(b,e){var j,k,g,i;j=b.getAttribute("data-ajax-confirm");if(j&&!window.confirm(j))return;k=a(b.getAttribute("data-ajax-loading"));i=b.getAttribute("data-ajax-loading-duration")||0;a.extend(e,{type:b.getAttribute("data-ajax-method")||undefined,url:b.getAttribute("data-ajax-url")||undefined,beforeSend:function(d){var a;f(d,g);a=c(b.getAttribute("data-ajax-begin"),["xhr"]).apply(this,arguments);a!==false&&k.show(i);return a},complete:function(){k.hide(i);c(b.getAttribute("data-ajax-complete"),["xhr","status"]).apply(this,arguments)},success:function(a,e,d){h(b,a,d.getResponseHeader("Content-Type")||"text/html");c(b.getAttribute("data-ajax-success"),["data","status","xhr"]).apply(this,arguments)},error:c(b.getAttribute("data-ajax-failure"),["xhr","status","error"])});e.data.push({name:"X-Requested-With",value:"XMLHttpRequest"});e.context=b;g=e.type.toUpperCase();if(!d(g)){e.type="POST";e.data.push({name:"X-HTTP-Method-Override",value:g})}a.ajax(e)}function i(c){var b=a(c).data(g);return!b||!b.validate||b.validate()}a(document).on("click","a[data-ajax=true]",function(a){a.preventDefault();e(this,{url:this.href,type:"GET",data:[]})});a(document).on("click","form[data-ajax=true] input[type=image]",function(c){var g=c.target.name,d=a(c.target),f=d.parents("form")[0],e=d.offset();a(f).data(b,[{name:g+".x",value:Math.round(c.pageX-e.left)},{name:g+".y",value:Math.round(c.pageY-e.top)}]);setTimeout(function(){a(f).removeData(b)},0)});a(document).on("click","form[data-ajax=true] :submit",function(c){var e=c.target.name,d=a(c.target).parents("form")[0];a(d).data(b,e?[{name:e,value:c.target.value,className:c.target.className}]:[]);setTimeout(function(){a(d).removeData(b)},0)});a(document).on("submit","form[data-ajax=true]",function(d){var c=a(this).data(b)||[];d.preventDefault();if(c.length>0&&c[0].className.indexOf("cancel")<0&&!i(this))return;e(this,{url:this.action,type:this.method||"GET",data:c.concat(a(this).serializeArray())})})})(jQuery)

I am disappointed that these critical normal behavioural fixes have not been corrected in such a long time (especially since there are just three simple edits). Even the latest September 2013 release of the AJAX toolkit is still using the now legacy "Sys" Microsoft AJAX Library whilst the rest of the world already migrated to jQuery UI. Maybe this will all be clarified with the RTM of Visual Studio 2013 specifically MVC 5?

A: As you are now using jQuery you need to wrap it in the $ to get the context. So the code will be something like
$(this).addClass("someclass");

You can find more from the api docs here.


text:
Q: How to reset a input number back to 0 when a new option is selected? I want to change/reset the input field back to zero when a new option is selected. I can set the value back to 0 but I want to have that displayed in the input field.

function inputField() {

  var weight = document.getElementById("weight").value;
  weight = 0;

  console.log(weight);
}
<form>
  <select id="pickOne" onChange="inputField()">
    <option id="optionOne" value="1">1</option>
    <option id="optionTwo" value="2">2</option>
  </select>
</form>

<input type="number" id="weight">

A: Try this:

function inputField() {
  var weight = document.getElementById("weight");
  weight.value = 0;
}
<form>
  <select id="pickOne" onChange="inputField()">
    <option id="optionOne" value="1">1</option>
    <option id="optionTwo" value="2">2</option>
  </select>
</form>

<input type="number" id="weight">


text:
Q: Is there a way to update comments when saving an Eclipse file? This isn't exactly a programming question, but my goal is to add a comment at the top of the class that shows when you last edited the file, updating when it saves. I know Eclipse can access the date and time, since adding a "Date Created:" comment was easy, but that's just editing the new file code templates so I would imagine it's not in the same area. I've been learning Java and Eclipse for about a year now, and this would be super helpful to keep track of files.
Here's a picture in case I wasn't clear

A: No, not out of the box. Someone could write a plug-in to do it, but as the comments have mentioned, once you're past a trivial example, this is usually the job for a source control system.


text:
Q: Deleting cell in collectionView bug. image overlaid on image I have a collectionView and deleting cells in it seems wrong.
https://giphy.com/gifs/9VIPAbXq8GScmDNiZa
As you can see when i tried to delete first cell, image overlaid on image. it happens randomly
DataSource for Cell
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        guard let cell = collectionView.dequeueReusableCell(withReuseIdentifier: CollectionViewCell.identifier, for: indexPath) as? CollectionViewCell else { return UICollectionViewCell() }
        if let image = ImageModel.images[indexPath.row].image {
            cell.configureCell(image: image)
        }
        return cell
    }

Delegate for deleting
func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        UIView.animate(withDuration: 0.5) {
            if let cell = collectionView.cellForItem(at: indexPath) as? CollectionViewCell {
                cell.image.center.x += 300 }
        } completion: { Bool in
            ImageModel.images.remove(at: indexPath.row)
            collectionView.deleteItems(at: [indexPath])
            collectionView.reloadData()
        }
    }

Delegate for downloading new Images
func scrollViewWillBeginDragging(_ scrollView: UIScrollView) {
        self.presenter?.fetchData()
    }

Also i have cell config with reusable cell
override func prepareForReuse() {
        super.prepareForReuse()
        self.image.image = nil
        self.image.center.x = 0
    }

What can be wrong with cell?


text:
Q: how to update by query to create incrementing ranking from sorted query in elasticsearch 6.4 I'm trying to _update_by_query in order to rank items in a sorted search. Is it possible to get the current "index" of the document in the script?
eg.
create index:
PUT test
{
    "mappings" : {
        "person" : {
            "properties" : {
                "score" : { "type" : "integer" },
                "rank" : { "type" : "integer" }
            }
        }
    }
}

add documents:
POST /test/person/1
{
  "score": 100,
  "rank": 0
}
POST /test/person/2
{
  "score": 200,
  "rank": 0
}

run _update_by_query:
POST /test/_update_by_query
{
  "script": {
    "source": "ctx._source.rank=3", // how to get document "index" in sort here?
    "lang": "painless"
  },
  "sort": { "score": "desc" }
}

results when sorting by ascending rank should be
score: 200, rank: 1
score: 100, rank: 2

A: Looks like you are trying to update a single document. For this, the _update API would be a more appropriate choice. For example:
POST test/_update/1
{
    "script" : {
        "source": "ctx._source.rank=params.rank",
        "lang": "painless",
        "params" : {
            "rank" : 4
        }
    }
}

In the above case, you can see the document ID is provided to the API which updates only that document.
In contrast, the _update_by_query API performs an update on every document in the index. So, if you need to update more than one document based on a script, this would be your go to.
Hope it helps...


text:
Q: angular modal service popup issue I have integrate angular modal before, but now i am getting this kind of issue when I try to open angular modal.
Here is an image related to that issueIssue in Showing Popup
I am not getting any kind of warning or Error in console.
I have used this angular-modal-service this package
controller-code:
App.controller('leadsController', ['$scope', 'ApiService', '$location', '$state', '$rootScope', 'toastr','ModalService', function($scope, ApiService, $location, $state, $rootScope, toastr, ModalService) {

and I am calling ModalService like this
 // Just provide a template url, a controller and call 'showModal'.
 ModalService.showModal({
     templateUrl: "pages/leadDetails.html",
     controller: "leadDetailsController"
 }).then(function(modal) {
     // The modal object has the element built, if this is a bootstrap modal
     // you can call 'modal' to show it, if it's a custom modal just show or hide
     // it as you need to.
     modal.element.modal();
     modal.close.then(function(result) {
         $scope.message = result ? "You said Yes" : "You said No";
     });
 });

but I don't know what is issue in showing pop-up.


text:
Q: Objective-c convert Long and float to String I need to convert two numbers to string in Objective-C.
One is a long number and the other is a float.
I searched on the internet for a solution and everyone uses stringWithFormat: but I can't make it work.
I try
NSString *myString = [NSString stringWithFormat: @"%f", floatValue]

for 12345678.1234 and get "12345678.00000" as output
and
NSString *myString = [NSString stringWithFormat: @"%d", longValue]

Can somebody show me how to use stringWithFormat: correctly?

A: This article discusses how to use various formatting strings to convert numbers/objects into NSString instances:
String Programming Guide: Formatting String Objects
Which use the formats specified here:
String Programming Guide: String Format Specifiers
For your float, you'd want:
[NSString stringWithFormat:@"%1.6f", floatValue]

And for your long:
[NSString stringWithFormat:@"%ld", longValue] // Use %lu for unsigned longs

But honestly, it's sometimes easier to just use the NSNumber class:
[[NSNumber numberWithFloat:floatValue] stringValue];
[[NSNumber numberWithLong:longValue] stringValue];

A: floatValue has to be a double.  At least this compiles correctly and does what is expected on my machine
Floats can only store about 8 decimal digits and your number 12345678.1234 requires more precision than that, hence only about the 8 most significant digit are stored in a float.
double floatValue = 12345678.1234;
NSString *myString = [NSString stringWithFormat: @"%f", floatValue];

results in
2011-11-04 11:40:26.295 Test basic command line[7886:130b] floatValue = 12345678.123400

A: You should use NSNumberFormatter eg:
    NSNumberFormatter * nFormatter = [[NSNumberFormatter alloc] init];
    [nFormatter setNumberStyle:NSNumberFormatterDecimalStyle];
    NSNumber *num = [nFormatter numberFromString:@"12345678.1234"];
    [nFormatter release];


text:
Q: Correct usage of the isset, recomended by IDE? I am using PHPStorm and the inspection is recommending that I switch this line of code:
$orderings['custom'][$child->id] = isset($custom_values[$child->id]) ? $custom_values[$child->id] : $next_order++;

to this:
$orderings['custom'][$child->id] = $custom_values[$child->id] ?? $next_order++;

But I can't find information in the PHP documentation about this change. Are changes like this non breaking and what is the ?? doing?

A: In this statement...
$orderings['custom'][$child->id] = $custom_values[$child->id] ?? $next_order++;
?? it work as

*

*if $custom_values[$child->id] value is not null then it use $custom_values[$child->id] value

*if $custom_values[$child->id] value is null then it use $next_order value


text:
Q: How can I detect if the atomic `__sync_bool_compare_and_swap` feature is supported by my C compiler? I want to use __sync_bool_compare_and_swap in my C programs.
How can I detect that the compiler supports this extension?

A: Write a short program that uses it and try to compile it. If it compiles- you are good to go.


text:
Q: mysql and java (observing updates, creating tables, removing tables and editing information) I am working on an application for java right now that will be using a remote mySQL database running on a linux machine. I am wanting to be able to observe the data (basically have an observer attached to one of the tables to let my application know when something has changed). I am wanting to be able to create tables, view tables and edit tables.
I was wondering what my options were in java for this type of need. Please let me know of any issues you ran into while trying to achieve this type of functionality.
Thanks for the assistance!

A: Closest answer i could find to what i wanted is JDBC.


text:
Q: Solutions for derived class and 'shadowing' I have a question similar to this one.
My problem is as follows:
I have some base messages that provide the base methods for all other messages
public class BaseMessage : ISpecificMessage1
{
    public MsgType {get;set;} //enum
    public abstract void read(BinaryReader br);
    public abstract void write(BinaryWriter bw);
}

and I have derived classes that override these basic methods. ie.
public class MessageType1 : BaseMessage
{
    public override void read(BinaryReader br)
    {
         //Do the read..
    }
    public override void write(BinaryWriter bw)
    {
         //Do the write..
    }
}

I have other derived classes a level deeper that override the methods again
public class MessageType1_Extended : MessageType1
{
    public override void read(BinaryReader br)
    {
         //Do the read different to MessageType1..
    }
    public override void write(BinaryWriter bw);
    {
         //Do the write different to MessageType1..
    }
}

My problem at the moment is that I am running a message parser, and I call a static method to remove the wrapper, decide which type the message will be and return the message as BaseMessage
public static BaseMessage extractMessage(byte[] msg)
{
    //Remove header... get type...
    switch(MsgType)
    {
          case type1_ext:
              return new MessageType1_Extended()
          //etc...
    }
}

When I call .read() on the extracted message, classes greater than 2 levels deep call only the read method for the level above BaseMessage.. Ie. MessageType1_extended will perform read for MessageType1.
I understand why this is happening from reading the earlier linked question, but my question is whether there is any way around this.
Is there any way to cast to its type and call its own override method without hardcoding the type in as
    ((MessageType1_extended)extractedMessage).read();
??
Thanks.

A: You can dynamically invoke the method on the correct type via Reflection.
However it strikes me that the overall solution is ripe for a redesign. You likely should not be using the base class to return a new instance of its own type. It's not entirely clear to me from the question what overall problem you're trying to solve, but you might consider whether a Visitor pattern implementation would be more clean for generating the parsed message.
Alternatively you could use polymorphic recursion to have each class call its base class's extract method and build up a result as the values are returned.


text:
Q: How to disable PackageKit software update password dialog? The PackageKit Project dialog keeps popping up to prompt for the root password on my Debian Jessie desktop, apparently assuming that the logged in account  has root permissions or knows the root password
Is there someway to disable it in the desktop settings?

A: Are you using KDE? I had this problem the other day, and systemctl stop/disable packagekit didn't help at all.
Here's the prompt:

In this example, polkit.subject-pid is PID 2201, which is:
username     2201  0.0  0.1 1354816 24440 ?       Sl   Oct27   2:46 kded5 [kdeinit5]

Which suggests that KDE might be doing something. On my system, KDE doesn't have package management settings in the system settings tool, but opening apper's settings menu I found this:

Setting this to Never took care of the problem for me.

Update: systemctl mask packagekit works as well. See for example http://0pointer.de/blog/projects/three-levels-of-off, which describes the difference between systemctl stop, disable, and mask. mask makes services completely unstartable until they are unmasked again.

A: There are distributions, where neither of this works ...
but one alternatively can disable the refresh manually:
su
cat <<EOF >> /etc/yum/pluginconf.d/refresh-packagekit.conf
[main]
enabled=0
EOF
service packagekit restart


text:
Q: AIF Document service Update operation error While doing update operation on using document service in 2009 we get below error. Can you please help me to resolve this issue?
'Update operations are not allowed across companies. Please use the 'changecompany' keyword to change the current company before updating the record'