text:
Q: How do you create a for loop with a changeable number of iterations? How do you iterate through a loop n amount of times when n is specified by the user at the beginning?
I have written a shell script and need to repeat a certain part of it n numbers of times (depending upon how many times the user wishes).
My script so far looks like this:
echo "how many times would you like to print Hello World?"
read num
for i in {1.."$num"}
do
echo "Hello World"
done

If I change "num" to a number such as "5" the loop works however I need to be able to let the user specify the amount of times to iterate through the loop.

A: You can use seq
for i in $(seq 1 "$num")

or your shell may support C-style loops e.g. in bash
for ((i=0; i<$num; i++))

A: echo "how many times would you like to run your loop ?"
read  max

i=0
while [ "$((i+=1))" -le "$max" ]
do
   # whatever you want to do here
done

A: Using "Arithmetic Evaluation" (bash only):
read -p "how many times would you like to print Hello World? " max

i=0
while  (( i++ < max ))
do
   echo "$i, Hello World."
done

Or use this if you want to make the program quite more robust.
This will extract only numbers from the input. Except for a very big number that could take a long time to be processed, any other input will be cleaned before its used.
while (( i++ < ${max//[^0-9]} ))

A: Yet another way with {1.."$num"}. Bash exapansion need to be evaluated before this can be transferred to the for loop. You can use expansion syntax this way to make it work :
for i in $(eval echo {1.."$num"});
do
 echo $i;
done


text:
Q: If tangent vectors are a vector space of same dimension at every point, does one has a manifold? Let $M$ be a non-empty subset of $\mathbb R^n$, $n \geq 2$.
Recall that a vector $v$ is tangent to $M$ at the point $m \in M$ if it exists a differentiable curve $\gamma : I \to M$ such that $\gamma(0) = m$ and $\gamma'(0) = v$, where $I \subset \mathbb R$ is an interval that contains a neighborhood of $t=0$.
Suppose that it exists an integer $k \geq 1$ such that, for every $m \in M$, the set of vectors that are tangent to $M$ at $m$ is a linear space of dimension $k$ (the same $k$ for every $m$).
Is it true that $M$ is a differential manifold of dimension $k$?

A: I found that the answer is no.
For $n=2$: take $M$ as the union of the two circles of radius 1 centered at $(\pm 1,0)$, at any point one has a tangent space of dimension $k=1$ but it is not a manifold (double point at $(0,0)$).
This idea should be generalizable to arbitrary $n$ and $k$.

redpajama_set_name: RedPajamaStackExchange


text:
Q: mv all files with different extention to a new directory with new filename and same extention could anyone tell my how I could make a script for moving files (filename given but all possible extentions) to another new directory with new filename but same extentions.
f.e. (dir or filename could have blanks in it)
     dir1/m.mobi
     dir1/m.epub

should be moved to
     newdir/dir1/9989.mobi
     newdir/dir1/9989.epub

I have tried this.
     mv "./dir1/m".* "./newdir/dir1/9989.*"

but I get the error that ./newdir/dir1/9989.* is not a directory.
WHere is my bug?
EDIT: I found that I could do a rename first  with rename 's/m/9989/' m.*
Thanks
Walter

A: I found a solution: this
   rename 's/m/9989/' ./dir1/m.* &&  mv ./dir1/9989.* ./newdir/dir1/


text:
Q: "sh: #: unknown operand" - How do I get rid of this error on shell script? I have a shell script which when executed works fine, but gives a warning:
sh: #: unknown operand

In this shell script, I want to comment out the processes namely "process1" and "process2", which are also shell scripts designed for other tasks, and after commenting them out, I want to transfer the contents of path1 to a file in path2
#!/bin/sh
rootpath="/opt/storage"
datestring=`date +"%y-%m-%d"`
touch newfile1
touch newfile2
autorun_contents=`cat FILE1`
if [ ! -f ${FILE1} ] || [ -z "`echo \"${FILE1}\" | tail -10 | grep EOF`" ]; then
echo "Something was wrong with the file"
return
fi
sed "s/.\/process1/# .\/process1/g" FILE1 > FILE2 | echo "Hi1"
sed "s/.\/process2/# .\/process2/g" FILE1 > FILE2 | echo "Hi2"

Any suggestions would be greatly appreciated. Thanks!


text:
Q: django url tag performance I was trying to integrate django-voting into my project following the RedditStyleVoting instruction.
In my urls.py, i did something like this:
    url(r'^sections/(?P<object_id>\d+)/(?P<direction>up|down|clear)vote/?$',
    vote_on_object,
    dict(
        model=Section,
        template_object_name='section',
        template_name='script/section_confirm_vote.html',
        allow_xmlhttprequest=True
        ),
    name="section_vote",

then, in my template:
    {% vote_by_user user on section as vote %}
{% score_for_object section as score %}

<form class="sectionvote" id="sectionup{{ section.id }}"{% if vote and vote.is_upvote %} action="{% url section_vote object_id=section.id, direction="clear" %}"{% else %} action="{% url section_vote object_id=section.id, direction="up" %}"{% endif %} method="POST">
<input type="image" id="sectionuparrow{{ section.id }}" src="{{ MEDIA_URL }}/aup{% if vote and vote.is_upvote %}mod{% else %}grey{% endif %}.png"></form>

{{ score.score|default:0 }}

<form class="sectionvote" id="sectiondown{{ section.id }}"{% if vote and vote.is_downvote %} action="{% url section_vote object_id=section.id, direction="clear" %}"{% else %} action="{% url section_vote object_id=section.id, direction="down" %}"{% endif %} method="POST">
<input type="image" id="sectiondownarrow{{ section.id }}" src="{{ MEDIA_URL }}/adown{% if vote and vote.is_downvote %}mod{% else %}grey{% endif %}.png"></form>

It takes over 1.3s to load the page, but by hard coding it like this:
<form class="sectionvote" id="sectionup{{ section.id }}"{% if vote and vote.is_upvote %} action="sections/{{section.id}}/clearvote/"{% else %} action="sections/{{section.id}}/clearvote/"{% endif %} method="POST">

<form class="sectionvote" id="sectiondown{{ section.id }}"{% if vote and vote.is_downvote %} action="sections/{{section.id}}/clearvote/"{% else %} action="sections/{{section.id}}/downvote/"{% endif %} method="POST">

I got 50ms. Just avoid the url tag resolving stuff I got a 20+ times performance improvement.
Is there something I did wrong? If not, then what's the best practice here, should we do things the right way or the fast way?

A: If you're using the development version, there has recently been a regression which has massively increased the time it takes to reverse-lookup URLs - see the ticket here. It is scheduled to be fixed before the final release of 1.2.


text:
Q: Remove all activities of an app from every existing task in Activity Back Stack Is there a way of removing all activities belonging to the app in foreground (my app)?
The activities might be present in different tasks. Also after removing all activities my app should return to home screen which is launcher activity of my app.
Any kind of help would be greatly appreciated.

A: You need to call your activity like this.
Intent login=new Intent(MainActivity.this,HomeActivity.class);
login.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK);
login.putExtra("flag",false);
startActivity(login);
finish();

A: You may need
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK|Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);

FLAG_ACTIVITY_CLEAR_TASK

Any existing task that would be associated with the current activity to be cleared before the desired activity is started. Simply old activities are finished.

FLAG_ACTIVITY_NEW_TASK

If set, this activity will become the start of a new task on this history stack.
for more details, Intent Flags

A:     Intent i = new Intent(OldActivity.this, NewActivity.class);
    // set the new task and clear flags
    i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
    startActivity(i);
finish();


text:
Q: Replace InvocationHandler in java.lang.reflect.Proxy I need to replace InvocationHandler in a Proxy object. But there is only getter for it and no setter. Why is this so and is there any workaround?
Thanks

A: I think you'll need to keep the same invocation handler but have it change its behaviour. This will be closer to what you're looking for if you use the State pattern in the invocation handler:
public class Handler implements InvocationHandler
{
    HandlerState state = new NormalState();

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

        // Make all method calls to the state object, not this object.
        this.state.doStuff();

        return this.state.doOtherStuff();
    }

    public void switchToErrorState(){
        this.state = new ErrorState();
    }
}

public interface HandlerState
{
    public void doStuff();
    public String doOtherStuff();
}

public class ErrorState implements HandlerState
{
    @Override
    public void doStuff() {
        // Do stuff we do in error mode
    }

    @Override
    public String doOtherStuff() {
        // Do other error mode stuff.
        return null;
    }
}

public class NormalState implements HandlerState
{
    @Override
    public void doStuff() {
        // Do normal stuff
    }

    @Override
    public String doOtherStuff() {
        // Do normal other stuff
        return null;
    }
}


text:
Q: Как открыть вкладку bootstrap 5 по ссылке? Есть пример вкладок из документации bootstrap 5. Как открыть нужную вкладку по ссылке?

<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BmbxuPwQa2lc/FVzBcNJ7UAyJxM6wuqIj61tLrc4wSX0szH/Ev+nYRRuWlolflfl" crossorigin="anonymous">

Ссылка должна открыть вкладку profile: profile

    <button class="nav-link active" id="home-tab" data-bs-toggle="tab" data-bs-target="#home" type="button" role="tab" aria-controls="home" aria-selected="true">Home</button>

    <button class="nav-link" id="profile-tab" data-bs-toggle="tab" data-bs-target="#profile" type="button" role="tab" aria-controls="profile" aria-selected="false">Profile</button>

    <button class="nav-link" id="contact-tab" data-bs-toggle="tab" data-bs-target="#contact" type="button" role="tab" aria-controls="contact" aria-selected="false">Contact</button>

Текст 1

Текст 2

Текст 3


text:
Q: Ruby: How to walk thru db record to return true key/value pair How can I return the key value pair that is true from this database record. Can't seem to get it this morning, probably need more coffee..
Here is my code:
def get_enabled_speeds_from_db
  @speed_details = []
  current_speeds.each do |speed|
    @speed_details << shop.speeds.find_by(shipping_speed: speed)
  end
end

In the above method current_speeds is just an array with the speeds listed, it looks like this:
["Standard", "Expedited"]

And when the method finishes, speed_details looks like this:
[#<Speed id: 51, shipping_speed: "Standard", fixed: false, fixed_amount: nil, flex: true, flex_dollar_or_percent: "$", flex_amount: #<BigDecimal:411ebb8,'0.1E2',9(18)>, free: false, free_shipping_amount: nil, created_at: "2018-07-11 18:39:17", updated_at: "2018-07-11 18:39:17", store_id: 15, enabled: true>, #<Speed id: 52, shipping_speed: "Expedited", fixed: true, fixed_amount: #<BigDecimal:3f6e2a0,'0.1E2',9(18)>, flex: false, flex_dollar_or_percent: "", flex_amount: nil, free: true, free_shipping_amount: 25.0, created_at: "2018-07-11 18:39:46", updated_at: "2018-07-11 18:39:46", store_id: 15, enabled: true>]

Now what I want to do is step thru speed_details to pull out the key/value pairs that are set to true. For example, in speed id:51 flex: true and enabled: true. And in speed id: 52 fixed is true.
This is my method to do this, but I can't use select on speed. I've tried changing to an array and enum, but I need the key/value pair, not just if true exists.
def get_enabled_speed_details_that_are_true
  speed_details.each do |speed|
    speed_name = {speed: speed[:shipping_speed]}
    whats_turned_on = speed.select{|k,v| v == true }
    walk_thru_each_rate_type(speed_name.merge(whats_turned_on))
  end
end

Any suggestions?

A: You might first want to get only those fields whose values are boolean i.e can be only true/false and then filter from it.
final_result = []
Model.select('field1, field2, field3').each do |model|
  current_matching_result = model.attributes.collect{|key,value| key if value ==true}
  if current_matching_result.compact.present?
    truthy_array = [true] * current_matching_result.count
    filtered_attributes_hash = current_matching_result.zip(truthy_array).to_h.merge!({id: model.id})
    final_result << filtered_attributes_hash
  end
end


text:
Q: PHP recursive function nesting level reached Good day. I have a parcer function that taker an array of string like this:
['str','str2','str2','*str','*str2','**str2','str','str2','str2']

And recursivelly elevates a level those starting with asterix to get this
['str','str2','str2',['str','str2',['str2']],'str','str2','str2']

And the function is:
function recursive_array_parser($ARRAY) {
    do {

        $i = 0;
        $s = null;
        $e = null;
        $err = false;

        foreach ($ARRAY as $item) {

            if (!is_array($item)) { //if element is not array
                $item = trim($item);
                if ($item[0] === '*' && $s == null && $e == null) { //we get it's start and end if it has asterix
                    $s = $i;
                    $e = $i;
                } elseif ($item[0] === '*' && $e != null)
                    $e = $i;
                elseif (!isset($ARRAY[$i + 1]) || $s != null && $e != null) { //if there are no elements or asterix element ended we elevate it
                    $e = $e == NULL ? $i : $e;
                    $head = array_slice($ARRAY, 0, $s);
                    $_x = [];
                    $inner = array_slice($ARRAY, $s, $e - $s + 1);
                    foreach ($inner as $_i)
                        $_x[] = substr($_i, 1);

                    $inner = [$_x];
                    $tail = array_slice($ARRAY, $e + 1, 999) or [];
                    $X = array_merge($head, $inner);
                    $ARRAY = array_merge($X, $tail);

                    $s = null;
                    $e = null;
                    $err = true;
                }
            } else {
                $ARRAY[$i] = recursive_array_parser($ARRAY[$i]); //if the item is array of items we recur.
            }
            $i++;

            if ($err == true) {
                break 1;
            }
        }
    } while ($err);
    return $ARRAY;
}

When this function runs, i get "Fatal error: Maximum function nesting level of '200' reached, aborting!" error.
I know it has something to do with infinite recursion, but i can't track the particular place where it occurs, and this is strange.

A: I don't normally rewrite code, but your code can be reduced and simplified while, from what I can see, getting the desired result. See if this works for you:
$a = array('a','b','c','*d','*e','**f','g','*h');
print_r($a);
$a = recursive_array_parser($a);
print_r($a);
function recursive_array_parser($array)
{
    $ret = array();
    for($i=0; $i<sizeof($array); $i++)
    {
        if($array[$i]{0}!='*') $ret[] = $array[$i];
        else
        {
            $tmp = array();
            for($j=$i; $j<sizeof($array) && $array[$j]{0}=='*'; $j++)
            {
                $tmp[] = substr($array[$j],1);
            }
            $ret[] = recursive_array_parser($tmp);
            $i = $j-1;
        }
    }
    return $ret;
}

Note that it isn't possible for $array[$i] to be an array, so that check is removed. The recursion takes place on the temp array created when a * is found. The $i is closer tied to $array to reset it properly after parsing the series of * elements.

A: Here's my solution. No nested loops.
function recursive_array_parser($arr) {
    $out = array();
    $sub = null;
    foreach($arr as $item) {
        if($item[0] == '*') { // We've hit a special item!
            if(!is_array($sub)) { // We're not currently accumulating a sub-array, let's make one!
                $sub = array();
            }
            $sub[] = substr($item, 1); // Add it to the sub-array without the '*'
        } else {
            if(is_array($sub)) {
                // Whoops, we have an active subarray, but this thing didn't start with '*'. End that sub-array
                $out[] = recursive_array_parser($sub);
                $sub = null;
            }
            // Take the item
            $out[] = $item;
        }
    }

    if(is_array($sub)) { // We ended in an active sub-array. Add it.
        $out[] = recursive_array_parser($sub);
        $sub = null;
    }

    return $out;
}


text:
Q: How to handle with NA's when doing glm in R (and not removing entire rows)? I want to make my first glm but in some of the variables I use are NA's. I can't find the right information about how to clean these columns so it can be used in glm.
Is it possible to handle this at once when making a model in the glm function? Or is it necessary to do it in advance for every column.
And what is the best way for doing this without removing entire rows in the dataframe? By using
na.omit() it removes all incomplete cases of a data object but I only want to ignore these NA's when modelling.
I found this one usefull for integer variables
df %>% mutate_all(~ifelse(is.na(.x), mean(.x, na.rm = TRUE), .x))

But what about numeric variables like 1 = male and 2 = female?
I think it is really a beginners issue, not that exciting for most of you I think.. But hopefully someone can help me.
Thanks in advance!

A: Missing information (NA) in variables is quite tricky to handle. First of all, NA values will be omitted. It is not possible to fit a regression model using NA values, so you have to handle them before fitting the glm model.
There are a lot of approaches, the easiest ones are omitting the rows with NAs (what glm does by default), imputing the NA values with the most frequent, the one from the previous row or the median/mean (those are called single imputation methods) or other more complex approaches that use two or more variables at once to get the right values (multiple imputation methods).
The solution will depend always on the context of the data. And you have to know that the existence of missing data will mean an error or bias in your results. So it is important to try to reduce this bias in the glm model.
For a bit more information, for example you can have a look to this post: https://www.kdnuggets.com/2017/09/missing-data-imputation-using-r.html#:~:text=In%20R%2C%20there%20are%20a%20lot%20of%20packages,and%20probably%20a%20gold%20standard%20for%20imputing%20values.


text:
Q: Conditional format cell if row contains one or more blank cells? Imagine a sheet where column A is names and the other columns contain relevant information for those names.  I want to conditionally format the cells in column A so that if there is a blank cell in that row that should be filled, the name cell will display the conditional formatting; think of it like a "there's missing info for this person" indicator.
Before this gets brought up: while it's trivial to set up conditional formatting to color empty cells, coloring the blank cell itself has proven to be not sufficiently noticeable due to the width of the spreadsheet.

A: It's exactly as @mehdi said. You need to use COUNTBLANK(range).
For conditional format, use the option "Format Cells where this formula is true". My formula in cell A2 is like this:
=IF(COUNTBLANK(2:2)>0;TRUE;FALSE)

After typing it, just change the range where this rule applies and select your range data.
I did it like you can see in the image below (please, note I got spanish version of Excel). In my case, if ANY cell in the row is blank, then it colours with yellow the cell.


text:
Q: Android: Out of Memory Exception / How does decodeResource add to the VM Budget? I am pretty new to Android and have been developing a game. Every now and again I have users reporting out of memory exceptions, which I find surprising since the bitmaps that I create are at most 200 kb in size. I call BitmapFactory.decodeResource() whenever I create a new sprite. Since my application is a zombie defense game, you could expect that I create sprites quite often.
Every time I create a sprite, I call decode resource to generate a bitmap. My question is if I was to only call decode resource at the start of each activitiy, and refer to the bitmap at package level, would this lessen the amount of memory placed on the VM Budget?

A: *

*When you decode the Bitmap from an image resource like png, it
depends more on the dimensions of image rather then the size in KBs.

*Try if you can reduce the dimensions of original image without really impacting your output.

*Try reusing the bitmaps rather then keep decoding them.

*Explore more options with BitmapFactory.Options() object, for example increasing inSampleSize can reduce the amount of memory required by the image.
e.g

BitmapFactory.Options o=new BitmapFactory.Options();
o.inSampleSize = 4;
o.inDither=false;                     //Disable Dithering mode
o.inPurgeable=true;                   //Tell to gc that whether it needs free memory, the Bitmap can be cleared
myBitMap=BitmapFactory.decodeResource(getResources(),ID, o);

*One useful tricky solution if no other optimizations are really working out for you is that, you can catch the OutOfMemoryException and then can reduce the quality to max.. i.e. setting the inSampleSize to 16. It will reduce the quality of your images but at least will save your application from crashing, i did this in one of my app where I needed to load huge MP image in a bitmap.

A: My snippet to get image from resources safety. You can set your own sampleSize as threshold of image quality (larger sampleSize is lower image quality).
public static Bitmap loadBitmapSafety(int resDrId,  Context context){
    return loadBitmapSafety(resDrId, 1, context);
}

private static Bitmap loadBitmapSafety(int resDrId, int sampleSize, Context context){
    BitmapFactory.Options ops = new BitmapFactory.Options();
    ops.inSampleSize = sampleSize;

    try {
        return BitmapFactory.decodeResource(context.getResources(), resDrId, ops);

    } catch (OutOfMemoryError e) {
        if (sampleSize == 4)
            return null;
        return loadBitmapSafety(resDrId, sampleSize +1, context);

    } catch (Exception e){
        return null;
    }
}


text: Q: Unknown class  in Interface Builder file, but only iOS 5 I am getting an error which says "Unknown class  in Interface Builder file". I have found lots of answers for this question but in mine it only happens on iOS 5. If I use iOS 6 it works fine. Why would it only fail on iOS 5?


text:
Q: Forming the "Usual" Push-out from a Colimit Diagram. Motivation.  Piggybacking a previous question that I posted, and drawing the colimit diagram for reference and notation:

I wanted to be able to formally say that $\phi_{X},\phi_{Y}$ were injections (in the usual sense) so that, for example, taking a pushout would give me the "natural" pushout (as opposed to some other colimit using different $\phi_{X}$ and $\phi_{Y}$ mappings which are not the injection mappings).  In some cases, I would explicitly be in some category (like spaces) and I could say something like $\phi_{X}(y) = y$ in order to force my map to be the injection map; but in other cases where the arrows between objects are not functions (like poset categories) I'm not sure how to say this formally.
Question.  When one talks about taking "the usual" pushout, how does one define the injective arrows $\phi_{X}$ and $\phi_{Y}$ for categories where the arrows are not functions (as in the category of posets).
I'm a bit new at this stuff, so if my question is not well-stated or garbled I will attempt to reword it!

A: To help you with wording, what you are asking is how the inclusions into the colimit are defined in categories which aren't concrete.
In any category, you have a notion of what a morphism is, and to define a morphism you simply have to specify which of these morphisms your inclusion is.  In a concrete category, this means that you can define a morphism by specifying what it does to each object in a set, but that's not the only way!
Consider the category whose objects are real numbers and we have a unique morphism $x\to y$ if $x\leq y$.  Then and subset $X\subseteq \mathbb R$ can be thought of as a diagram in our category, and the colimit of this diagram would be a real number $L$ such that for every $x\in X$, we have a map $x\to L$, and if we have any other number $M$ such that each $x\in X$ has a map $x\to M$, then we have a factorization $x\to L\to M$.  Since the existence of a map $x\to y$ just means $x\leq y$, this is another way of saying that $L=\sup X$ (if it exists!  This category isn't complete or cocomplete meaning limits and colimits need not exist).  In this case, the maps into the colimit are the only maps they can be.  I.e. the map $\phi_x\colon x\to L$ is the unique map given since $x\leq L$.
As an exercise, try writing down something similar for the case of limits, and then work out what limits and colimits are in an arbitrary poset.
As another side note, technically a poset is a concrete category, meaning it's equivalent to one whose underlying objects are sets.  See if you can work out how this is done.

A: In category theory, there is a notion of a monic map, which is typically used in place of the notion of an injective function. If both $\phi$ and $\psi$ are cocones, then $\phi_X$ is monic if and only if $\psi_X$ is monic.
However, I think you didn't mean "injection", but instead "inclusion". In general, things in category theory are only defined up to isomorphism. There typically is no literal analog of the set-theoretic notion of "subset".
However, it's not hard to use monic maps to define a notion of "subobject": a subobject of $X$ is just an isomorphism class of "monic maps to $X$" Specifically, if  $f : Y \to X$ and $g : Z \to X$ are monic, then a morphism of "monic maps to $X$" from $f$ to $g$ is given by a morphism $h : Y \to Z$ such that $gh = f$. It's an isomorphism of "monic maps to $X$" iff $h$ is an isomorphism.
This reproduces the notion of inclusion when you couple it with the notion of a generalized element. A generalized element of $X$ is simply a morphism $a : Y \to X$. If $S$ is a subobject of $X$, then we can $a \in S$ iff there is a factorization $a = fb$ (where $f$ is any representative of the isomorphism class $S$).
Also, if $g : X \to Z$ is a morphism, we write $g(a)$ for the generalized element $ga$ of $Z$.

That said, the maps $\phi_X$ aren't always monic, so even in $\mathbf{Set}$, you can't arrange for them to be inclusions (or even injections). (e.g. in a pushout diagram, if all of the arrows are epimorphisms, then the maps $\phi_X$ are epimorphisms too)
Even if they are monic, you still can't always arrange for them to be inclusions. For example, consider the pushout of the diagram
$$
\begin{array}{ccc}
\{ x \} &\to&  \{ y \}
\\
\downarrow
\\
\{ x \}
\end{array}
$$
The pushout is a one-element set, but if $x \neq y$, it cannot contain both $\{x\}$ and $\{ y \}$.


text:
Q: Change in scope variable updating Service variable Can somebody please have a look at below plunker?
http://plnkr.co/edit/oTHJcVVzJE5CwMnFMEpS?p=preview
Problem: Change in the scope variable "specifications.selectedColor" is overwriting the specifications of other products i.e changing the selectedColor of all the products.
Steps to reproduce:
1) Click on Buy Now.  checkoutProductList[0].selectedColor is set to Red.
2) Select Blue color from the drop-down.
3) Click on Buy Now. checkoutProductList[0].selectedColor is set to Blue.
On clicking Buy Now second time(step 3 above), it adds another product in checkoutProductList Array i.e checkoutProductList[1], it should not change
checkoutProductList[0].selectedColor from Red to Blue.
What can be done to keep specifications of each product separately?
Code:
Contoller
var app = angular.module('plunker', ['ui.select', 'ngSanitize']);

app.controller('MainCtrl', function($rootScope, $scope,checkoutService) {

  $scope.productAvailableColors=['Red','Blue'];
  $scope.specifications={'selectedColor':'Red'};

  $scope.buyNow = function (){

    checkoutService.setCheckoutProductList($scope.specifications);
  };

});

app.service ('checkoutService', function (){
  var checkoutProductList=[];
  this.setCheckoutProductList = function ( specs){
    checkoutProductList.push(specs);
    window.alert(checkoutProductList.length);
    window.alert(checkoutProductList[0].selectedColor);
  }

})

HEAD
HTML:
<!DOCTYPE html>

  <meta charset="utf-8" />
  <title>AngularJS Plunker</title>

  <link rel="stylesheet" href="style.css" />

  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.3/css/bootstrap.min.css" integrity="sha384-MIwDKRSSImVFAZCVLtU0LMDdON6KVCrZHyVQQj6e8wIEJkW4tvwqXrbMIya1vriY" crossorigin="anonymous">
  <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css">

  <link rel="stylesheet" href="http://cdnjs.cloudflare.com/ajax/libs/select2/3.4.5/select2.css">
  <link rel="stylesheet" href="http://cdnjs.cloudflare.com/ajax/libs/selectize.js/0.8.5/css/selectize.default.css">

  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-select/0.19.4/select.min.css">

BODY

Buy Now

            <ui-select ng-model="$parent.specifications.selectedColor"
              theme="bootstrap"
              ng-disabled="false"
              close-on-select="true"
              style="color: black;"
              title="Choose Color and Design"
              >
              <ui-select-match placeholder="Choose Color/Design">{{$parent.specifications.selectedColor}}</ui-select-match>
              <ui-select-choices repeat="listItem in productAvailableColors | filter:$select.search">

              </ui-select-choices>
           </ui-select>

  {{specifications | json}}

A: Problem
The problem lies in deep copy and shallow copy in JavaScript. When you are pushing an object to the array, it's not really creating a copy of the object and pushing it instead it just stores a reference to the original object (which is $scope.specifications in your case). Since you are changing the $scope.specifications object in your controller your array is also getting changed.
Solution
You can leverage the angular.copy method which is used to create deep copy of an object. So what you can do is before pushing the object to the array, you can make a deep copy of the object and then push it to the array.
In your service where you are pushing the object to the array make this change
checkoutProductList.push(angular.copy(specs));

Full Service
app.service ('checkoutService', function (){
    var checkoutProductList=[];
    this.setCheckoutProductList = function ( specs){
    checkoutProductList.push(angular.copy(specs));
    window.alert(checkoutProductList.length);
    window.alert(JSON.stringify(checkoutProductList));
 }

I have also created a plunkr to demonstrate the working solution. You can see it here.


text:
Q: PHP add single quotes to comma separated list When I implode my array I get a list that looks like this:
qwerty, QTPQ, FRQO

I need to add single quotes so it looks like:
'qwerty', 'QTPQ', 'FRQO'

Can this be done using PHP?

A: Use ' before and after implode()
$temp = array("abc","xyz");

$result = "'" . implode ( "', '", $temp ) . "'";

echo $result; // 'abc', 'xyz'

A: It can also be as short as this:
sprintf("'%s'", implode("', '", $array))

A: You can set the glue to ', ' and then wrap the result in '
$res = "'" . implode ( "', '", $array ) . "'";

http://codepad.org/bkTHfkfx

A: Here is another way:
$arr = ['qwerty', 'QTPQ', 'FRQO'];

$str = implode(', ', array_map(function($val){return sprintf("'%s'", $val);}, $arr));

echo $str; //'qwerty', 'QTPQ', 'FRQO'

sprintf() is a clean way of wrapping the single quotes around each item in the array
array_map() executes this for each array item and returns the updated array
implode() then turns the updated array with into a string using a comma as glue

A: Similar to what Rizier123 said, PHP's implode method takes two arguments; the "glue" string and the "pieces" array.
so,
$str = implode(", ", $arr);

gives you the elements separated by a comma and a space, so
$str = implode("', '", $arr);

gives you the elements separated by ', '.
From there all you need to do is concatenate your list with single quotes on either end.

A:     $ids = array();
    foreach ($file as $newaarr) {
        array_push($ids, $newaarr['Identifiant']);

    }
   $ids =array_unique($ids);
    //$idAll=implode(',',$ids);

     $idAll = "'" . implode ( "', '", $ids ) . "'";

A: function implode_string($data, $str_starter = "'", $str_ender = "'", $str_seperator = ",") {
    if (isset($data) && $data) {
        if (is_array($data)) {
            foreach ($data as $value) {
                $str[] = $str_starter . addslashes($value) . $str_ender . $str_seperator;
            }
            return (isset($str) && $str) ? implode($str_seperator, $str) :  null;
        }
        return $str_starter . $data . $str_ender;
    }
}

A: You can use the method called 'implode' in the PHP.
That will help you to concatenate all the array values with th given delimiter.
$arr = ['qwe', 'asd', 'zxc'];
echo implode(',', array_map(function($i){return "'".$i."'";}, $arr));

You output will be something like below:
'qwe','asd','zxc'


text:
Q: Issue With Jellybean Menu button Android When I press the menu the screen button the screen fades away slowly and up pops my apparently in Jellybean. Is these issue with my code or any other stuff going on? I can't seem to find out how to change it.
Anyone know this thing?
Here is my java code with onCreateOption Menu :
  @Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.activity_main, menu);
    return true;
}

My menu xml file "activity_main" :
<menu xmlns:android="http://schemas.android.com/apk/res/android">
<item android:id="@+id/menu_settings"
    android:title="@string/menu_settings"
    android:orderInCategory="100"
    android:showAsAction="never" />
</menu>

Thanks,
Jay Patel

A: Phones with hardware menu button wont show three dot overflow button. Instead when you press the hardware menu button the actionar items will show in popup. I dont know if that is your issue as you really provide very little info and your grammar is very unreadable.


text:
Q: Cocoa JSON - Check whether array or dictionary I am using the Cocoa JSON framework ( http://code.google.com/p/json-framework/ ) to communicate with an API.
The problem is that the API returns a dictionary if there is an error but returns an array of the results if it works.
Is there a good way to detect if the JSONValue is an array or a dictionary?
Thanks.

A: You can use isKindOfClass: to test whether the object is an instance of NSDictionary or of any subclass thereof.
In most circumstances, you would be better served by a respondsToSelector: check, but this is one case where you really are better off testing its class membership.
Of course, you can test whether it's an array instead of whether it's a dictionary; as long as the API you're using only returns an array or dictionary, the effect is the same.
For true robustness, test both array and dictionary membership, and throw an exception or present an error if the object is neither.

A: Maybe try to check length property.
if (jsonObj.length) {
   //doSomeWork
}

A: Try this:
if ([YourData isKindOfClass:[NSArray class]])
{
    NSLog(@"Array format found");
}
else
{
    NSLog(@"Dictionary format found");
}


text:
Q: Django how to send html-designed email bodies On my Django project I am trying to send beautiful mails with colorful body and so on. My mail body constructing function looks like the following:
def construct_mail_body():
    user = User.objects.get(id=1)
    context = {
        'username': user.username,
    }
    template = render_to_string('mail/mail_body.html', context=context)
    message = strip_tags(template)
    return message

mail_body.html:
{% load static %}

Hello {{ username }},

You've successfully completed our Tutorial!>

Congratulations!

But it doesn't work as expected. My mail bodies looks like:
Body 1:

Body 2 (Btw, why this happens? Why the mail is in purple?):

So how to make HTML tags work properly and is it possible to add some styling properties of css?
Thanks!
Solved:
I found a way how to do that:
from django.core.mail import EmailMessage

mail = EmailMessage(
        subject,
        body,
        settings.EMAIL_HOST_USER,
        [email],
    )
mail.fail_silently = False
mail.content_subtype = 'html'
mail.send()

This way it works properly.

A: This is possible, but stick to hex colours, e.g. #ff0000, instead of a named colour.
Text can all go purple, as Willem commented, when something is repeated, or for replies. If you change the subject line when testing, it won't group them, and so it won't do this.
Keep using inline CSS, but stick to HTML4 and CSS2 (higher can be achieved but as a progressive enhancement for some email clients only).


text:
Q: Visualforce page with Full Calendar Events not populating I am looking at setting up a custom calendar using Full Calendar (https://fullcalendar.io/ ) and am following the guide here: https://salesforceprojects.quora.com/Implement-full-calendar-drag-and-drop-in-Visualforce-page
I have updated to the Below Visualforce Page and Controller Reference, but do not see any events on the rendered calendar even though my query is returning results?  Also would it be better to write this with Remote Actions?
Visualforce Page:
<apex:page id="pg" standardStylesheets="false"  Controller="CalendarController" action="{!pageLoad}">
    <link href="{!$Resource.fullCalendarCSS}" rel="stylesheet" />
    <link href="{!$Resource.fullCalendarPrintCSS}" rel="stylesheet" media="print" />

    <apex:outputPanel id="calPanel">
        <apex:form id="theForm">
            <apex:actionFunction name="setEvnt" action="{!setEvent}" reRender="pg" >
                <apex:param value="" name="item" assignTo="{!eventIdTemp}"/>
                <apex:param value="" name="test" assignTo="{!st}"/>
                <apex:param value="" name="test1" assignTo="{!ed}"/>
            </apex:actionFunction>

        </apex:form>
    </apex:outputPanel>
</apex:page>

Controller:
public class CalendarController {
    public list <CalendarEvent> events {get;set;}
    //This allows a toggle to show personal events
    public Boolean includeMyEvents {get;set;}

    //The calendar plugin is expecting dates is a certain format. This string is used to format the dates correctly
    String dtFormat = 'EEE, d MMM yyyy HH:mm:ss z';

    // As Events can be dynamically dragged around the calender variables are used for these selections
    public String eventIdTemp   {get;set;}  //Selected event Id coming from vf page
    public String st    {get;set;}  //Selected event start date
    public String ed    {get;set;} //Selected event end date
    public List <Event> eventList = new List <Event> ();

    public CalendarController() {
       eventList = [Select Id, Subject, isAllDayEvent, StartDateTime, EndDateTime, CreatedDate, LastModifiedDate
                    From Event
                    Where OwnerId = '005j000000C1f0AAAR' ];
}

//Method to query requested event records and place in calendar
    public PageReference pageLoad() {
   //     eventList = [SELECT CreatedDate,EndDateTime,IsAllDayEvent,LastModifiedDate,StartDateTime,Subject FROM Event WHERE OwnerId = '005j000000C1f0AAAR'];
        List <CalendarEvent> events = new list <CalendarEvent> ();
            for(Event e : eventList){
            DateTime startDt = e.StartDateTime;
            DateTime endDt = e.EndDateTime;
            DateTime createdOn = e.CreatedDate;
            DateTime modifiedOn = e.LastModifiedDate;
            CalendarEvent newEvent = new CalendarEvent();
            newEvent.eventId = e.Id;
            newEvent.eventTitle = e.Subject;
            newEvent.allDay = e.isAllDayEvent;
            newEvent.eventStart = startDt.format(dtFormat);
            newEvent.eventEnd = endDt.format(dtFormat);
            newEvent.url = '/' + e.Id;
            newEvent.className = 'event-personal';
            events.add(newEvent);
        }
        return null;
    }
//   Parse the date format and set values
    public void setEvent() {
        List <String> stringParts = ed.split('T');
        List <String> dateParts = stringParts[0].split('-');
        List <String> timeParts = stringParts[1].split(':');
        DateTime dt1 = DateTime.newInstance(Integer.valueOf(dateParts[0]), Integer.valueOf(dateParts[1]), Integer.valueOf(dateParts[2]), Integer.valueOf(timeParts[0]), Integer.valueOf(timeParts[1]), Integer.valueOf(timeParts[2]));
        stringParts = st.split('T');
        dateParts = stringParts[0].split('-');
        timeParts = stringParts[1].split(':');
        DateTime dt2 =  DateTime.newInstance(Integer.valueOf(dateParts[0]), Integer.valueOf(dateParts[1]), Integer.valueOf(dateParts[2]), Integer.valueOf(timeParts[0]), Integer.valueOf(timeParts[1]), Integer.valueOf(timeParts[2]));
        for(Event e : eventList) {
            if(e.Id == eventIdTemp) {
                e.EndDateTime = dt1;
                e.StartDateTime = dt2;
                update e;
            }
        }
    }
}

CalendarEvent Class:
//Class to hold the Calendar Events that are used fullcalendar http://fullcallendar.io

public class CalendarEvent {

//Variables are set from the CalendarController Class

    public String eventId       {get;set;}
    public String eventTitle    {get;set;}
    public String eventEnd      {get;set;}
    public String eventStart    {get;set;}
    public String eventColor    {get;set;}
    public String url           {get;set;}
    public Boolean allDay       {get;set;}
    public String className     {get;set;}
}

A: I realized in my pageLoad method I was re-declaring my events variable rather than declaring at the class level.  It now works great.

//Method to query requested event records and place in calendar
    public PageReference pageLoad() {
   //     eventList = [SELECT CreatedDate,EndDateTime,IsAllDayEvent,LastModifiedDate,StartDateTime,Subject FROM Event WHERE OwnerId = '005j000000C1f0AAAR'];
          events = new list <CalendarEvent> ();
            for(Event e : eventList){
            DateTime startDt = e.StartDateTime;
            DateTime endDt = e.EndDateTime;
            DateTime createdOn = e.CreatedDate;
            DateTime modifiedOn = e.LastModifiedDate;
            CalendarEvent newEvent = new CalendarEvent();
            newEvent.eventId = e.Id;
            newEvent.eventTitle = e.Subject;
            newEvent.allDay = e.isAllDayEvent;
            newEvent.eventStart = startDt.format(dtFormat);
            newEvent.eventEnd = endDt.format(dtFormat);
            newEvent.url = '/' + e.Id;
            newEvent.className = 'event-personal';
            events.add(newEvent);
        }
        return null;
    }

A: is it still work? Because i tried your code but my event not rendered in VF.
It just show blank calendar.


text:
Q: how to display woocommerce product tags on single product page.? I'm looking like a crazy person if there is a way to display the tags of a product on the single product page with woocommerce ( wordpress plugin). I can not find anything about ti and I've been trying to tweak the code, but without success . . .
if anybody has some high lite, it will be wonderful,
thank you very much

A: Ok, so depending on the WordPress theme you use, they might show automatically (just checked and it works right away with the "official" Storefront theme).
If you're writing a plugin (or a theme) though, you're most likely to want the PHP solution. In that case, according to this, you should be good to go with the following:
global $product; // gets the Product object (correspoding to the single page)
$product->get_tags( $product ); // returns an array with product tags

A: According to this post, you have to use get_terms('product_tag').


text:
Q: WooCommerce Template Override for Archive-Product.php (Main Shop Page) Not Working I can't for the life of me manage to override the main shop page.
My understanding is that it's archive-product.php
I've attempted to copy it into the Woocommerce directory I created in my theme's root directory and modify it.  No dice.
I've also attempted to modify it directly in the Woocommerce plugin directory.  No dice there either.
I've even gone as far as adding an underscore before the archive-product.php file name in both locations (woocommerce directory and my theme template directory) in an attempt to hopefully BREAK it - just to see if I could impact SOME change - and that doesn't seem to have any effect either.
I'm not running any cache plugins and every other Woocommerce template file I've attempted to modify up until this point has worked fine.
Any ideas?

A: You are doing this correctly. You'll have to double check the locations as per:

*

*Shop template is in
plugins/woocommerce/templates/archive-product.php

*You can copy to my-themes/woocommerce/archive-product.php to
override the core woocommerce file.

A: I just had the same issue,
What worked for me, is removing the woocommerce.php file, because before, it applied the template woocommerce.php to the shop, and not the archive-product.

A: The answer is that when you updated to the newest version of WooCommerce, you have to "reinstall" the WooCommerce pages because the old system did not use the wc_get_page_id() function, which looks for the shop page.
Luckily this is super easy! Go to your admin, then to WooCommerce, then to System Status, then click on the Tools tab. Then click the button to the right of Install WooCommerce Pages. This will only install the missing WooCommerce pages and, get this, will reinstall the shop page with the proper wc_get_page_id.
NOTE: if you have content in the original WordPress shop page, although it didn't erase it for me, you might just want to copy the content first just in case.

A: I was able to fix this by using the suggestion here - Changes on archive-product.php doesn't work
but, it seems like a bug to me.  WooCommerce claims that you need that root woocommerce.php page in order to incorporate the plugin into  your custom theme - http://docs.woothemes.com/document/third-party-custom-theme-compatibility/ - but, this does work.
I'd love to know the reasoning behind this.
Switching to the twentyeleve/twentytwelve theme's and trying to override the archive-product.php file in the same fashion worked great, but they don't include a native woocommerce.php file in their root directory either.  What gives?


text:
Q: How to change a cursor to a pointer when hovering over a dynamic list using JQuery I have a list that I am appending to after the screen loads.  I want to change the cursor to a pointer after hovering.  So far I've tried using the .on event but it doesn't seem to be working.  Please look at the line with....   $('.item').on('mouseover', function() {
            $('.item').css('cursor', 'pointer');
        });
$(document).ready(function() {
    $('input').focus(function() {
        $('input[name=checklistInput]').css('outline-color','#FF0000');
    });
    $('#add').click(function() {
        var toAdd = $('input[name=checklistInput]').val();
        $('.list').append('
' + toAdd + '
');
        $('input[name=checklistInput]').val('');
    });

    $('.item').on('mouseover', function() {
        $('.item').css('cursor', 'pointer');
    });

    $(document).on('click','.item', function() {
    $(this).remove();
    });
});

Let me know if you need more details on what the overall goal of the code above is.
Thanks,

A: How about using plain css using :hover pseudo
.item:hover { cursor: pointer; }

If you must use javascript, use mouseenter instead of mouseover and reset to default on mouseleave.

A: You can achieve this using plain css. Use of :Hover does not make any sense.
.item{

 cursor:pointer;
}

A: Just with css
.item:hover {cursor : pointer}


text:
Q: Different XML-related behaviour under Windows and Linux In the open-source project Rultor. In that project there is a unit test com.rultor.agents.IndexesRequestsTest#retrievesIndexFromSibling, which looks like this:
@Test
public void retrievesIndexFromSibling() throws Exception {
    final String first = "first";
    final Talks talks = new Talks.InDir();
    talks.create("", first);
    talks.get(first).modify(
        new Directives().xpath("/talk")
            .add("wire").add("href").set("#3").up().up()
            .add("archive")
            .add("log").attr("id", "3").attr("title", "title3")
            .attr("index", "1").up()
    );
    final String second = "second";
    talks.create("", second);
    talks.get(second).modify(
        new Directives().xpath("/talk")
            .add("wire").add("href").set("#4").up().up()
            .add("archive")
            .add("log").attr("id", "4").attr("title", "title4")
            .attr("index", "2").up()
    );
    final String third = "third";
    talks.create("", third);
    talks.get(third).modify(
        new Directives()
            .xpath("/talk").add("wire").add("href").set("#5").up().up()
            .add("request").attr("id", "a67890")
            .add("args").up()
            .add("type").set("merge").up()
    );
    new IndexesRequests().execute(talks);
    MatcherAssert.assertThat(
        talks.get(third).read(),
        XhtmlMatchers.hasXPaths("/talk/request[@index='5']")
    );
}

Now look at the call talks.get(third).read() at the end of the test.
Under Windows, its result is equal to
<?xml version="1.0" encoding="UTF-8"?>
<talk later="false" name="third" number="1" public="true">
   <wire>
      <href>#5</href>
   </wire>
   <request id="a67890" index="5">
      <args/>
      <type>merge</type>
   </request>
</talk>

Under Linux, the result of talks.get(third).read() is equal to
<?xml version="1.0" encoding="UTF-8"?>
<talk later="false" name="third" number="1" public="true">
   <wire>
      <href>#5</href>
   </wire>
   <request id="a67890" index="3">
      <args/>
      <type>merge</type>
   </request>
</talk>

Difference: Under Windows the index attribute of request is 5, under Linux - 3.
Why?
The class, which generates the index is com.rultor.agents.IndexesRequests:
public final class IndexesRequests implements SuperAgent {
    @Override
    public void execute(final Talks talks) throws IOException {
        int idx = this.index(talks);
        for (final Talk talk : talks.active()) {
            idx += 1;
            talk.modify(
                new Directives()
                    .xpath("/talk/request")
                    .attr("index", Integer.toString(idx))
            );
        }
    }

    /**
     * Calculates maximal index value for a {@link Talks} object.
     * @param talks The {@link Talks} object
     * @return The maximal index value
     * @throws IOException if the content of one {@link Talk} object can't be read
     */
    private int index(final Talks talks) throws IOException {
        int index = 0;
        for (final Talk talk : talks.active()) {
            final int idx = this.index(talk);
            if (idx > index) {
                index = idx;
            }
        }
        return index;
    }

    /**
     * Calculates maximal (existing) index value of a {@link Talk} object.
     * @param talk The {@link Talk} object
     * @return The maximal index value
     * @throws IOException if the content of the {@link Talk} object can't be read
     */
    private int index(final Talk talk) throws IOException {
        final Iterable<Integer> indexes = Iterables.transform(
                talk.read()
                .xpath("/talk/archive/log/@index|/talk/request/@index"),
            new Function<String, Integer>() {
                @Override
                public Integer apply(final String input) {
                    return Integer.parseInt(input);
                }
            }
        );
        final int index;
        if (indexes.iterator().hasNext()) {
            index = Ordering.natural().max(indexes);
        } else {
            index = 0;
        }
        return index;
    }
}

Are there any other places in the code, which may behave differently under Windows and Linux, apart from the XPath call in the index method?
Update 1 (23.01.2015 14:47 MSK): If I add
System.out.println("Index first: " +
    new IndexesRequests().index(talks.get(first)));
System.out.println("Index second: " +
    new IndexesRequests().index(talks.get(second)));
System.out.println("Index third: " +
    new IndexesRequests().index(talks.get(third)));

the results are the same for both Linux and Windows:
Index first: 1
Index second: 2
Index third: 0

After adding these diagnostic messages, the test doesn't fail under Linux.
Update 2 (23.01.2015 15:07 MSK):
I added the code for printing out the talks.active() result.
final Iterable<Talk> activeTalks = talks.active();

System.out.println("activeTalks (START)");

for (final Talk talk : activeTalks) {
    System.out.println("Talk XML: " + talk.read().toString());
}

System.out.println("activeTalks (END)");

Windows:
activeTalks (START)
Talk XML: <?xml version="1.0" encoding="UTF-8"?>
<talk later="false" name="first" number="1" public="true">
   <wire>
      <href>#3</href>
   </wire>
   <archive>
      <log id="3" index="1" title="title3"/>
   </archive>
</talk>
Talk XML: <?xml version="1.0" encoding="UTF-8"?>
<talk later="false" name="second" number="1" public="true">
   <wire>
      <href>#4</href>
   </wire>
   <archive>
      <log id="4" index="2" title="title4"/>
   </archive>
</talk>
Talk XML: <?xml version="1.0" encoding="UTF-8"?>
<talk later="false" name="third" number="1" public="true">
   <wire>
      <href>#5</href>
   </wire>
   <request id="a67890">
      <args/>
      <type>merge</type>
   </request>
</talk>
activeTalks (END)

Linux:
activeTalks (START)
Talk XML: <?xml version="1.0" encoding="UTF-8"?>
<talk later="false" name="third" number="1" public="true">
   <wire>
      <href>#5</href>
   </wire>
   <request id="a67890">
      <args/>
      <type>merge</type>
   </request>
</talk>
Talk XML: <?xml version="1.0" encoding="UTF-8"?>
<talk later="false" name="second" number="1" public="true">
   <wire>
      <href>#4</href>
   </wire>
   <archive>
      <log id="4" index="2" title="title4"/>
   </archive>
</talk>
Talk XML: <?xml version="1.0" encoding="UTF-8"?>
<talk later="false" name="first" number="1" public="true">
   <wire>
      <href>#3</href>
   </wire>
   <archive>
      <log id="3" index="1" title="title3"/>
   </archive>
</talk>
activeTalks (END)

A: Your algorithm for computing the @index depends on the order of these elements being delivered by talks.active(). If this returns the values of a say, HashMap or HashSet, they may be returned in one order on this system, and in another order on that system.
Defining a hashCode may not produce a reliable order.
One reliable way would be a Map or Set maintaining the order of insertion (as in LinkedHash*).


text:
Q: Hide second drop down box using css only-not working I want to hide the second drop down box in the following code using css only.

.dt select:nth-child(2) {
  display: none;
}

  <select>
    <option>1</option>
    <option>2</option>
    <option>3</option>
  </select>
  :
  <select>
    <option>a</option>
    <option>b</option>
    <option>c</option>
  </select>
  :
  <select>
    <option>x</option>
    <option>y</option>
    <option>z</option>
  </select>

But this is not working..How can I do this?
FIDDLE

A: Just change the 2 to 3 and it works:
.dt select:nth-child(3) {
    display:none;
}

Apparently, the first element is not at the index 0, but 1.

A: .dt select:nth-child(2) will apply only if the select element happens to be the second element in .dt. In this case a b is the second element. What you need to use is nth-of-type which will get the second select element in .dt.

.dt select:nth-of-type(2) {
  display: none;
}

    <select>
        <option>1</option>
        <option>2</option>
        <option>3</option>
    </select>
    :
     <select>
        <option>a</option>
        <option>b</option>
        <option>c</option>
    </select>
     :
     <select>
        <option>x</option>
        <option>y</option>
        <option>z</option>
    </select>

A: Try like this: Demo
p:nth-child(2) {
    display:none;
}
p {
    float:left;
}

CSS:

<select>
        <option>1</option>
        <option>2</option>
        <option>3</option>
    </select>
        :

     <select>
        <option>a</option>
        <option>b</option>
        <option>c</option>
    </select>
    :

     <select>
        <option>x</option>
        <option>y</option>
        <option>z</option>
    </select>

A:

.dt select:nth-child(3) option {
    display:none;
}

    <select>
        <option>1</option>
        <option>2</option>
        <option>3</option>
    </select>
    :
     <select>
        <option>a</option>
        <option>b</option>
        <option>c</option>
    </select>
     :
     <select>
        <option>x</option>
        <option>y</option>
        <option>z</option>
    </select>


text:
Q: Условие внутри функции и не правильный вывод результата Здраствуйте. Этот код если не ошибаюсь должен выводить 1 2 3 4 5 если х равно asc и 9 8 7 6 5 если x не равно asc.
<?php
$x = 'asc';
function fun()
{
    if($GLOBALS['x'] == 'asc')
    {
        static $counter = 0;
        $counter++;
        echo "$counter
";
    }
    else
    {
        static $counter = 10;
        $counter--;
        echo "$counter
";
    }
}
fun();
fun();
fun();
fun();
fun();
?>

Но оно выводит 11 12 13 14 15 если х равно asc и 9 8 7 6 5 если х не равно asc.
Почему условие не работает и в любом случае на counter устанавливается значение 10?

A: Статические значения сохранятся между вызовами функции, поэтому такие переменные заводятся перед тем как осуществляется первый вызов функции с fun().
При этом берется последнее определение статической переменной $counter, не обращая внимание на внутреннюю логику функции - логика начинает работать потом, при вызове. Поэтому у вас значение $counter у вас всегда начинается с 10.
static $counter = 10;


text:
Q: How to insert a Please Wait form while a query is running I want to display a "Please Wait" form while a 60+ second query is running.  I have the query and the form made (easy enough), except the macro won't bring them together.  Here is my autoexec macro:

*

*SetWarnings=False

*Open Wait Form

*Run the query & Display Results

*Close Wait Form

The problem is that I can only see the outline of my wait form while the maketable query is running. I can only guess that the macro doesn't wait for the form to completely load before going to the next step.
And just for fun:
The Wait form has a Timer that shows the number of seconds elapsed. How do I run the query while still allowing the form to update itself at the same time?
-------Update----------
Repaint only updates the background color before moving on to the query. I also tried 6 repaints in a row with no difference (I thought that might get around the bug you people mentioned). The form is very simple.  A single text box that uses "loading" for the control source and a timer function (disabled for the moment). Here is my macro in slightly greater detail:

*

*SetWarnings=False

*Open Wait Form (modal=yes, popup=no)

*Repaint the form

*Open a maketable query (this query saves alot of time)

*Close Wait Form

*Open the display query

A: Firstly, you just need to Repaint the wait form after it is shown for it to show correctly, it's just a bug in VBA that sometimes causes forms not to be displayed properly even if they are drawn at the correct point in the code.
Secondly, if you set the wait form's ShowModal property to false then you will be able to update it through your routine.  I use a public function that takes a 0-100 argument to update a progress bar.  This works best in a loop where you can normally calculate the number of loops remaining and provide an accurate guide to the elapsed progress, but even when performing a series of operations you can time and pass suitable values through to the progress form so that the user is kept informed.  This works better than most Windows progress bars!

A: The first problem is easy to solve, try putting me.Repaint before the query runs, sometimes access can get a bit lazy with screen painting and you have to force it.
As for the other thing that is a bit more complicated. You would have to execute the query asynchronously. You can do this in ADO by adding the adAsyncExecute option when executing the query. You would then catch the finishing event to tell the users the query is done
Here is a link on the Microsoft knowledge base http://support.microsoft.com/kb/262311

A: If you are using an Action Query you can track the number of executed rows by using a vba-function which returns the same value that was passed to it. Of course you have to know the total number of rows, to know when the query is done or display progress (This can often be achieved relatively fast using a lightweight counting query*).
'first some global vars to keep track of the number
Dim lngCurrentRow as Long
Dim lngTotalRows as Long 'We assume lngTotalRows have been set elsewhere

'Here is the function
Public Function UpdateProgress(FieldValue as Variant) as Variant

    lngCurrentRow = Nz(lngCurrentRow, 0)

    If (lngCurrentRow >= lngTotalRows) then
        MsgBox "Query Done!"
    Else
        'Do stuff to show progress
    End If

    lngCurrentRow = lngCurrentRow + 1

End Function

For displaying the progress I have used an Unbound form, with an empty textfield with transparent background (progressFrame) and a label (progressLabel) which has a blue background and is placed behind the textbox to the left. For each call to UpdateProgress you can then set the width of the label:
progressLabel.Width = progressFrame.Width * (lngCurrentRow / lngTotalRows)

*: F.ex. if the query is based on one table, with some added data, so that the number of records the query will produce is equal to that of the table, a count can be done on the table alone so that it will be faster..
I hope this was helpful, or at least inspiring :)

A: I had the same issue with a pop up form which took a few seconds before it displayed the text which informs the user that something is processing so please wait. I added the line of code below after the code which opens the form and before the next bit of code which runs the update queries (which takes a while hence the need to inform the user that something was processing)
DoCmd.RepaintObject acForm, "frmMyForm"
Works perfectly for me.


text:
Q: Have php sprintf omit return if string is empty I am wresting with printing shipping labels and getting the final output to omit a second address line if one exists. Is there a way to conditionally exclude the line break if $address2 is empty when using sprintf()?
            while($rows=mysql_fetch_array($result)){
                $name = $rows['address_name'];
                $address = $rows['street1'];
                $address2 = $rows['street2'];
                $citystatezip = $rows['city'].', '.$rows['state'].' '.$rows['zip'];
                $country = $rows['country'];
                $text = sprintf("%s\n%s\n%s\n%s\n", $name, $address, $address2, $citystatezip, $country);
                $pdf->Add_Label($text);
            }

A: Your sprintf only has 4 '%s' and 5 params.
In this code, I removed the \n from the sprintf into a conditional above.
        // Don't use mysql_xxxx functions
        // Should really be using PDO
        //          +---------------+
        //          |               |
        while($rows=mysql_fetch_array($result)){
            $name = $rows['address_name'];
            $address = $rows['street1'];
            $address2 = $rows['street2'];
            $citystatezip = $rows['city'].', '.$rows['state'].' '.$rows['zip'];
            $country = $rows['country'];
            $addr2 = empty($address2) ? '' : $address2 . "\n";
            $text = sprintf("%s\n%s\n%s%s\n%s\n", $name, $address, $addr2, $citystatezip, $country);
            $pdf->Add_Label($text);
        }


text:
Q: How do I add the Postgis distance to the result set Here's my current query which currently returns the name and point of eligible results ordered by distance, how can I include the distance as well in the result set?
Query:
select name, ST_AsText(location) from places where ST_DWithin(
    ST_GeogFromText('SRID=4326;POINT($point)'),
    location,
    $distance
) ORDER BY ST_Distance(
    ST_GeogFromText('SRID=4326;POINT($point)'),
    location
)

$distance and $point will need to be guarded against sql injection in due course obviously.

A: SELECT name,
       ST_AsText(location),
       ST_Distance(ST_GeogFromText('SRID=4326;POINT($point)'),location)
FROM places
WHERE ST_DWithin(ST_GeogFromText('SRID=4326;POINT($point)'), location, $distance)
ORDER BY ST_Distance( ST_GeogFromText('SRID=4326;POINT($point)'), location);

However, for your query to work location should also be casted to a geography (if it is not).


text:
Q: SVG filter using d3 js not working in IE im creating svg hexagaon using d3 line. i want to add shadow to it. it works in chrome but not in IE. below is a part of code.
container = d3.select('#' + attrs.id)
              .append('svg');

//---------------------------------------Filters-------------------
var defs = container.append("defs");

// create filter with id #drop-shadow
// height=130% so that the shadow is not clipped
var filter = defs.append("filter")
                 .attr("id", attrs.id+"drop-shadow")
                 .attr("height", "130%").attr("width", "130%");

// SourceAlpha refers to opacity of graphic that this filter will be applied to
// convolve that with a Gaussian with standard deviation 3 and store result
// in blur
filter.append("feGaussianBlur")
      .attr("in", "SourceAlpha")
      .attr("stdDeviation", 6)
      .attr("result", "blur");

// translate output of Gaussian blur to the right and downwards with 2px
// store result in offsetBlur
filter.append("feOffset")
      .attr("in", "blur")
      .attr("dy", 5)
      .attr("result", "offsetBlur");

// overlay original SourceGraphic over translated blurred opacity by using
// feMerge filter. Order of specifying inputs is important!
var feMerge = filter.append("feMerge");

feMerge.append("feMergeNode")
       .attr("in", "offsetBlur")
feMerge.append("feMergeNode")
       .attr("in", "SourceGraphic");
//----------------------------------------------------------------------
container.style("filter", "url(#" + attrs.id + "drop-shadow)").attr('height', containerHeight)
         .attr('width', containerWidth + 100);

A: found the bug.
i was adding filter to svg and not to the "g" element inside svg. Adding filter to "g" worked in IE for me


text:
Q: Is it possible to tamper client-side code in Angular app? I'm not much experienced in JavaScript programming or Angular app development, but my general understanding is, when JavaScript reaches the client end, it can be tampered.
I've come across some sample implementation of role-based authorization in Angular app where the user roles are sent to the client on successful login (even though they are using JWT, which is supposed to be "self-contained"). The user role values are then saved on the client side (local storage or variable), and used in canActivate route-guard.
(I'm aware that the values used in canActivate will decide only whether to activate the route and render the component in question, and the real role validation happens on server side when the component code tries to fetch data.)
My question is, can these client-stored values be tampered, or Angular has any ability to provide any code-safety?
Thanks in advance.

A: Yes.
All code running within a browser, and all the data, is subject to manipulation by the user.
You don't even know it is a browser that is running the code, it could be some other tool designed specifically to subvert your application.


text:
Q: tabbar.el (v.2.0) -- organize buffers by tab groups associated with frames Is it possible to have tabbar.el display buffers arbitrarily assigned to a given frame, but not organized by group?
If so, what would be the init.el configuration snippet?
The default configuration is grouping all buffers in all frames together and it is difficult to visually determine what buffer is associated with what frame.
Example:
Frame #1:
   *Messages*
   *scratch*
   buffer_three.txt
   buffer.four.tex

Frame #2:
    buffer_five.html
    buffer_six.cvs

I have been experimenting with frame-cmds.el and frame-fns.el, which gives the ability to rename the frame.  I have tried frame-bufs.el, but that one gives me some error messages.
Here is an example of four (4) frames, with arbitrary tabs associated with different frames.

(source: lawlist.com)

A: Tabs can be grouped by frame using the following code snippet with tabbar.el and the frame-bufs library written by Alp Aker:  https://github.com/alpaker/Frame-Bufs
(defun my-buffer-groups ()
"Doc-string."
  (list
    (cond
      ((memq (current-buffer) (frame-bufs-buffer-list (selected-frame)))
        "A")
      (t
        "N") )))

(setq 'tabbar-buffer-groups-function 'my-buffer-groups)


text:
Q: Restrictions of Modules and Dimensions Let K be a finite field and let R,P be groups (with R a subgroup of P). I know that the irreducible KP-modules have dimensions 1,4 and 16 over K. I have a KP-module M, and I know that M has dimension at most 5 over K. I also know that M does not have a quotient of dimension 1 over K. Moreover, if I consider M as a module over KR, it has a 2-dimensional irreducible module. Is it necessarily the case that M is a 4-dimensional irreducible module over KP? (my initial reasoning can be found in a comment below)

A: I see no reason in general if $\operatorname{Ext}_P^1(4,1) \neq 0$ that, on restriction to R the four dimensional simple can't drop down and have a 2-dimensional submodule. I.e. On restriction to R it looks like:
\begin{equation}\begin{array}{c}
  2\\ 2
\end{array} \oplus 1
\end{equation}
If you knew on restriction to KR the only irreducible submodule was two dimensional then this would be ruled out.


text:
Q: How do I add square root to my JavaScript/HTML calculator? How do I add square root to my JavaScript/HTML calculator? Have been trying to add it for atleast 3 hours :(
Also, how could I make a button that multiplies a number with itself (also in my calculator)?

<!DOCTYPE html>

<title>Calc</title>

    <form name="calc">
    <input type="text" name="result" size="30px" readonly>
    </form>

    <button type="button" id="1" onclick="myFunction(this.id)">1</button>
    <button type="button" id="2" onclick="myFunction(this.id)">2</button>
    <button type="button" id="3" onclick="myFunction(this.id)">3</button>

    <button type="button" id="4" onclick="myFunction(this.id)">4</button>
    <button type="button" id="5" onclick="myFunction(this.id)">5</button>
    <button type="button" id="6" onclick="myFunction(this.id)">6</button>

    <button type="button" id="7" onclick="myFunction(this.id)">7</button>
    <button type="button" id="8" onclick="myFunction(this.id)">8</button>
    <button type="button" id="9" onclick="myFunction(this.id)">9</button>

    <button type="button" id="0" onclick="myFunction(this.id)">0</button>
    <button type="button" id="+" onclick="myFunction(this.id)">+</button>
    <button type="button" id="-" onclick="myFunction(this.id)">-</button>

    <button type="button" id="*" onclick="myFunction(this.id)">x</button>
    <button type="button" id="/" onclick="myFunction(this.id)">÷</button>
    <button type="button" id="ANS" onclick="compute()">=</button>

<button type="button" id="CLEAR" onclick="Clear()">c</button>
<button type="button" id="3.141592653589793" onclick="myFunction(this.id)">π</button>
<button type="button" id="6.283185307179586" onclick="myFunction(this.id)">τ</button>

A:

function myFunction(clickedId) {
    document.calc.result.value+=clickedId;
}
function Clear() {
    document.calc.result.value="";
}
function compute() {
    try{
    var inp=eval(document.calc.result.value);
    document.calc.result.value=inp;
    }catch(err){
            document.calc.result.value="error";
    }
}
function doMath(){
  var inputNum1=document.calc.result.value;
  var result = Math.sqrt(inputNum1);
  document.calc.result.value = result;
}
<!DOCTYPE html>

<title>Calc</title>

    <form name="calc">
    <input type="text" name="result" size="30px" readonly>
    </form>

    <button type="button" id="1" onclick="myFunction(this.id)">1</button>
    <button type="button" id="2" onclick="myFunction(this.id)">2</button>
    <button type="button" id="3" onclick="myFunction(this.id)">3</button>

    <button type="button" id="4" onclick="myFunction(this.id)">4</button>
    <button type="button" id="5" onclick="myFunction(this.id)">5</button>
    <button type="button" id="6" onclick="myFunction(this.id)">6</button>

    <button type="button" id="7" onclick="myFunction(this.id)">7</button>
    <button type="button" id="8" onclick="myFunction(this.id)">8</button>
    <button type="button" id="9" onclick="myFunction(this.id)">9</button>

    <button type="button" id="0" onclick="myFunction(this.id)">0</button>
    <button type="button" id="+" onclick="myFunction(this.id)">+</button>
    <button type="button" id="-" onclick="myFunction(this.id)">-</button>

    <button type="button" id="*" onclick="myFunction(this.id)">x</button>
    <button type="button" id="/" onclick="myFunction(this.id)">÷</button>
    <button type="button" id="ANS" onclick="compute()">=</button>

    <button type="button" id="CLEAR" onclick="Clear()">c</button>
    <button type="button" id="3.141592653589793" onclick="myFunction(this.id)">π</button>
    <button type="button" id="6.283185307179586" onclick="myFunction(this.id)">τ</button>

    <button type="button" id="SQRT" onclick="doMath()">√</button>
    <button type="button" > </button>
    <button type="button" > </button>

Added to the snippet. Please check your function was right you just needed to reference the variables


text:
Q: getting "multiple definition" errors with simple device function in CUDA C I have a simple script formed by 2 CUDA files: main.cu and kernel.cu. Their goal is to calculate the sum of 2 vectors.
// main.cu
#include <stdio.h>
#include <stdlib.h>
#include <cuda_runtime.h>
#include <cuda.h>

#include "kernel.cu"

int main(){
/* Error code to check return values for CUDA calls */
cudaError_t err = cudaSuccess;

srand(time(NULL));
int count = 100;
int A[count], B[count];
int *h_A, *h_B;
h_A = A; h_B = B;

int i;
for(i=0;i<count;i++){
    *(h_A+i) = rand() % count; /* Oppure: h_A[i] = rand() % count; */
    *(h_B+i) = rand() % count; /* Oppure: h_B[i] = rand() % count; */
}
/* Display dei vettori A e B. */
printf("\nPrimi cinque valori di A = ");
for(i=0;i<4;i++){printf("%d ", A[i]);}
printf("\nPrimi cinque valori di B = ");
for(i=0;i<4;i++){printf("%d ", B[i]);}

int *d_A, *d_B;

err = cudaMalloc((void**)&d_A, count*sizeof(int));
if (err != cudaSuccess){fprintf(stderr, "Failed to allocate device vector A (error code %s)! \n", cudaGetErrorString(err));exit(EXIT_FAILURE);}
err = cudaMalloc((void**)&d_B, count*sizeof(int));
if (err != cudaSuccess){fprintf(stderr, "Failed to allocate device vector A (error code %s)! \n", cudaGetErrorString(err));exit(EXIT_FAILURE);}

err = cudaMemcpy(d_A, A, count*sizeof(int), cudaMemcpyHostToDevice);
if (err != cudaSuccess){fprintf(stderr, "Failed to copy vector A from host to device (error code %s)!\n", cudaGetErrorString(err));exit(EXIT_FAILURE);}
err = cudaMemcpy(d_B, B, count*sizeof(int), cudaMemcpyHostToDevice);
if (err != cudaSuccess){fprintf(stderr, "Failed to copy vector A from host to device (error code %s)!\n", cudaGetErrorString(err));exit(EXIT_FAILURE);}

int numThreads = 256;
int numBlocks = count/numThreads + 1;
AddInts<<<numBlocks,numThreads>>>(d_A,d_B); err = cudaGetLastError();

err = cudaMemcpy(A, d_A, count*sizeof(int), cudaMemcpyDeviceToHost);
if (err != cudaSuccess){fprintf(stderr, "Failed to copy vector C from device to host (error code %s)!\n", cudaGetErrorString(err));exit(EXIT_FAILURE);}

err = cudaFree(d_A);
if (err != cudaSuccess){fprintf(stderr, "Failed to free device vector A (error code %s)!\n", cudaGetErrorString(err));exit(EXIT_FAILURE);}
err = cudaFree(d_B);
if (err != cudaSuccess){fprintf(stderr, "Failed to free device vector A (error code %s)!\n", cudaGetErrorString(err));exit(EXIT_FAILURE);}

printf("\nPrimi cinque valori di A = ");
for(i=0;i<4;i++){printf("%d ", A[i]);}

printf("\n");
return 0;}

Here there's the kernel.cu file:
// kernel.cu
__device__ int get_global_index(){
return (blockIdx.x * blockDim.x) + threadIdx.x;
}

__global__ void AddInts(int *a, int *b){
           int ID = get_global_index();
           *(a+ID) += *(b+ID);

}

I am 100 % sure that the main.cu script is correct; I also know that i could just add the kernel directly in the the main script but that is not the intention of my test; I also know that I could just get rid of the __device__ function and put it directly inside of the __global__ but it's not my intention either.
When i compile the test by typing nvcc main.cu kernel.cu in the terminal I get however the following error message:
/tmp/tmpxft_0000248b_00000000-30_kernel.o: In function `get_global_index()':
tmpxft_0000248b_00000000-8_kernel.cudafe1.cpp:(.text+0x15): multiple definition of `    get_global_index()'
/tmp/tmpxft_0000248b_00000000-21_main.o:tmpxft_0000248b_00000000-3_main.cudafe1.cpp:(.text+0x15): first defined here
/tmp/tmpxft_0000248b_00000000-30_kernel.o: In function `__device_stub__Z7AddIntsPiS_(int*, int*)':
tmpxft_0000248b_00000000-8_kernel.cudafe1.cpp:(.text+0x7c): multiple definition of `__device_stub__Z7AddIntsPiS_(int*, int*)'
/tmp/tmpxft_0000248b_00000000-21_main.o:tmpxft_0000248b_00000000-3_main.cudafe1.cpp:(.text+0x68e): first defined here
/tmp/tmpxft_0000248b_00000000-30_kernel.o: In function `AddInts(int*, int*)':
tmpxft_0000248b_00000000-8_kernel.cudafe1.cpp:(.text+0xe5): multiple definition of `AddInts(int*, int*)'
/tmp/tmpxft_0000248b_00000000-21_main.o:tmpxft_0000248b_00000000-3_main.cudafe1.cpp:(.text+0x6f7): first defined here
collect2: error: ld returned 1 exit status

I believe the error is caused by the definition of the the device function called get_global_index() but I don't understand what's wrong with it; does anyone have any idea of what it is wrong?

A: Two options:

*

*Just compile main.cu (nvcc main.cu)  It will already pick up kernel.cu, since you're including it.

*Don't include kernel.cu in main.cu.
When you include kernel.cu in main.cu (and pass both files to the compiler) it causes the compiler to compile that code (kernel.cu) twice, once when it is compiling main.cu, and once when it is compiling kernel.cu.   If you choose this option, you'll need to provide a prototype (forward reference) for  the AddInts kernel in main.cu, perhaps by inclusion of a header file with just that prototype.  And in the more general case, if you spread things out into more files, you may need to add -rdc=true to your compile command line, if you have files with __global__ functions that are referencing __device__ functions in other files, for example.


text:
Q: Overhead for Golang's logger if set to discard I have a HTTP handler that has 40 loggers that is set to os.Stdout.
It works just fine for me as I am the only one testing at the moment.
But, when it goes to the production, I'm afraid it will have too much overhead.
Currently loggers are set to os.Stdout and os.Stderr.
But once it gets to the production, os.Stdout will be set to ioutil.discard.
Q1. Will it impact the performance if I still have the logger in set to discard?
Q2. For the best practice, is it better to remove loggers completely from the HTTP handler?
---- UPDATE ----
package main

import (
    "time"
    "fmt"
    "log"
    "io/ioutil"
    "io"
)

func testPrintf(w io.Writer, note string, cnt int) {
    l := log.New(w, "", 0)
    t1 := time.Now()
    for i:=0; i<cnt; i++ {
        l.Printf("%s - %d", "test", i)
    }
    t2 := time.Now()
    fmt.Printf("%-15s  %-15s, %v\n","Printf ", note, t2.Sub(t1))
}

func testPrintln(w io.Writer, note string, cnt int) {
    l := log.New(w, "", 0)
    t1 := time.Now()
    for i:=0; i<cnt; i++ {
        l.Println("test" + string(i))
    }
    t2 := time.Now()
    fmt.Printf("%-15s  %-15s, %v\n","Println", note, t2.Sub(t1))
}

func testDoNothing(w io.Writer, note string, cnt int) {
    //l := log.New(w, "", 0)
    t1 := time.Now()
    for i:=0; i<cnt; i++ {
        _ = "test" + string(i) // evaluated but didn't do any.
    }
    t2 := time.Now()
    fmt.Printf("%-15s  %-15s, %v\n", "DoNothing", note, t2.Sub(t1))
}

func main() {
    cnt := 10000000 // ten million
    testPrintf(ioutil.Discard, "discard.Attempt.1", cnt)
    testPrintln(ioutil.Discard, "discard.Attempt.1", cnt)
    testDoNothing(ioutil.Discard, "discard.Attempt.1", cnt)
    fmt.Println("\n")
    testPrintf(ioutil.Discard, "discard.Attempt.2", cnt)
    testPrintln(ioutil.Discard, "discard.Attempt.2", cnt)
    testDoNothing(ioutil.Discard, "discard.Attempt.2", cnt)
    fmt.Println("\n")
    testPrintf(ioutil.Discard, "discard.Attempt.3", cnt)
    testPrintln(ioutil.Discard, "discard.Attempt.3", cnt)
    testDoNothing(ioutil.Discard, "discard.Attempt.3", cnt)
}

--- RESULT ---
Printf           discard.Attempt.1, 2.663697209s
Println          discard.Attempt.1, 2.4289759s
DoNothing        discard.Attempt.1, 190.480694ms

Printf           discard.Attempt.2, 2.493506245s
Println          discard.Attempt.2, 2.426081786s
DoNothing        discard.Attempt.2, 182.899574ms

Printf           discard.Attempt.3, 2.480853275s
Println          discard.Attempt.3, 2.481552836s
DoNothing        discard.Attempt.3, 180.916608ms

*

*I ran for 10M times for each.

*2~3 sec for 10M log to io.Discard is faster than I thought.. I guess I don't have to worry about the speed.

*os.Stdout which I didn't mean to use; (my original concern was keeping code with ioutil.Discard vs remove the code), but since os.Stdout was not buffered, it was slow.

*By the way, printf() was a lot faster than I thought. Almost same as println()

I don't write Go code daily basis, so this test may be inaccurate. If you see misleading info from the test, please leave a comment here for others to aware. Thank you.

A: Benchmarks
While my gut says that dropping the logs to Discard will have minimal impact to your code I would recommend setting up a benchmark to test the performance impact of your loggers.
Fortunately Go makes this very easy by writing a func BenchmarkXxxxx(*testing.B) function in your unit tests and running go test -bench. More information can be found in the documentation. For your benchmark I recommend writing two tests, one with the os.Stdout and the other with ioutil.Discard - make sure the inputs to both tests are the same.
Relevant code from ioutil to show just what will happen "under the hood":
// ioutil.go
type devNull int

func (devNull) Write(p []byte) (int, error) {
    return len(p), nil
}

func (devNull) WriteString(s string) (int, error) {
    return len(s), nil
}

Logging Best Practices
One approach to logging is the common "Level Based Logging" where you pick the severity of the message wishing to be logged (DEBUG/INFO/WARN/ERROR etc.) then choose which levels to display when deploying your application (e.g. DEBUG and above in development but WARN and above in production).
As you will have noticed Go only provides Print and Error level statements in the standard library so you will need an external package to benefit from something like this (these can also help structuring your logs in a more machine readable/search friendly JSON format too). Dave Cheney has justified the reasoning behind this decision in a blog post.
In your case 40 log statements sounds like a lot but this may depend on how many are simple Print logs; size and complexity of the handler etc. Print logging can be exceptionally helpful as a temporary measure in development and Error to help diagnose during failures if you are not surfacing the error to the client.


text:
Q: Remove duplicate value inside the arraylist from a dynamically created layout Android I have created a dynamic add/removable UI where the user will enter an item's cost in a edit text, and when the user click add. The value will be saved in an ArrayList and at the same time a text view will be added with the same value in there. When the user click remove, the value will be removed from the ArrayList, and the text view will be removed as well.
So it works just the way I wanted had the user enter something like [1.00 2.00 3.00 4.00 5.00 6.00].
However if the user enter something with a duplicate value like [1.00 2.00 3.00 2.00 4.00 2.00].
If remove was clicked on one of the text view with value "2.00", then sometimes the incorrect index with "2.00" will be removed, and the sequence inside my ArrayList becomes out of sync with my text view.
I've been trying several approaches for the past 2 weeks, but just couldn't get it right. If you guys can help me out?
Below is my implementation:
row.xml
<?xml version="1.0" encoding="utf-8"?>

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:id="@+id/rowLinearLayoutItem"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_marginRight="50dp"
        android:layout_marginLeft="50dp"
        android:baselineAligned="true" >

        <Button
            android:id="@+id/rowButtonRemove"
            android:text="-"
            android:layout_width="35dp"
            android:layout_height="35dp"
            android:background="@drawable/circle_button"/>

        <TextView
            android:id="@+id/rowItemCost"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:inputType="numberDecimal"
            android:ems="10"
            android:layout_weight="1" />

        <TextView
            android:id="@+id/rowItemTotal"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:inputType="numberDecimal"
            android:ems="10"
            android:layout_weight="1" />

    </LinearLayout>

</LinearLayout>

Fragment.java
    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.advButtonAddItem:
                String itemAddString = editBoxItemAdd.getText().toString();
                if (itemAddString.isEmpty()){
                    Toast.makeText(getActivity(), "Please Enter Item Cost", Toast.LENGTH_LONG).show();
                }
                else {
                    LayoutInflater layoutInflater = (LayoutInflater) getActivity().getBaseContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                    final View addView = layoutInflater.inflate(R.layout.row, null);
                    final TextView rowItemTotal = (TextView) addView.findViewById(R.id.rowItemTotal);

                    Button rowButtonRemove = (Button) addView.findViewById(R.id.rowButtonRemove);

                    rowItemTotal.setText(editBoxItemAdd.getText().toString());

                    itemList.add(rowItemTotal.getText().toString());

                    updateCost();

                    rowButtonRemove.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            ((LinearLayout)addView.getParent()).removeView(addView);
                            itemList.remove(rowItemTotal.getText().toString()); //Remove inputted Item Cost into ArrayList itemList

                            updateCost();
                        }
                    });
                    row.addView(addView);
                }
                break;
        }
    }

A: ((LinearLayout)addView.getParent()).removeView(addView);

it will always delets the previously added item
because addview is the lastitem you used
so change it to
((LinearLayout)addView.getParent()).removeView(v);


text:
Q: volume buttons have no effect when playing through ear piece In my Xamarin Forms Android app I'm sending audio through the ear piece instead of the normal speaker. I'm doing something like:
myMediaPlayer.SetAudioAttributes(new AudioAttributes.Builder().SetLegacyStreamType(Stream.VoiceCall).Build());

The deprecated version of the above is
myMediaPlayer.SetAudioStreamType(Stream.VoiceCall);

Either way, this seems to work (though, if there is a better way, please let me know).
HOWEVER, I cannot control the volume. The sound correctly comes out of the ear speaker only, but it is at a constant volume, ignoring my volume key presses (though the volume meter displays on the screen going up and down as a press the buttons). ... (for clarification, I'm not trying to control the volume programatically, I simply want the device to adjust the volume as one would expect.)
Any help?
UPDATE
I've also tried this code:
myMediaPlayer.SetAudioAttributes(new AudioAttributes.Builder().SetContentType(AudioContentType.Music).SetUsage(AudioUsageKind.VoiceCommunication).Build());

I have two goals:

*

*Play only out of the ear piece (or headphones if attached)

*Be able to control the volume (which I thought would be a given)

UPDATE with Code Sample
The following will play through the earpiece, but not change volume.
        public void Play(string url)
        {
            var myMediaPlayer = new MediaPlayer();
            myMediaPlayer.SetDataSource(url);

            if (Build.VERSION.SdkInt >= BuildVersionCodes.Lollipop)
                myMediaPlayer.SetAudioAttributes(new AudioAttributes.Builder().SetContentType(AudioContentType.Music).SetUsage(AudioUsageKind.VoiceCommunication).Build());
            else
                myMediaPlayer.SetAudioStreamType(Stream.VoiceCall);

            myMediaPlayer.Prepare();
            myMediaPlayer.Start();
        }


text:
Q: Doubt about Hard Sphere Model I couldn't find a proper answer about this question: if I have a gas formed by a single species (ex: biatomic gas like O2), what is the diameter $\sigma$ of the relative hard sphere model?
Is it the diameter of the molecule or the diameter of the potential influence or something else?


text:
Q: How to print multiple pages per side with one(right) page blank? Input file is any pdf document. I want to have right side space for writing notes.
output.pdf looks like
!

A: For this you can combine pdftk and pdfnup:
First create a pdf with an empty page (with LibreOffice/OpenOffice, inkscape, (La)TeX, scribus, etc.) called empty.pdf
Then call in your shell or via a shell script:
INPUTPDF=input.pdf
NUMPAGES=$(pdftk "$INPUTPDF" dump_data | grep NumberOfPages | egrep -o '[0-9]*')
pdftk "A=$INPUTPDF" B=empty.pdf cat $(for i in $(seq $NUMPAGES) ; do echo A$i B1 ; done) output output.pdf
pdfnup output.pdf
mv output-nup.pdf output.pdf

The pdftk command line is expanded to:
 pdftk A=input.pdf B=empty.pdf cat A1 B1 A2 B1 [...]

A: In addition to jofel's answer,
pdfjam also allows doing this directly, if you are creative with its options.
pdfjam --landscape --offset '-8cm 0cm' document.pdf

By default, --landscape without any nup option would center the page; using a negative offset you can move it to the left hand side as far as you like (optimal value will depend on your input).

A: The PyPdf library in Python makes it easy to rearrange pages in a PDF file. Here's a little script that rotates each page and shrinks it to half size. Warning: untested.
#!/usr/bin/env python
import copy, sys
from pyPdf import PdfFileWriter, PdfFileReader
input = PdfFileReader(sys.stdin)
output = PdfFileWriter()
for p in [input.getPage(i) for i in range(0,input.getNumPages())]:
    p.rotateClockwise(270)
    (w, h) = p.mediaBox.upperRight
    p.mediaBox.upperRight = (w/2, h/2)
    output.addPage(p)
output.write(sys.stdout)


text:
Q: How can I override css of 3rd party(recaptcha) in scope css? I want to hide badge of google recaptcha. If I inspect element, it looks like this :

I try like this :
<style scoped>
   .grecaptcha-badge {
        display: none !important;
    }
</style>

But it does not works
If I try like this :
<style>
   .grecaptcha-badge {
        display: none !important;
    }
</style>

It works
But for this case, I have to use scope because I only want to hide the badge of recaptcha on certain pages
How can I solve this problem?


text:
Q: this class is not key value coding-compliant for the key nextTimeLabel.' I get this error while trying to load data into my cells using a custom cell:
Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<NSObject 0x8d61570> setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key nextTimeLabel.'

I read some of the solutions here regarding this error. I know it is some issue with an deleted IBOutlet , so i did the following:

*

*removed all connections and connected again with new views

*deleted the xib file entirely and changed the names of the xib file and the subviews

*I looked in the whole project(including the source file of the xib) for "nextTimeLabel" - nothing.
4.Quiting simulator/deleting the app/ clearing content
EDIT. code:
-(void)viewDidLoad
{
    [super viewDidLoad];
    UINib *nib = [UINib nibWithNibName:@"BNRCellView" bundle:nil];

    [self.tableView registerNib:nib forCellReuseIdentifier:@"BNRCells"]; //lets try to change that later

}

#pragma mark - TableView Data source methods

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    BNRCell *cell = [tableView dequeueReusableCellWithIdentifier:@"BNRCells" ];
    NSDictionary *dic = self.courses[indexPath.row];
    cell.courseNameLabel.text= dic[@"title"];

    return cell;
}

Any other suggestions?

A: In the BNRCellView XIB for this cell (with registered identifier BNRCells), somewhere you have an outlet named nextTimeLabel connected to something which would seem to have the wrong class (an NSObject instance rather than what should presumably be a controller or view instance).
Check all of your class name settings and any outlet connections to the file owner.


text:
Q: Installing a .bundle file in Fedora linux So I am using Ozone OS which is basically just fedora with a cool theme, and a lot less crap installed. I tried installing VMWare Horizon view client from here: https://my.vmware.com/web/vmware/details?downloadGroup=VIEWCLIENTS_LINUX_32&productId=421&rPId=7320
and then i renamed the file to vmware.bundle, when i make it runnable with:
chmod +x vmware.bundle

i ran the file using:
./vmware.bundle

this is what happens in my terminal
VMWare Horizon Client is an x86 application but you are trying to install it to an x64 Linux.
To run this installation, you may need to install 32-bit runtime libraries. Do you want to proceed? (yes/no)yes
Extracting VMware Installer...done.

but when i try going to the application menu, I can find VMware anywhere

A: There is really no such thing as ".bundle" files on Fedora. The only format for installable software on Fedora are RPM files.
All that this ".bundle" file appears to be, is the vendor's custom installation script, that's all. It's not any kind of a standard packaging format, of any kind.
You will be able to find a newly-installed application on your application menu only if the application correctly installed a .desktop file in the right location. If this installation script did not do so, you won't get anything in the application menu.
It is the application script's responsibility to install a .desktop file in order for the application to appear in the application menu.

A: try running /bin/vmware
that is the default install location


text:
Q: Hovering over election vote button shows irrelevant information On the moderator election page, the tooltip will display the text used for voting on a question; this is incorrect.
Steps to reproduce:

*

*Cast a vote for or against any candidate

*Undo that vote

At this point, the tooltip content is changed, at least for that candidate.
See screenshots:

As you can see, the message doesn't quite fit here; these are certainly not questions.

A: The primary phase election voting tooltips were overridden by the default post voting tooltips. This shouldn't be happening anymore after build rev 2014.3.4.2013 on meta and 2014.3.4.1420 on sites.


text:
Q: How to spy on a Method that belongs to an object not accessible from outside? I'm very new to Mockito and I have a situation for which I can't find a solution. There's a method that I want to test using Mockito. The problem is that inside this method, there's an object created and that object has a function that I want to mock.
So for example, here is a small sample code which illustrates my issue:
public class ClassA {
    public functionDoingDBStuff() {
        //...........
    }
}

public class ClassB {
    final ClassA classAObj = null;

    public functionXYZ() {
        classAObj = new ClassA();

        classAObj.functionDoingDBStuff();
    }
}

@Test
MyTestFunction() {
    ClassB classBObj = new ClassB();

    // How can I access and mock functionDoingDBStuff() here?
}

So in MyTestFunction(), I want to test functionXYZ(), but mock the function functionDoingDBStuff() that is called inside functionXYZ(). By mock, I mean return a specific result that I want for the test. However function functionDoingDBStuff() belongs to an object that's created inside functionXYZ(), so I don't know how I can tell Mockito to access it from within MyTestFunction(). I hope you're able to understand what I mean.

A: To me if a piece of code can't be easily tested that suggests a problem with the structure of the code. Anyway, why does new ClassA() need to be done inside the functionXYZ? Can't be instantiated (better still injected) at Object level? If so you can inject a mock instance of ClassA.
If it still has to be instantiated within the method, may be instead of doing new ClassA(), it should be wrapped inside a factory method. Then you can mock the factory to return a mock ClassA.