text:
Q: Openshift: create passthrough secure route I'm new to Openshift and I'm currently trying to learn how to create a secure passthrough route. So far I have to create a private key, generate a CSR, and generate a self-signed certificate. I'm getting stuck on the next steps. I believe I have to create a TLS secret and then mount cert inside the container? Can anyone show me the next steps?
Generate private key
$ openssl genrsa -out php.key 2048

generate CSR
$ openssl req -new -key php.key -out php.csr  \
-subj "/C=GB/ST=London/L=London/O=IT/OU=IT/CN=www.example.com"

generate self-signed certificate
$ openssl x509 -req -days 366 -in php.csr  \
  -signkey php.key -out php.crt

After this step I'm not sure how to do the TLS secret and mount cert in container

A: *

*create a secret under same project
$ oc create secret tls php --cert=php.crt --key=php.key

*Inject secret in Deployment.
$ oc set volumes dc php --add -t secret --secret-name=php -m /usr/local/etc/ssl/certs

*Expose your service
$ oc create route passthrough php --service=php --hostname=php.apps.example.com
Note: /CN name should be "php.apps.example.com"


text:
Q: git: list remote changes I have a git remote "mine" (happens to be a github fork) that has managed to get ahead by 2 commits. My local master branch is ahead of it by 244 commits (pulled from the original gitub repo). As a result, pushing to "mine" is not fast-forward.
How can I list the 2 commits by which "mine" is ahead?

A: Your question is a little unclear, but it sounds like you want to list the commits on the remote branch that don't exist in your local branch yet. This is simply accomplished using a commit range ..:
# Get the most recent updates from the remote
git fetch <remote>

# List all commits that are in <remote>/<branch> but not in your local <branch>
git log --oneline <branch>..<remote>/<branch>

Documentation
From the official Linux Kernel git log documentation:

<since>..<until>

Show only commits between the named two commits. When either <since> or <until> is omitted, it defaults to HEAD, i.e. the tip of the current branch. For a more complete list of ways to spell <since> and <until>, see gitrevisions(7).

See Also

*

*Pro Git § 6.1 Git Tools - Revision Selection - Commit Ranges

redpajama_set_name: RedPajamaStackExchange


text:
Q: Azure B2C - Using Single Sign Out returns 302 status code instead of 200 To preface, I do have SLO working for my apps, using logout URLs, OIDC JWT tokens with B2C custom policies, etc.
However, from this Microsoft doc:
Applications must respond to this request by clearing any session that identifies the user and returning a 200 response.
Unfortunately, using the following code for silent logoff (code mostly taken from a Microsoft B2C sample) I receive a 302 back with what appears to be the app's OIDC PostLogoutRedirectUri value.  Despite my efforts to force a 200 OK return, it's still sending back a 302 to the browser with the redirect.  Is there a quick fix I need to make to my code to make it stop the redirect?
        [HttpGet]
        public ActionResult LogOffSilent()
        {
            var authTypes = HttpContext.GetOwinContext().Authentication.GetAuthenticationTypes();
            HttpContext.GetOwinContext().Authentication.SignOut(authTypes.Select(t => t.AuthenticationType).ToArray());
            Request.GetOwinContext().Authentication.GetAuthenticationTypes();
            HttpContext.Response.StatusCode = 200;

            return new HttpStatusCodeResult(HttpStatusCode.OK);
        }


text:
Q: What is the preferred method of accessing WWW::Mechanize responses? Are both of these versions OK or is one of them to prefer?
#!/usr/bin/env perl
use strict;
use warnings;
use WWW::Mechanize;

my $mech = WWW::Mechanize->new();
my $content;

# 1
$mech->get( 'http://www.kernel.org' );
$content = $mech->content;
print $content;

# 2
my $res = $mech->get( 'http://www.kernel.org' );
$content = $res->content;
print $content;

A: They are both acceptable. The second one seems cleaner to me because it returns a proper HTTP::Response object which you can query and call methods on, and also means that if you make another Mechanize request, you'll still have access to the old HTTP response. With your first approach, each time you make a request, the content method will change to something new, which sounds error-prone.
Btw, for either method, you should check $response->is_success or $mech->success before accessing the content, as the request may have failed.

A: The content() method is sometimes more convenient:
$mech->content(...)

Returns the content that the mech uses internally for the last page fetched. Ordinarily this is the same as $mech->response()->content(), but this may differ for HTML documents if "update_html" is overloaded, and/or extra named arguments are passed to content():
$mech->content( format => 'text' )

Returns a text-only version of the page, with all HTML markup stripped. This feature requires HTML::TreeBuilder to be installed, or a fatal error will be thrown.
$mech->content( base_href => [$base_href|undef] )

Returns the HTML document, modified to contain a  mark-up in the header. $base_href is $mech->base() if not specified. This is handy to pass the HTML to e.g. HTML::Display.

A: $mech->content is specifically there so you can bypass having to get the result response.  The simpler it is, the better.


text:
Q: What are the integer coeffcients of a cubic polynomial having two particular properties? Let $f(x) = x^3 + a x^2 + b x + c$ and $g(x) = x^3 + b x^2 + c x  + a\,$ where $a, b, c$ are integers and $c\neq 0\,$. Suppose that the following conditions hold:

*

*$f(1)=0$

*The roots of $g(x)$ are squares of the roots of $f(x)$.

I'd like to find $a, b$ and $c$.
I tried solving equations made using condition 1. and relation between the roots, but couldn't solve.
The equation which I got in $c$ is $c^4 + c^2 +3 c-1=0$ (edit: eqn is wrong).
Also I was able to express $a$ and $b$ in terms of $c$. But the equation isn't solvable by hand.

A: Let $u$, $v$ and $w$ be the roots of $f$, so that $u^2$, $v^2$ and $w^2$ are the roots of $g$. Then comparing the coefficients of
$$(x-u)(x-v)(x-w)=f(x)=x^3+ax^2+bx+c,$$
$$(x-u^2)(x-v^2)(x-w^2)=g(x)=x^3+bx^2+cx+a,$$
yields the equations
\begin{eqnarray*}
a&=&-u-v-w&=&-u^2v^2w^2,\\
b&=&uv+uw+vw&=&-u^2-v^2-w^2,\\
c&=&-uvw&=&u^2v^2+u^2w^2+v^2w^2.
\end{eqnarray*}
This immediately shows that $a=-c^2$, and the identities
\begin{eqnarray*}
u^2+v^2+w^2&=&(u+v+w)^2-2(uv+uw+vw),\\
u^2v^2+u^2w^2+v^2w^2&=&uvw(u+v+w)-(uv+uw+vw)^2,
\end{eqnarray*}
show that $-b=a^2-2b$ and $c=ac-b^2$, respectively, hence $b=a^2=c^4$ and so
$$f(x)=x^3-c^2x^2+c^4x+c,$$
for some $c$. Then $f(1)=1$ implies that
$$c^4-c^2+c+1=0,$$
which has the clear root $c=-1$.  Then $a=-1$ and $b=1$.

A: Hint: Condition 2 can be expressed as $f(x)$ divides $g(x^2)$.

A: The conditions 1 and 2 imply that

*

*$\;c\,$ must be $\,0\,$ or $\,-1$,

*$\;a= -c^2$, and $\:b= c^2-c-1\,$.

Condition 1 gives $0=f(1)=1+a+b+c=g(1)\,.\,$ Hence both $f$ and $g$ have a zero at $1$ and factor as
$$f(x) \,=\, (x-1)\big(x^2 + (a+1)x -c\big)\\[1.5ex]
g(x) \,=\, (x-1)\big(x^2 -(a+c)x -a\big)\,.$$
Denote the roots of the quadratic factor of $f$ by $x_1$ and $x_2$. Condition 2 says that the roots of $g$ are contained in $\{1,x_1^2,x_2^2\}$. By Vieta's formula one gets
$$\,-a \,=\, x_1^2x_2^2=(-c)^2 \,=\, c^2\,,\;\text{thus}\;\;
b \,=\, -a-c-1 \,=\, c^2-c-1\,.\tag{1}$$
Note that condition 2 remains true when restricted to the quadratic factors of $f$ and $\,g$. These are
$$q_f \,=\,x^2 + \left(1-c^2\right)x -c\tag{2}\\
q_g \,=\,x^2 -c\,(1-c)x +c^2$$
when written in terms of $\,c$.
It is shown next that condition 2 cannot hold if $c\neq 0\,$ or $\,-1$.

*

*Assume $c\geqslant 1$. Then $q_f(0)=-c<0$, and the roots $x_1,x_2$ of $q_f$ are real and distinct. By Vieta's formula regarding $q_g$ one reaches  the contradiction $0<x_1^2+x_2^2=c(1-c)\leq 0\,$.

*Assume $c\leq -2\,$. Then the discriminant $\left(1-c^2\right)^2+4c$ in $(2)$ is positive, and we run into the same contradiction as before.
So we are left with the two solutions (with condition 2 obviously satisfied)

*

*$a=0,b=-1,c=0\:$ which was ruled out a priori
then $f(x)=x(x+1)(x-1)\:$ and $\:g(x)=x^2(x-1)$

*$a=-1,b=1,c=-1\:$
where $f(x)=\left(x^2+1\right)(x-1)\:$ and $\:g(x)=(x+1)^2(x-1)$


text:
Q: How to convert the sample rate with ffmpeg-python I'm using ffmpeg-python. I would like to change the sample rate of the audio file.
In ffmpeg-, it seems that you can change the sample rate as follows.
ffmpeg -i" movie.mp3 "-y" movie.flac "-ar 44100

-ar is sample rate.
How do I change the sample rate by ffmpeg-python?
This is my source code that is currently being written.
stream = ffmpeg.input(input_file_path)
audio = stream.audio
stream = ffmpeg.output(audio, output_file_path)
ffmpeg.run(stream, capture_stdout=True, capture_stderr=True)

A: I soleved.
I can set keyword arguments like this.
stream = ffmpeg.output(audio, output_file_path, **{'ar': '16000','acodec':'flac'})

It is important to keep the ** in place. If you remove it, you will get an error.


text:
Q: Arduino compiler throws "invalid type argument of unary *" I am trying to program a nonblocking led-blink.
Therefor i programed a little class:
03: class timer {
04: private:
05:   int startMillis;
06:   int delayMillis;
07: public:
08:  timer ( int pDelay ) {
09:    reset ( pDelay );
10:  }
11:  void start () {
12:    startMillis = millis();
13:   }
14:   void reset ( int pDelay ) {
15:     delayMillis = pDelay;
16:   }
17:   boolean checkTimer () {
18:     if ( (millis() - startMillis) >= delayMillis ) {
19:       return true;
20:     } else {
21:       return false;
22:     }
23:   }
24: };

Then i want to do something like this in loop():
42: void switchLed (int *pPin, timer *pTimer) {
43:   if ( (*pTimer->checkTimer()) == true ) {
44:     if ( bitRead(PORTD, *pPin) == HIGH ) {
45:       digitalWrite(*pPin, LOW);
46:     } else {
47:       digitalWrite(*pPin, HIGH);
48:     }
49:     *pTimer->start();
50:   }
51: }

I call the switchLed() function in loop() with parameter "(&led[0], &ledTimer01)".
I think it should work, but my compiler says
nonblockingblink:5: error: 'timer' has not been declared
nonblockingblink.ino: In function 'void switchLed(int*, timer*)':
nonblockingblink:43: error: invalid type argument of 'unary *'
nonblockingblink:49: error: void value not ignored as it ought to be

Where is the problem?
Thanks for help :).

A: pTimer->checkTimer() has type boolean
So this:
*pTimer->checkTimer()

is invalid as boolean is not of a pointer type.
Same for other functions, why are you using the * operator?
This is incorrect:
*pTimer->start();

this is correct:
pTimer->start();

or
(*pTimer).start();  // equivalent to above, prefer the above form

A: You use two types of pointer dereferencing. First you use -> to access the pTimer structure member, and then you use * again on a non-pointer type (the boolean returned by checkTimer). Remove the asterisk and it should work.


text:
Q: xpath find location in document Trying to find the value of "aging-timer" in the following XML document:
<ospf3-database-information xmlns="http://xml.juniper.net/junos/11.1R2/junos-routing">
    <ospf3-database external-heading="OSPF3">
        <lsa-type>Extern</lsa-type>
        <lsa-id>0.0.0.1</lsa-id>
        <advertising-router>172.27.255.6</advertising-router>
        <sequence-number>0x80000001</sequence-number>
        <age>1792</age>
        <checksum>0x90bd</checksum>
        <lsa-length>28</lsa-length>
        <ospf3-external-lsa>
            <ospf3-prefix>::/0</ospf3-prefix>
            <ospf3-prefix-options>0x0</ospf3-prefix-options>
            <type-value>1</type-value>
            <metric>0</metric>
        </ospf3-external-lsa>
        <ospf-database-extensive>
            <aging-timer junos:seconds="1808">
                00:30:08
            </aging-timer>
            <installation-time junos:seconds="1790">
                00:29:50
            </installation-time>
            <expiration-time junos:seconds="1808">
                00:30:08
            </expiration-time>
            <send-time junos:seconds="1790">
                00:29:50
            </send-time>
            <lsa-changed-time junos:seconds="1790">
                00:29:50
            </lsa-changed-time>
            <lsa-change-count>1</lsa-change-count>
        </ospf-database-extensive>
    </ospf3-database>
</ospf3-database-information>

The only caveat is that I only want it if "ospf3-prefix" has a text of ::/0.
I am trying this xpath:
//x:ospf3-external-lsa[x:ospf3-prefix=\"::/0\"]/ancestor::x:ospf3-database/x:ospf-database-extensive/x:aging-timer

using the x to handle namespaces in perl:
   my $xdatav6 = XML::LibXML->load_xml(string => $defv6);
   my $dataxv6 = XML::LibXML::XPathContext->new($xdatav6);
   $dataxv6->registerNs("x", "http://xml.juniper.net/junos/11.1R2/junos-routing");

but this doesn't work, it seems that when I use the ancestor it can grab everything except anything under the "ospf-database-extensive" tree.

A: The XML you show isn't valid as it doesn't have a URI for the junos namespace that is used in junos:seconds. I changed the root tag to read
xmlns:junos="http://xml.juniper.net/junos/11.1R2/junos-routing"

to get things working.
This is the longest XPath expression I've seen, but this does the trick! Put the appropriate namespace prefixes in as needed.
/ospf3-database-information/ospf3-database[ospf3-external-lsa/ospf3-prefix="::/0"]/ospf-database-extensive/aging-timer


text:
Q: How to know when MIDI file has finished with OS X MusicPlayer I want to be able to play MIDI files that are included as resources in my app. I have a very simple function to do this, given the name of the resource (minus the .MID) file extension:
MusicPlayer  musicPlayer;
MusicSequence  sequence;
int MusicPlaying=0;

void PlayMusic(char *fname)
{
    OSStatus    res=noErr;

    res = NewMusicPlayer(&musicPlayer);
    res = NewMusicSequence(&sequence);
    strcpy(TmpPath, "MUSIC/");
    strcat(TmpPath, fname);
    strcat(TmpPath, ".MID");
    NSString *iName = [NSString stringWithUTF8String:TmpPath];
    NSURL   *url = [[NSBundle mainBundle] URLForResource:iName withExtension:nil];

    res = MusicSequenceFileLoad (sequence, (__bridge CFURLRef _Nonnull)(url), 0, kMusicSequenceLoadSMF_ChannelsToTracks);
    res = MusicPlayerSetSequence(musicPlayer, sequence);
    res = MusicPlayerStart(musicPlayer);

    if( res==noErr ) MusicPlaying = 1;
}

This all works fine and dandy, takes very little code... the problem is that I can't figure out how to know when the MIDI file has finished playing.  I've tried MusicPlayerIsPlaying() (it ALWAYS returns true, LONG after the file has finished).  I've tried checking MusicPlayerGetTime(), but the time count keeps on going after the MIDI finishes.  I can't find any way to get a notification from this or any other way to determine that the actual MIDI data has finished playing.
Any ideas?

A: Apple's PlaySequence example shows how to do this:

*

*You have to determine the length of the sequence by getting the length of each track:
MusicSequenceGetTrackCount(sequence, &ntracks);
for (UInt32 i = 0; i < ntracks; ++i) {
    result = MusicSequenceGetIndTrack(sequence, i, &track);
    result = MusicTrackGetProperty(track, kSequenceTrackProperty_TrackLength,
                    &trackLength, &propsize);
    if (trackLength > sequenceLength)
        sequenceLength = trackLength;
}

*Then wait until you have reached that time:
while (1) {
    usleep (2 * 1000 * 1000);
    result = MusicPlayerGetTime(player, &time);
    if (time >= sequenceLength)
        break;
}


text:
Q: JS: awaiting promises in map I asked a question that was closed due to similar questions but even after reading those and seeing that map is not Promise aware, I have tried to use await Promise.all() around my mapping.
let foo = [1,2,3];

(async() => {
   await Promise.all(foo.map(x => {
      return new Promise(async function(resolve) {
         await setTimeout(() => {
            console.log("X")
            resolve()
         }, 3000)
      });
   }))
})()

instead of sequentially getting a "X" log every 3 seconds, it's just waiting 3 seconds and then logging them all.  I am not sure what I am doing wrong at this point.

A: You are setting all the timeouts together at once. You need to increase the timeout duration in each iteration, maybe like this:

let foo = [1,2,3];

(async() => {
   await Promise.all(foo.map((x, i) => {
      return new Promise(async function(resolve) {
         await setTimeout(() => {
            console.log("X")
            resolve()
         }, 3000 * (i + 1))
      });
   }))
})()


text:
Q: Formula to return percentage of a number up to a maximum value Can someone help me construct a formula in Excel?  I have it close but can't figure out how to incorporate the "Maximum of 5" and "Maximum of 25" for ranges >10-50 and 51+.  See my chart below to calculate sample size given a population.
If Population is:
1
>1 - 10
>10 -50
51+

Sample Size is:
1
2
25% of Population up to a Maximum of 5
10% of Population up to a Maximum of 25

My formula now, which does not return what I want:
=IF(G4=1,1,IF(AND(G4>1,G4<=10),2,IF(AND(OR(G4>10,G4<=50),(0.25*G4),AND(G4>50,(0.1*G4),G4>25,25)),IF(G4>5,5))))

A: I think this is what you're looking for, note the use of MIN():
=IF(A1=1,1,IF(AND(A1>1,A1<=10),2,IF(AND(A1>10,A1<=50),MIN(5,A1*0.25),IF(A1>=51,MIN(25,0.1*A1)))))

where A1 is the value of the population.

A: I have clarified the parameters by changing the layout of your formula to:
=IF(G4=1,1,
    IF(AND(G4>1,G4<=10),2,
       IF(AND(OR(G4>10,G4<=50),(0.25*G4),
                 AND(G4>50,(0.1*G4),G4>25,25)
             ),IF(G4>5,5)
         )
      )
   )

Several things become clear:

*

*The final IF() has a true value, but no false value.

*The final AND() checks 4 values, two conditional and two numeric.

*The previous AND() checks 3 values, an OR(), a numeric and an AND().

I'm not sure how you were trying to formulate your conditions, but there are clearly some IF() clauses missing.
Note that your AND() clauses are unnecessary, since one of the conditions is implicit in each case, so I would propose:
=IF(G4<=1,G4=1,
    IF(G4<=10,2,
       IF(G4<=50,
            IF(G4>20,5,0.25*G4),
            IF(G4>250,25,0.1*G4)
         )
      )
   )

I have added allowing for a sample size of zero if G4 is zero or negative. I have compared population size limits to save calculating the sample size twice (which is also avoided in Bruce Wayne's use of MIN()).


text:
Q: Ventana Modal, Obtener Valor Fila,Tabla bootstrap tengo una duda.
Tengo una tabla en la cual muestro los de un cliente, de una tabla llamada Clients  con campos: user_first, user_last, user_uid...

Luego tengo un boton con el simbolo ' # ' que al presionarlo me muestra una ventana modal con valores de otra tabla que tienen relacion con este cliente, la otra tabla se llama ABONOS.
Cada cliente cuenta con ese botoncito ' # ' para mostrar esos datos en la ventana modal.
Como hago para que al presionarlo me detecte el valor de la fila que presiono o el username??
actualmente lo hice rude: "SELECT loan_id,loan_amount,loan_totalint FROM loans WHERE user_uid='Don mario'";

Pero como no se cuantos usuarios o los nombres que tendran como hago para identificar la fila?
Me ayudan porfavor?
mi codigo es el siguiente:
       <?php
       $sql2= "SELECT loan_id,loan_amount,loan_totalint FROM loans WHERE
       user_uid='Don mario'";

       $result2 = mysqli_query($connect, $sql2);

        ?>

        <?php

        echo '

               <button type="button" class="close" data-
               dismiss="modal">×</button>

Loan Info

                 Id
                 Monto Actual
                 Total Interes

';

               if(mysqli_num_rows($result2) > 0)
               {
               while($row = mysqli_fetch_array($result2))
               {
               echo'

              '.$row["loan_id"].'

              '.$row["loan_amount"].'

              '.$row["loan_totalint"].'

';

              }
              echo '

';

            }

           echo '

             <button type="button" class="btn btn-default" data-
             dismiss="modal">Close</button>

  ';

A: Puedes crear un metodo que muestre los datos del user que quieres, luego para ejecutar la funcion segun el usuario, creas un boton que ejecute ese metodo y dentro le mandas los parametros del usuario,
En javaScript seria algo mas on menos asi

cuando ejecute la funcion, esta va a saber de que usuario se trata y asi cargara los datos y los mostrara, trata de usar eso con PHP


text:
Q: Combining 3 select queries I am working with a MySQL database. I am suppose to combine three select queries, to "improve performance". Each select below is dependent on the previous ID retrieved.
Here is the workflow to get data references between the tables.
There are three tables:
pUserMatch  |  pGroupMatch  |  ProfileData
----------- |  -----------  |  ----------
* username
* GroupID .... GroupID
               ProfileID ....  ID
                               ParentUser

My three select queries...
# get the group ID for the specific username
group_id = select GroupID from Profiles.pUserMatch where username = "<username>";

# now, get the group match ID for the group ID
profile_id = select ProfileID from Profiles.pGroupMatch where GroupID = "<group_id>"

# now, get the profile data for this ID
profile = select * from Profiles.ProfileData where ID = "<profile_id>"

I know a little bit about using joins, but I thought that they were only used when multiple tables have matching data.
So far, I've tried the following...
# multiple select from tables
select usermatch.username, groupmatch.GroupID
  from pUserMatch as usermatch, pGroupMatch as groupmatch
  where usermatch.username = <"username">

# inner join...
select pUserMatch.GroupID, pGroupMatch.GroupID,
  from pUserMatch
    inner join pGroupMatch
      on pUserMatch.GroupID = pGroupMatch.GroupID

I need to select the pGroupMatch.GroupID and ProfileData.ID based on a username param. Is there a way to query this data in a single statement?

A: As far as I know you don't need foreign keys to make joins.
Also, you don't even need to use the "inner/outer join" syntax to make joins!
So, following your schema:
pUserMatch  |  pGroupMatch  |  ProfileData
----------- |  -----------  |  ----------
* username
* GroupID .... GroupID
               ProfileID ....  ID
                               ParentUser

The query would be:
select u.username, u.GroupID, g.ProfileID, p.ParentUser
from pUserMatch u, pGroupMatch g, ProfileData p
where u.GroupID = g.GroupID
  and g.ProfileID = p.ID
  and usermatch.username = <"username">

Anyway the "join" syntax would be the following:
select u.username, u.GroupID, g.ProfileID, p.ParentUser
from pUserMatch u
  inner join pGroupMatch g
    on u.GroupID = g.GroupID
  inner join ProfileData p
    on g.ProfileID = p.ID
 where usermatch.username = <"username">

Use "left outer join" instead of "inner join" if you want to see all the records of the first table (i.e. pUserMatch) even if there's no the linked record on the other one (i.e. pGroupMatch).


text:
Q: Why switch on String compiles into two switches I read JVM specification on compiling switches and became interested in how switch statement on String is compiled. Here is the test method I examined (JDK1.7.0_40):
static int test(String i) {
    switch (i) {
        case "a":  return  -100;
        case "45b":  return  1;
        case "c":  return  2;
        default: return -1;
    }
}

I expect this method to be compiled into simple lookupswitch on hashCode of string, but suddenly
static int test(java.lang.String);
Code:
   0: aload_0
   1: astore_1
   2: iconst_m1
   3: istore_2
   4: aload_1
   5: invokevirtual #6         // Method java/lang/String.hashCode:()I
   8: lookupswitch  { // 3
                97: 44
                99: 72
             51713: 58
           default: 83
      }
  44: aload_1
  45: ldc           #7 // String a
  47: invokevirtual #8 // Method java/lang/String.equals:(Ljava/lang/Object;)Z
  50: ifeq          83
  53: iconst_0
  54: istore_2
  55: goto          83
  58: aload_1
  59: ldc           #9  // String 45b
  61: invokevirtual #8  // Method java/lang/String.equals:(Ljava/lang/Object;)Z
  64: ifeq          83
  67: iconst_1
  68: istore_2
  69: goto          83
  72: aload_1
  73: ldc           #10 // String c
  75: invokevirtual #8  // Method java/lang/String.equals:(Ljava/lang/Object;)Z
  78: ifeq          83
  81: iconst_2
  82: istore_2
  83: iload_2
  84: tableswitch   { // 0 to 2
                 0: 112
                 1: 115
                 2: 117
           default: 119
      }
 112: bipush        -100
 114: ireturn
 115: iconst_1
 116: ireturn
 117: iconst_2
 118: ireturn
 119: iconst_m1
 120: ireturn

As you could see, in branches of first lookupswitch JVM is not doing the real work generating indices for subsequent tableswitch (line 84) instead.
Tableswitch should work fast so doesn't bring a lot of extra work. But anyway, what is the purpose of generating additional switch?
Update
I understand possibility of hashCode collisions. What I'm trying to say is that instead of subsequent tableswitch, compiler could move all the real work from subsequent tableswitch to first and then use ifeq to jump to the end of all switch branches. So the one possible answer I see here: that in first switch compiler tries to precompute label for ifeq jump based on known number of cases, but I'm not sure that it is the only reason.
Update2
As @ericbn suggested, I tried to compile
switch (i) {
   case 97: return -100;
   case 51713: return 1;
   case 99: return 2;
   default: return -1;
}

with i as int and compiler gave me plain lookupswitch.

A: The cite from the javac source code:
         * The general approach used is to translate a single
         * string switch statement into a series of two chained
         * switch statements: the first a synthesized statement
         * switching on the argument string's hash value and
         * computing a string's position in the list of original
         * case labels, if any, followed by a second switch on the
         * computed integer value.  The second switch has the same
         * code structure as the original string switch statement
         * except that the string case labels are replaced with
         * positional integer constants starting at 0.
         *
         * The first switch statement can be thought of as an
         * inlined map from strings to their position in the case
         * label list.  An alternate implementation would use an
         * actual Map for this purpose, as done for enum switches.
         *
         * With some additional effort, it would be possible to
         * use a single switch statement on the hash code of the
         * argument, but care would need to be taken to preserve
         * the proper control flow in the presence of hash
         * collisions and other complications, such as
         * fallthroughs.  Switch statements with one or two
         * alternatives could also be specially translated into
         * if-then statements to omit the computation of the hash
         * code.


text:
Q: PERL: Using REGEX to match a string without the first token repeated in the string. (ABC, not AAA ABC) I am relatively new to perl and I apologize in advance if this question is simple and I am missing something completely obvious, however, I've been looking around for the answer for a couple of days now and can't find a solution.
I am trying to use a regular expression to match the FIRST instance where A is followed by C without another A in between A and C. Note that in this text string there are other instances following the first A.C combination that could also fit the A.C, (specifically note the ADC) Here is the text:
$text = "AAA ABC ADE AFG ADC AHI AJK AIZ XXB NBV";

I first tried:
@finds1=$TEXT=~m/(A.*?C)/;
$result = $finds1[0];
print "result = $result\n";

This prints the following:
result = AAA ABC

When what I want is just:
result = ABC

Note that I am trying to create a regular expression that could be used where B could be any string of characters.  For example ADC, AFGHJKC, AYUIOKJHGTC.
I next tried to use a look-forward combined with an if then else statement.  Here is the code:
@finds1=$TEXT=~m/(A(?(?!.*?A.*?C).*?C|Z{100}))/;
$result = $finds1[0];
print "result = $result\n";

The first part of the REGEX, (A, tells perl to find an occurrence of A. Once found, perl then processes the if then else statement where the conditional statement is that there are no instances of .?A.?A following the A, if none are found then perl looks for .*?C, if at least one is found, then it searches for 100 instances of Z. (my way of getting Perl to move on since neither in this text nor in the text I'm trying to parse are there 100 Zs.)
This returns:
result = ADC

I have considered using a positive look-behind after identifying C for the first time.  However, like I mentioned above, The number of characters between the first A.C combination without an A in between them is variable.  As far as I know PERL can't do variable-length look-behinds.
Any help or direction you could provide would be GREATLY appreciated!!
Thanks in advance!

A: Don't you simply want
/A[^AC]*C/

A: As far as I can tell, you're wanting:

*

*An "A"

*Followed by any number of characters that aren't A

*Followed by a "C"

This can be achieved with the regular expression
/A[B-Z]*?C/
Characters in square brackets [] represent a character class. With a character class you can tell the regex engine to match only one out of several characters. Simply place the characters (or ranges of characters) you want to match between square brackets (http://www.regular-expressions.info/charclass.html). Say you wanted to do this with another letter, Q, you would have a slightly different character class
/Q[A-PR-Z]*?C/
If you wanted to modify it to accommodate spaces between the A and the C, you can approach it in two different ways. You can negate a character class, and it will match any character apart from the ones in it, like so:
/A[^AC]*C/
Which will match an A, then any number of characters apart from A and C, then a C.
OR, you can add a space to the original character class, like so:
/A[B-Z ]*?C/ (note the space after the Z)
If you want any sort of whitespace, replace the space with \s, which represents any whitespace, like so:
/A[B-Z\s]*?C/


text:
Q: Invalid convert from std::sqlString to char const* in C++ and Mysql con->setSchema(DATABASE);
// Query section
stmt = con->createStatement();
res = stmt->executeQuery("SELECT * FROM  `submission` WHERE  'status' = 0");
while (res->next()) {
 // Access column data by alias or column name
 string insert = res->getString('pid');
 const char* p = insert.c_str();

  pipe = fopen(p, 'w');

  fprintf(pipe,"Successfully created");
}

How can i convert the res->getString('pid') value into fopen() as filename. I get error because its asking for char const*

A: con->setSchema(DATABASE);
// Query section
stmt = con->createStatement();
res = stmt->executeQuery("SELECT * FROM  `submission` WHERE  'status' = 0");
while (res->next()) {
// Access column data by alias or column name

string insert = res->getString('pid'); //changed 'pid' to "pid"

const char* p = insert.c_str();

FILE *pipe = fopen(p, 'w'); // Declared pipe as FILE

fprintf(pipe,"Successfully created");
}


text:
Q: tf.nn.conv2d_transpose in Julia? Hello
A simple question but I don't find it: What is the equivalent of tf.nn.conv2d_transpose in Julia ?
Moreover, I have this link with some Julia commands for TensorFlow: https://github.com/malmaud/TensorFlow.jl/blob/master/docs/src/ops.md
Do you know an other link with more or other commands ?
Thank you

A: Looking at a part of the logistic regression example on the github page for the julia wrapper:
https://github.com/malmaud/TensorFlow.jl
Y=nn.softmax(X*W + B)
Loss = -reduce_sum(log(Y).*Y_obs)
optimizer = train.AdamOptimizer()
minimize_op = train.minimize(optimizer, Loss)
saver = train.Saver()

It looks like the TF packages are mimicked in Julia, and I specifically see the nn package referenced in the example as nn.softmax, so extrapolating from that example it must be nn.conv2d_transpose.


text:
Q: How to clear datagrid items in wpf while having button in column of each row I want to delete datagrid items in wpf.
I have tried
 dataGridfix.Items.Clear();
 dataGridfix.Items.Refresh();
 dataGridfix.ItemsSource = null;

but due to having button in each row , it stops to clear datagrid.
can u suggest good idea?
full code is here
   private void showfix()
   {
         dataGridfix.ItemsSource = null;
         DataTable dt = new DataTable();
         dt.Columns.Add("ID");
         dt.Columns.Add("Account");

         SqlDataAdapter msadapt = new SqlDataAdapter("select * from fdetails  order by fdid desc", mscon);
         DataTable msdata = new DataTable();
         msadapt.Fill(msdata);

         for (int i = 0; i < msdata.Rows.Count; i++)
         {
             string id = msdata.Rows[i].ItemArray[0].ToString();
             string acc = msdata.Rows[i].ItemArray[2].ToString();
             dt.Rows.Add(id, acc);
         }

         dataGridfix.ItemsSource = dt.DefaultView;
         dataGridfix.Columns[0].Width = 50;
         dataGridfix.Columns[1].Width = 50;
         dataGridfix.Columns[2].Width = 180;
     }

xaml code is
                                <DataGridTemplateColumn >
                                    <DataGridTemplateColumn.CellTemplate >
                                        <DataTemplate>
                                            <Button Name="btndelfix" Click="btndelfix_Click" >Delete</Button>
                                        </DataTemplate>
                                    </DataGridTemplateColumn.CellTemplate>
                                </DataGridTemplateColumn>
                            </DataGrid.Columns>

A: Have you tried doing dataGridfix.ItemsSource = null then doing
dataGridfix.Items.Refresh() instead of the other way around as seen here?
You need to clear the itemsSource property for the binding to stop working. Then nothing should block you from emptying the datagrid.
To me the DataTemplate using a button is not related to your problem.


text:
Q: Idris: Implicit parameters in records When I try to compile this example
record R where
    f: () -> {t: Type} -> t

I get this error:
Type mismatch between
        () -> t1 (Type of f)
and
        () -> t (Expected type)

Specifically:
        Type mismatch between
                t1
        and
                t

On the other hand this example
record R where
    f: {t: Type} -> () -> t

works just fine. Can you tell me what's wrong with the first one?

A: This is a bug in Idris: sometimes the -> operator is not right-associative: issue #4077.
To see it we can desugar the record syntax:
data R : Type where
  MkR : (() -> {t : Type} -> t) -> R

Now we need to manually implement the f projection. It turns out that
f : R -> (() -> {t : Type} -> t)
f (MkR g) = g

does not typecheck, but
f : R -> () -> {t : Type} -> t
f (MkR g) = g

does.
It seems to me Idris uses the first variant to desugar record into data, hence the error you observed.


text:
Q: SQL Server - how to ensure identity fields increment correctly even in case of rollback In SQL Server, if a transaction involving the inserting of a new row gets rolled back, a number is skipped in the identity field.
For example, if the highest ID in the Foos table is 99, then we try to insert a new Foo record but roll back, then ID 100 gets 'used up' and the next Foo row will be numbered 101.
Is there any way this behaviour can be changed so that identity fields are guaranteed to be sequential?

A: What you are after will never work with identity columns.
They are designed to "give out" and forget, by-design so that they don't cause waits or deadlocks etc.  The property allows IDENTITY columns to be used as a sequence within a highly transactional system with no delay or bottlenecks.
To make sure that there are no gaps means that there is NO WAY to implement a 100-insert per second system because there would be a very long queue to figure out if the 1st insert was going to be rolled back.
For the same reason, you normally do not want this behaviour, nor such a number sequence for a high volume table. However, for very infrequent, single-process tables (such as invoice number by a single process monthly), it is acceptable to put a transaction around a MAX(number)+1 or similar query, e.g.
declare @next int
update sequence_for_tbl set @next=next=next+1
.. use @next

A: SQL Identity (autonumber) is Incremented Even with a Transaction Rollback


text:
Q: What is phpMyAdmin doing to my UNION ALL query? The following query returns 1 row:
SELECT `coach_id` FROM `table_a` WHERE `coach_id` = 8
UNION ALL
SELECT `coach_id` FROM `table_b` WHERE `coach_id` = 8

But SELECT coach_id FROM table_b WHERE coach_id = 8 returns 2 rows.
And SELECT coach_id FROM table_a WHERE coach_id = 8 returns 1 row.
I'm using UNION ALL to avoid the DISTINCT filtering, because I'm actually just interested in the total number of rows. Still it seems to behave like regular UNION a.k.a UNION DISTINCT.
Whats going on here? Query is executed in phpMyAdmin 4.5.2 interface on MariaDB 10.1.9 Server.
Update
I just discovered that the mysql command line client behaves like expected. So the failure has to be somewhere within my stack of nginx 1.8.0, PHP 5.6.16 mysqli and phpmyadmin.
Update 2
When I run the query from a php script (using mysqli) it also correctly returns 3 rows. I guess that leaves nothing but phpMyAdmin to cause this phenomenon. Thanks for the help so far and sorry that the question has been misleading. I didn't know better...

A: This is a phpMyAdmin bug, which is fixed in v4.5.3.0 (2015-12-23).

A: schema
create schema testThenDrop123;
use testThenDrop123; -- use that database

create table table_a
(   id int auto_increment primary key,
    coach_id int not null
);

create table table_b
(   id int auto_increment primary key,
    coach_id int not null
);

insert table_a (coach_id) values (8);
insert table_b (coach_id) values (8),(8);

query
SELECT `coach_id` FROM `table_a` WHERE `coach_id` = 8
UNION ALL
SELECT `coach_id` FROM `table_b` WHERE `coach_id` = 8;
+----------+
| coach_id |
+----------+
|        8 |
|        8 |
|        8 |
+----------+

.
drop schema testThenDrop123; -- cleanup by dropping db

So I don't see what you are seeing.

A: Is it possible you have dirty data? Spaces or some other character in with the ids? use LENGTH(coach_id), coach_id in your query. Then if it is more than one character it won't return those rows but you would know why.


text:
Q: Is there any possibility to use Bittorrent protocol for streaming video via flash or html5 video player? Is there any possibility to use Bittorrent protocol (or another p2p) for streaming video via flash or html5 video player embedded into web site page? Preferable via html5 video plyaer.

A:
html5

In the specific case of html5 it is not possible to implement existing p2p protocols since web APIs do not provide access to raw TCP or UDP sockets.
There are websockets and the webrtc protocol which provide p2p connections, but they layer additional protocols ontop of the underlying network sockets and thus cannot be used to talk to software using other protocols.
Privileged code in browsers (i.e. extensions/addons) may provide access to proper sockets and thus could be used to implement clients for existing p2p protocols.
But bittorrent can transfer all kinds of video contents, .mkv is a popular container for example. Web browsers are less powerful than dedicated media players and may not be able to decode some videos.
Ontop of that streaming is possible via bittorrent but it goes against one of its design goals (the rarest-first policy).
So it's possible if you're willing to write browser extensions, but in my opinion you would end up with a piece of software that can do less than existing, dedicated solutions (i.e. a bittorrent client + a media player).

A: Tribler is an open-source project that uses the BitTorrent protocol.
However the demos were using SwarmPlayer on the client side. You can get more info on their site. See also the streaming experiment.
GoalBit is another P2P open-source project which uses something similar to BitTorrent. The demo works with JWPlayer.
Just do a web search since there are many other projects. You can also find paid solutions like Streamroot to name one.


text: Q: how to type procee.env.FOO as non-null string in TypeScript I was wondering if there's a recommended way to do this without passing procee.env.FOO into nullthrows on TypeScript. I tried appending a bang to it but I'm still seeing the linter yell at me. Thank you.


text:
Q: Efficient hashing of `std::bitset` or `boost::dynamic_bitset<>` for Boost's unordered containers I'm wondering if there's some efficient way to hash std::bitset or boost::dynamic_bitset<> for Boost's unordered containers?
I'm currently converting std::bitset or boost::dynamic_bitset<> to std::string first before hashing them, but it seems this is going to be slow.
Is there some better way?

A: The C++11 requires standard library to have std::hash<std::bitset> specialized. IOW it should have hash already.
For boost you should use config: #define BOOST_DYNAMIC_BITSET_DONT_USE_FRIENDS then the dynamic_bitset::m_bits member becomes public and you can make hash on it.


text:
Q: SQL Pivot on two dynamic columns I know there are a lot of PIVOT two Columns on stack overflow, but none seems to suit my needs :(
Here's the table that I have:

I want to pivot it to this:

And here's the initial setup:
CREATE TABLE TblPivot
(ID         INT IDENTITY(1, 1),
 Shop    VARCHAR(MAX),
 ElementId  VARCHAR(10),
 QuestionId VARCHAR(10),
 [Value]    VARCHAR(20)
);

GO
INSERT INTO TblPivot (Shop,ElementId,QuestionId,[Value]) VALUES ('Shop1','elem10','question1','one')
GO
INSERT INTO TblPivot (Shop,ElementId,QuestionId,[Value]) VALUES ('Shop1','elem11','question1','two')
GO
INSERT INTO TblPivot (Shop,ElementId,QuestionId,[Value]) VALUES ('Shop1','elem20','question2','1')
GO
INSERT INTO TblPivot (Shop,ElementId,QuestionId,[Value]) VALUES ('Shop1','elem20','question3','p1')
GO
INSERT INTO TblPivot (Shop,ElementId,QuestionId,[Value]) VALUES ('Shop1','elem21','question2','2')
GO
INSERT INTO TblPivot (Shop,ElementId,QuestionId,[Value]) VALUES ('Shop1','elem21','question3','p2')

I suspect it must be something with CROSS-APPLY and PIVOT, but I am not sure on how to tackle this.
PS: The element ID can be null
Thanks!

A: Do the conditional aggregation:
select Shop,
       max(case when (QuestionId = 'question1' and ElementId = 'elem10')
                then value end) [question1- elem10],
       . . .
from TblPivot p
where QuestionId in ('question1', 'question2', 'question3') and
      ElementId in ('elem10', 'elem11', 'elem20', 'elem21')
group by Shop;


text:
Q: Neo4j JDBCCypherExecutor blocks thread I am using neo4j 2.1.5 and using JDBCCypherExecutor to post my cypher queries.
often the cypher executor thread gets stuck making the app unusable after sometime.
The only option after sometime is to restart the spark webapp.
Has anyone encountered this problem?
The jstack of one of the blocked thread is
"qtp1639509299-63" prio=10 tid=0x00007fe454001000 nid=0x1e0e waiting on condition [0x00007fe564fea000]
   java.lang.Thread.State: WAITING (parking)
    at sun.misc.Unsafe.park(Native Method)
    - parking to wait for  <0x0000000586cf6e88> (a java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject)
    at java.util.concurrent.locks.LockSupport.park(LockSupport.java:186)
    at java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject.await(AbstractQueuedSynchronizer.java:2043)
    at org.apache.http.impl.conn.tsccm.WaitingThread.await(WaitingThread.java:158)
    at org.apache.http.impl.conn.tsccm.ConnPoolByRoute.getEntryBlocking(ConnPoolByRoute.java:403)
    at org.apache.http.impl.conn.tsccm.ConnPoolByRoute$1.getPoolEntry(ConnPoolByRoute.java:300)
    at org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager$1.getConnection(ThreadSafeClientConnManager.java:224)
    at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:391)
    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:820)
    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:754)
    at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:732)
    at org.restlet.ext.httpclient.internal.HttpMethodCall.sendRequest(HttpMethodCall.java:336)
    at org.restlet.engine.adapter.ClientAdapter.commit(ClientAdapter.java:114)
    at org.restlet.engine.adapter.HttpClientHelper.handle(HttpClientHelper.java:112)
    at org.restlet.Client.handle(Client.java:180)
    at org.restlet.routing.Filter.doHandle(Filter.java:159)
    at org.restlet.routing.Filter.handle(Filter.java:206)
    at org.restlet.resource.ClientResource.handle(ClientResource.java:1136)
    at org.restlet.resource.ClientResource.handleOutbound(ClientResource.java:1225)
    at org.restlet.resource.ClientResource.handle(ClientResource.java:1068)
    at org.restlet.resource.ClientResource.handle(ClientResource.java:1044)
    at org.restlet.resource.ClientResource.post(ClientResource.java:1453)
    at org.neo4j.jdbc.internal.rest.TransactionalQueryExecutor.post(TransactionalQueryExecutor.java:98)
    at org.neo4j.jdbc.internal.rest.TransactionalQueryExecutor.commit(TransactionalQueryExecutor.java:133)
    at org.neo4j.jdbc.internal.rest.TransactionalQueryExecutor.executeQueries(TransactionalQueryExecutor.java:204)
    at org.neo4j.jdbc.internal.rest.TransactionalQueryExecutor.executeQuery(TransactionalQueryExecutor.java:214)
    at org.neo4j.jdbc.internal.Neo4jConnection.executeQuery(Neo4jConnection.java:370)
    at org.neo4j.jdbc.internal.Neo4jPreparedStatement.executeQuery(Neo4jPreparedStatement.java:48)
    at com.zahoor.graph.executor.JdbcCypherExecutor.query(JdbcCypherExecutor.java:28)

A: Separate threads might be the issue here, as the JDBC driver keeps the transaction in a thread local, so if you spawn new threads it creates new transaction objects and new connections (if you don't reuse the same Connection instance.
And the default pooling of HttpClient is (afaik) 10 parallel connections.


text:
Q: Google Sheets>New Entries pop up at the top On the attendance tracker below incidents are affiliated with a point value system. Each entry is entered on the left (itemized with details) and consolidated on the right (past the black line). On the right-hand side, the 'Action Taken' column(Column U) is populated based on the number in the 'Total Points' column (Column T).
I would like the 'Status' column (Column V) to revert back to 'Not Started', and reflect a different color when the number changes (increases/decreases) in the 'Total Points' column.  I would like the new entries to also pop up at the top. Let me know, please!
https://docs.google.com/spreadsheets/d/1Bfs41hC6qxLadwuVv1qc4HV1hDoiw9bGi9UsiSzeG_0/edit?usp=sharing

A: I understand that there are two different topics in your issue. The first one is to modify the V column after every edit on the T column. The second one is to add new entries at the top of the table. With the following functions, you will be able to accomplish both.
The first function will change the color and value of the V column after every edit on the T column. It will use an event object of a simple trigger to run. I choose azure as an example colour, but you can change it.
The second function will insert a new blank row at the top of your table, and will populate it later with different values. I wrote example values to exemplify the code, but you can fill it with your chosen values.
function onEdit(e) {
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(
    'Attendance Tracker');
  if (e.range.getColumn() == 20) {
    var status = e.range.offset(0, 2);
    status.setBackgroundRGB(0, 127, 255);
    status.setValue('Not Started');
  }
}

function newEntry() {
  var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(
    'Attendance Tracker');
  sheet.insertRowBefore(3);
  sheet.getRange(3, 1, 1, 23).setValues(["Value A", "Value B",
  "Value C" … "Value W"]);
}

Please, remember to update the values row separating each value with commas (notice how I used «…» to make the example shorter). Do not hesitate to ask for any additional clarification or for further help.


text:
Q: extrar informacion y colocarlo en una tabla con una funcion PHP hola buenas necesito realizar una tabla con informacion de una base de datos usando funciones que aparecen en el codigo cololarlos en una tabla a esto hacerle un bucle para que se se vallan agregando datos nuevos este es mas o menos el codigo que tengo me dijieron q usara un WHILE pero no me esta funcionando al llamar al objeto y dandonde una variable........................................................................................................................
<?php

class MysqliDb {

private $host = "localhost";
private $user = "root";
private $pass = "";
private $dbname = "alumnos";

private $connection;

function __construct()
{
    $this->connection = mysqli_connect(
        $this->host,
        $this->user,
        $this->pass,
        $this->dbname
    );
    $this->connection->set_charset("utf8");
}
function executeQuery($sql){
    $data = array();
    $result = mysqli_query($this->connection, $sql);
    if(mysqli_num_rows($result) > 0){
        while($row = mysqli_fetch_assoc($result)){
            array_push($data, $row);
        }
    }
    return $data;
}

function numRows($sql){
    $result = mysqli_query($this->connection, $sql);
    return mysqli_num_rows($result);
}

$db = new MysqliDb();
?>

        id
        nombre
        apellido
        idCarrera

    <?php
        $num = $db->numRows("SELECT * FROM `alumno`");
        while(.......){

            $id= $num ["id"];
            $nom= $num ["nombre"];
            $ape= $num ["apellido"];
            $idcar= $num ["idCarrera"]
    ?>

                <?php echo $id; ?>

                <?php echo $nom; ?>

                <?php echo $ape; ?>

                <?php echo $idcar; ?>

        <?php

        }
        ?>

<?php

A: La solución pasa por cerrar primero la clase (error tipográfico) agregando un cierre de llave } antes de esta línea:
$db = new MysqliDb();

y después cambiar esto:
$num = $db->numRows("SELECT * FROM `alumno`");
while(.......){

por esto:
$items = $db->executeQuery("SELECT * FROM `alumno`");
foreach($items as $num) {

pues el numRows() de esa clase poco nos importa para recorrer los datos, es más cómodo con un foreach() aprovechando que el método executeQuery() de la clase nos devuelve un array con los datos.


text:
Q: Store/retrieve image in Artifactory using cURL I am using cURL to PUT image files to an Artifactory server, like so:
curl -u "username:pwd" -X PUT \
-F 'imageX=@/Users/me/my-images/cat.jpeg' \
http://maven.nabisco.com/artifactory/cdt-repo/folder/my-unique-file

When I download the file from the server, it looks like:
--------------------------7c3eb0ea54288120
Content-Disposition: form-data; name="image"; filename="cat_cat_cat.jpeg"
Content-Type: image/jpeg

ˇÿˇ‡JFIFˇ€Ñ ( %!1"%)+...383-7(-.+
...yadda yadda yadda

so as far as I can tell, it's saving all of the form data onto the Artifactory server, not just the one file in the form data.
So three questions -
(a) is there some way to tell the server to just store the raw data from the one file in the form data?
(b) if I download the data from server, using cURL, is there some way to extract the image data from the form data, if I know the key of the form (in this case the key is "imageX")?
(c) is there a way to write a file with cURL without using form-data?

A: If I understand you correctly, all you want to do is deploy an image and resolve it later on.
You can upload any file, without specifying the type of the file. in your scenario the command can even be more simple by using '-T' for sending the file, and using this you don't have to add the file name at the end of the Artifactory URL. It will take the name of the origin file:
curl -u "username:pwd" -T /Users/me/my-images/cat.jpeg "http://maven.nabisco.com/artifactory/cdt-repo/folder/"
Regarding the resolution of the file, all you need to do is:
curl -u "username:pwd" "http://maven.nabisco.com/artifactory/cdt-repo/folder/cat.jpeg" -O
(Adding the '-O' at the end will make sure that cURL will save the file as it is named on the remote server)


text:
Q: Poor results from matching against key points and descriptors in OpenCV Python using FAST, BRIEF and FLANN I'm trying to write a scale and rotation insensitive pattern matcher using a key point approach but I'm struggling to get good results even without changes in scale and rotation.
I'd like to avoid SIFT and SURF if possible as I'd prefer the approach to be patent free.  I've experimented with FAST and ORB and have found that FAST seems to be picking up suitable key points.  I've then used Brief to extract the descriptors for those points and fed those descriptors into a FLANN pattern matcher (I also tried Brute Force).  Despite the template image coming from the same image the search is being conducted on, the results are terrible.  Using matchTemplate works well.
This is the code I'm using:
import cv2 as cv
import numpy as np
from matplotlib import pyplot as plt

directory = "C:\\Users\\MickeyCrozier\\Documents\\Digital Microscope\\Default\\Picture\\"
image = "1.bmp"
tmplImage = "tmpl1.bmp"

img = cv.imread(directory+image,flags = cv.IMREAD_GRAYSCALE)
template = cv.imread(directory+tmplImage,flags = cv.IMREAD_GRAYSCALE)

fast = cv.FastFeatureDetector_create()
fast.setNonmaxSuppression(0)
kp1 = fast.detect(img,None)
kp2 = fast.detect(template,None)

brief = cv.xfeatures2d.BriefDescriptorExtractor_create()

kp1, d1 = brief.compute(img,kp1)
kp2, d2 = brief.compute(img,kp2)

d1 = np.float32(d1)
d2 = np.float32(d2)

output = cv.drawKeypoints(img, kp1, -1, (255,0,0))
cv.imshow('Original',output)
cv.waitKey(0)

output = cv.drawKeypoints(template, kp2, -1, (255,0,0))
cv.imshow('Original',output)
cv.waitKey(0)

matcher = cv.FlannBasedMatcher()
knn_matches = matcher.knnMatch(d1, d2, 2)

#-- Filter matches using the Lowe's ratio test
ratio_thresh = 0.8
good_matches = []
for m,n in knn_matches:
    if m.distance < ratio_thresh * n.distance:
        good_matches.append(m)

print(good_matches)

output = cv.drawMatches(img,
                        kp1,
                        template,
                        kp2,
                        good_matches,None,
                        flags = cv.DrawMatchesFlags_NOT_DRAW_SINGLE_POINTS)

cv.imshow('Original',output)
cv.waitKey(0)

Here are the results of the key points and match:

Any idea how to improve the match results?


text:
Q: Regular Expression for "AND"? Let's say I gave you the following text:
allow_httpd_anon_write --> off
allow_httpd_mod_auth_ntlm_winbind --> off
allow_httpd_mod_auth_pam --> off
allow_httpd_sys_script_anon_write --> off
httpd_builtin_scripting --> on
httpd_can_check_spam --> off
httpd_can_network_connect --> off
httpd_can_network_connect_cobbler --> off
httpd_can_network_connect_db --> off
httpd_can_network_memcache --> off
httpd_can_network_relay --> off
httpd_can_sendmail --> off
httpd_dbus_avahi --> on
httpd_enable_cgi --> on
httpd_enable_ftp_server --> off
httpd_enable_homedirs --> on
httpd_execmem --> off
httpd_read_user_content --> off
httpd_setrlimit --> off
httpd_ssi_exec --> off
httpd_tmp_exec --> off
httpd_tty_comm --> on
httpd_unified --> on
httpd_use_cifs --> off
httpd_use_gpg --> off
httpd_use_nfs --> off

What I want to do is create a regular expression that can parse text like this looking for two or more words on the same line.  For example, if I was looking for a SELinux boolean that covered "ftp" AND "home" on the same line, I would currently do the following:
getsebool -a | grep -i ftp | grep -i home

However, I am looking for a regular expression that does the same thing.  Specifically, find all of the words in any order on a line...

A: You could also use awk instead.  With awk you can easily use Boolean constructs.
getsebool -a | awk '/ftp/ && /home/ {print}'
# case insensitive
getsebool -a | awk 'tolower($0)~/ftp/ && tolower($0)~/home/ {print}'

A: Maybe something like
getsebool -a | egrep -i ".*(ftp.*home|home.*ftp).*"

would work for you?


text:
Q: Have mathematical structures equipped with "generalized relations" been considered in a systematic way? A binary relation on $X$ is basically just a function $X^2 \rightarrow \mathbb{B}$, where $\mathbb{B}$ is the prototypical Boolean algebra $\{0,1\}.$ We can generalize by replacing $\mathbb{B}$ with a more complicated partially ordered structure. Thus, we have:
Heuristic idea. A generalized relation on $X$ is a function $X^n \rightarrow P$, where $P$ is a partially ordered set possibly having additional structure.
For example, a metric space can be viewed as set $X$ equipped with a generalized relation $d : X^2 \rightarrow [0,\infty)$ satisfying the usual axioms.
Question. Have mathematical structures equipped with generalized relations been considered in a systematic way? A reference would be nice.

Discussion. Here's the example I am most interested in.
Suppose $X$ and $Y$ are sets, and that $R$ is a binary relation on $Y$. That is, $R$ is a function $Y \times Y \rightarrow \mathbb{B}$. Then the family $Y^X$ can naturally be equipped with a generalized binary relation $R' : Y^X \times Y^X \rightarrow \mathbb{B}^X$ defined by asserting that $R'(f,g)$ equals the characteristic function of
$$\{x \in X \mid R(f(x),g(x))\}.$$
Anyway, the point is that if $\mathcal{Y} = (Y,R)$ is a relational structure, then really $\mathcal{Y}^X$ is most naturally viewed as equipped not with a relation $R'$ having codomain $\mathbb{B}$, but rather a generalized relation having codomain $\mathbb{B}^X.$ We might call such a beast a "generalized relational structure."
Metric spaces presumably undergo a similar generalization, although I'm still trying to work out the details.

A: I've thought about that idea as well.  I don't think that there's a systematic theory along those lines.  This might mean that there's nothing to be said in full generality.  A single generalized relation is the same as a family of relations $P_i$ such that $P_i \implies P_j$ for $i \leq j$, so in some sense you don't get anything new.
You do see applications of the idea around mathematics.  Lord Farin already mentioned Boolean-valued and Heyting-valued models.  Another variant comes from theoretical computer science, and goes by the name domain theory.  Computable functions are modeled as functions on a partially-ordered set.  Functions higher in the partial order are "more defined" than functions lower.
For the specific application of metric spaces, there has been some development along the lines you have in mind.  Look for "Lawvere metric spaces".  The idea is expressed in category-theoretic language, but the underlying notion is the same as what you have in mind.


text:
Q: how to change ionic text colors when some condition occur in my ionic project i want some conditional colors for text.
that is ,i receive a data from API, if it is " Landed" the text want to display in Green color, if "Cancelled" the text want to display in red color.how to possible.
Arrival.ts
export class ArrivalsPage {
  objectData: any = [];
.................
...................
  }
  get_arrivalflights() {
    var communicationParams = {
      showLoader: true,
      reqUrl: "",
      reqBody: {},
      callBackSuccess: (response) => {
        console.log(response);
        this.objectData = response.flightStatuses;

        //this.publishedDeparture = response.flightStatuses.operationalTimes;
      },
      callBackFailure: (response) => { console.log("failure dude"); console.log(response); }
    };
    this.restservice.makeGetRequest(communicationParams);
  }

Arrival.html
  <ion-card *ngFor= "let item of objectData" (click)="goToArrivalflightDetails(item,item.operationalTimes.publishedArrival.dateLocal,item.operationalTimes.actualRunwayArrival.dateLocal,item.airportResources.departureTerminal);">

    <ion-card-content>

{{item.departureAirportFsCode}}

{{item.carrierFsCode}}{{item.flightNumber}}

{{item.status | statusupdator}}

    </ion-card-content>

  </ion-card>

statusupdator is pipe:
@Pipe({
  name: 'statusupdator'
})
export class StatusUpdater {
  transform(value, args) {
    let status=value;
    if(value=='L')
    {
      status='Landed'
    }
    if(value=='A')
    {
      status='Estimated'
    }
    if(value=='C')
    {
      status='Cancelled'
    }
    if(value=='S')
    {
      status='Scheduled'
    }
    if(value=='U') {
      status = 'Unknown'

    }
    return status;
  }

in this code i want to display
{{item.status | statusupdator}}

in colors when item.status will occur the condition.

A: Ok! Try this way.
Arrival.html
<ion-card *ngFor="let item of objectData" (click)="goToArrivalflightDetails(item,item.operationalTimes.publishedArrival.dateLocal,item.operationalTimes.actualRunwayArrival.dateLocal,item.airportResources.departureTerminal);">
        <ion-card-content>

{{item.departureAirportFsCode}}

{{item.carrierFsCode}}{{item.flightNumber}}

{{item.status | statusupdator}}

        </ion-card-content>
    </ion-card>

Inside you scss
page-example{
  .L {
    color: green;
  }
  .C {
    color: red;
  }
}

Let me know if having any problem. :)


text:
Q: How can I add loading view at Launching time? I'm using storyboard to develop my app, and the initial view controller is a Tab Bar Controller. At the AppDelegate I did some thing work to get the jsonData from my website. It will take 10-20 seconds . You know, I want to do something to notice user is loading, not just showing a default.png picture. How can I do it?

A: Well, you can have your rootViewController have a loading state (maybe an UIActivityIndicatorView on top of the other views and some public methods like showLoading and hideLoading.
Steps :

*

*In the AppDelegate application:didFinishLaunchingWithOptions: method, build your rootView controller as usual and call your method that loads the JSON files.

*Call the showLoading method when you're starting the request

*Call the hideLoading method when you receive the response.

Also, remember to use asynchronous request or make it in a different thread to prevent blocking the main thread.


text:
Q: Call a java Rest webservice on email event I have a webservice x exposed.If I get a mail in my email containing attachment I want to call
this webservice.I am not asking for code.I am asking your suggestion in high level how this can be done?

A: *

*You need REST. So - you cant use org.apache.http.client library. (Other way, if you'll have web service you can use wsimport to create WebService java-client.)

*Use javax.mail library to open mailbox and iterate letters.

*Process letters. Mark or delete processed letters.

*Add crontab/sheduler task to run your app. (As for me, It's better, than create a thread app). Dont forget to use run-one option to prevent double execution.

Here some code example that reads "*.xls" files from mailbox messages:
    public void processEmail() throws MessagingException {

    Store emailStore = null;
    Folder emailFolder = null;

    try {
        // connecting
        Properties properties = new Properties();
        properties.setProperty("mail.store.protocol", "imaps");
        Session emailSession = Session.getDefaultInstance(properties);

        Main.getLog().debug("CONNECT TO : " + config.mailServer + " ["
                + config.mailUser + "] DEBUG: "+config.debug);

        // check mailbox
        emailStore = emailSession.getStore("imaps");
        emailStore.connect(config.mailServer, config.mailUser,
                config.mailPassword);
        Main.getLog().debug("CONNECT DONE");

        emailFolder = emailStore.getFolder("INBOX");
        emailFolder.open(Folder.READ_WRITE);

        Message[] messages = emailFolder.getMessages();
        Main.getLog().debug("RECEIVED " + messages.length + " MESSAGSES");

        // for each letter
        for (Message message : messages) {
            try {
                Main.getLog().debug("\nPROCESS LETTER : "
                        + message.getSubject());
                if (message.getFlags().contains(Flags.Flag.DELETED)) {
                    continue; // don't process such letters
                }

                if (message.getFlags().contains(Flags.Flag.SEEN)) {
                    continue; // don't process such letters
                }
                //
                Map<String, String> parseResult = new HashMap<String, String>();
                String auditId = "";

                // get file
                if (message.getContent() instanceof Multipart) {
                    Multipart multipart = (Multipart) message.getContent();
                    for (int i = 0; i < multipart.getCount(); i++) {
                        BodyPart bodyPart = multipart.getBodyPart(i);
                        if (!Part.ATTACHMENT.equalsIgnoreCase(bodyPart
                                .getDisposition())) {
                            continue;
                        }
                        // Process file
                        if (bodyPart.getFileName().contains(".xls")) {
                            auditId = maintainExcelFile(bodyPart.getInputStream());
                        }
                    }
                } else if (message.getContent() instanceof BASE64DecoderStream) {
                    // Process file
                    if (message.getFileName().contains(".xls")) {
                        auditId = maintainExcelFile(((BASE64DecoderStream) message
                                .getContent()));
                    }
                }
                if (!config.debug && auditId!=null && !auditId.equals("")) {
                    message.setFlag(Flags.Flag.SEEN, true);
                }
                if (!config.debug) {
                    sendAcceptMail(message, auditId);
                }
            } catch (Exception e) {
                // Process errors
                if (!config.debug) {
                    message.setFlag(Flags.Flag.SEEN, true);
                    sendErrorMail(message, e);
                }
                Main.getLog().error(e.getMessage(), e);
                throw new Exception(e);
            }
        }
    } catch (Exception e) {
        Main.getLog().error(e.getMessage(), e);
    } finally {
        emailFolder.close(true);
        emailStore.close();
    }
}


text:
Q: Most reliable way to detect when element overflows print width I have a <table> where users customize the number of elements, font, and font size, and users often print the table.  If the table is too wide to fit on a single printed page, some columns get cut off and the user may not realize until later, at which point the user is upset.
Is there a good way to detect when the table overflows the print width so I can warn the user?  I know that the proper answer is "web browsers were not designed for printing, you can't do that", so I'm happy with a hack.  Right now I use jQuery outerWidth() to see if the width is greater than 700px.  Is there a better way?

A: The best way is to use a media print css style sheet where you specify the max width of the table, and make sure that you use table-layout:fixed;. Additionally you can set word-wrap in such a way that everything breaks nicely when you deal with large input.
@media print {
    html{
        width: 100%;
        max-width: 700px;
    }
    .toprinttable {
        font-size: 11px;
        max-width: 700px;
        border: 0;
        table-layout:fixed; /*This is important*/
        word-wrap:break-word;
        border-collapse:collapse;
    }
}


text:
Q: convergence radius of two specific power series I did two calculations that I think are wrong but I am not sure why.
I have to compute the convergence radius of the following power series
a) $\sum_0^{\infty} \ln(k!)x^k$,
b) $\sum_0^{\infty} k8^kx^{3k}$.
Here's my attempt:
a)
$$ \limsup_{k \rightarrow \infty} \sqrt[k]{a_k} = \limsup_{k \rightarrow \infty} \sqrt[k]{\ln(k!)} = \ln (\limsup_{k \rightarrow \infty} \sqrt[k]{k!})= \infty. $$
Therefore the convergence radius should be $0$ and the series only converges for the value $x=0$. Unfortunately, Wolfram alpha gives me another answer. Where's the mistake ?
b)
$$ \limsup_{k \rightarrow \infty} \sqrt[k]{a_k} = \limsup_{k \rightarrow \infty} \sqrt[k]{k8^k} = \limsup_{k \rightarrow \infty} \sqrt[k]{k} \sqrt[k]{8^k} = 8 \limsup_{k \rightarrow \infty} \sqrt[k]{k} = 8. $$
I would now conclude that the convergence radius is $\frac{1}{8}$, but it appears to be $\frac{1}{2}$, what did I miss ?
Thank you for your help.

A: Answer for b). What you have calculated is the radius of convergence of $\sum k8^{x}x^{k}$. The given series is convergent if $|x^{3}| < \frac 1 8$ and divergent for $|x^{3}| >\frac 1 8$. Can you see from this that the radius of convergence is $\frac 1 2$?.
Part a). It is not true that $(k!)^{1/k} \to \infty$ as $k \to \infty$. Use Stirling's approximation for this part.

A: For a) you have made the error of assume the log and the exponent commute. That is $$\ln \sqrt[k]{k!} \ne \sqrt[k]{ \ln k!}$$ and hence $$ \limsup_{k \to \infty} \sqrt[k]{ \ln k!} \ne \ln \left( \limsup_{n \to \infty} \sqrt[k]{k!} \right)$$
I have to disagree with the other answer on how to evaluate this limit (after the error). Using Stirling's approximation gives $$ \sqrt[k]{k!} \sim \sqrt[k]{ \sqrt{2 \pi k} \left( \frac{k}{e} \right)^k } = \left(2 \pi k \right)^{\frac{1}{2k}} \frac{k}{e} \to \infty$$
Of course the actual problem was the one I pointed out before. Here's how I would attack it.
$$\lim_{k \to \infty} \sqrt[k]{ \ln k!}=\lim_{k \to \infty} \frac{ \ln (k+1)!}{\ln (k!)}=\lim_{k \to \infty} \frac{\sum_{j=0}^{k+1} \ln j}{\sum_{j=0}^{k} \ln j}=\lim_{k \to \infty} \frac{\ln (k+1)}{\ln k}=1$$ Note I used the Stolz–Cesàro theorem in the third equality.
I agree with the other answer for (b). You missed the $3k$ in the exponent


text:
Q: Phusion Passenger fails to compile on CentOS I'm trying to install Phusion passenger (aka mod_rails) for the default Apache2 install on a CentOS 5.9 box.  I successfully installed the gem using the following, sudo gem install passenger but when I go to run the next command, sudo passenger-install-apache2-module I get a warning stating that my system doesn't have enough memory, but I can continue with the install.  It then proceeds to begin the compile of Phusion Passenger but then fails.
Is there a place I can check to see specifically why the compile is failing?

A: The reason Phusion Passenger would not compile was due to lack of memory on the VPS.  I ended up creating a VM on my local machine, and installing all the same components, then compiling passenger on the VM, finally transferring the passenger gem to the VPS.


text:
Q: Slow Router Speeds I've been encountering a weird issue with routers in my house where the wired speeds slow down to around 50mb/s instead of the 500-600mb/s I get when directly connected . This first happened on a ~5 year old Airport Extreme which I just chalked up to random failure, but I've since had the same thing happen with a Netgear AC1600 and I'm trying to figure out what might be happening.
Our ISP provides an ONT modem but in the closet - so I have two switches setup with VLANs so that I can have my router in the living room as below . We use a ton of data each day (60GB / day at peak), so I don't know if these routers are just underpowered and eventually fry themselves somehow.
Any ideas on what might be happening?

A: Ended up figuring out that a firmware update to my modem caused the issue (thanks AT&T). It only affected machines set to receive the public IP which is why it wasn't more obvious.


text:
Q: how to retrive the BTLE peripherals when user manually quit app from background? Explanation :
I am connecting to BTLE peripheral using core bluetooth framework, saving the peripheral identifier in a database.At the same time, I am saving the peripherals in an array to handle reconnection with peripherals.But, when user manually quit the app, my array becomes empty. due to which I won't be able to reconnect those peripherals again.
Now, I have peripherals identifiers in my database. I have read about it and found that there is a delegate method
- (NSArray<CBPeripheral *> *)retrievePeripheralsWithIdentifiers:(NSArray<NSUUID *> *)identifiers NS_AVAILABLE(NA, 7_0)

To get the peripherals but it returns nothing.How I can get the peripherals again?
https://developer.apple.com/library/content/documentation//NetworkingInternetWeb/Conceptual/CoreBluetooth_concepts/BestPracticesForInteractingWithARemotePeripheralDevice/BestPracticesForInteractingWithA
I also check above document. In that they mentioned about the methods to reconnect to the peripherals
Retrieving a List of Known Peripherals

The first time you discover a peripheral, the system generates an identifier (a UUID, represented by an NSUUID object) to identify the peripheral. You can then store this identifier (using, for instance, the resources of the NSUserDefaults class), and later use it to try to reconnect to the peripheral using the retrievePeripheralsWithIdentifiers: method of the CBCentralManager class. The following describes one way to use this method to reconnect to a peripheral you've previously connected to.

When your app launches, call the retrievePeripheralsWithIdentifiers: method, passing in an array containing the identifiers of the peripherals you've previously discovered and connected to (and whose identifiers you have saved), like this:

    knownPeripherals =
        [myCentralManager retrievePeripheralsWithIdentifiers:savedIdentifiers];
The central manager tries to match the identifiers you provided to the identifiers of previously discovered peripherals and returns the results as an array of CBPeripheral objects. If no matches are found, the array is empty and you should try one of the other two reconnection options. If the array is not empty, let the user select (in the UI) which peripheral to try to reconnect to.

When the user selects a peripheral, try to connect to it by calling the connectPeripheral:options: method of the CBCentralManager class. If the peripheral device is still available to be connected to, the central manager calls the centralManager:didConnectPeripheral: method of its delegate object and the peripheral device is successfully reconnected.

Note: A peripheral device may not be available to be connected to for a few reasons. For instance, the device may not be in the vicinity of the central. In addition, some Bluetooth low energy devices use a random device address that changes periodically. Therefore, even if the device is nearby, the address of the device may have changed since the last time it was discovered by the system, in which case the CBPeripheral object you are trying to connect to doesn't correspond to the actual peripheral device. If you cannot reconnect to the peripheral because its address has changed, you must rediscover it using the scanForPeripheralsWithServices:options: method.

A: On application startup I would just discover all the peripherals and then compare discovered peripherals with the peripheral identifiers stored in the database.
After the comparison of the discovered peripherals and peripherals, the connections for desired peripherals can be made.


text:
Q: How can I reduce time to finish (For loop) to compare two Excel columns using C# as below code : in case rows count is more than 100 rows this code takes very long time sometimes more than hours , is there any other method to reduce the time ?
for (int i = 2; i < ws5.UsedRange.Rows.Count; i++)
{
    for (int n = 2; n < ws6.UsedRange.Rows.Count; n++)
    {
        if(Convert.ToDouble(ws5.Cells[i, 3].Value) == Convert.ToDouble(ws6.Cells[n, 3].Value)
            && Convert.ToString(ws5.Cells[i, 2].Value) == Convert.ToString(ws6.Cells[n, 2].Value))
        {
            ws5.Cells[i, 2].Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Orange);
            ws5.Cells[i, 3].Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Orange);
            ws6.Cells[n, 2].Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Orange);
            ws6.Cells[n, 3].Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Orange);
        }
        else if (Convert.ToDouble(ws5.Cells[i, 3].Value) != Convert.ToDouble(ws6.Cells[n, 3].Value)
            && Convert.ToString(ws5.Cells[i, 2].Value) == Convert.ToString(ws6.Cells[n, 2].Value))
        {
            ws5.Cells[i, 4].Value = Convert.ToDouble(ws6.Cells[n, 3].Value) - Convert.ToDouble(ws5.Cells[i, 3].Value) ;
            ws6.Cells[n, 4].Value = Convert.ToDouble(ws5.Cells[i, 3].Value) - Convert.ToDouble(ws6.Cells[n, 3].Value) ;

            ws5.Cells[i, 2].Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Yellow);
            ws5.Cells[i, 3].Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Yellow);
            ws6.Cells[n, 2].Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Yellow);
            ws6.Cells[n, 3].Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Yellow);

        }
        progressBar1.Value = (100 * i) / (ws5.UsedRange.Rows.Count);
    }
}

A: Not going into the details of what you are trying to acheive with excel, instead of doing the loop inside of another loop (that's O(n^2) time complexity), create a dictionary <string,money>, such that you can look up invoice amounts based on invoice numbers, and then go through the 2nd spreadsheet, checking if you have the same value(s) in your dictionary. That wasy you reduce time complexity to O(2n)


text:
Q: Error using C++/CLI dll in Azure function (zip deployed) So I have:

*

*a c++/cli wrapper withini a clr c++ dll

*a c# net6 azure function which is referencing the c++/cli project

The issue:

*

*It works perfectly when I'm testing it in local (with visual studio)

*When it's published (zip) on Azure I can call functions that don't use the c++/cli dll,
but when I'm calling (via Test/Run button) a function that use my c++/cli lib
I have this error code 500 Internal Server Error and this error message:
Could not load file or assembly 'C:\home\site\wwwroot\bin\MyCliDll.dll'. Format of the executable (.exe) or library (.dll) is invalid.
I have try a lot of different publishing configuration but non of them worked.
at this point I don't have any idea of what to change i order to make it works, is it a compatibility problem between my c++ and Azure ?
In case, here both of my setup:
<!--Publishing Setup-->
<Project>
  <PropertyGroup>
    <UserName>XXXXX</UserName>
    <WebPublishMethod>ZipDeploy</WebPublishMethod>
    <PublishProvider>AzureWebSite</PublishProvider>
    <LastUsedBuildConfiguration>Release</LastUsedBuildConfiguration>
    <LastUsedPlatform>x64</LastUsedPlatform>
    <SiteUrlToLaunchAfterPublish>XXXXXX</SiteUrlToLaunchAfterPublish>
    <LaunchSiteAfterPublish>false</LaunchSiteAfterPublish>
    <ResourceId>XXXXXXXX</ResourceId>
    <_SavePWD>true</_SavePWD>
    <PublishUrl>XXXXXXXX</PublishUrl>
    <TargetFramework>net6.0</TargetFramework>
    <SelfContained>false</SelfContained>
    <SkipExtraFilesOnServer>true</SkipExtraFilesOnServer>
  </PropertyGroup>
</Project>

<!--csproj-->
<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
      <TargetFramework>net6.0</TargetFramework>
    <AzureFunctionsVersion>v4</AzureFunctionsVersion>
    <OutputType>Library</OutputType>
    <_FunctionsSkipCleanOutput>true</_FunctionsSkipCleanOutput>
      <IncludeAllContentForSelfExtract>true</IncludeAllContentForSelfExtract>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Azure.Storage.Blobs" Version="12.11.0" />
    <PackageReference Include="Microsoft.NET.Sdk.Functions" Version="4.1.0" />
  </ItemGroup>
  <ItemGroup>
      <ProjectReference Include="..\..\MyCliDllProject\build\MyCliDll.vcxproj" />
  </ItemGroup>
  <ItemGroup>
    <None Update="host.json">
      <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
    </None>
    <None Update="local.settings.json">
      <CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
      <CopyToPublishDirectory>Never</CopyToPublishDirectory>
    </None>
  </ItemGroup>
</Project>

A: Ok I feel a bit dumb I just needed to go to the portal Azure in Configuration->General Settings->Platform and set it to 64 bit...


text:
Q: Differences between Facade Pattern and other patterns I have a question about patterns. I really have problems with design patterns. Can you tell me the differences between Facade Pattern and Builder, Factory and Abstract Factory patterns?

A: The facade pattern is used when you want to hide an implementation or otherwise make available a different interface externally.  The builder/factory pattern is used when you want to hide the details on constructing instances.

A: The Facade pattern abstracts details away from the developer and makes a certain portion of code easier to use.
The Builder pattern separates the construction of an object from its representation. That makes it possible to use the same construction process across multiple types.
The Factory and Abstract Factory both deal with instantiating a related set of classes based on certain parameters used when the call to the Factory is made.

A: Those and also other patterns might often look quite similar. The difference is in the design decisions you made to use a pattern.
Facade is about changing the interface of some class or set of classes. Builder hides the process of construction by decomposing it in smaller steps. Factories are about hiding the concrete implementation or instantiation of an object or object graph.
The confusion might come from the fact that often Builder in a way changes the interface of an object to allow a better way of construction, which could be also done by a Facade. It is similar with Factories.
So don't forget about small differences in the implementations of those patterns and that the most important part about design patterns are the design decisions you make.


text:
Q: Determining if this collection of sets is a topology on the real numbers? Let $\tau$ consist of $\mathbb{R}$, $\emptyset$ and every interval $[-r, r]$, for $r$ any positive irrational number.
i) $\mathbb{R}, \emptyset$ are in $\tau$
ii) $[-r_1, r_1] \bigcup [-r_2, r_2] \bigcup ... = [-r_k, r_k]$ where $r_k =$ max$\{r_i\}, i = 1, 2, ...$
iii) $[-r_1, r_1] \bigcap [-r_2, r_2] = [-r_k, r_k]$ where $r_k =$ min$\{r_1, r_2\}$
But I have a feeling this is wrong as I have read somewhere that this is not a topology. So what am I missing?

A: Hint:
Consider a sequence of irrational numbers $r_i$ monotonically increasing and with limit $1$.
What is $\bigcup_{i\to\infty}[-r_i,r_i]$?


text:
Q: Using jQuery DataTables and yadcf I want to display a sortable/filterable table of data using the jQuery yadcf plugin, that runs with DataTables.
First thing I did is the DataTables integration, that can be seen on this page
This first step works fine, so I went on to the next step.
I then set up another page with exactly the same HTML/PHP and Datatables code, but adding the enqueue of the yadcf script+css, I can see several issues:

*

*column 0: the search works only on the first line (the link) of each row, though with DataTables alone both lines are searched

*using the filter of any column displays the expected result, but the controls immediately disappear, so it is not possible to add another filter, or clear the existing one.

*same behaviour when one clicks on any "clear filter" button

*some filter types are not recognized: range_number_slider is not displayed properly and select2 provokes an error as select2 is not a defined function; but I've no idea how to integrate the missing functions.

*all the controls / messages and such remain in english, and I don't know how /where to translate them

*column 0 "autocomplete" results in an ugly display, as the helper message is inserted at the beginning of 1st row, propelling the following columns further on the right.

Currently, my js file is the following:
jQuery(function() {
    jQuery(document).ready(function() {
        'use_strict';

        var oTable;

        oTable = jQuery('#hebergements').DataTable({
            "columns": [
                null,
                null,
                null,
                null,
                null,
                { "bFilter": false, "bSort": false},
                { "bFilter": false, "bSort": false},
                { "bFilter": false, "bSort": false},
                { "bFilter": false, "bSort": false},
            ],
            "language": {
                "processing": "Préparation des données ...",
                "lengthMenu": "_MENU_ hébergements par page",
                "zeroRecords": "Désolé, aucun hébergement avec ces critères",
                "info": "_PAGE_ / _PAGES_",
                "infoEmpty": "Aucun enregistrement disponible",
                "infoFiltered": "<span>- (filtre à partir de _MAX_ hébergements)</span>",
                "search": "recherche",
                "paginate": {
                    "first":    "premier",
                    "previous": "précédent",
                    "next":     "suivant",
                    "last":     "dernier"
                }
            },
            "sScrollX": "100%",
            "sScrollXInner": "200%",
            "bJQueryUI": true,
            "bstateSave": true
        });

        yadcf.init(oTable, [
            { column_number: 0,
                column_data_type: "html",
                html_data_type: "text",
                filter_type: "auto_complete"
            },
            { column_number: 1,
                column_data_type: "html",
                html_data_type: "text"
            },
            { column_number: 2,
                column_data_type: "html",
                html_data_type: "text"
            },
            { column_number: 3,
                column_data_type: "html",
                html_data_type: "text"
            },
            { column_number: 4,
                filter_type: "range_number_slider"
            }
        ]);

    } );
});

As these scripts will be used in an only page of the site, the enqueues have been put in the functions file:
function specific_scripts() {
    if ( !is_admin() )
        if (is_page( array(932, 934 ) ) ) {
            wp_enqueue_script('datatable', get_template_directory_uri() . '/js/jquery.dataTables.js', array('jquery'));
            wp_enqueue_script('liste-hebergements', get_template_directory_uri() . '/js/liste-hebergements.js', array('jquery', 'datatable'));
            wp_enqueue_style('liste-hebergements-style', get_template_directory_uri() . '/css/jquery.dataTables.css');
            wp_enqueue_style('liste-hebergements-style2', get_template_directory_uri() . '/css/jquery.dataTables_themeroller.css');

            if (is_page(934)) {
                wp_enqueue_script('yadcf', get_template_directory_uri() . '/js/jquery.dataTables.yadcf.js', array('datatable', 'jquery', 'jquery-ui-autocomplete', 'jquery-ui-slider'));
                wp_enqueue_style('liste-hebergements-style3', get_template_directory_uri() . '/css/jquery.dataTables.yadcf.css');
            }
        }
    }
}
add_action( 'wp_print_scripts', 'specific_scripts');

At this stage, I'm stuck and don't know how to proceed further.
Thanks for helping.


text:
Q: What language/API to use for a standalone live-input audio visualizer app? I develop with Actionscript and was glad to see that AIR 2.0 was going to give access to mic input data. I planned to use this to create a visualizer set to the tempo of the incoming live audio. After doing a few days of google research it seems unlikely that it will be possible to analyze the data of the mic input in Flash/AIR. If anyone has ideas on how I can achieve this in AIR please let me know. (I'm open to workarounds.)
That being said, I don't want to give up on the idea so I'm interested in suggestions for other language/API to use. My requirements for the app are:

*

*Run on OSX

*Two windows - one that can go fullscreen while the other(controller GUI) stays put

*Able to access live mic input data

I've done reading on FFT and understand what needs to be done on the sound side so no need to help with that.

A: I would recommend Processing.
It's a great language (it's java but with a lot of "help") and a very logical next step after programming in Actionscript. Processing has a great and helpful community and there are many tutorials and libraries available.
I've seen several processing applications which do what you describe. Most can be found on the openprocessing site or in the exhibition section.
Also see the available sound libraries.
From the processing site:

Processing is a programming language,
  development environment, and online
  community that since 2001 has promoted
  software literacy within the visual
  arts. Initially created to serve as a
  software sketchbook and to teach
  fundamentals of computer programming
  within a visual context, Processing
  quickly developed into a tool for
  creating finished professional work as
  well.

If you want to give it a quick glance, just download it and open and run the bundled examples.


text:
Q: How can I get the top N solutions to a bin packing algorithm? I'm trying to find/create algorithm to pack bins and return back the top N solutions, not the "most" optimal one only.
Normal bin-packing is pretty straightforward, but it seems I need to add some type of algorithm over the top of it to try different configurations.
example. I have a list of items with varying sizes from 0.5 to 7.5 and need to figure out the top 5 solutions for bins that have a capacity of 20. Goal is minimal amount of bins.
results:

*

*7 bins, [x7 bin descriptions, with waste count]

*7 bins, [x7 bin descriptions, with waste count]

*8 bins, [x8 bin descriptions, with
waste count]

*8 bins, [x8 bin descriptions, with waste count]

*8 bins, [x8 bin descriptions, with waste count]


text:
Q: Lazy @ModelAttribute in Spring MVC Is there such thing like lazy model attrubute annotation in spring?
below peace of code to explain what im looking for
@Controller
class MyController {
    private boolean hasValue=false;

@RequestMapping(value "test.html")
public String testMEthod(ModelMap model, @RequestParam(value = "person", defaultValue = "null") Person person)
    person==null ? false : true;
    return "testResults";
}

@ModelAttribute("hasValue")
public boolean hasValue(){
     return hasValue;
}

code above will always put false to model, because all @ModelAttribute are executed before calling any @RequestMapping. To work, it would need force to put hasValue to model after method called from request mapping.

A: With the default @ModelAttribute annotation, like you have mentioned the @ModelAttribute methods will get evaluated before the @RequestMapping annotated methods. Probably two ways to do it lazily would be the following:
a. Explicit, have a method which sets your model attributes post method call, call it from your @RequestMapping methods:
public void setLazyModelAttribs(Model model){
     model.addAttribute("hasValue", hasValue);
}

@RequestMapping
public void testMethod(..Model model, ...){
    //normal request mapping
    setLazyModelAttribs(model);
}

b. Doing it using after aspectj advice.


text:
Q: Regex and taking care of possible whitespace I need help with my regex expression. I am trying to match keyword this but only when it is in parenthesis (this). So far I have:
(\()\bthis\b(\))

But looks like it also matches the parenthesis wrapping the word, while I only need to grab the word itself. Another issue is that it won't work if there are whitespaces inside the parenthesis: ( this )

A: What about group matching with that kind of REGEXP expression:
\((this)\)

Also if you want to match when there are white spaces (spaces, tabs, etc.):
\(\s*(this)\s*\)

Try it out here : Regex101. All the details about each character I'm using in the regex are detailed on that site.
You can retrieve the this value matched in the group by code. Please, check out the documentation related to the language you're using for that.


text:
Q: Uninstalling program I have installed Xilinx ISE IDE following this tutorial: Install Xilinx Ise on the Ubuntu
and now I want to uninstall it but I have no idea how to do it cause there is no tutorial for this.

A: On terminal, go to:
/opt/folder you have installed Xilinx/.xinstall/bin/lin

or lin64, it depends on how you have installed it.
Then run this command:
sudo ./xsetup -uninstall

Hope it helps.

A: I am writing a solution since the one by Andreea D has a typo and I cannot comment.

*

*Navigate to the folder where Xilinx is installed. In my case it was in /tools/Xilinx/

*Then enter cd Xilinx/.xinstall/bin/lin

*Run sudo ./xsetup -Uninstall
Hope it helps somebody!


text:
Q: How to attach an object in J3d core, J3d util I have got a dynamically moving 3d object, say a cube. I intend to attach another object, say a sphere, on one side of this cube.
What I want is that as this cube (primary object) moves, the secondary object should move along with it, remaining totally attached/glued to it.
I am wondering if you could help.
Thank you

A: Conceptually it's simple, but given the few information in the question, the answer may sound vague: You have to attach them to the same transform group.
Some pseudocode with overly suggestive variable names here:
// The transform group that moves the cube
TransformGroup tgThatMovesTheCube = new TransformGroup();
tgThatMovesTheCube .addChild(new ColorCube(0.4));

// The transform group that "attaches" the sphere to the cube:
TransformGroup tgThatAttachesTheSphere = new TransformGroup();
tgThatAttachesTheSphere.addChild(new Sphere(...));

// The transform of this transform group: It is a transform
// that moves the sphere (from its original position) to
// one side of the cube (at its original position)
Transform3D attachingTransform = new Transform3D();
attachingTransform.setTranslation(new Vector3f(1,0,0));
tgThatAttachesTheSphere.setTransform(attachingTransform);

// Attach the transformed (!) sphere to the same TG as the cube:
tgThatMovesTheCube.addChild(tgThatAttachesTheSphere);

Now, changing the transform of the tgThatMovesTheCube will cause the cube and the sphere to move in the same way.
The relative placement of the sphere and the cube is only determined by the tgThatAttachesTheSphere, and if you do not change its transform, it will behave as if the sphere was "stuck" on the cube.


text:
Q: git ls-tree HEAD returns nothing and git mv returns not under version control I am using GIT under windows with the GIT Bash tool and was trying to move a file from one directory to the another.
I tried different methods like clean, commit again etc. but everytime I got a reply while using git mv that the said file is not under version control. However, git status -u shows that everything is OK.
After trying a lot I found the answer which I am going to answer myself.

A: I found out that the reason was a uppercase in the directory name. Well, GIT under Windows does not detect the difference in the case when looking for changed files through git status -u.
The file which I wanted to move was in a directory whose name was ABCD,  but the commited version was abcd. I dont know how the directory name changed to uppercase, but thats not the point here.
If you have such a constellation where the commmitted version differs from the checkout version with respect to the case of the directory name, git status -u  will never complain.


text:
Q: tcl analog of ruby REST request I have the following ruby code (from Codeacademy API course).
require 'open-uri'

# Open http://placekitten.com/ for reading on line 4!
kittens = open('http://placekitten.com')
body = kittens.read[559, 441]

# Add your puts statement below!

puts body

How to write it in tcl?

A: If I understand correctly, you just want to dump the document? If so, the following is the minimal code:
package require http
puts [http::data [http::geturl "http://placekitten.com"]]


text:
Q: Set JAVA_HOME for docker in NLTK for Stanford NLP I am a beginner in using Docker.
I'm using Docker toolbox for Windows 7 , i built an image for my python web app and everything works fine.
However, for this app, i use nltk module which also needs java and java_home setting to the java file.
When running on my computer, i can mannualy set the java_home, but how to do it in the dockerfile so that it wont get error when running on another machine.
Here is my error :

p.s : Answer below

A: When you are running a container you have the option of passing in environment variables that will be set in your container using the -e flag. This answer explains environment variables nicely: How do I pass environment variables to Docker containers?
docker container run -e JAVA_HOME='/path/to/java' <your image>
Make sure your image actually contains Java as well. You might want to look at something like the openjdk:8 image on docker hub.
It sounds like you need a docker file to build your image. Have a look at the ENV command documented here to set the JAVA_HOME var: https://docs.docker.com/engine/reference/builder/#env and then build your image with docker build /path/to/Dockerfile
I see you've already tried that and didn't have much luck.. run the container and instead of running your application process just run a bash script along the lines of echo $JAVA_HOME so you can at least verify that part is working.
Also make sure you copy in whatever files/binaries needed to the appropriate directories within the image in the docker file as noted below.

A: i finally found the way to install the java for dockerfile , it is use the java install commandline of ubuntu image.
Below is the docker file . Thanks for your reading.
RUN apt-get update
RUN apt-get install -y python-software-properties
RUN apt-get install -y software-properties-common
RUN add-apt-repository -y ppa:openjdk-r/ppa

RUN apt-get update
RUN apt-get install -y openjdk-8-jdk

ENV JAVA_HOME /usr/lib/jvm/java-8-openjdk-amd64/
RUN export JAVA_HOME