text:
Q: Prevent successive clicks bound on a div with jQuery I am playing with a slider script. In the script, left and right arrow wrapped in a div and click event bound over the div. It works no problem, but what I need when it clicked on the div, I need to prevent successive clicks for two seconds. Then it should be clickable again. I'd appreciate any advice.
$container.find('.laos-slider-controls').bind('click',function(){
  var target = $(this).attr('data-target');
  if(target!='next'&&target!='prev') target=parseInt(target);
  changeSlides(target);
});

HTML is :

‹

›

A: Use the unbind function in jQuery in combination with the setTimeout function
function SliderClickEvent(){
 var target = $(this).attr('data-target');
 if(target!='next'&&target!='prev') target=parseInt(target);
 changeSlides(target);

 //unbind the event
 $container.find('.laos-slider-controls').unbind('click');

 //Do a timeout and rebind the event
 setTimeout(function() {
            $container.find('.laos-slider-controls').bind('click',SliderClickEvent);
        }, 2000);
}

$container.find('.laos-slider-controls').bind('click',SliderClickEvent);

A: One possible solution is to use a flag variable isClickable and a Timeout to reset this flag variable after a specific time.
(function () {
    var isClickable = true;

    $container.find('.laos-slider-controls').bind('click',function(){
        if (isClickable) {
            var target = $(this).attr('data-target');
            if(target!='next'&&target!='prev') target=parseInt(target);
            changeSlides(target);

            isClickable = false;

            setTimeout(function () {
                isClickable = true;
            }, 2000);
        }
    });
})();

A: How about something like this:
var timeout;
var changeTheSlides = true;
$container.find('.laos-slider-controls').bind('click',function(){
  if(changeTheSlides) {
    var target = $(this).attr('data-target');
    if(target!='next'&&target!='prev') target=parseInt(target);
    changeSlides(target);

    timeout = setTimeout(function() {
        changeTheSlides = false;
    }, 2000); // 2sek timeout
    },
    function () {
      clearTimeout(timeout);
      changeTheSlides = true;
    });
  }
}

A: I think you can use two different techniques :

*

*On the click event, remove the Event Listener, then use setTimeout
to set it again.

*Use a global variable to store current time and
    check if a happened less than  s ago when the user clicks on your
    div

The problem with solution #1 is that if your user clicks a lot, it will become very uggly when it comes to performance. In addition, if he keeps clicking, the timer will be reset every time, and he will never see the next slide.
I think solution #2 is the better one here. You could implement it like so :
var time = 0;
var newTime;
$container.find('.laos-slider-controls').bind('click',function(){
  newTime = new Date().getTime(); // current time in ms !
  if (newTime - time >= 2000){
      var target = $(this).attr('data-target');
      if(target!='next'&&target!='prev') target=parseInt(target);
      changeSlides(target);
      time = newTime;
  }
});

A: Two options come to mind, both using a timeout.
1) You could create a variable to act as a flag, set it to try on click, then have a setTimeout() that sets it back to false. Then, in your function, you check that flag, if true, you return false, so your click even never actually happens.
var clickFlag = false;

$container.find('.laos-slider-controls').bind('click',function(){
    if (clickFlag) {
        return false;
    }

    var target = $(this).attr('data-target');
    if(target!='next'&&target!='prev') target=parseInt(target);
    changeSlides(target);

    clickFlag = true;
    setTimeout(function() { clickFlag = false; }, 2000);
});

2) You could do something similar, except that instead of using a flag, you unbind the click event on the DIV, and rebind it on the 2 second timeout.
function BindSliderClick() {
    $container.find('.laos-slider-controls').bind('click', SliderClick);
}

function SliderClick(){
    var target = $(this).attr('data-target');
    if(target!='next'&&target!='prev') target=parseInt(target);
    changeSlides(target);

    $('.laos-slider-controls').unbind('click');
    setTimeout(BindSliderClick, 2000);
}

Personally, I would probably recommend the first option.


text:
Q: couchbase synchronous retrieval get API I have ran into a problem while dealing with bucket.get() API of the couchbase. I need to see, if some set of DocIDs are already stored in couchbase server or not, if not then I need to do some XML parsing.
var policy_bucket = cluster.openBucket('ss_policy_db');
function someFun(){
    for (var i = 0; i < Policies.length; i++) {
        var Profile = Policies[i];
        var polID = Profile.get('id');
        var ret = retrievePolicyNew(polID)
        // do some action on the basis of ret.
    }
}
function retrievePolicyNew(id) {
    var result = policy_bucket.get(id.toString()); // TypeError: Second argument needs to be an object or callback.
    console.log(result);
    // return -1, on if we find the ID.
}

The problem with bucket.get() is that, it is a asynchronous (not properly know how to make synchronous call), I don't want to handle callback for every ID search. Is their any other way to search the list of ID in couchbase. It would be great if someone can help me getting synchronous call API set, that will solve my lot of other problems also. Because it not looks very good to make very small search also and handling it in callback.
I have stored very less data in DB, so performance is not a issue here.

A: You should be able to use this in a synchronous manner.  I think either the code sample you provide above is incomplete and somewhere you're calling CouchbaseBucket.async() or something else.  In any case, the docs are pretty clear that get() takes a string and returns a JsonDocument

redpajama_set_name: RedPajamaStackExchange


text:
Q: Compass sprites: applying individual styles to every sprite class without writing out each sprite name manually I'm magic-importing my sprites:
// Creating a concatenated sprite image out of all sprites in the "/images/sprites/" folder
$sprites-layout:  vertical
@import           sprites/*.png

$sprites-sprite-dimensions: true  // Image width and height will be applied to all sprite classes

+all-sprites-sprites      // Generate all sprite classes

I would like to add custom styles to every sprite. I managed to add styles common to all sprites by declaring a class before magic-importing (magic import seems to extend this class for every sprite):
.sprites-sprite                   // This code will be applied to all sprite classes
  @extend         %inline-block

But I would also like to apply styles individual to each sprite. E. g. I would like to use min-width instead of width.
As a temprorary solution, I list all my sprite names manually:
=sprite-custom-styles($item)
  +sprites-sprite($item)
  padding-left: px(sprites-sprite-width($item) * 1.3)
  min-width:    sprites-sprite-width($item)

@each $item in foo, bar, baz, quux
  .sprites-#{$item}
    +sprite-custom-styles($item)

This is very burdensome, I would like to do this automatically.
Maybe magic importing creates a list of names that I can use? Or maybe I could define a mixin with a certain name that magic importing would call on every sprite class?

A: You can retrieve the list of names with the function sprite-names($map), like that:
@each $item in sprite-names($sprites-sprites)
  ...

Compass creates the sprite map $<map>-sprites after importing images (@import "<map>/*.png").


text:
Q: grep for a list of variables that are referenced by a script? I have some scripts that use various variables, and I want to grep (from within bash on FreeBSD) each of them for the list of variables that are used by the script. These are not shell scripts, but the syntax of referencing a variable is similar to that used in bash. Specifically, a reference to a variable can be like:

*

*$X, or

*${X}

and the name of the variable ("X" in this case) can include alphanumerics and underscores. At this point I want to explicitly note that I imagine that bash itself probably has a more complicated set of possible ways to reference variables, but if so, I do not care about that for the purposes of this question.
I would like to find all variable names that are so referenced in a given file - just the name, not the entire line. So something of the form awesomegrepcmd filename | sort | uniq, or something like that.
Note that there may be multiple different variables referenced on a single line.
I have been fighting regex and escaping rules via largely ignorant stab-in-the-dark attempts (e.g. "OK, maybe I need to put TWO backslashes here, but only ONE there") for a while now, and googling to try to find others who have done this sort of thing, but have thus far been unable to accomplish what I want. How can this be done? Thanks.
EDIT: Example: Let's say the content of a file is this (just pseudocode, not meant as bash or anything):
SPECIFICS={ "be born", "die", "plant", "reap", "kill", "heal", "laugh", "weep" }

CHORUS_PREFIX="To every thing"
CHORUS_INFIX="there is a season"
CHORUS_SUFFIX="and a time to every purpose under heaven."
CHORUS_SEPARATOR=", turn, turn, turn, "
CHORUS = $CHORUS_PREFIX + ${CHORUS_SEPARATOR} + $CHORUS_INFIX + $CHORUS_SEPARATOR + ${CHORUS_SUFFIX}

SPECIFIC_PREFIX="A time to "

UNUSED=${SOMETHING}

echo $CHORUS

foreach SPECIFIC in $SPECIFICS {
   echo $SPECIFIC_PREFIX + " " + ${SPECIFIC}
}

echo ${CHORUS}

Then the output I would want would be:
CHORUS
CHORUS_INFIX
CHORUS_PREFIX
CHORUS_SEPARATOR
CHORUS_SUFFIX
SOMETHING
SPECIFIC
SPECIFIC_PREFIX
SPECIFICS

A couple things to note:

*

*${CHORUS} and $CHORUS (for example) both refer to the same variable, named CHORUS

*The UNUSED variable is not in the output, because it is not actually used in the script (despite having been defined in it)

*The SOMETHING variable, used only to define the unused UNUSED variable, is in the output, since it was used

*The various CHORUS_xxx variables are only used in the one single line defining the CHORUS variable, but they are all present in the output.

A: Using an Extended regular expression:
me@lappy386:/tmp$ grep -Eoi '\$(\{[a-z0-9_]+\}|[a-z0-9_]+)' \
  /tmp/example |tr -d '{}$'|sort|uniq
CHORUS
CHORUS_INFIX
CHORUS_PREFIX
CHORUS_SEPARATOR
CHORUS_SUFFIX
SOMETHING
SPECIFIC
SPECIFIC_PREFIX
SPECIFICS

A: Using grep and sed
grep -oE '\$[A-Za-z_]+|\${[A-Za-z_]+}' inputFile|  sed -r 's/[${}]//g' | sort | uniq

Example :
$ grep -oE '\$[A-Za-z_]+|\${[A-Za-z_]+}' inputFile |  sed -r 's/[${}]//g' | sort | uniq
CHORUS
CHORUS_INFIX
CHORUS_PREFIX
CHORUS_SEPARATOR
CHORUS_SUFFIX
SOMETHING
SPECIFIC
SPECIFICS
SPECIFIC_PREFIX


text:
Q: How does this searching work in Perl? my ($len, $longest) =0;
length > $len and ($longest, $len)=($_, length) for @matches;

@matches stores some substrings. This code catches the longest substring from @matches, then stores it in $longest.
Source code:
#!usr/bin/perl

use strict;
use Data::Dumper;

my $needle = "axibidm";
my $haystack = "axididm";
my @matches;

for my $start (0..length $needle) {
for my $len (1 .. ((length $needle)-$start)) {
    my $substr = substr($needle, $start, $len);
       push @matches, $haystack =~ m[($substr)]g;
    print "$substr\t";
    print "@matches\t\n";
  }
}

my ($len, $longest) = 0;

length > $len and ($longest, $len) = ($_, length) for @matches;

print "The longest common substring between\n", $needle, "\nand\n", $haystack, "\nis '$longest'\n";

A: Someone was being far too clever, or they made a typo.  Or both.  Probably both.
There's some things going on with that code which don't do what it appears to be doing.  This does not initialize both variables to zero.
my ($len, $longest) = 0;

Its a deceptive way to write this.
my $len = 0;
my $longest;

for $matches is silly, there's only one thing to iterate over so why use a loop?  This idiom is very occasionally used to put the value into $_ and use it in various default constructs, but that's not much use here.
Next, the following is a very tortured way to write do this if that.  It's written that way to make it a single expression which will work within the for loop statement modifier.
length > $len and ($longest, $len)=($_, length)

It is much better written like this.
if( length > $len ) {
    $longest = $_;
    $len = length;
}

Expanding it out, and removing the useless for loop, we get...
my $len = 0;
my $longest;

if( length $match > $len ) {
    $longest = $match;
    $len = length $match;
}

The other option is that $matches is an array references and they meant for @$matches.  for $matches would still "work" but it would always return a length of 21 because an array reference stringifies as something like ARRAY(0x7fc07c800468).

A: That looks almost deliberately obfuscated. Here's a more verbose expression of the same logic.
my $len = 0;
my $longest;

foreach my $match (@matches) {
  if (length($match) > $len) {
    $longest = $match;
    $len = length($match);
  }
}

So let's compare.
my ($len, $longest) = 0;

This declares the two lexical (my) variables $len and $longest, and sets the first one ($len) to 0, leaving $longest at its default value of undef.
This structure:
 (code goes here) for @matches;

is the same as this:
 for (@matches) {
     (code goes here)
 }

So we're iterating over the @matches array and running the code once per element.  Within the body of the code, the special variable $_ will hold the current element.
length > $len and ($longest, $len) = ($_, length);

First, (expression) and (code) is a shorthand way of writing if ( (expression) ) { (code) }.  It works because in Perl, and is evaluated left-to-right in a short-circuiting fashion.  That is, if the left side expression is false, Perl doesn't bother evaluating the right side, since its value doesn't matter; false and anything is false.
When length is called without an argument, it means length($_), so that's the length of the current element of @matches that is being examined.
And ($var1, $var2) = ($val1, $val2) is parallel assignment that sets $var1 to $val1 and $var2 to $val2.

A: EXPR for LIST;

is roughly the same as
for (LIST) { EXPR; }

EXPR1 and EXPR2;

is roughly the same as
if (EXPR1) { EXPR2; }

(This is not a generally accepted practice, except when EXPR2 is a flow control expression (next, die, etc).)

length defaults to using $_ as its argument (length($_)).

( $x, $y ) = ( EXPR1, EXPR2 )

is roughly the same as
$x = EXPR1;
$y = EXPR2;

(One notable difference is that you can do ($x,$y)=($y,$x) to swap values, but that's used here.)
(Using a list assignment when two scalar assignments would do is also not a generally accepted practice.)

A more conventional way of writing the code would be:
my $len = 0;
my $longest;
for (@matches) {
   if (length($_) > $len) {
      $longest = $_;
      $len = length($_);
   }
}


text:
Q: How can you print 1 to 10 & 10 to 1 by using recursion with single variable I am preparing for my interview tomorrow -- I need the answer to this question:
How can you print 1 to 10 & 10 to 1 by using recursion with single variable

A: I'm going to get downvoted I just know it but here is (a) solution.  Not the best one but you should be able to make it better yourself.
class Program
{
    static void Main(string[] args)
    {
        printNumDown(10);
    }

    static void printNumDown(int num)
    {
        Console.WriteLine(num.ToString());
        if (num > 1)
            printNumDown(num - 1);
        else
            printNumUp(num + 1);
    }

    static void printNumUp(int num)
    {
        Console.WriteLine(num.ToString());
        if (num < 10)
            printNumUp(num + 1);
    }
}

A: You should be able to figure this out yourself.
Hint: Make a method that takes a 10 as a parameter, then prints the parameter and calls itself with 9.

A: Here's a sneaky way:
#include <stdio.h>

static void recur_up (int n) {
    if (n > 1)
        recur_up (n - 1);
    printf ("%d\n", n);
}

static void recur_down (int n) {
    printf ("%d\n", n);
    if (n > 1)
        recur_down (n - 1);
}

int main (void) {
    recur_up (10);
    recur_down (10);
    return 0;
}

which generates:
1
2
3
4
5
6
7
8
9
10
10
9
8
7
6
5
4
3
2
1

It would have been a lot more elegant going down then up since you could do that with a single function:
static void recur_both (int n) {
    printf ("%d\n", n);
    if (n > 1)
        recur_down (n - 1);
    printf ("%d\n", n);
}

A: Javascript version:
printNumber(1);

function printNumber(num){
  document.write(num);
  if (num < 10)
     printNumber(num + 1);
  document.write(num);
}

A: Why are you guys all being so difficult? In Pseudocode:
function recurfunc(n) {
    if (n < 10) {
    echo (-1 * (floor(abs(n)) - 10));
        recurfunc(n+1);
    }
}

Then call recurfunc with -9.5 as its start.
Seems kind of obvious to me that the answer is using absolute value.

A: void print_recursive(int n) {
    printf("%d\n", n);
    if (n < 10)
        print_recursive(n+1);
    printf("%d\n", n);
}

A: With one function and one variable only:
void recurs(int num) {
    printf("%d\n", num);
    if (num < 10) {
        recurs(num + 1);
    }
    printf("%d\n", num);
}

int main() {
    recurs(1);
    return 0;
}

A: Here's one in Ruby:
puts (r = ->n=1 { if n<=10 then [n] + r.(n+1) + [n] else [] end }).()

Note: before you conclude that Ruby is an unreadable mess even worse than Perl, let me assure you: this is not idiomatic Ruby. Idiomatic Ruby would be more like
def recursive_count_up_and_down(n=1)
  return [] unless n<=10
  [n] +
  recursive_count_up_and_down(n + 1) +
  [n]
end

puts recursive_count_up_and_down

Of course, Ruby is an imperative language, so doing it really idiomatically would not use recursion:
1.upto(10) do |i| puts i end
10.downto(1) do |i| puts i end

Here's another neat one that unfortunately doesn't use recursion, either:
puts Array.new(20) {|i| if i < 10 then i+1 else 20-i end }

BTW: all the solutions so far, including mine, are actually cheating, because technically they use two variables, because
function foo {}

is equivalent to
var foo = λ{}

So, in my example above, there are two variables: recursive_count_up_and_down and n. We could eliminate both of those by writing in a tacit point-free style (for example in the SK-calculus), but I'll leave that as an exercise to the reader. (Meaning I can't figure it out :-) )

A: #include<stdio.h>
void c(int n)
{
   static int i;
   if(i<n)
   {
     i++;
     printf("%d",i);
     c(n);
   }
}
int main()
{
  c(5);
}

A: import java.util.Scanner;
public class PrintNumberFrom1To10{
public static void printNumber(int num){

    if(num<=10){

    System.out.println(num);

    printNumber(num+1);

    }
}

public static void main(String[] args) {

    System.out.println("Enter Your Number: ");

    Scanner sc = new Scanner(System.in);

    int num = sc.nextInt();

    printNumber(num);

}

}


text:
Q: express. js findById with react if I would like to search for a post using (express. js, MongoDB ) findById, how can I do this with react

Block quote

A: You can create an API with express where create the search with MongoDB and return the data, after that, across from React you make the request


text:
Q: Using a logic table show $(P\rightarrow Q)\land(Q\rightarrow R)$ is logically equivalent to $(P\rightarrow R)$? How to show, using logic table:
$(P\rightarrow Q)\land(Q\rightarrow R)$ is logically equivalent to $(P\rightarrow R)$?
I had 8 rows, and found the truth values for $(P\rightarrow Q)$, $(Q\rightarrow R)$, $(P\rightarrow Q)\land(Q\rightarrow R)$, which lead to the truth values for $(P\rightarrow R)$. However, these values were not equivalent with $(P\rightarrow R)$ (their truth values were different even with the same truth values of $P, Q$, and $R$ )

A: They are not logically equivalent.  There is a logical implication, but it only goes one way.
$$\underbrace{(P\to Q ) \wedge (Q\to R)}_{\text{antecedant}} \;\implies\; \underbrace{(P\to R)}_{\text{consequent}}$$
Your truth table should show that the antecedent is true whenever the consequent is; but not necessarily the other way about.


text:
Q: Initializing an array in the constructor then executing it in the main method So I am trying to figure out how to create this constructor that allows me to make an array in within the constructor
public class knapsack {
    private int num[];

    knapsack(int [] numbers){
        this.num = numbers;
    }

now paying attention to the main file, I am trying to create an object that also allows me to use an array in it, like so:
public class main {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        knapsack newKnapsack = new newKnapsack({40, 10, 46, 23, 22, 16, 27, 6});

however, I keep running into issues with the knapsack newKnapsack = new Knapsack line. I am not sure if this is how you create a constructor to create an array and store it.
I am very new to java, so any help will be greatly appreciated!

A: When you are creating the object you are not calling to the constructor in here. Also the way you have created the array is wrong. This is the correct way to create it,
public class Knapsack {
    private int num[];

    Knapsack(int[] numbers) {
        this.num = numbers;
    }

    public static void main(String[] args) {
        Knapsack newKnapsack = new Knapsack(new int[]{40, 10, 46, 23, 22, 16, 27, 6});

        for (int i = 0; i < newKnapsack.num.length; i++) {
            System.out.println(newKnapsack.num[i]);
        }

        Knapsack.bestTwoValues(newKnapsack.num, 1); //you can access only static members by calling like this
        newKnapsack.bestTwoValues(newKnapsack.num, 1); //this way you can access both static and instance variables
    }

    static int bestTwoValues(int numbers[], int target) {
        //your code
        return 0;
    }
}

Also please try to follow camel notation when you writing code. So in here class name should be Knapsack instead of knapsack


text:
Q: Java SE 8.0 in server application I'm going to develop a long-term project, which should scan online news sites, crawl them and store their data in my own database for the further business logic. Since the further business logic will be implemented in Java, I consider implementing the crawling/gathering part in Java as well.
As far as I know, if there is a need to implement a webservice in Java that will constantly run on a server, I have to use Java EE instead of Java SE. But the problem is that Java EE is still 7.0 (till 2017) and lacks many great features, which came with the 8.0 release of Java SE.
Is there any way to use Java SE 8.0 features in my Java application, which runs on a server and monitors web pages or I have to use Java EE instead?

A: The good news is

*

*You don't have to use Java EE to build a Java service with Web endpoints

*You don't have to limit yourself to JDK 7 to use JEE 7

Alternatives to JEE for your use cases would include

*

*vert.x  : very fast asynchronous node.js style event loop for Java

*spring boot : automagically configures whatever you need from the Spring stack

*dropwizard (Jersey & Jetty microservices)

If you want to make use of Spring with Jersey Rest end points, you could also take a look at Microserver, a library we maintain @ Aol.
All of the options above can deploy and run as a single standalone app (no app server neccessary - if you want to use Tomcat / JBoss etc Spring MVC is anther alternative to JEE).


text:
Q: File deletion bypassing trash on OS Mavericks Deleting files in finder is now permanently deleting the files (i.e. basically doing  rm filename) and is not moving the items to trash. How do I fix this behavior? I like being able to undo my deletes.

A: Check what the permissions and owner for ~/.Trash/ are:
$ ls -led ~/.Trash
drwxr-xr-x  39 lauri  staff  1326 Apr 17 02:49 /Users/lauri/.Trash

If the owner is root, run sudo chown $USER ~/.Trash. If the permissions are for example dr-xr-xr-x instead of drwxr-xr-x, run chmod 755 ~/.Trash.


text:
Q: bad kerning of italics in beamer \documentclass{beamer}

\begin{document}
\begin{frame}
  ``Here is text that ends in \emph{italics!}''
  \bigskip

  ``Here is text that ends in \emph{italics!}\kern1.5pt''
\end{frame}
\end{document}

Is this a bug? Is there a better fix than manually adjusting the spacing around the inverted commas?

A: It's a "feature" due to how \emph is redefined in beamer. In beamerbaseoverlay we find
\newcommand<>{\emph}[1]{{\only#2{\itshape}#1}}

\mode
<article>
{
  \renewcommand<>{\emph}{\only#1{\beameroriginal\emph}}
}

which means that in presentation mode doing \emph{abc} is the same as {\itshape abc}, so the italic correction is not automatically added at the end. Quite strangely, the redefinitions of \textit and similar commands are
\mode
<all>
{
  \renewcommand<>{\textbf}{\only#1{\beameroriginal{\textbf}}}
  \renewcommand<>{\textit}{\only#1{\beameroriginal{\textit}}}
  \renewcommand<>{\textsl}{\only#1{\beameroriginal{\textsl}}}
  \renewcommand<>{\textsf}{\only#1{\beameroriginal{\textsf}}}
  \renewcommand<>{\textrm}{\only#1{\beameroriginal{\textrm}}}
}

There must be a reason for this difference, but I can think to none.
You have two choices: either use \textit or hack beamer into making it use a proper redefinition of \emph.
Here's an example:
\let\origemph\emph
\documentclass{beamer}

\renewcommand<>{\origemph}{\only#1{\beameroriginal{\origemph}}}

\begin{document}
\begin{frame}
``Here is text that ends in \emph{italics!}'' (\texttt{\string\emph})

\medskip

``Here is text that ends in \textit{italics!}'' (\texttt{\string\textit})

\medskip

``Here is text that ends in \origemph{italics!}'' (\texttt{\string\origemph})
\end{frame}
\end{document}

I used \origemph in order to show what happens: if I save the meaning of \emph before beamer enters into action and then use the same method as with \textit for redefining it, it works as expected. Indeed, note that \textit inserts the italic correction.

How could a hack for being able to type \emph and not \origemph in that way?
\documentclass{beamer}

% redefine \emph to be as in the kernel
\expandafter\def\expandafter\emph\expandafter{%
  \expandafter\protect\csname emph \endcsname
}
% now redefine it to be overlay aware
\renewcommand<>{\emph}{\only#1{\beameroriginal{\emph}}}

\begin{document}
\begin{frame}
``Here is text that ends in \emph{italics!}'' (\texttt{\string\emph})

\medskip

``Here is text that ends in \textit{italics!}'' (\texttt{\string\textit})
\end{frame}
\end{document}


text:
Q: Toolbar scrolls when I scrolling the window I am writing win32 program, and I have a window with a scroll bar, and now I added a toolbar.
My problem is, the toolbar is scrolls when I scrolling the window.
how do I set the toolbar to stand in his place, such as a menu?
This is an example of code that shows how the toolbar scrolls when scrolling the window, the code is not perfect, but it shows how the toolbar scroll when you sroll the window line up, or line down:
#include <windows.h>
#include <stdlib.h>
#include <CommCtrl.h>
#pragma comment(lib, "comctl32.lib")

LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);

HINSTANCE instance;

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow)
{
    instance = hInstance;

    WNDCLASSEX wcex;

    wcex.cbSize = sizeof(WNDCLASSEX);
    wcex.style           = CS_HREDRAW | CS_VREDRAW;
    wcex.lpfnWndProc    = WndProc;
    wcex.cbClsExtra     = 0;
    wcex.cbWndExtra     = 0;
    wcex.hInstance      = hInstance;
    wcex.hIcon          = LoadIcon(hInstance, MAKEINTRESOURCE(IDI_APPLICATION));
    wcex.hCursor        = LoadCursor(NULL, IDC_ARROW);
    wcex.hbrBackground  = (HBRUSH)(COLOR_WINDOW+1);
    wcex.lpszMenuName   = NULL;
    wcex.lpszClassName  = L"Example";
    wcex.hIconSm        = LoadIcon(wcex.hInstance, MAKEINTRESOURCE(IDI_APPLICATION));

    RegisterClassEx(&wcex);

    HWND hWnd = CreateWindow(L"Example", L"", WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT,
        500, 500, NULL, NULL, hInstance, NULL);

    ShowWindow(hWnd, nCmdShow);

    MSG msg;

    while (GetMessage(&msg, NULL, 0, 0))
    {
        TranslateMessage(&msg);
        DispatchMessage(&msg);
    }

    return (int) msg.wParam;
}

LRESULT CALLBACK WndProc(HWND hWnd, UINT message, WPARAM wParam, LPARAM lParam)
{
    switch (message)
    {
    case WM_CREATE:
        {
            // create toolbar
            HWND hWndToolbar = CreateWindowEx(0 , TOOLBARCLASSNAME, NULL, WS_CHILD | TBSTYLE_TOOLTIPS,
                0, 0, 0, 0, hWnd, (HMENU)0, instance, NULL);

            HIMAGELIST hImageList = ImageList_Create(16, 16, ILC_COLOR16 | ILC_MASK, 3, 0);

            SendMessage(hWndToolbar, TB_SETIMAGELIST, (WPARAM)0, (LPARAM)hImageList);
            SendMessage(hWndToolbar, TB_BUTTONSTRUCTSIZE, (WPARAM)sizeof(TBBUTTON), 0);

            TBBUTTON tbb[4] =
            {
                {0,0,TBSTATE_ENABLED,TBSTYLE_BUTTON,},
                {1,1,TBSTATE_ENABLED,TBSTYLE_BUTTON,},
                {2,2,TBSTATE_ENABLED,TBSTYLE_BUTTON,},
                {0,0,TBSTATE_ENABLED,BTNS_SEP}
            };

            SendMessage(hWndToolbar, (UINT) TB_ADDBUTTONS, 4, (LPARAM)&tbb);

            SendMessage(hWndToolbar, TB_AUTOSIZE, 0, 0);
            ShowWindow(hWndToolbar , SW_SHOW);

            // scrollbar
            SCROLLINFO si;
            si.cbSize = sizeof(SCROLLINFO);
            si.fMask = SIF_ALL;
            si.nMax = 1000;
            si.nMin = 0;
            si.nPos = 0;
            si.nPage = 500;
            SetScrollInfo(hWnd, SBS_VERT, &si, TRUE);
        }
    break;

 case WM_VSCROLL:
        switch(LOWORD(wParam))
        {
        case SB_LINEDOWN:
                ScrollWindow(hWnd, 0, -20, NULL, NULL);
            break;

        case SB_LINEUP:
                ScrollWindow(hWnd, 0, 20, NULL, NULL);
            break;
        }
    return 0;

    default:
        return DefWindowProc(hWnd, message, wParam, lParam);
    }
}

A: Most any C++ class library does this by creating a frame window.  The outer window that's the main window of the app.  And creates separate view windows to display content.  Those view windows are the ones that have a scrollbar.   Even the lowly Notepad uses this technique:

Note how the status bar at the bottom is its own child window of the frame window and doesn't get scrolled when you use the scroll bars in the edit child window.  The menu is different however, that's in the non-client area of the frame window.  Very specific to traditional menus.  You can use the Spy++ utility to poke around in other apps to see how they organized their windows.

A: There are a couple options to try.
If you create your host window with WS_CLIPCHILDREN, ScrollWindow() may ignore areas taken up by child windows (including your toolbar).   I'm not 100% sure that's the case, although I've used ScrollWindowEx() in various combinations with SW_SCROLLCHILDREN to solve child window scrolling.
Another option with your existing code would be to exclude the area taken by the toolbar from your region you're requesting to scroll.  Instead of passing NULL, pass a client rectangle, deducting for the size of your toolbar.
Something like this:
RECT toolRect;
GetClientRect(hWndToolbar, &toolRect);
RECT clientRect;
GetClientRect(hWnd, &clientRect);
// Adjust clientrect by the height of the toolbar
clientRect.top += toolRect.bottom;
// Scroll the region of our client area minus the toolbar at the top
ScrollWindow(hWnd, 0, 20, &clientRect, NULL);

A: Add another level to the window hierarchy, so that the scrollbars and the area they scroll are in a child window positioned below the toolbar.


text:
Q: linear-gradient with background image displays differently on ios mobile I'm trying to achieve exactly this, using chrome on mobile ios device.
It looks perfect on desktop, just not on mobile.
CSS:
html {
    background-color: black;
    background-image: linear-gradient(rgba(0, 0, 0, 0.4), rgba(0, 0, 0, 0.95)), url("data:image/png;base64,my image b64");
    background-image: -webkit-linear-gradient(rgba(0, 0, 0, 0.4), rgba(0, 0, 0, 0.95)), url("data:image/png;base64,my image b64");
    background-attachment: scroll;
    background-size: 64px;
    image-rendering: pixelated;
    font-family: arial;
    font-weight: bold;
    text-shadow: 0 0 6px #000;
    color: white;
}

The image is 16x16px. Here's what it looks like in browser first:

Here's what it looks like on chrome ios mobile:

The upscaling doesn't seem to be working, but also the gradient.
Any help is appreciated, thanks

A: I ended up adding an absolute positioned div with 100% width and height with z-index -1000 and applied the linear gradient to that. Looks great on firefox, chrome and their mobile counterparts.
For the upscaling I used image-rendering: crisp-edges and pixelated and the -webkit variants for all around support.
Hope that's useful for someone :)


text:
Q: ghostscript: mactex conflicts with homebrew I am using auctex and previewing equations in emacs does not work for me. It seems that the problem is related to ghostscript. I tried to reinstall ghostscript using brew, but got the following error.
brew reinstall ghostscript
==> Reinstalling ghostscript
==> Downloading https://homebrew.bintray.com/bottles/ghostscript-9.52.mojave.bottle.tar.gz
Already downloaded: /Users/user/Library/Caches/Homebrew/downloads/91f3c9535bda739dd9663190e036d7661f4e27463b96ea05c9b5db5a98ca9abe--ghostscript-9.52.mojave.bottle.tar.gz
==> Pouring ghostscript-9.52.mojave.bottle.tar.gz
Error: The `brew link` step did not complete successfully
The formula built, but is not symlinked into /usr/local
Could not symlink bin/dvipdf
Target /usr/local/bin/dvipdf
already exists. You may want to remove it:
  rm '/usr/local/bin/dvipdf'

To force the link and overwrite all conflicting files:
  brew link --overwrite ghostscript

To list all files that would be deleted:
  brew link --overwrite --dry-run ghostscript

Possible conflicting files are:
/usr/local/bin/dvipdf
/usr/local/bin/eps2eps
/usr/local/bin/gsbj
/usr/local/bin/gsdj
/usr/local/bin/gsdj500
/usr/local/bin/gslj
/usr/local/bin/gslp
/usr/local/bin/gsnd
/usr/local/bin/lprsetup.sh
/usr/local/bin/pdf2dsc
/usr/local/bin/pdf2ps
/usr/local/bin/pf2afm
/usr/local/bin/pfbtopfa
/usr/local/bin/pphs
/usr/local/bin/printafm
/usr/local/bin/ps2ascii
/usr/local/bin/ps2epsi
/usr/local/bin/ps2pdf
/usr/local/bin/ps2pdf12
/usr/local/bin/ps2pdf13
/usr/local/bin/ps2pdf14
/usr/local/bin/ps2pdfwr
/usr/local/bin/ps2ps
/usr/local/bin/ps2ps2
/usr/local/bin/unix-lpr.sh
/usr/local/share/man/man1/dvipdf.1
/usr/local/share/man/man1/eps2eps.1 -> /usr/local/share/man/man1/ps2ps.1
/usr/local/share/man/man1/gs.1
/usr/local/share/man/man1/gsbj.1 -> /usr/local/share/man/man1/gslp.1
/usr/local/share/man/man1/gsdj.1 -> /usr/local/share/man/man1/gslp.1
/usr/local/share/man/man1/gsdj500.1 -> /usr/local/share/man/man1/gslp.1
/usr/local/share/man/man1/gslj.1 -> /usr/local/share/man/man1/gslp.1
/usr/local/share/man/man1/gslp.1
/usr/local/share/man/man1/gsnd.1
/usr/local/share/man/man1/pdf2dsc.1
/usr/local/share/man/man1/pdf2ps.1
/usr/local/share/man/man1/pf2afm.1
/usr/local/share/man/man1/pfbtopfa.1
/usr/local/share/man/man1/printafm.1
/usr/local/share/man/man1/ps2ascii.1
/usr/local/share/man/man1/ps2epsi.1
/usr/local/share/man/man1/ps2pdf.1
/usr/local/share/man/man1/ps2pdf12.1 -> /usr/local/share/man/man1/ps2pdf.1
/usr/local/share/man/man1/ps2pdf13.1 -> /usr/local/share/man/man1/ps2pdf.1
/usr/local/share/man/man1/ps2pdf14.1 -> /usr/local/share/man/man1/ps2pdf.1
/usr/local/share/man/man1/ps2pdfwr.1
/usr/local/share/man/man1/ps2ps.1
==> Summary
  /usr/local/Cellar/ghostscript/9.52: 671 files, 87.4MB
==> `brew cleanup` has not been run in 30 days, running now...
Error: Permission denied @ apply2files - /usr/local/share/ghostscript/9.10/Resource/Font/logo10.pfb

I looked online and saw that there is probably a conflict with MacTex (see this GitHub issue). Indeed I have MacTex 2015 installed.
I am not sure how to proceed in solving the problem.
Should I uninstall MacTex and then reinstall it? (It seems it cannot be done thoroughly)
Should I force the homebrew links as it suggests? It seems like other stuff will be broken by it.
I am a simple TeX user, so I don't really understand all the dependencies. My goal it to be able to preview the equations when writing latex in emacs. (BTW, I am able to view the equations when I write in orgmode on emacs).

A: I use brew doctor and get a list of all broken symlinks.
In this list you will find /usr/local/share/ghostscript/9.10/Resource/Font/logo10.pfb and some other like this.
Then use sudo rm '/usr/local/share/ghostscript/9.10/Resource/Font/logo10.pfb' to remove it.
Maybe there are more than one in the same directory so you can use sudo rm -r '/usr/local/share/ghostscript/9.10/Resource/Font'.
Maybe this helps.


text:
Q: how do I change the border of controlsfx SegmentedButton with CSS? SegmentedButton
I'm trying to add a border to the ControlsFX SegmentedButton. When I change the background colors they keep the correct shape as shown in the above image.
Here is the CSS:
.segmented-button{
    -fx-focus-color: transparent;
    -fx-faint-focus-color: transparent;
    -fx-background-color:  -color-background-light-purple;
}

.segmented-button:selected{
    -fx-background-color: -color-heading-dark-blue;
    -fx-text-fill: white;
 }

But when I try to add a border, the shape is not adhered to.
SegmentedButton with Border
Here is the CSS:
.segmented-button{
    -fx-focus-color: transparent;
    -fx-faint-focus-color: transparent;
    -fx-background-color:  -color-background-light-purple;
    -fx-border-color: -color-heading-dark-blue;
    -fx-border-width: 0.2;
}

Can someone please tell me how to add the border to keep the shape of each button within the SegmentedButton?

A: The ControlsFX-SegmentedButton contains ToggleButtons and thus you have to assign your style to the ToggleButton with .segmented-button .toggle-button {...}.
For example:
 .segmented-button .toggle-button {
     -fx-background-color: derive(STEELBLUE,30%);
     -fx-border-color: derive(STEELBLUE,0%);
     -fx-border-width: 2;
 }

 .segmented-button .toggle-button:selected,
 .segmented-button .toggle-button:focused {
     -fx-background-color: derive(STEELBLUE,-10%);
     -fx-border-color: derive(STEELBLUE,-40%);
     -fx-border-width: 2;
     -fx-text-fill: WHITE;
 }

results in:

The portion
 .segmented-button {
     -fx-background-color: derive(ORANGE,30%);
     -fx-border-color: derive(ORANGE,0%);
     -fx-border-width: 10
 }

merely styles the SegmentedButton (i.e. the container) itself:

EDIT:
You can distinguish between the left, intermediate and right-buttons with
.segmented-button .toggle-button.left-pill {...}
.segmented-button .toggle-button.center-pill {...}
.segmented-button .toggle-button.right-pill {...}
for a different styling of the buttons (e.g. rounded corners). The radius can be set as usual with -fx-background-radius. This allows the following style with rounded corners for the outer buttons (similar to yours):

A good blueprint for a custom styling is the SegmentedButton.css of ControlsFX. You can find it inside the controlsfx-9.0.0.jar at org\controlsfx\control\segmentedbutton.css.


text:
Q: How to get one record from one to many relationship table I have 2 tables, one is contact, one is company, the primary key for mapping is using Client code.
ContactTable

Contact code
Client name
Client code
LoginName

1
MR YEO KWONG
00005
YEOW

2
MR DAVID Chan
00005
David

3
MS May Chen
00005
NULL

4
MS YORK
200150
MSYORK

Company Table

Company code
Company name
Contact Person
Client code

Co0001
Company One
MR YEO KWONG
00005

Co0002
David&Co.
MR DAVID Chan
00005

Co0003
TESTING MAC LTD.
MS May Chen
00005

Co0004
YORK Ltd.
MS YORK
200150

I would like to have the result as below,
The Result I want is as below:

Client code
Company name
Contact Person
Have Login

00005
Company One
MR YEO KWONG
MR YEO KWONG

00005
David&Co.
MR DAVID Chan
NULL

00005
TESTING MAC LTD.
MS May Chen
NULL

200150
YORK Ltd.
MS YORK
MS YORK

I tried the left join & inner join, but in the last column, I don't know how to get one record that has the login name to show only.
---- New add
Client Table

Client code
Client name
Company Code

00005
Client 1
Co0001

00005
Client 1
Co0002

00005
Client 1
Co0003

Co0004
Client 2
Co0004


text:
Q: Why was this character paid? Listening to Blood Rites again, and noticed something for the first time. At the end, Harry's debt to a certain mercenary is paid for him. But the character who did it would not have known that Harry had that debt at all, nor to whom.  At least, as of when it would have been paid, through only information available to anyone but Harry or Murphy is a dollar figure and a bank account number. Seems like scant information to assume it represents an IOU.  Am I missing a key story detail?  On camera at least, Harry doesn't ever tell him about hiring a mercenary or why, afaik

A: Thomas was around long enough to figure it out.
In the last chapter of Blood Rites, Harry brings Thomas to his basement home after clearing the air with Lara and his final visit to Justine. The very next paragraph is Harry trying to scare up money for the rest of the day to pay Kincaid, which of course, fails. So Thomas was definitely hanging around while Harry tried rather frantically to pay a bill... and then he found the "bill", Kincaid's card.  They're family, he has money, that's enough.
Thomas may also have gotten a brief summary of the lair raid from Murphy while they were taking turns trying to take care of Harry's charbroiled hand.  Murphy wouldn't know about Kincaid's fees, but could say enough about what happened that Thomas would know a highly professional and lethal (and therefore expensive) mercenary was involved.  That's not explicitly shown, but it might have been another way he put the details together.


text:
Q: AVAudioPlayer: Sounds overlapping i made a simple app where i can record myself and then sample what i've recorded. Since i like spamming buttons, i tried it with my own app. The result was, about 20 the same sounds of myself talking overlapping and creating a horrible mess. How can i prevent such thing in the future?
That's my code:
.h
-(IBAction)record {

        TempRecFile = [NSURL fileURLWithPath:[NSTemporaryDirectory() stringByAppendingPathComponent:[NSString stringWithString:@"VoiceFile"]]];

        recorder = [[AVAudioRecorder alloc] initWithURL:TempRecFile settings:nil error:nil];
        [recorder setDelegate:self];
        [recorder prepareToRecord];
        [recorder record];

}

-(IBAction)playback {

    [recorder stop];

    AVAudioPlayer *player = [[AVAudioPlayer alloc] initWithContentsOfURL:TempRecFile error:nil];
    player.volume = 1;
    [player play];

}

Later on i want to play multiple sounds attached to multiple buttons and if all of those start overlapping, the users ears would probably start bleeding very shortly... :(
The problem with multiple sound buttons would be: I would need to restrict every sound to overlapping only with itself. How can I do such thing?

A: In your Playback method, disable the button first thing. When you init your class, set your class to be the delegate for the AVAudioPlayer and implement the protocol AVAudioPlayerDelegate, specifically you want to catch the audioPlayerDidFinishPlaying:successfully: event. In the event, re-enable the button.
So, this will disable the button, play the sound, and when the sound is done playing enable the button.
Now, for multiple buttons, just do the same thing for each. The catch is you'll need to keep track of an AVAudioPlayer for each button and know which player goes with which button. An NSDictionary could be used to keep the list of players, along with key values.
EDIT: To stop previous playback and start over at the beginning...
Declare an AVPlayer at the class level rather than create a new one for each button press. When the button is pressed you can send it a seekToTime message to start over at the beginning. For multiple buttons have multiple class level AVPlayers.
Edit: If you use AVAudioPlayer class you could do the same thing setting the currentTime property.


text:
Q: Building a eloquent query belongsTo for octobercms I'm working on a report widget for OctoberCMS and need to build in some conditional statements for my query.
I have a table (user_access_log) that contains records for the user id, ip address, and time stamps.
My access log model is this:
/**
 * @var array
 */
 public $belongsTo = [
    'user' => ['Models\User']
 ];

My user model is such:
/**
 * @var array Relations
 */
public $belongsToMany = [
    'groups' => ['Models\UserGroup', 'table' => 'users_groups']
];

UPDATE:
Now I have extended the user model like so:
UserModel::extend(function($model)
{
    $model->hasMany['logs'] = [
        'Models\AccessLog',
        'key' => 'user_id',
    ];
});

and updated the query for my widget to:
$query = UserGroup::whereHas('user',function($query) {
    $query->whereHas('logs',function($query) {
        // Just some query to get a resultset back so count() > 1
        $query->whereNotNull('created_at');
    });
 });

$userLog = $query->where('name', 'Users')->get();

However, I am still not returning any results. In fact, its as if the query is not even running. Nothing is displayed in my Debugbar. I tried to pass the array to my view and it now says I have an undefined variable.

A: I think you have to do the query before call all() because at these point you will got an Eloquent Collection and no the Query Builder
$log = AccessLog::whereHas('user', function($q){
     $q->whereHas('groups', function($subquery){
      $subquery->where('name', '=', 'staff');
     }
})->get()->groupBy('user_id');

This could be works :D

A: A recap of what you have:
An accesslog entry that belongs to ONE user.
An User that belongs to Many groups.
A group that belongs to Many users.
What you want, is to see which groups have come from all access logs.
You need to implement a hasMany relationship in your user.
$hasMany = [
      'logs' => [
         'Models\AccessLog',
         'key'=> 'user_id'
       ],
];

Then you can build a query like:
$query = UserGroup::whereHas('user',function($query) {
   $query->whereHas('logs',function($query) {
       // Just some query to get a resultset back so count() > 1
       $query->whereNotNull('created_at');
   });
});
$staff = $query->where('name','staff')->get();


text:
Q: how to check if ms office product is installed and version of it VC++? I want to find whether ms office is installed and version of it...
how can i do it ?

A: Since you've tagged it as visual C++, I'm assuming you want to do it in C++.
One way is to parse through the following registry key
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall
For e.g.
Enumerate this key and find out if the value displayname contains Microsoft Office Excel MUI (English) 2007
You may also find the version number in other values like version, versionmajor, verisonminor
FYI you can use this registry key to find out almost any software which 'installs' on your system.
This is only for 32 bit installation though. For 64-bit installation, you'll need to find a similar tree structure inside registry node WOW6432Node.

A: Microsoft Office Version Detector

How does it work?
The code is based on an outdated Microsoft knowledge base article Q247985 (the code in the knowledge base article does not work for Office 2003 or 2007). The code looks for a specific registry key which holds the version for each application (e.g. HKEY_CLASSES_ROOT/Excel.Application/CurVer for Excel) which contains the version encoded in a string ("Excel.Application.11" on my computer). The internal Microsoft version number (i.e. the "11" at the end of "Excel.Application.11" ) is then mapped to the external "marketing" name, that you will be more familiar with (e.g. the internal version "11" is more commonly known as "Office 2003").


text:
Q: How to find the simplest form of integer matrix polynomial? For my toy project, related to cellular automata in non-euclidean spaces, I want to find an algorithm that solves the following problem.
Let $M$ is a fixed matrix with characteristic polynomial $p(x)=x^2-3x+1$.
For example, $M$ could be $\left(\begin{matrix}2&1\\1&1\end{matrix}\right)$.
Let $P$ is a Laurent polynomial in $M$ with integer coefficients:
$$P= \dots + a_2M^2 + a_1M + a_0I + a_{-1}M^{-1} + \dots, a_i\in\mathbb{Z}$$
Define complexity of $P$ as the sum of absolute values of its coefficients:
$$C(P) = \sum_i|a_i|$$
The problem is: given a specific polynomial $P$ in $M$, find equal with minimal complexity.
Example: let's $P=3M^0$. It has complexity 3. The simplest equal polynomial is $M+M^{-1}$ of complexity 2, obtained by adding $p(M)M^{-1}$.
My question is: what is (and is there) an algorithm to find the least complex form?
The problem can be reformulated like this: given 2-side infinite array of integer numbers $(\dots,a_2,a_1,a_0,a_{-1},\dots)$, where only finite amount of numbers are non-zero, minimize $\sum|a_i|$ by adding or subtracting $(1,-3,1)$ to any 3 consequent numbers.
It is not as trivial as it could seem. At first, I thought that the simple "greedy" algorithm solves the problem: add or subtract (1,-3,1) at all possible locations, until it reduces complexity.
However, it does not!
The simplest example I have is $5M+5M^0$ or (5,5), complexity 10. Application of greedy algorithm produced $2M^2+M+M^0+2M^-1$, or (2,1,1,2), complexity 6. Apparently, there is no way to reduce complexity in one step. However, manual check can show that it is equal to $M^3+M^{-2}$, or (1,0,0,0,0,1) of complexity 2.


text:
Q: Create Jquery Plugin with dynamic parameters for MULTIPLE usage I creating jquery plugin, looks like this :
(function ( $ ) {

    // -- This is Person Object used for plugin
    var PersonObject = function(elem, options)
    {
       this.elem = elem;
       this.options = options;
       this.run();
    };

    PersonObject.prototype = {

       run: function()
       {
          // console.log(this.options.person_name);
          self = this;
          tpl = 'one';

          self.elem.after(tpl);

            $('.content').on('click', '.btncok', function(e) {
                e.stopImmediatePropagation();
                self.show();
            });

          return self.options.person_name;
       },

       show: function()
       {
            console.log(this.options.person_name);
       }
    };
    // -- end Person Object

    // -- This is my jquery fn function
    $.fn.myPlugin = function(options) {

       // here is default options
       var default_options = {person_name: 'father'};

       options = $.extend({}, default_options, options);

       return this.each(function() {

          new PersonObject($(this), options);

       });
    };
    // -- end jquery plugin

}( jQuery ));

.
.
so then, when the above plugin are used by many elements with different situation like this :

one

two

the parameters is not work expected.
all the element that using the plugin will receive same parameters by last element call
how to fix this problem :(

A: You are seeing the same value because of the below click handler
$('.content').on('click', '.btncok', function(e) {
  e.stopImmediatePropagation();
  self.show();
});

$('.content').on('click', '.btncok', .... is does not delegate event as expected. Instead attach an event to tpl directly. Something like this
this.appendedEl = $(''+this.options.person_name+'');
this.elem.after(this.appendedEl);
this.appendedEl.on('click', function(e) { // <--- this way the event is attached to the right element
  e.stopImmediatePropagation();
  this.show();
}.bind(this)); // <--- I used bind instead of self

Here is a demo http://jsbin.com/jafulo/edit?js,output


text:
Q: Custom header styles with Sass I am building out a page that has headers for each section that are different colors and each has an underline that is the same color as the heading text.  Because the underlines stretch from the left of the screen to the end of text, I've built them as pseudo elements (using :after). I did it this way because my content is in a container and the underlines need to stretch beyond the container.  Is there a way I can dynamically program the color and width for each header?  Right now I've got class for each header, which I know is not DRY at all, but I'm unsure about a better way to do it.

.header-white {
    position: relative;
    &::after {
        content: "";
        border-bottom: 2px solid $color-white;
        top:70px;
        left: -119px;
        right:0;
        position: absolute;
        width: 36.5%;
    }
}

.header {
    position: relative;
    &::after {
        content: "";
        border-bottom: 2px solid $color-quaternary;
        top:70px;
        left: -119px;
        right:0;
        position: absolute;
        width: 53.5%;
    }
}

As I am anticipating several more headers, this is not the optimal way to go.  Any ideas or advice would be greatly appreciated.  Thank you!!

A: You can use mixins to pass parameters
@mixin rtl( $ltr-value, $rtl-value) {
  width: $ltr-value;
  color: $rtl-value;

}

Below is the method to include mixins in any CSS declaration.
.header {
  @include rtl(100px, white);
}

Please follow the link for more info :https://sass-lang.com/documentation/at-rules/mixin


text:
Q: Reload browser reset page scroll even forcing to scrollTo 0, 0 I have a small app in react Next.js and it is scroll-based animation fun page. Because of this I need to reset scroll position to top after reloading the page, but no matter what I try, the page change the scroll position back to the state where it was before the reload.
Even I forced the page to change scroll with useEffect, setTimeout, window.scrollTo or window.scroll, clearing the timeout on return (in useEffect) and set useEffect with and without [], the position always changed back.
I deleted everything from the project and left only the base Next generated and index with empty divs with height to have some page height to scroll and console.logs to see the scroll position and now it seems like the position changes to 0 after reload but immediately changes to position where I was before the reload. Why?


text:
Q: Margin ignored by LinearLayout I'm creating dynamically views containing a LinearLayout and add them to an outer LinearLayout. I would like to set a margin around the created views, but the layout_margin in the XML file is ignored. It works, if I set the parameters in the code, but I would like to specify the margin in the layout XML.
Setting the margin in the XML layout will be ignored:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_margin="20dp"
    android:orientation="vertical" >

    ...
</LinearLayout>

Setting the margin while creating is honored:
LinearLayout productView = (LinearLayout) getLayoutInflater().inflate(R.layout.product_preview, null);

LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
params.setMargins(50, 50, 50, 50);
productView.setLayoutParams(params);

This is the outer layout. The views are added to dealer_activity_product_list.

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical" >

    <ImageView
        android:id="@+id/dealer_activity_dealer_image"
        android:layout_width="match_parent"
        android:layout_height="150dp"
        android:contentDescription="@string/dealer_activity_dealer_image_desc" />

    <TextView
        android:id="@+id/dealer_activity_dealer_address"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal" >

        <LinearLayout
            android:id="@+id/dealer_activity_product_list1"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:orientation="vertical" />

        <LinearLayout
            android:id="@+id/dealer_activity_product_list2"
            android:layout_width="0dp"
            android:layout_height="match_parent"
            android:layout_weight="1"
            android:orientation="vertical" />
    </LinearLayout>
</LinearLayout>

A: Are you setting the attribute for the inner LinearLayout or the containing LinearLayout?
At least, the following does work inside a LinearLayout:
<TextView
    android:id="@+id/xxx"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:textSize="20sp"
    android:layout_margin="10dp"
    />

A: set padding instead of layout_margin in outer view.
Hope it will work

A: There is a common "nested layouts" pattern.
That is, you create an auxiliary container layout and achieve the desired effect positioning the internal layout within the container layout.
Sort of:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <LinearLayout
        ...
        android:layout_margin="20dp"
        >
    ...
    </LinearLayout>
</LinearLayout>


text:
Q: KVM Switch - takes forever to recognize HDMI input for 1 of my laptops? I have this KVM:
https://www.amazon.ca/gp/product/B08H4FKJPN/ref=ppx_yo_dt_b_asin_title_o03_s00?ie=UTF8&th=1
My KVM and laptops works with my previous monitor, my BenQ 1080 60hz monitor:
https://www.amazon.ca/BenQ-GW2480-Brightness-Intelligence-Flicker-Free/dp/B072XCZSSW
Recently replaced my BENQ with a 1440p 144 hz Gigabyte M27Q (I downscaled it to 60hz just for my KVM; i also know the M27Q have their own KVM, I plan to use it for my 2nd laptop!):
https://www.amazon.ca/Gigabyte-Monitor-Display-Response-FreeSync/dp/B08JWCHR5N
My KVM works immediatley if I plug it in with my Dell XPS 13 laptop (smaller laptop):
https://www.dell.com/en-ca/shop/dell-laptops/xps-13-laptop/spd/xps-13-9310-laptop
Problem:
My KVM takes ~30 seconds to switch to  Lenovo Flex 5 (larger laptop). It is super slow and I'm wondering what the fix for this is?
https://www.amazon.ca/Lenovo-Graphics-included-81X20005US-Graphite/dp/B086226DDB
Any ideas what's up? the KVM does not like my new 1440p 144hz monitor I think and that's where the problem lies?


text:
Q: How to assign a variable to the variables decalred with  I recently used a library <gmp.h> and I am having difficulty assigning a value to the variable mpf_t x I declared. I used mpf_init2 (x,256) to initialize it and when I do x=1.234029187340918239082372984509283475029845702
I get
highprecision.cc:7:7: error: incompatible types in assignment of 'double' to 'mpf_t' {aka '__mpf_struct [1]'}
    7 |     x=1.234029187340918239082372984509283475029845702;
      |       ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

this error. Any idea why? I am using C++17 GCC btw. The documentary is also very confusing. Sorry.

A: mpf_set_d(x, 1.234029187340918239082372984509283475029845702);

Maybe reading the documentation would help?
BTW if you think you are going to get 256 digits of precision in a double literal you are mistaken. 1.234029187340918239082372984509283475029845702 is still going to have the regular precision of a double on your system (around 17 to 19 digits usually).


text:
Q: Decorating text (Bold/Italic) of Label programmatically in Codename One I want to decorate Label text as Bold or Italic or both.
So far to make it work, I'm applying label.setUIID("BoldItalic_Label") or setting different UIID in same manner.
But now I want to decorate Label Text programmatically. I've tried mostly all  style properties which can be applied to label text, it doesn't work for me.
Can anybody suggest the workaround ?

A: Try label.getUnselectedStyle().setFont(font).
You can create the font object using the Font class's factory methods.


text:
Q: How to fix : Navigation bar icons still showing, when pop-up menu is opened (Full screen - Immersive sticky) I'm trying to achieve a full-screen application, where the user doesn't have any access to the status- & navigation-bar.
Preferably I would want them to be removed completely, but from what I've read this is not possible unless you root the device
So my question basically is: How do I hide the navigation-bar icons, when I show the pop-up menu?
BEFORE

AFTER

So far, I have tried:

*

*Calling hideNavigation() before & after the pop-up menu is shown

*Calling hideNavigation() in onCreate(), onResume() & onWindowFocusChanged()

*Requesting focus to another view

*Trying to clear the focus from the drop-down (Failed attempt, didn't really find a way to do this)

*Changing the icon colors, "faking" it would be hidden (Failed attempt, didn't really find a way to do this)

*Using hideNavigation() in combination with Handler (Failed attempt, maybe I didn't do it correctly)

*Trying to configure some COSU/KIOSK-mode options (Perhaps there is some way to complete disable the whole navigation-bar? I haven't found a way to hide the back-button yet)

ACTIVITY

    class PinCodeActivity, HasTitleBar {
        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            setContentView(R.layout.activity_pin_code)
            initTitleBarWith(this)
            hideNavigation()
        }

        override fun onResume() {
            super.onResume()
            hideNavigation()
        }

        fun hideNavigation() {
            window.decorView.apply {
                systemUiVisibility = FLAGS
            }
        }

        override fun onWindowFocusChanged(hasFocus: Boolean) {
            super.onWindowFocusChanged(hasFocus)
            hideNavigation()
        }
    }

const val FLAGS = (View.SYSTEM_UI_FLAG_LOW_PROFILE or View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or View.SYSTEM_UI_FLAG_HIDE_NAVIGATION or View.SYSTEM_UI_FLAG_FULLSCREEN or View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY)

TITLE-BAR

    fun HasTitleBar.initTitleBarWith(activity: Activity, resId: Int = R.id.titleBar) {
        val langButton = activity.findViewById<View>(resId).findViewById<Button>(R.id.tbLanguageChoiceBtn)
        val wrapper = ContextThemeWrapper(activity, R.style.MyPopupMenu)
        val popupMenu = PopUpLanguageMenu(wrapper, langButton)
        langButton.setOnClickListener {
            activity.hideNavigation()
            popupMenu.showMenu()
            activity.hideNavigation()
        }
    }

POP-UP MENU

    class PopUpLanguageMenu constructor(context: Context, view: View) : PopupMenu(context, view) {

        private var popupHelper: MenuPopupHelper

        init {
            val popUpMenu = PopupMenu(context, view).apply {
                inflate(R.menu.menu_language_dropdown)
            }

            popupHelper = MenuPopupHelper(context, popUpMenu.menu as MenuBuilder, view)
            popupHelper.run {
                gravity = Gravity.END
                setForceShowIcon(true)
            }
        }

        fun showMenu() {
            popupHelper.show()
        }
    }

EXPECTED RESULT: Navigation-bar & it's icons are hidden, after the pop-up menu is shown, the icons are still HIDDEN
ACTUAL RESULT: Navigation-bar & it's icons are hidden, after the pop-up menu is shown, the icons are SHOWN

A: The nav bar re-appears because there is a new DecorView (PopupDecorView) is newly drawn on the top of the Views stack, which isn't affected by your FLAGs set before.
There is no silver bullet here, my approach is to dig into the WindowManagerGlobal by reflection and catch out the peek View, apply the system FLAGs on it again, so after the PopupMenu shows up, it manages to hide the Navigation bar right after that (there is still, a show up from the Navigation Bar once).
Here is the code:
override fun onWindowFocusChanged(hasFocus: Boolean) {
    super.onWindowFocusChanged(hasFocus)
    if (hasFocus) {
        hideNavigation()
    } else {
        // When PopupMenu appears, the current Activity looses the focus
        setFlagsOnThePeekView() // Hijack to the current peek view, apply the Flags on it
    }
}

@SuppressLint("PrivateApi")
fun setFlagsOnThePeekView() {
    try {
        val wmgClass = Class.forName("android.view.WindowManagerGlobal")
        val wmgInstance = wmgClass.getMethod("getInstance").invoke(null)
        val viewsField = wmgClass.getDeclaredField("mViews")
        viewsField.isAccessible = true

        val views = viewsField.get(wmgInstance) as ArrayList<View>
        // When the popup appears, its decorView is the peek of the stack aka last item
        views.last().apply {
            systemUiVisibility = FLAGS
            setOnSystemUiVisibilityChangeListener {
                systemUiVisibility = FLAGS
            }
        }
    } catch (e: Exception) {
        e.printStackTrace()
    }
}

A: Because PopupMenu use new DecorView (PopupDecorView), try:
@Override
public void onWindowFocusChanged(boolean hasFocus) {
    super.onWindowFocusChanged(hasFocus);
    if(hasFocus)
    {
        fullSceen(getWindow().getDecorView());
    }
    else {
        try {
            Object wmgInstance = Class.forName("android.view.WindowManagerGlobal").getMethod("getInstance").invoke(null);
            Field viewsField = Class.forName("android.view.WindowManagerGlobal").getDeclaredField("mViews");

            viewsField.setAccessible(true);
            ArrayList<View> views = (ArrayList<View>) viewsField.get(wmgInstance);
            for (View view: views) {
                fullSceen(view);

                view.setOnSystemUiVisibilityChangeListener(new View.OnSystemUiVisibilityChangeListener() {
                    @Override
                    public void onSystemUiVisibilityChange(int visibility) {
                        fullSceen(view);
                    }
                });
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        AppUtils.console(this,TAG, "hasFocus == false");
    }
}
private void fullSceen(View view){
    view.setSystemUiVisibility(
            View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                    | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
                    | View.SYSTEM_UI_FLAG_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
}


text:
Q: Browser display german language character issue my issue is i am displaying german language character and my browser convert some character in question mark symbol.
I have added image here you can see what is exact issue.
I have tried meta tag also like

still i am getting same issue. please help to correct code
my code
<meta charset="utf-8">
        <meta http-equiv="X-UA-Compatible" content="IE=edge">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <meta name="description" content="">
        <meta http-equiv="Content-Language" content="de, fr, it, en">
        <meta name="author" content="">

A: Hi I have find answer myself
Data comes from db using php server side scripting thats why html meta tag not working but we can do it using php header. please check below one line of code to do it.
header('Content-Type: text/html; charset=ISO-8859-1');

A: So there are a few possibilities:
Maybe (if you work on a web server) the configuration is wrong. Search for settings about ISO 8859-1.
It also could be the configuration of your browser. Check this topic on stackoverflow. It describes how to force browsers to use UTF-8 using .htaccess.
And if everything of this doesn't work you could change every character to the html code with search and replace. This should work without UTF-8.

*

*Ä = Ä

*ä = ä

*Ö = Ö

*ö = ö

*Ü = Ü

*ü = ü
I hope you find a solution.


text:
Q: Starting supervisor programs as another user I have a docker (php:7-fpm-alpine) container with supervisor installed. It is added to a default installation by:
RUN apk add nginx composer php7-fpm php7-session supervisor && \
    ... ... ...
    cp supervisord.conf /etc/supervisor.d/conf.ini

Supervisor has its default config (didn't change it after installation), I have added my own config to append to it (supervisord.conf):
[program:php-fpm7]
command = /usr/sbin/php-fpm7 --nodaemonize --fpm-config /etc/php7/php-fpm.d/www.conf
autostart=true
autorestart=true
priority=5
stdout_logfile=/var/log/supervisor/php-fpm.log
stderr_logfile=/var/log/supervisor/php-fpm.error.log

[program:nginx]
command=/usr/sbin/nginx -g "daemon off;"
autostart=true
autorestart=true
priority=10
stdout_logfile=/var/log/supervisor/nginx.log
stderr_logfile=/var/log/supervisor/nginx.error.log

Now the original issue I have is that my Laravel app can't write to storage folder. I could chmod 777 the folder recursively, and it works, but is not what I want.
So steps I took first is to chown -R nginx:nginx /var/www/* leaving permissions as is. This resolved nothing, still can't write.
Doing a ps aux revealed this:
PID   USER     TIME  COMMAND
    1 root      0:00 {supervisord} /usr/bin/python2 /usr/bin/supervisord --nodaemon --configuration /etc/supervisord.conf
    8 root      0:00 {php-fpm7} php-fpm: master process (/etc/php7/php-fpm.d/www.conf)
    9 root      0:00 nginx: master process /usr/sbin/nginx -g daemon off;
   10 nginx     0:00 nginx: worker process
   11 nginx     0:00 nginx: worker process
   12 nginx     0:00 nginx: worker process
   13 nginx     0:00 nginx: worker process
   14 nginx     0:00 {php-fpm7} php-fpm: pool www
   15 nginx     0:00 {php-fpm7} php-fpm: pool www

So php-fpm is running as nginx user (I've changed it's original config to replace user nobody to nginx). This did nothing good, as with this settings instead of nobody user, request returns 502 error.
Nginx master process is running as root, and worker processes as nginx.
This is a tad confusing as I am not sure which user is my web server using here? Root or nginx? Does it take the user from supervisor, nginx master or nginx worker?
I've tried changing supervisor to start as nginx user, but that fails as supervisor needs root access to create pid.
Reverting supervisor to root and adding user=nginx to [program:nginx] section made supervisor not start nginx at all.
How can I do the permissions here the right way?

A: I think the best you can do , is to run both nginx and php-fpm as www-data:www-data
step one
add/edit this to your nginx.conf:
user www-data www-data;

step two
add/edit php-fpm.conf and set user and group to www-data more info here
I hope that will help you


text:
Q: Latency issue with encrypted and compressed BTRFS filesystem I have big latency problems with my BTRFS filesystem configuration under Pop OS 20.04.
When I make updates, it freeze my computer and I have to wait sometimes 5 seconds just to refresh a web page on my browser.
To start iTunes on a Windows 10 virtual machine, it can take up to 6 minutes! And running the Windows 10 virtual machine is just horrible for my POP OS responsiveness.
Here is my configuration:
UUID=7e73aae9-1da1-4ea6-b8a5-20f5c2689f23  /  btrfs  defaults,subvol=@,ssd,noatime,space_cache,commit=15,compress=zstd  0  0
UUID=7e73aae9-1da1-4ea6-b8a5-20f5c2689f23  /home  btrfs  defaults,subvol=@home,ssd,noatime,space_cache,commit=15,compress=zstd  0  0
#UUID=7e73aae9-1da1-4ea6-b8a5-20f5c2689f23  /var/www  btrfs  defaults,subvol=@www,ssd,noatime,space_cache,commit=15,compress=zstd  0  0
UUID=7e73aae9-1da1-4ea6-b8a5-20f5c2689f23  /swap  btrfs  defaults,subvol=@swap,ssd,noatime,space_cache,commit=15  0  0

The partition is also encrypted with LUKS Encryption (version 2):
sudo cryptsetup luksDump /dev/nvme0n1p3
LUKS header information
Version:        2
Epoch:          3
Metadata area:  16384 [bytes]
Keyslots area:  16744448 [bytes]
UUID:           08e59f5b-ec3e-4c3d-b383-82baeb7e8ece
Label:          (no label)
Subsystem:      (no subsystem)
Flags:          (no flags)

Data segments:
  0: crypt
    offset: 16777216 [bytes]
    length: (whole device)
    cipher: aes-xts-plain64
    sector: 512 [bytes]

Keyslots:
  0: luks2
    Key:        512 bits
    Priority:   normal
    Cipher:     aes-xts-plain64
    Cipher key: 512 bits
    PBKDF:      argon2i
    Time cost:  4
    Memory:     1048576
    Threads:    4
    Salt:       f8 8c b8 70 71 8a 49 a6 bb 72 76 34 fb cb ce a6
                e2 95 44 82 6b f6 28 25 01 97 0e 2e 6b ea 0d de
    AF stripes: 4000
    AF hash:    sha256
    Area offset:32768 [bytes]
    Area length:258048 [bytes]
    Digest ID:  0
Tokens:
Digests:
  0: pbkdf2
    Hash:       sha256
    Iterations: 86802
    Salt:       6c 04 be 69 12 05 09 13 36 24 87 5d 8a 59 17 ab
                82 9e c3 9f d7 3c 62 1c d3 29 8b 2a 29 eb 68 98
    Digest:     f7 dd b2 93 03 ef 5c de 18 8b ba 21 c0 5f 9c c0
                54 62 42 63 ec 39 aa 89 6d df db 88 3d e0 90 ac

Does the latency issue comes more from the zstd compression or from the Luks encryption?
Should I change the compression type of all the disk?

A: The luks encryption is probably the biggest latency hog. Than you can try to switch off zstd compression. Both take severely cpu cycles and cause your latency issues!


text:
Q: The measurability in a proof of Doob's martingale maximal inequalities Let $(\Omega, \mathcal F, \mathbb P)$ be a probability space and $M=(M_t, t\ge 0)$ a continuous martingale with respect to a filtration $(\mathcal F_t, t\ge 0)$. Let $T>0, \lambda >0$, and $p \ge 1$.
I'm reading a proof of below theorem from this link.

Theorem If $\mathbb E [ |M_T|^p] < \infty$ then
$$
\mathbb P \bigg [ \sup_{t \in [0, T]} |M_t| \ge \lambda \bigg ] \le \frac{\mathbb E [ |M_T|^p ]}{ \lambda^p}.
$$

Proof For $p \ge 1$, the map $x \mapsto |x|^p$ is convex. It follows from $\mathbb E [ |M_T|^p] < \infty$ and Jensen's inequality that $(|M_t|^p, t \in [0, T])$ is a sub-martingale w.r.t. $(\mathcal F_t, t\ge 0)$. Let
$$
\tau := T \wedge \inf \{t \ge 0 :  |M_t| \ge \lambda\}.
$$
Then $\tau$ is a stopping time w.r.t. $(\mathcal F_t, t\ge 0)$ such that $\tau \le T$. By Doob's optional stopping theorem for a sub-martingale,
$$
\mathbb E [|M_{\tau}|^p] \le \mathbb E [|M_{T}|^p].
$$
By definition of $\tau$,
$$
\begin{align}
|M_{\tau}|^p &= |M_{\tau}|^p 1_{\{\sup_{t \in [0, T]} |M_t| \ge \lambda\}} + |M_{\tau}|^p 1_{\{\sup_{t \in [0, T]} |M_t| < \lambda\}} \\
&\ge \lambda^p 1_{\{\sup_{t \in [0, T]} |M_t| \ge \lambda\}} + |M_T|^p 1_{\{\sup_{t \in [0, T]} |M_t| < \lambda\}}.
\end{align}
$$
Thus
$$
\mathbb P \bigg [ \sup_{t \in [0, T]} |M_t| \ge \lambda \bigg ] \le \frac{\mathbb E [|M_T|^p 1_{\{\sup_{t \in [0, T]} |M_t| \ge \lambda\}}]}{\lambda^p} \le \frac{\mathbb E [|M_T|^p]}{\lambda^p}.
$$

My understanding Let $(X_t, t \in [0, T])$ be a stochastic process. Then $\sup_{t \in [0, T]} |X_t|$ is not necessarily Borel measurable because $[0, T]$ is uncountable. Let $(t_n, n \in \mathbb N)$ be a dense subset of $[0, T]$. Because $M$ has continuous paths,
$$
\sup_{t \in [0, T]} |M_t| = \sup_n  |M_{t_n}|.
$$
The supremum over a countable collection of Borel measurable functions is again Borel measurable. So $\sup_{t \in [0, T]} |M_t|$ is Borel measurable.

Could you confirm if my above understanding is correct?


text:
Q: MySQL timezone not in sync with system PHP timezone:
date.timezone   Europe/Helsinki Europe/Helsinki
MySQL timezone:
@@global.time_zone:
SYSTEM
@@session.time_zone:
SYSTEM
MySQL NOW();
2015-06-22 10:22:28
Ubuntu "date":
Mon Jun 22 11:22:28 EEST 2015

I would like to have MySQL time sync with the system time, which is the correct time. Apparently the problem is, that MySQL does not recognize summertime which means that time should be +1 hour to normal time.
How to switch MySQL time to summertime just like the system does, without changing the timezone?


text:
Q: short git revision hashes not working I don't see what I could be doing wrong, but on my Windows computer Git doesn't seem to recognize short revision hashes. I've made sure they're 7 characters. Here's what happens, diffing the history of a file named "compile":
Short revision (taking the final 7 characters from the revision):
C:\mydir>git diff 417864c 6cca022 -- compile
fatal: bad revision '417864c'

Long revision:
C:\mydir>git diff b91a07a79c919ea4b981a32597b84aa1f417864c 6b59a420837c38586180325f45e23ea35d7676d3  -- compile
diff --git a/bin/compile b/bin/compile
index 2a5f3dd..b81e4bc 100755
--- a/bin/compile
+++ b/bin/compile
[snip]

I'm not really sure what to check for. Any suggestions?

A: I don't know where did you get the idea that the tail* of the hash is meaningful.
Try the head*:
git diff b91a07a79 6b59a4208

* edit - erm.. of course HEAD has its meaning in Git. I meant end of the string and beginning of the string, respectively.


text:
Q: Recommendations for securing Internet-facing IIS Host? I'm setting up an Internet-facing ASP.NET MVC application, on Windows 2008. It uses SQL Server 2008 for its database. I'm looking for best-practices for securing it.
I found this article, but it's a bit dated now. How much of that advice is still valuable?
Some background -- it's a personal site, behind my home NAT/firewall box; and I'll only forward ports 80 and 443 to it. The IIS server itself is a Windows 2008 host running on HyperV (I only have one physical box to spare).
One useful thing that's mentioned in that article (which had occurred to me already) is that the IIS box shouldn't be a member of the domain, so that an intruder can't easily get off the box. I'll be removing it from the domain in a moment :)
What other tips should I (and anyone deploying to a bigger environment) bear in mind?
I know that this isn't strictly a programming-related question (there's no source code in it!), but I guess that most programmers have to dabble in operations stuff when it comes to deployment recommendations.

A: I don't know about removing it from the domain, but I'd certainly disable LanMan hashes, keep the system fully patched, and use good password security.  Make sure that any processes running in IIS run from least privileged accounts, i.e., don't run the worker processes under IDs that are in Local Administrators.

A: You might take a look at these two tools:
Best Practices Analyzer for ASP.NET
SQL Server 2005 Best Practices Analyzer (even though you are using 2008, still might be of help)

A: This will be of great help, certainly:
Microsoft Web Application Configuration Analyzer v2.0


text:
Q: Movable Navigation at the bottom which stays there at window resize I want to make myself a little website and I'm almost completely new to this world (did some stuff in school and know how to make a basic page, but nothing special). I wanted to ask you how to make a movable navigation at the bottom which stays there at window resize.
I tried it by myself already, but since I use bootstrap and materializecss I think I wrote some useless lines in the css and can't really show what I've done so far. I tried something with absolute positioning, but it screwed over when people turn off the chrome browser bookmark bar, so I switched back to relative.
Long story short, I really want to have a navbar like on this website: http://www.reverse-magazine.com/

A: This should get you going:
https://jsfiddle.net/f26eudd7/2/

$(document).ready(function() {
  var navbar_el = $('.navbar');
  var navbar_top = navbar_el.offset().top;

  $(window).scroll(function () {
    if ($(window).scrollTop() > navbar_top) {
      navbar_el.addClass('sticky');
    } else {
      navbar_el.removeClass('sticky');
    }
  });

  $(window).resize(function() {
    navbar_top = navbar_el.offset().top;
  });
});
html,body {
  height: 100%;
  margin: 0px;
  padding: 0px;
}

.full-height {
  height: 100%
}

header {
  position: relative;
  display: block;
  background-image: url('http://placehold.it/1920x1080');
  background-repeat: no-repeat;
  background-size: cover;
  background-position: center;
}

.navbar {
  background: #ffffff;
  position: absolute;
  bottom: 0;
  left: 0;
  width: 100%;
  height: 65px;
}

.navbar.sticky {
  position: fixed;
  top: 0;
  z-index: 100;
}

#content {
  background: #ff0000;
  height: 1000px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<header class="full-height">
  <nav class="navbar">
    Your navbar
  </nav>
</header>

<div id="content">
  Your content
</div>


text:
Q: Unable to run python file in java I have to call example.py (having another dependencies windrose, matlab, numpy ) python file from java to create wind graph but it unable to import any dependency while calling from java but its runs fine independently using python,  I got
   Error: no module name windrose

but this module is already in folder please let me know how to do it
  windroseGraph ie = new windroseGraph();

  ie.execfile("E:\\example.py");

  PyInstance hello = ie.createClass("test", "None");

  hello.invoke("run");

python file  example.py
  from windrose import WindroseAxes
  from numpy.random import random
  from numpy import arange
  from matplotlib import pyplot as plt
  import matplotlib.cm as cm

  class test:

     def new_axes():
        fig = plt.figure(figsize=(8, 8), dpi=80, facecolor='w', edgecolor='w')
        rect = [0.1, 0.1, 0.8, 0.8]
        ax = WindroseAxes(fig, rect, axisbg='w')
        fig.add_axes(ax)
        return ax

     def set_legend(ax):
       l = ax.legend(borderaxespad=-0.10)
       plt.setp(l.get_texts(), fontsize=8)

     def run(self,wd,ws):

       ax = new_axes()
       ax.bar(wd, ws, normed=True, opening=0.8, edgecolor='white')
       set_legend(ax)

       ##print ax._info
       plt.show()

example.py is python file having function with parameter and generate wind graph using windrose.py module (python lib online available )


text:
Q: TimePickerDialog : Clicking "Cancel" button calls onTimeSet() method I use TimePickerDialog with onTimeSet() method. I have added a cancel button with onClickListener.
My problem is that when I click cancel button, onTimeSet() method is called. Why is it? Any way to solve this issue?
// Create timePicker and set listener
timeListener = new TimePickerDialog.OnTimeSetListener() {

    @Override
    public void onTimeSet(TimePicker view, int hourOfDay, int minute) {

        };

    timePicker = new TimePickerDialog(RS_CreateTripActivity.this,
                timeListener, hour, min, false);
    timePicker.setCanceledOnTouchOutside(false);
    timePicker.setCancelable(false);

    // Set negative button click listener
    timePicker.setButton(DialogInterface.BUTTON_NEGATIVE, "Cancel",
                new DialogInterface.OnClickListener() {

        @Override
        public void onClick(DialogInterface dialog, int which) {
                        datePicker.dismiss();
        }
});

I tried by setting positive button with onClickListener but in that case I could not get time selected by user. If any one tells me how to get time within onClickListener, then it would also solve my problem.

A: You have to used this way.
private TimePickerDialog.OnTimeSetListener mTimeSetListener =
            new TimePickerDialog.OnTimeSetListener() {
                public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
                    mHour = hourOfDay;
                    mMinute = minute;
                    time = ""+mHour+":"+mMinute;

           }
    };

@Override
   protected Dialog onCreateDialog(int id) {
        switch (id) {
        case TIME_DIALOG_ID:
            TimePickerDialog myTime = new TimePickerDialog(this,mTimeSetListener, h, m, false);
            myTime(new DialogInterface.OnCancelListener(){
            @Override
            public void onCancel(DialogInterface arg0) {
                //your cancel task.
            }
            );//For cancel button

        return myTime; //Return the dialog
        break;
        return null;
    }

It is work like charm.

A: There is an issue with the DatePickerDialog and the TimePickerDialog (Issue #34833). You could use a counter as a work-around to get rid of this issue.
Pls. refer to : Date Picker with cancel option in android


text:
Q: Looking for an element (in i position) in one list and returning a element (in the same i position) of another list what I have is:
present_tense = ["say","make","go",'take','come','see',"know", "get", "give", "find", "think", "tell", "become", "feel", "leave"]
past_tense = ["said","made",...]

And I want the program searches if the word introduced in a raw_input is in present_tense and if so, it retrieves the element in the past_tense list placed in the same position.
At the moment this is what I have, but I suppose there is a neat way.
def pasttense(verb):
    if verb in present_tense [0]:
      pastform = "said"
    elif verb in present_tense [1]:
      pastform = "made"
    elif verb in present_tense [2]:
      pastform = "went"
    elif verb in present_tense [3]:
      pastform = "took"

A: try something like this
pastform = past_tense[present_tense.index(verb)]

but if verb not in present_tense then raise exception
so if exception not expected you can check that verb in present_tense
if verb in present_tense:
    pastform = past_tense[present_tense.index(verb)]


text:
Q: Account clean up log out hook not working correctly in Mavericks I created a bash script to run on log out that goes through and deletes users except for a specific subset of users. The code is as follows:
#!/bin/bash
# Logout script to remove nonadmin accounts from Users folder
# Script deletes by name, not by admin rights, as to not mess with
# group settings.

# TO SET UP SCRIPT, RUN COMMAND sudo defaults write com.apple.loginwindow LogoutHook /some/path/name/to/script

# If user is an admin, exit script
if [ $USER = "admin" ] || [ $USER = "cas_admin" ] ; then
echo "LOGOUT: admin folders will not be deleted."

# This for loop is a redundancy system, to delete any user accounts that may have
# been left over from a quick shut down.

for dir in /Users/*
    do
        if [ $dir != "/Users/admin" ] && [ $dir != "/Users/cas_admin" ] && [ $dir != "/Users/Shared" ]; then
            echo ${dir}
            rm -R $dir
            dscl . -delete $dir
        fi
    done

exit 1
fi

# If home directory exists, delete
if [ -d "/Users/$USER" ]; then
    echo "LOGOUT: user account cleanup."
    rm -R /Users/"$USER"
    dscl . -delete /Users/"$USER"
fi

# This for loop is a redundancy system, to delete any user accounts that may have
# been left over from a quick shut down.

for dir in /Users/*
do
    if [ $dir != "/Users/admin" ] && [ $dir != "/Users/cas_admin" ] && [ $dir != "/Users/Shared" ] ; then
        echo ${dir}
        rm -R $dir
        dscl . -delete $dir
    fi
done

exit 0

This code is executed on log out using LogoutHook and works perfectly fine in X.6-X.8. However in X.9 Mavericks, the script only works correctly if run directly in bash (deleting both the user's directory and removes the user from the user list), but when run from a LogoutHook, the entire /Users directory gets deleted but the users themselves do not. If the machine is restarted and you select a user from the login screen, the machine goes through the Apple initial setup and generates a new /Users directory and a new directory for the user in question. From the little bit of looking around I have done Login/Logout hooks have issues working with Mavericks, but none of the other solutions I have seen seem to pertain to this issue. This will be used for a computer lab setting and we cannot downgrade to X.8, any suggestions?

A: The script finally works after removing most of the code to:
for dir in /Users/*
  do
    if [ ! "$dir" = "/Users/admin" ] && [ ! "$dir" = "/Users/cas_admin" ] && [ ! "$dir" = "/Users/Shared" ] ; then
      echo ${dir}
      rm -R $dir
      dscl . -delete $dir
    fi
  done

exit 0

following @konsolebox suggestions and changing ownership to root, permissions to rwx--x--x, and using a different text editor (dos to unix headaches). Thank you for all the help.


text:
Q: Openshift and net-ssh incompatibility? (2.9.3-beta1 vs 2.9.2) by searching to access my Postgres DB on Openshift, i'm currently facing problem using net-ssh.

*

*At this step - note that the installed Ruby version is 2.2.0 and net-ssh is 2.9.3-beta1

To be able to access the DB from my local DB IDE, i need to execute:
rhc port-forward myappname
But the execution returns this error: Checking available ports ... Could not parse PKey: no start line
As you can see in this post (an other ones e.g. this one), the fix is to back to a stable version of net-ssh. the 2.9.2.
What i've succesfully done.
But now, running rhc port-forward myappname is giving me the following error: .../2.2.0/rubygems/core_ext/kernel_require.rb:54:in 'require': cannot load such file
And the fix is to upgrade net-ssh to the 2.9.3-Beta1 version (see this post).
This is really weird! Seems that "the snake is biting its own tail" (don't know if that french expression got english translation).
Note that i've tried to make a clean setup with new ssh key gen (automatically and manually).
My system is runnin' Win 7 64bits.
I made uninstall/install of last version of Ruby.
Reinstall of rhc.
Last version running on rhc-1.36.4. The problem goes on.
Can you help?
Should i install an older version of ssh-net and/or Ruby (i'm not allowed to use ssh-net 2.5.2 due to new version of rhc)?
(sorry for my bad english)

A: rhc/Gemfile & rhc/rhc.gemspec required gem "net-ssh", "<= 2.9.2"
net-ssh version 2.9.2 use require dl/import atleast on pageant.rb
dl/import is removed from ruby see https://github.com/ruby/ruby/blob/v2_2_0/NEWS#L148-L149
instead fiddle is recommended
net-ssh 3.* seems to fix this(uses fiddle/{import,{ for ruby >= 2.1)
net-ssh version 3. seems to have drop in compatibility(still working on mine) for rhc
So a simple hack is to modify rhc/Gemfile & rhc/rhc.gemspec and install the gem
A guy already have done it.
A Solution(Untested)
gem 'rhc', :git => 'git://github.com/thrasher-redhat/rhc.git'

from https://stackoverflow.com/a/7421712/2382629
Alternative Solution(Tested even on windows 7 32bit :p)
git clone https://github.com/openshift/rhc
cd rhc

modify rhc/Gemfile & rhc/rhc.gemspec like https://github.com/openshift/rhc/pull/748/files then
gem build rhc.gemspec

it should output like
blah! blah! blah! warnings and msgs......
Successfully built RubyGem
Name: rhc
Version: 1.38.4
File: rhc-1.38.4.gem

then run
gem install rhc-1.38.4.gem

A: You need to use an older version of Ruby, try 1.9.3 or 2.0, or maybe even 2.1.


text:
Q: Can't find the workflow source code of a list or library on SharePoint Designer I'm new using SharePoint. I am having trouble with find the code or workflow structure of a list or a library. In the left menu i can see the "Workflows" button but all workflows are not there.
There is a workflow section In the "List and libraries" view showing the running workflows in these list, but when i click on one of them it just move me to its settings in the browser and  no to the structure or code that is what i'm looking for.
Is there a way to find the code or structure of my running workflows?
PD: I am working in place of the previous developer who build the entire site, however, he didn't show me anything about.
Thanks.

A: If these are workflows created using SharePoint Designer then:

*

*Open SharePoint Designer

*Open the site

*Click on Lists and Libraries

*Click on the list name

*There will be a heading titled "Workflows"

*Click on the workflow you are wanting to look at

*Click "Edit Workflow" to view it

*Go From there

If you are wanting to see the status of a workflow in regards to the item:

*

*Go to the list

*I recommend creating a personal view (so only you see it)

*You can select the fields you are interested in and each workflow should have a column in the list associated with it. Include the column in your view

*Go to your new view and you can click on the link to view the current status of the workflow

A: Go to All Files > Workflows Folder. Then select the workflow you want to work with. Right Click on the "xoml" file then select "Open With" > "SharePoint Designer (open as workflow)"
Once it's opened, published it again. Then it will show up again in the Workflow tab.

A: The workflow was a visual studio sequential workflow deployed in the site as a feature. It was not a SharePoint Designer one. Thanks


text:
Q: Final classes in Python 3.x- something Guido isn't telling me? This question is built on top of many assumptions. If one assumption is wrong, then the whole thing falls over. I'm still relatively new to Python and have just entered the curious/exploratory phase.
It is my understanding that Python does not support the creating of classes that cannot be subclassed (final classes). However, it seems to me that the bool class in Python cannot be subclassed. This makes sense when the intent of the bool class is considered (because bool is only supposed to have two values: true and false), and I'm happy with that. What I want to know is how this class was marked as final.
So my question is: how exactly did Guido manage to prevent subclassing of bool?
>>> class TestClass(bool):
        pass

Traceback (most recent call last):
  File "<pyshell#2>", line 1, in <module>
    class TestClass(bool):
TypeError: type 'bool' is not an acceptable base type

Related question: Why I can't extend bool in Python?

A: You can simulate the same effect from Python 3.x quite easily:
class Final(type):
    def __new__(cls, name, bases, classdict):
        for b in bases:
            if isinstance(b, Final):
                raise TypeError("type '{0}' is not an acceptable base type".format(b.__name__))
        return type.__new__(cls, name, bases, dict(classdict))

class C(metaclass=Final): pass

class D(C): pass

will give the following output:
Traceback (most recent call last):
  File "C:\Temp\final.py", line 10, in <module>
    class D(C): pass
  File "C:\Temp\final.py", line 5, in __new__
    raise TypeError("type '{0}' is not an acceptable base type".format(b.__name__))
TypeError: type 'C' is not an acceptable base type

A: Final and @final types are now available in typing_extensions.
I wrote an article covering almost every part of this new type: https://sobolevn.me/2018/07/real-python-contants
Some examples with classes:
from typing_extensions import final

@final
class HRBusinessUnit(AbstractBusinessUnit):
    def grant_permissions(self) -> None:
        self.api.do_some_hr_stuff()

class SubHRBusinessUnit(HRBusinessUnit):  # mypy will raise an error
    def grant_permissions(self) -> None:
        self.api.do_some_it_stuff()

And with constants:
from typing_extensions import Final

DAYS_IN_A_WEEK: Final = 7
DAYS_IN_A_WEEK = 8  # mypy will raise an error

Also we have a small library to write final classes that are also checked at runtime! https://github.com/wemake-services/final-class
from final_class import final

@final
class Example(object):  # You won't be able to subclass it!
    ...

class Error(Example):  # Raises `TypeError`
    ...

Features:

*

*No metaclass conflicts

*No runtime overhead

*No dependencies

*Type hints included

*Designed to be as simple as possible

A: You could do this only via the C API. Clear the Py_TPFLAGS_BASETYPE bit of the tp_flags of the type object.
As example, bool cannot be subclassed (cpython-code on github):
PyTypeObject PyBool_Type = {
    PyVarObject_HEAD_INIT(&PyType_Type, 0)
    "bool",
    ...
    0,                                          /* tp_as_buffer */
    Py_TPFLAGS_DEFAULT,                         /* tp_flags */
    ...
};

but int can (cpython-code on github):
PyTypeObject PyLong_Type = {
    PyVarObject_HEAD_INIT(&PyType_Type, 0)
    "int",                                      /* tp_name */
    ...
    0,                                          /* tp_as_buffer */
    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE |
        Py_TPFLAGS_LONG_SUBCLASS,               /* tp_flags */
    ...
};

because Py_TPFLAGS_BASETYPE-bit is set in tp_flags.

A: You should block subclassing without using a metaclass like this:
class SomeBase:

    def __init_subclass__(cls, **kwargs):
        super().__init_subclass__(**kwargs)
        if cls is not SomeBase:
            raise TypeError("SomeBase does not support polymorphism.  Use composition over inheritance.")

class Derived(SomeBase):
    pass

In Python 3.8, you should also use the final decorator to induce type-checking errors:
from typing import final

@final
class SomeBase:
    ...

Type-checking is done by programs like MyPy, which are optional.


text:
Q: How do I convert a DOM object created using `node-htmlparser` back to text? I'm using node-htmlparser to manipulate some HTML. Once I've manipulated the DOM object, how can I convert it back to a text string?

A: Use jsdom. It will offer the typical DOM objects and functions you get in the browser:
var jsdom    = require("./lib/jsdom").jsdom,
var document = jsdom("hello world");
var html = document.innerHTML;


text:
Q: Exception creating bean of class org.apache.struts.validator.DynaValidatorForm When accessing a JSP page the following exception is thrown:
Exception creating bean of class org.apache.struts.validator.DynaValidatorForm

Other actions that use this class too are working fine.
Unfortunately we don't know at what problem this exception does hint. Do you have any idea?

A: Try this it worked for me once :
Change
<form-bean name="deptForm" type="org.apache.struts.action.DynaValidatorForm">

to
<form-bean name="deptForm" type="org.apache.struts.[B]validator[/B].DynaValidatorForm">

A: Turned out it was a class loader problem. The same application was deployed two times.
We could have seen it in the log files all along.

A: Check whether the .class file is generated or not in the classes folder.
Some times it happens when you just copy and paste your Java Class and it can't find the class at the time of build.


text:
Q: Where to set delegate of custom table view cell? I'm using  same custom table view cell in multiple classes, the cell has a button in it.
To make button work in different tableviews( in different classes),a protocol method is called when the button on the cell is pressed.
This protocol method is implemented in all the classes in which the custom table view cell is used.
Can anyone please tell me where to set the delegate for the protocol?
Thanks

A: I think you can set cell.delegate in tableview's datasource method: tableView:cellForRowAtIndexPath:. Something like cell.delegate = self;.