text:
Q: on('connection') in Socket.IO gets triggered all the time. How to fix? Hi I've been using socket.io 4 years ago last time in my open-source node.js project and now when I updated everything to the new node and socket.io versions and when i call io.on('connection') from my app.js it seems to get triggered all the time even if there's no new connection to the server.
why is that? how i can fix that?
here's the code:
io.on('connection', function(socket){
    console.log('a user socket connected');
    socket.on('disconnect', function(data){
        console.log('user disconnected');
        <!-- ... -->
    }
    <!-- ... -->

});
So that message a user socket connected gets emitted even when i'm just looking at the page (not loading it). Is there some new way of doing things there which I don't know about?
Before it just emitted a user socket connected once and waited until the page is reloaded, which is the behavior I want.
Just in case the full source code (and of the app.js file) is available on http://github.com/noduslabs/infranodus
Thanks!

A: Are you 100% sure that your client version of socket.io is exactly the same as your server version? When they are mismatched, this is what can happen as the client keeps trying to connect over and over again. For others, I've seen people using a specific socket.io version from a CDN that does not matched the newly upgraded server version. If you fetch the client script with
<script src="/socket.io/socket.io.js"></script>

then you are guaranteed a match.  Also, if you just recently updated the socket.io.js file that you server is serving to the client without changing its name, you may be subject to browser caching issues (where it caches the old version because it doesn't know there is a newer version).


text:
Q: Wait until Timer has elapsed until next instructions is executed Background: first of all I know some of my code is messy, please don't hate me. Basically I want to animate the movement of a TextBox object on a Windows Forms window. I have managed to do this by using a Timer. However, the rest of my code executes whilst the timer is running (and so the TextBox is still moving). How do I stop this from happening.
Here is some of my code:
move method:
        private void move(int x, int y)
    {
        xValue = x;
        yValue = y;

        // Check to see if x co-ord needs moving up or down
        if (xValue > txtData.Location.X) // UP
        {
            xDir = 1;
        }
        else if (xValue < box.Location.X) // DOWN
        {
            xDir = -1;
        }
        else // No change
        {
            .xDir = 0;
        }

        if (yValue > box.Location.Y) // RIGHT
        {
            yDir = 1;
        }
        else if (yValue < Location.Y) // LEFT
        {
            yDir = -1;
        }
        else // No change
        {
            yDir = 0;
        }

        timer.Start();
    }

Timer Tick method:
private void timer_Tick(object sender, EventArgs e)
{
        while (xValue != box.Location.X && yValue != box.Location.Y)
        {
            if (yDir == 0)
            {
                box.SetBounds(box.Location.X + xDir, box.Location.Y, box.Width, box.Height);
            }
            else
            {
                box.SetBounds(box.Location.X, box.Location.Y + yDir, box.Width, box.Height);
            }
        }
}

move calls:
        move(478, 267);
        move(647, 267);
        move(647, 257);

A: I'm not sure exactly what you're asking, but if you're trying to force the program to stop running code until the animation is done, you could try using async await.  You'll need at least .Net 4.5 to use async await, however.
private async void moveData(int x, int y)
{
    Variables.xValue = x;
    Variables.yValue = y;

    // Check to see if x co-ord needs moving up or down
    if (Variables.xValue > txtData.Location.X) // UP
    {
        Variables.xDir = 1;
    }
    else if (Variables.xValue < txtData.Location.X) // DOWN
    {
        Variables.xDir = -1;
    }
    else // No change
    {
        Variables.xDir = 0;
    }

    // Check to see if y co-ord needs moving left or right
    if (Variables.yValue > txtData.Location.Y) // RIGHT
    {
        Variables.yDir = 1;
    }
    else if (Variables.yValue < txtData.Location.Y) // LEFT
    {
        Variables.yDir = -1;
    }
    else // No change
    {
        Variables.yDir = 0;
    }

    await Animate();
}

private async Task Animate()
{
    while (Variables.xValue != txtData.Location.X && Variables.yValue !=     txtData.Location.Y)
    {
        if (Variables.yDir == 0) // If we are moving in the x direction
        {
            txtData.SetBounds(txtData.Location.X + Variables.xDir, txtData.Location.Y, txtData.Width, txtData.Height);
        }
        else // We are moving in the y direction
        {
            txtData.SetBounds(txtData.Location.X, txtData.Location.Y + Variables.yDir, txtData.Width, txtData.Height);
        }
        await Task.Delay(intervalBetweenMovements);
    }
}

This way it will wait for move(x, y) to complete before moving to the next line.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Show that if $f'$ is greater than $0$, then $f(t_2) \geq f(t_1)$ if $t_1 < t_2$ $f: [a,b] \to R, C^0$ on $[a,b]$, and Differentiable $(a,b)$
If $f'(x) \geq 0$ on $(a,b)$ then $f(t_2) \geq f(t_1)$ if $a \leq t_1 < t_2 \leq b$
I can clearly see that it is true. However, I'm honestly not sure how I would show this. All I know is that $f'(x) \geq 0$. I don't know anything about what $f(x)$ would send $t_2$ or $t_1$ to. So I'm not sure how to get the result from these assumptions. Any help is appreciated!

A: Well yes,restrict the domain to $[t_{1} , t_{2}]$ then as $f$ is differentiable by Lagrange mean value theorem there exist $c\in (t_{1} ,t_{2})$ such that $f^{'}(c)=\frac{f(t_{2})-f(t_{1})}{t_{2}-t_{1}} \geq 0$ so $f(t_{2})\geq f(t_{1})$ as $t_{2}>t_{1}$.
Hope this helps.


text:
Q: Autoexp.dat Versions I'm working on a project where I need switch between a couple of different (incompatible) autoexp.dat files.  Currently, that involves closing all instances of Visual Studio, copying the file I want to the new location, and then opening Visual Studio again.  Is there a better way to do this?  Maybe a command line option to specify the location of autoexp.dat?  Ideally, I'd like to be able to run two instances of Visual Studio at the same time, with each using a different autoexp.dat file.

A: Have you tried doing what you suggest? I know there is a way to make it a plugin to visual studio, as mentioned Here. Perhaps you could modify this setup to dynamically load the autoexp.dat file you want to use?


text:
Q: Expression cannot begin with "$\sum_{j=0}^{\floor*\frac{a}{b}} j$"
This is my first time using Wolfram Mathematica and writing in TeX. I'm on the free trial version of Mathematica, and I'm writing in a notebook, using the "Inline TeX Input" option on the "Insert" tab. Previously, I have only ever written mathematics in MathJax.
I tried the above first without the dollar signs.

It didn't work then either. I figured maybe the problem was the lack of dollar signs. It appears not. A further confusing detail here is that the slash in front of the sum is red in the last picture, whereas it isn't in the one above. So I thought, maybe I have to add a dollar sign in front of all of them (not that that makes any sense to me, but I have no idea what I'm doing).

It still didn't work, but in this instance, the slashes aren't red anymore. I don't understand why this isn't working, according to this guide, sigma functions are displayed by writing "\sum".
EDIT:
I tried doing as instructed in the answer by @Nasser, but upon pressing enter, the box turned red. Here's the code:
 Failure["TeXAssistantError", Association[
   "MessageTemplate" -> "Errors: `Errors`",
   "MessageParameters" -> Association["Errors" -> {}],
   "Input" -> "crtl$ \\sum_{j=0}^{3} j"]]

A: You have to first type ctrl$ then type the LATEX there with no $'s, since it is implied math mode.  like this

Which was entered using

Then hit the return key.
For more info, see  InlineTeXInput.html
btw, no one really writes * in Latex as multiplication is implied with just the space. Better not use * in Latex.
Here is a video.  Hitting CTRL$ is just a short cut for using the menu. Both work the same.


text:
Q: Magento 2 - How to call parent function inside the plugin I have created the plugin for a particular function. That function is also calling another protected function of the core file.
public function afterPopulateTaxRateData(
    \Magento\Tax\Model\Calculation\Rate\Converter $subject,
    $result,
    $formData
) {
    if ($this->_helper->isEnable()) {
        if (isset($formData['zip_is_range']) && $formData['zip_is_range']) {
            if ($this->_helper->isRangeEnable()) {
                $result->setTaxCity($this->extractFormData($formData, 'tax_city'));
            } else {
                $result->setTaxCity("");
            }
        } else {
            $result->setTaxCity($this->extractFormData($formData, 'tax_city'));
        }
    }

    return $result;
}

How to call the protected function extractFormData inside this plugin.
Thanks.


text:
Q: Perl: "Variable will not stay shared" I looked up a few answers dealing with this warning, but neither did they help me, nor do I truly understand what Perl is doing here at all. Here's what I WANT it to do:
sub outerSub {
  my $dom = someBigDOM;
  ...
  my $otherVar = innerSub();
  return $otherVar;

  sub innerSub {
    my $resultVar = doStuffWith($dom);
    return $resultVar;
  }
}

So basically, I have a big DOM object stored in $dom that I don't want to pass along on the stack if possible. In outerSub, stuff is happening that needs the results from innerSub. innerSub needs access to $dom. When I do this, I get this warning "Variable $dom will not stay shared".
What I don't understand:

*

*Does this warning concern me here? Will my intended logic work here or will there be strange things happening?

*If it doesn't work as intended: is it possible to do that? To make a local var visible to a nested sub? Or is it better to just pass it as a parameter? Or is it better to declare an "our" variable?

*If I push it as a parameter, will the whole object with all its data (may have several MB) be pushed on the stack? Or can I just pass something like a reference? Or is Perl handling that parameter as a reference all by itself?

*In "Variable $foo will not stay shared" Warning/Error in Perl While Calling Subroutine, someone talks about an anonymous sub that will make this possible. I did not understand how that works, never used anything like that.

*I do not understand that explanation at all (maybe cause English is not my first language): "When the inner subroutine is called, it will see the value of the outer subroutine's variable as it was before and during the first call to the outer subroutine; in this case, after the first call to the outer subroutine is complete, the inner and outer subroutines will no longer share a common value for the variable.":
What does "the first call to the outer subroutine is complete? mean"
I mean: first I call the outer sub. The outer sub calls the inner sub. The outer sub is of course still running. Once the outer sub is complete, the inner sub will be finished as well. Then how does any of this still apply when the inner sub is already finished? And what about the "first" call? When is the "second" call happening... sorry, this explanation confuses me to no end.
Sorry for the many questions. Maybe someone can at least answer some of them.

A: You need to have an anonymous subroutine to capture variables:
my $innerSub = sub  {
  my $resultVar = doStuffWith($dom);
  return $resultVar;
};

Example:
sub test {
    my $s = shift;

    my $f = sub {
        return $s x 2;
    };

    print $f->(), "\n";

    $s = "543";

    print $f->(), "\n";
}

test("a1b");

Gives:
a1ba1b
543543

A: If you want to minimize the amount of size passing parameters to subs, use Perl references. The drawback / feature is that the sub could change the referenced param contents.
my $dom = someBigDOM;
my $resultVar = doStuffWith(\$dom);

sub doStuffWith {
   my $dom_reference = shift;
   my $dom_contents = $$dom_reference;
   #...
}

A: In brief, the second and later times outerSub is called will have a different $dom variable than the one used by innerSub.  You can fix this by doing this:
{
    my $dom;
    sub outerSub {
        $dom = ...
        ... innerSub() ...
    }
    sub innerSub {
        ...
    }
}

or by doing this:
sub outerSub {
    my $dom = ...
    *innerSub = sub {
        ...
    };
    ... innerSub() ...
}

or this:
sub outerSub {
    my $dom = ...
    my $innerSub = sub {
        ...
    };
    ... $innerSub->() ...
}

All the variables are originally preallocated, and innerSub and outerSub share the same $dom.  When you leave a scope, perl goes through the lexical variables that were declared in the scope and reinitializes them.  So at the point that the first call to outerSub is completed, it gets a new $dom.  Because named subs are global things, though, innerSub isn't affected by this, and keeps referring to the old $dom.  So if outerSub is called a second time, its $dom and innerSub's $dom are in fact separate variables.
So either moving the declaration out of outerSub or using an anonymous sub (which gets freshly bound to the lexical environment at runtime) fixed the problem.

A: Following http://www.foo.be/docs/perl/cookbook/ch10_17.htm , you should define a local GLOB as follows :
local *innerSub = sub {
    ...
}
#You can call this sub without ->
innerSub( ... )

Note that even if warning is displayed, the result stay the same as it should be expected : variables that are not defined in the inner sub are modified in the outer sub scope.  I cannot see what this warning is about.


text:
Q: Unable to gain permission to directory on disk
Possible Duplicate:
Can't delete folder, need permission from adminstrator?

Here´s the deal:
I have a folder, it´s the folder of one of my smaller projects and it used to contain a couple of images. Just a couple of minutes ago I was commiting the images to my git repo (since I was finished for the day with them), but suddenly when I press commit I get this strange error:
    Access is denied

The strangest thing of it all is that I have one account (the default administrators account). I have tried all these things:

*

*Changing the permissions of the folder

*Deleting it with the shell

*Deleting it through an elevated command prompt
(I even tried setting the folder as a symlink directory junction to NUL, but alas, nothing but the aforementioned error)

*Logout/in and restarting my shell/computer

But to no avail, whatever I try to do, throws me that blasted error (either as plain text or as an actual window). Although it contains nothing, it´s still sitting there, alive and well.
So, what are my options (apart from actually formatting the drive)?
Note that I don´t care about recovering the contents of the folder, it just annoys me that I can´t gain permissions to open it!


text:
Q: Keyboard Controls? Hello World I am creating a financial software working on a touch panel machine. I have created a Keyboard control for User Input. I want to open start menu on my keyboard's Window button click. How's that possible?

A: you can't send keystrokes from a Silverlight app to the OS, neither can you execute shell operations. Just remember that SL apps run in a browser. If you were able to do things like simulating keystrokes etc., that would be a serious security issue.
Cheers, Alex

A: Silverlight does not allow you to directly send commands to the OS, as it runs within a secure browser sandbox. Even when the application is running out-of-browser, the majority of the security restrictions remain.
There are workarounds, however. The simplest of these is to implement a service or native application that can execute the commands, and then connect to it from your Silverlight application with a TCP socket or similar.

A: I haven't used it but Silverlight 4 has COM interop for out of browser applications. Maybe you can use that. If not directly then another application or service can be installed with a COM api and the SL4 application can send commands to it and that in turn sends keystrokes.
Here is some idea on how to do it.
http://elegantcode.com/2010/02/20/silverlight-4-com-interop-and-the-cool-stuff-you-can-do-with-it/


text:
Q: Format Numbers in K,Lacs,Crore I'd like to format numbers into the numbers next to them with k, lacs, crores in jQuery:
1000 to 1K
1500 to 1.5K
100000  to 1Lac
150000   to 1.5Lac
1000000  to 10Lac
10000000   to 1cr and so on !
<!DOCTYPE html>
<html>
<head>
    <title>Number Differentiation</title>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function(e){
              $('#numbr').bind('keypress', function (e) {
                                return (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57) && e.which != 46) ? false : true;
              });
            $("#submitBut").click(function(e){

                alert(numDifferentiation( $("#numbr").val()))
            })
            function numDifferentiation($val){
               return $val;
            }
        })
    </script>
</head>
<body>
<input id="numbr" type="text"/>
<button id="submitBut">Click</button>
</body>
</html>

A: This should do it:
function numDifferentiation(val) {
    if(val >= 10000000) val = (val/10000000).toFixed(2) + ' Cr';
    else if(val >= 100000) val = (val/100000).toFixed(2) + ' Lac';
    else if(val >= 1000) val = (val/1000).toFixed(2) + ' K';
    return val;
}

A: You can also use the js inbuilt Intl library
const formatter = new Intl.NumberFormat('en-IN', {
  style: 'currency',
  currency: 'INR',
  minimumFractionDigits: 0,
  maximumFractionDigits: 2,
  notation: 'compact',
  compactDisplay: 'long',
})

and use it like
const value = 200000
formatter.format(value) // => 2L

One can optionally change the locale en-IN to en-US to suit their style of notations.
It will also round off your value to the nearest notation to make it look cleaner.


text:
Q: YouTube API getAvailableQualityLevels() doesn't work function onPlayerStateChange(event) {
    if(event.data == YT.PlayerState.PLAYING) {
        ql = event.target.getAvailableQualityLevels();
        console.log(ql);
    }
}

I want to print the quality array. This works most of the times in Safari but not always and it does't work in Chrome nor Firefox. I don't understand why it works some times in Safari and why other times not and why it doesn't work in other browsers?
This is how I call the API
  var player;
  function onYouTubePlayerAPIReady() {
    player = new YT.Player('ytplayer', {
            height: height,
            width: width,
            videoId: yt_id,
            playerVars: {
            html5: 1,
            wmode: "transparent",
            controls: 0,
            showinfo: 0,
            rel: 0,
            modestbranding: 1,
            iv_load_policy: 3 //anottations
            },
            events: {
                'onError': onPlayerError,
                'onReady': onPlayerReady,
                'onStateChange': onPlayerStateChange
            }
        });
    };


text:
Q: Selenium ide - How do I copy and paste a randomly generated name Would like to know if its possible to copy a randomly generated username and paste into a login field. Most of the StoreValue commands don't apply here as the name is generated new each time, so i need to find a script that would capture/store an unknown value if possible.
Test scenario is like this
Account is registered and a random username and specified password is generated on the web page. The format of the username shows up as:
Registration complete!
Username: Xxxxxxxxxx
Password: Xxxxxxxxxx
I need to now ask Selenium to read that username, copy it and paste it to a login field.

A: Can you try this, Store the required text in variable like I stored in variable s and Try to access same variable using command ${s}
|Command | Target | Value |
|storeText | //ul/li | s |
|echo |${s}|
Also you can get more help from http://voices.yahoo.com/selenium-ide-commands-functions-data-verification-6633440.html?cat=15


text:
Q: Django filter on relational data I defined some models in Django with relationships. When I want to get data by filtering relation data I got error.
Models:
class User(models.Model):
    UserId = models.CharField(max_length=255, primary_key=True)
    Username = models.CharField()
    RelatedPerson = models.ForeignKey(
        People,
        db_column='PersonId',
        on_delete=models.CASCADE,
    )

class Staff(models.Model):
    RelatedUser = models.ForeignKey(
        User,
        on_delete=models.CASCADE,
        db_column='StaffUserId',
        related_name='RelatedUser'
    )

My query is this:
staff = Staff.objects.filter(RelatedUser__UserId=user_id).first()

I also tried to get with other field which is not primary key and it didn't work too:
staff = Staff.objects.filter(RelatedUser__UserId=user_id).first()

And this is the error I get :
django.db.utils.ProgrammingError: ('42S22', "[42S22] [Microsoft][ODBC Driver 13 for SQL Server][SQL Server]Invalid column name 'id'. (207) (SQLExecDirectW); [42S22] [Microsoft][ODBC Driv
er 13 for SQL Server][SQL Server]Statement(s) could not be prepared. (8180)")


text: Q: ROI solver that is applicable for a general objective function (F_objective) and binary variables Is there any ROI solver in R that is applicable for a general (nonlinear) objective function (F_objective) and binary variables?


text:
Q: How to Customizing/add a class to the ActiveForm items with Material Bootstrap design classes on Yii2 I'm trying to add a class for a TextField like this one:

                    <?= $form->field($model, 'email'); ?>

Output:

And that would be something like this?(the label will be inside the TextField).i mean, can we use it like below codes?
Example:
I need something like this:

  Write something to make the label float
  <input class="form-control" id="focusedInput1" type="text">

http://fezvrasta.github.io/bootstrap-material-design/bootstrap-elements.html

Forms section-first one.

So, the question is,
How can i add a class to this item with above codes on Yii2 ActiveForm?

A: You need to use fieldConfig Propertie in ActiveForm.
Like as
<?php $form = ActiveForm::begin([
    'id' => 'active-form',
    'fieldConfig' => [
        'template' => "
{label}{input}{error}
",
    ],
]); ?>

For more info read Docs


text:
Q: how to implement time persistence in drools? I am new to drools and I was wondering if there was a way to write rules that express persistence in time :
if (condition true for X seconds) then doSomething()
Rule "Example"
when
  r: Room(Temperature > 100 for 10 minutes )
then
  doSomething()
end

A: There are two modes for firing Drools rules -- the default is "Cloud" mode, where we evaluate all of the facts in working memory at a single point in time. This is the oldest and most common way to fire rules. The other mode is "stream" mode, where data is played in continuously, and the Drools engine is aware of time.
When in stream mode, Drools has a set of temporal operators (link to Drools documentation) which can be used to write conditions against facts which occur over time.
One way that you can use the temporal operators for your use case would be as follows:
rule "Detect temperature over 100 for 10 minutes"
when
  $t: Temperature(this >= 100) from entry-point "TemperatureStream"
  not(
    Temperature(
      this != $t,
      this < 100,
      this after[0s,10m] $t) from entry-point "TemperatureStream")
then
  doSomething()
end

This simple rule expects that you're sending Temperature events from an entrypoint (TemperatureStream) via some external mechanism. When it detects a temperature over 100 degrees (instance $t), the first condition triggers.
The second condition is where the magic happens. The second condition will only trigger if it does not receive a Temperature event of less than 100 degrees in the 10 minutes following the receipt of $t.
As your monitoring application sends temperature events, each one over 100 will trigger the first condition, and then start monitoring the stream to see if the second holds true. If it does, the consequence of the rule will fire. Otherwise the rule match will be discarded.
Alternatively, you could use a sliding window over 10 minutes to see if the temperature minimum ever drops below 100.
rule "Detect temperature over 100 for 10 minutes - sliding window"
when
  not(
    Number(doubleValue < 100) from accumulate(
      Room( $temperature: Temperature ) over window:time(10m),
      min( $temperature )
    )
  )
then
  doSomething()
end

Here, window:time(10m) is a sliding window over a 10 minute period. Unlike the other solution which observes each even as it comes in, and then tries to check if a second condition matches, this one simply looks at all events over a period of time. If the minimum temperature never goes below 100 for the entire window, the right hand side triggers.
There's probably other ways of doing this, these are just the two that I came up with offhand. The documentation is particularly good for this part of Drools, so you might find another way that better fits your use case.


text:
Q: Buissness validation logic is there any nice solution to validate domains after changing?
For example:
In our buisiness case we got Users as domain object.
The UserGlobal has a expiration timeframe (activeFrom and activeTo). When the admin is changing this timeframe it needs to check serval other domains like BankDataExpiration timeframes, Contract timeframes etc.... Today we use a big ugly block with all checks in one class.
some pseudo code:
public class UsersService {
    public void onUserChange(Users users) {

        checkContracts();
        checkBankdata();
        // much other validation checks....
    }
}

After the whole ugly check thing, it is possible that data should change automatically. For example Some of the timeframes could be cut.
But all of this is hurts the "Single Responsibility Principle" and its unreadable and unmaintainable. Is there a nice and clever solution out there, I didn't find yet?
We thought already about a interface for checking and validation that will be autowired via spring beans. But we got trouble with hibernates session handling. We changed some reletad data in the session a error apeard, the user changed the data and tries to revalidate it. The validation passes and the previously changed objects will be comitted too.
I hope this question is not to general :S

A: You can create your own custom validators. Follow the below steps:

*

*declare your own annotation using '@Constraint'
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy=BankDataExpirationValidator.class)
public @interface BankDataExpiration {

*Implement the validation logic by implementing ConstraintValidator interface e.g. BankDataExpirationValidator

*Then annotate the Users class with the above created annotation, @BankDataExpiration
You can create different kinds of validators this way and map it to your domain objects.


text:
Q: unity player moving on the x axis with the finger does not work Hey I'm developing an android game with unity its in 3d and the main point is that you are a square which you have to move on the x-Axis. I want that the player can place his finger wherever he wants and swipe left or right (still touching the display) and the distance between the positions where he starts touching and where he is now the square should move right or left. When the player is not touching it should not move at the x-Axis. I did this but my code has a problem when I release my finger and touch again without moving right or left the square deflects to one side very fast. Of course when the finger not move the square shouldn't move.
Picture for better understand
// My Code
public class PlayerMovement : MonoBehaviour
{
    void FixedUpdate()
    {
        // move the player constantly forward
        transform.position += Vector3.forward * Time.deltaTime * speed;

        if (Input.touchCount > 0)
        {
            touch = Input.GetTouch(0);

            // the current finger position
            touchedPosMoved = Camera.main.ScreenToWorldPoint(new Vector3(touch.position.x, touch.position.y, 10));

            switch (touch.phase)
            {
                case TouchPhase.Began:
                    // get finger position when touch start
                    touchedPosBegan = Camera.main.ScreenToWorldPoint(new Vector3(touch.position.x, touch.position.y, 10));

                    startX = transform.position.x;
                    break;

                case TouchPhase.Moved:
                    // claculate the distance between start and curent position of the finger
                    differenz = Mathf.Abs(touchedPosBegan.x - touchedPosMoved.x);

                    if (touchedPosBegan.x > touchedPosMoved.x)
                    {
                        differenz = differenz * -1;
                    }
                    break;
            }

            // Move player at the X-axis
            Vector3 idk = new Vector3((startX + differenz) * 8, transform.position.y, transform.position.z);
            gameObjectStart = new Vector3(startX, transform.position.y, transform.position.z);
            transform.position = Vector3.Lerp(gameObjectStart, idk, Time.deltaTime * 2);
        }
    }
}

Does anyone know the problem or has another solution for my to move the player as described above

A: Here I find a better code without these problems I hope this can help other programmers ;)
   private void FixedUpdate()
{
    transform.position += Vector3.forward * Time.deltaTime * speed;

    if (Input.touchCount > 0)
    {
        touch = Input.GetTouch(0);

        if (touch.phase == TouchPhase.Moved)
        {
            transform.position = new Vector3(
                transform.position.x + touch.deltaPosition.x * multiplier,
            transform.position.y,
            transform.position.z + touch.deltaPosition.y * multiplier);
        }
    }
}


text:
Q: Showing the tiered price under the product title on group products On my grouped products if the product has a tier price then it shows it in each table row for every product. Is there a way i can get the tier price to show just under the title of the product. I have added a picture to show you the problem and also where i want the tier price to be shown.

My grouped.phtml looks like this
<?php $this->setPreconfiguredValue(); ?>
<?php $_product = $this->getProduct(); ?>
<?php $_associatedProducts = $this->getAssociatedProducts(); ?>
<?php $_hasAssociatedProducts = count($_associatedProducts) > 0; ?>
<?php if ($_product->isAvailable() && $_hasAssociatedProducts): ?>

<?php echo $this->__('Availability:') ?> <?php echo $this->__('In stock') ?>

<?php else: ?>

<?php echo $this->__('Availability:') ?> <?php echo $this->__('Out of stock') ?>

<?php endif; ?>

<?php if (Mage::getStoreConfig('settings/labels/sku')): ?>

<?php echo $this->__('Code:') ?> <?php echo $_product->getSku() ?>

<?php endif; ?>
<?php echo $this->getChildHtml('product_type_data_extra') ?>

    <col />
    <col />
    <col width="1" />

            <?php echo $this->__('Size') ?>
            <?php if ($this->getCanShowProductPrice($_product)): ?>
            <?php echo $this->__('Price') ?>
            <?php endif; ?>
            <?php if ($_product->isSaleable()): ?>
            <?php echo $this->__('Qty') ?>
            <?php endif; ?>

    <?php if ($_hasAssociatedProducts): ?>
    <?php foreach ($_associatedProducts as $_item): ?>
        <?php $_finalPriceInclTax = $this->helper('tax')->getPrice($_item, $_item->getFinalPrice(), true) ?>

            <?php echo $this->htmlEscape($_item->getName()) ?>
            <?php if ($this->getCanShowProductPrice($_product)): ?>

                <?php if ($this->getCanShowProductPrice($_item)): ?>
                <?php echo $this->getPriceHtml($_item, true) ?>
            <?php $this->getTierPriceHtml($_item)?>

                <?php if ( $_item->getTierPrice()): ?>
                <?php echo $this->getTierPriceHtml($_item)?>
                <?php endif; ?>
                <?php endif; ?>

            <?php endif; ?>
            <?php if ($_product->isSaleable()): ?>

            <?php if ($_item->isSaleable()) : ?>
                <input type="text" name="super_group[<?php echo $_item->getId() ?>]" maxlength="12" value="<?php echo $_item->getQty()*1 ?>" title="<?php echo $this->__('Qty') ?>" class="input-text qty" />
            <?php else: ?>

<?php echo $this->__('Out of stock') ?>

            <?php endif; ?>

            <?php endif; ?>

    <?php endforeach; ?>
    <?php else: ?>

           <td colspan="<?php if ($_product->isSaleable()): ?>4<?php else : ?>3<?php endif; ?>"><?php echo $this->__('No options of this product are available.') ?>

    <?php endif; ?>

This block of code show my tier price
    <?php $this->getTierPriceHtml($_item)?>

        <?php if ( $_item->getTierPrice()): ?>
        <?php echo $this->getTierPriceHtml($_item)?>
        <?php endif; ?>

I tried to just move this to where the SKU is being called but i get the error, calling on a non-object. I assume this si because the main product doesnt have a tier price and the associated products haven't been loaded yet. IF this is the case how can i get the associated products to load so i can grab the tier price
If i am not being clear just let me know and i will try to clear it up for you.
Thank you in advance for your help.

A: as you define you want tire price as the arrow indicate.
So in this case if i am not wrong you want the tire price only one time at the top of the list.?!
so you have to just make another loop structure same as hall product collection get and only get tire price and store in variable and display at top.
if i am not getting your question describe in depth.
Thanks.


text:
Q: How could we find the largest number in the sequence $ \sqrt{50},2\sqrt{49},3\sqrt{48},\cdots 49\sqrt{2},50$? How to find the largest number in the sequence$$ \sqrt{50},2\sqrt{49},3\sqrt{48},\cdots 49\sqrt{2},50$$
I am interested in a "calculus-free" approach.
Thanks,

A: I would like to apply calculus whenever it is possible. So, here is my trying (IMO this is not a better solution though):
Consider the function $f(x)=x^2(51-x)$ over $[1,50]$. Then as usual, $f'(x)=0\Rightarrow x=0,34$ and $f''(0)>0,f''(34)<0$ implies $f$ has a unique global maximum at $x=34$ and global minimum at $x=0$. So,...

A: The $n$-th term in the sequence is $n\sqrt{51-n}=\sqrt{n^2(51-n)}$. So the question is: for which $n$ ($1\le n\le 50$), does $n^2(51-n)$ become the largest?
If you want to avoid calculus, you could use the AM-GM inequality:
if $x,\,y,\,z\ge 0$, then $$\frac{x+y+z}{3}\ge\sqrt[3]{xyz},$$
with equality if and only if $x=y=z$.
If we set $x=y=n/2$ and $z=51-n$, we obtain: $$\frac{51}{3}\ge \sqrt[3]{\frac{n}{2}\cdot\frac{n}{2}\cdot (51-n)},$$
with equality if and only if $n/2=51-n$ or $n=34$.
It follows that $n^2(51-n)\le 4\cdot 17^3$, or $\sqrt{n^2(51-n)}\le 2\cdot 17^{3/2}$, where equality holds for $n=34$.

A: I like the AM-GM argument a lot, but here's another more down-to-earth solution.
Write $a_n=n\sqrt{51-n}$, $1\le n\le 50$. Everything in sight is positive, so $a_n\le a_{n+1}$ if and only if
$$
a_n^2\le a_{n+1}^2\Leftrightarrow n^2(51-n)\le (n+1)^2(50-n).
$$
This latter inequality simplifies to the quadratic inequality $-3n^2+99n+50\ge0$. The plot of this function is a parabola opening downwards. Therefore the inequality holds between the zeros $n_1\approx-0.5$ and $n_2\approx 33.5$.
We have shown that $a_{n+1}$ is larger than $a_n$, when $1\le n\le 33$, and that $a_{n+1}$ is smaller than $a_n$, when $n\ge 34$. Therefore we can conclude that $a_{34}$ is the largest of this lot.


text:
Q: Dropdown list loses value on gridview RowCommand I have a DropDownList in a GridView. I am filling the GridView dynamically in GridView RowCreated(). I want to get that DropDownList's value when I click the GridView's Command Button.
In the RowCommand function, I am trying to get the value. However, I can't find the control in that function. Surprisingly, another DropDownList works fine in the same function.
C# code follows:
if (Request.Params["ID"] != null && Request.Params["ID"] != "")
{
    FirmID = Convert.ToInt32(Request.Params["ID"]);
    //OfficeList = IFARecord.GetOffices(FirmID);
}
if (!IsPostBack)
{
    GV_SABAdvisers.DataSourceID = "objectDataSourceSAV";
    GV_SABAdvisers.DataBind();
}

protected void GV_SABAdvisers_RowCommand(object sender, GridViewCommandEventArgs e)
{
    if (e.CommandName == "Index")
    {
        int Index = Convert.ToInt32(e.CommandArgument);
        GridViewRow row = GV_SABAdvisers.Rows[Index];

        //Not working
        DropDownList Offices = row.FindControl("ddlLocation") as DropDownList;
        String officeID = (Offices is DropDownList) ? Offices.SelectedValue : null;

        DropDownList ddlJobTitle = row.FindControl("ddlJobTitle") as DropDownList;

        if (ddlJobTitle is DropDownList)
        {
            newAdviserJobTitle.JobTitleID = Convert.ToInt32(ddlJobTitle.SelectedValue);// this works fine.
        }
    }
}

protected void GV_SABAdvisers_RowCreated(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        DropDownList ddlLocation = e.Row.FindControl("ddlLocation") as DropDownList;
        DropDownList ddlJobTitle = e.Row.FindControl("ddlJobTitle") as DropDownList;
        DataTable OfficeList = GetOffices(FirmID);
        DataTable dtJob = MyTouchstone.Advisers.AdviserFirmJobTitle.AllJobTitle();

        foreach (DataRow aOffice in OfficeList.Rows)
        {
            ddlLocation.Items.Add(new ListItem(aOffice["Address1"].ToString() + ", " + aOffice["Postcode"].ToString(), aOffice["OfficeID"].ToString()));
        }

        foreach (DataRow aJob in dtJob.Rows)
        {
            ddlJobTitle.Items.Add(new ListItem(aJob["JobTitle"].ToString(), aJob["JobTitleID"].ToString()));
        }
    }
}

ASP markup:
<asp:UpdatePanel ID="UpdatePanel1" runat="server" UpdateMode="Conditional" ChildrenAsTriggers="True">
    <ContentTemplate>
        <asp:GridView ID="GV_SABAdvisers" AutoGenerateColumns="false" PageSize = "10"
            CssClass="cssPager" AllowPaging="true" AllowSorting="true"
            OnPageIndexChanging="GV_SABAdvisers_PageIndexChanging"
            runat="server" onrowcommand="GV_SABAdvisers_RowCommand"
            onrowcreated="GV_SABAdvisers_RowCreated">
            <PagerStyle />
            <Columns>
                <asp:TemplateField HeaderText="Job Title">
                    <ItemStyle Width="80px" />
                    <ItemTemplate>
                        <asp:DropDownList ID="ddlJobTitle" Width="80px" runat="Server"></asp:DropDownList>
                    </ItemTemplate>
                </asp:TemplateField>
                <asp:TemplateField HeaderText="Location">
                    <ItemStyle Width="200px" />
                    <ItemTemplate>
                        <asp:DropDownList ID="ddlLocation" Width="80px" runat="Server"></asp:DropDownList>
                    </ItemTemplate>
                </asp:TemplateField>
            </Columns>
        </asp:GridView>

Can anyone help me, please?

A: I don't see where have you used the CommandName "Index" in your source code.


text:
Q: Can we create SQL Server Aliases in Linux clients? Can we create "Server Aliases" in Linux clients (webservers etc.) so that you can change connections without touching the application's DB URL string?
The official documentation seems to talk about a GUI way of doing this in Windows, so I was wondering if something like this exists for Linux. This has lots of benefits, especially during containerization of apps.

My high level objective is to see if I can create some level of indirection so that the application always thinks of DB as DSN=myDsn;Uid=myUsername;Pwd=myPwd; while the real driver redirects it to DSN=realDsn;Uid=realUsername;Pwd=realPwd;. Initially I was thinking of something like socat, but I am not sure how password changes can be handled! "Server Aliases for client" seems to do something like this, hence the question.

A: Aliases on Windows are set using the SQL Server Configuration Manager GUI. The Linux equivalent is mssql-conf, but there isn't an equivalent to aliases on Linux.
(I don't think this is a case of "isn't supported yet" related to Linux support being relatively new. My guess on the future is just a hunch & guessing rather than fact.)
If you need server name redirection, I'd recommend using a CNAME to redirect that name for all clients centrally, rather than a client by client setting. Alternatively, I'd use the hosts file to redirect from one server name to another.
If you need to also do credential impersonation (your example implies this), allowing the user to supply one credential, and using something different to connect to the database, that sounds like something to be handled by your application, rather than expecting the drivers to do it for you.


text:
Q: Alternative approach for eliminating $watch As mentioned in the title in my angular application due to the below approach it leads to creation of many watch, i want to find some alternative methods for this.

    <first></first>

   var myApp = angular.module('myapp', []);

    myApp.directive('first', [
        function() {
            return {
                restrict: 'AE',
                replace: true,
                transclude: true,
                template: '
<second id="second" param="paramData"></second>
',
                scope: {
                },
                controller: [
                    '$scope',
                    '$element',
                    '$attrs',
                    function($scope, $element, $attrs) {

                    }
                ],
                link: function(scope, element, attrs, ctrl,$timeout) {
                    scope.paramData = "Test";
                    scope.updateParamData = function(){
                        scope.paramData = "TimeOut";
                    };
                    //$timeout(scope.updateParamData,5000);
                }
            };
        }
    ]);

    myApp.directive('second', [
        function() {
            return {
                restrict: 'AE',
                replace: true,
                template: '

',
                scope: {
                    param: '=param'
                },
                controller: [
                    '$scope',
                    '$element',
                    '$attrs',
                    function($scope, $element, $attrs) {
                            console.log("inside controller",$scope.param);
                    }
                ],
                link: function(scope, element, attrs) {
                    console.log("inside link",scope.param);
                    scope.$watch(scope.param,function(){
                        console.log("inside watch",scope.param);
                        element.innerHTML = scope.param;
                    });
                }
            };
        }
    ]);

In the above example the param which is passed from first directive to the second directive is controlled by first directive so the para can change at any time so in the second directive i am using the watch to update the second directive HTML based on the param update.
So now the problem is if i used same kind of approach in my application at many places it leads to multiple watch, so i want to check is this approach is correct or is there is any other alternative approach for this.?

A: There must be a $watch somewhere to detect the change in the value.
One way to reduce the number of watches is not to use two-way binding scope: {param: "="} in the second directive, and instead use one-way binding of "&".
.directive("second", function(){
  return {
    scope: { param: "&" }, // this does not create a watch on the parent
    template: "
{{param()}}
" // {{ }} creates a watch
  }
})

Of course, you can also explicitly add a $watch in the link/controller (although in your particular example where you use element.innerHTML) it can easier be done with the template approach above):
link: function(scope, element){
   scope.$watch(function(){ return scope.param(); },
     function(newValue, oldValue){
       console.log(newValue, oldValue);
     });
}

So, the number of watches is 1 in each case.

A: I see no way to improve this. Since you need to actually listen for changes for param I do not see a way different from watchers in this case.


text:
Q: How do I start a tmux service in the user's directory on user login using systemd I'm trying to set up my system so that when a user logs in, a tmux session will automatically be created for them, and this session is restarted if it ever exits, and the session starts in the user's home directory. I would like this to work for any user, or any new user added to the system, without a static unit file for each user. I'm having trouble making this work in a generic way, because I need to specify User and WorkingDirectory in the unit file for the tmux session to be created for the correct user in the correct directory.
So far my unit file looks like the following:
/etc/systemd/system/tmux-session-service.service...
---------------------------------------------------

[Unit]
Description=Tmux Session Service

[Service]
Type=forking
User=my-user
WorkingDirectory=/home/my-user
ExecStart=/usr/bin/tmux new-session -s tmux-session-service -d
ExecStop=/usr/bin/tmux kill-session -t tmux-session-service
Restart=on-failure

[Install]
WantedBy=multi-user.target

When I install and enable this, everything works like I expect as long as I am logged is as my-user. However if I log in as another user, the tmux session isn't created with the right permissions or working directory for the new user.
I looked into template files, but I can't quite get things to work. I tried setting the target to default.target, and using the %u template directive, but that seems to just refer to the user running the service manager, which is root.
One option would be to run systemctl run tmux-session-service@new-user.service when new-user logs in. Then I could use %i in the User and WorkingDirectory directives in the unit file. But then I need some process that has systemctl permissions to kick that off on user login, and I can't think of a way to do that.
I'm running:

*

*Arch Linux

*tmux v3.1c

*systemd v247

A: Under Ubuntu, I install the ....service file under:
/usr/lib/systemd/user/...

With the Debian packager, that is not automatic if you installed using the .service in the debian installation folder. Instead, you have to do it manually so it goes in the correct folder. So say you have a project defined like so:
tmux-session-service/debian/tmux-session-service.docs
tmux-session-service/debian/tmux-session-service.install
tmux-session-service/debian/tmux-session-service.service   <-- wrong!

Then for each user I would enable the service like so:
# Make sure the target folder exists
mkdir -p /home/${USER}/.config/systemd/user/default.target.wants

# If you're root when doing that, you want to fix the ownership
# (for the group, you may need a different variable)
chown -R ${USER}:${USER} /home/${USER}/.config/systemd

# If already installed, remove the link before re-creating it
rm -f /home/${USER}/.config/systemd/user/default.target.wants/${SERVICE}.service

# Again, I do this as root, so I need to use special care to run the
# following command as $USER isntead
sudo -H -u ${USER} sh -c "ln -s /usr/lib/systemd/user/${SERVICE}.service /home/${USER}/.config/systemd/user/default.target.wants/${SERVICE}.service"

If you want (can) do it manually, then install the file under /usr/lib/systemd/user/... as mentioned above, and then use the enable option:
systemctl --user enable ${SERVICE}.service

The problem with this technique is that you need to log in as each user to order to enable your service.
I think there is a way to have a service auto-start for all users, but that I haven't found out how to make it work yet...

A: Could it be as simple as putting something in new user's .bashrc files (or in the  /etc/profile file to get a system wide effect) that attaches to a tmux session called 'main' (this would create it if it doesn't already exist)?
That's what I have in mine, and it's as if tmux is just a built in feature of my terminal:
# Launch tmux
if command -v tmux>/dev/null; then
    [[ ! $TERM =~ screen ]] && [ -z $TMUX ] && tmux new-session -A -s main
fi


text:
Q: strange extended characters in ncurses I'm writing an ncurses application, and there's a strange issue with how special characters are printed to the screen. Here's an example:
#include <ncurses.h>

int main(int argc, char *argv[])
{
  initscr();
  noecho();
  keypad(stdscr, TRUE);
  cbreak();
  curs_set(0);

  addch(ACS_LARROW);
  addch(' ');
  addch(ACS_UARROW);
  addch(' ');
  addch(ACS_DARROW);
  addch(' ');
  addch(ACS_RARROW);
  addch(' ');

  refresh();

  getch();

  endwin();

  return 0;
}

So, when I run this on a tty, the characters are correctly printed as arrows (←, ↑, ↓, →), but when I try and run this on a terminal (I've tried on gnome-terminal and LXTerminal) this is the output:
< ^ v >

Is there any reason for this difference? I thought it might be font related, but I'm really out of my territory here, and my googling didn't help.
Any suggestion on how to force lxterminal (or any other terminal) to output the same characters of the tty?

A: ncurses decides which character to output for ACS_LARROW and friends based on your termtype. It's likely that in a tty your termtype is set to 'linux', whereas in gnome-terminal, etc it'll most likely be set to 'xterm'. Although I'm not certain, it's quite possible that the xterm termtype doesn't support these characters.
You could try running you application as so:
env TERM=linux ./a.out

Other termtypes to try are gnome, rxvt and vt102. These will output extended ASCII characters and your terminal emulator should support them. You could also try rxvt-unicode if you have it installed, that should output the correct unicode codepoints for these special symbols.

A: terminal emulations are sometimes coded in 7bit ASCII, and there is no corresponding Value for the arrows (with line and wedge) in this code page, so the terminal displays what comes near (that is: only the wedge).
on tty you have all the capacities of you computer (UTF-8, color encoding, ...), so the terminal can draw the arrow.

A: The setting of TERM is largely irrelevant.  What matters is

*

*the locale

*the choice of library

*the particular terminal emulator

The usual reason for this is that the program is built-with and linked-to the ncurses library rather than ncursesw:

*

*if you use the former (ncurses) in a locale using UTF-8, ncurses will use ASCII graphics simply because it cannot draw UTF-8.  ncursesw can draw using UTF-8 characters.

*using ncursesw, the program will use UTF-8 as needed (since 2002, it can use either the terminfo information, or a built-in table of Unicode values).  The Linux console and screen are known special cases where the terminfo cannot describe the behavior of the terminal.  For others (terminals which do not support VT100 line-drawing in UTF-8 mode), you would set NCURSES_NO_UTF8_ACS.

*the terminal database does in fact have an extended capability addressing the lack of VT100 compatibility vs UTF-8 (see U8 note in the terminal database). However, most people set TERM to xterm or linux and often equate those (see note in xterm FAQ).


text:
Q: Is there any difference in strtotime +day or +days? Was googling this, but couldn't find the answer. Was wondering, if there is a difference in these two scripts?
+3 day:
echo date( 'd.m.Y H:i:s', strtotime( '+3 day' ) );

+3 days:
echo date( 'd.m.Y H:i:s', strtotime( '+3 days' ) );

The output is exactly the same.
So is that implemented to make sure people get less errors or what?
And witch one should be preferred to use?

A: That is basically same thing, and for usability and pretty purposes:
strtotime( '+1 day' );
strtotime( '+3 day' );
strtotime( '+1 days' );
strtotime( '+3 days' );
strtotime( '+1 weeks' );
strtotime( '+3 week' );

You can use the one you like more, basically the one that defines de number, 1 day, 3 days


text:
Q: html5 template-element AngularJS Im experimenting with template elements and Angular.
<template id="loginTemplate">

    <form class="form-inline text-center" id="loginForm" data-ng-submit="login()">
      <input type="email" class="input-big" placeholder="Email" data-ng-model="loginEmail">
      <input type="password" class="input-mini" placeholder="Password" data-ng-model="loginPass">
      <input type="text" class="input-small" placeholder="Display name" data-ng-model="loginName" data-ng-show="register">
      <button type="submit" class="btn-small">Sign in</button>
      <button type="button" class="btn-small" data-ng-hide="register" data-ng-click="register=true">Register</button>
    </form>

</template>

JS:
(function init(){
"use strict";
var loginTemplate = document.querySelector("#loginTemplate").content;
document.body.appendChild(loginTemplate.cloneNode(true));
return;
})();

This works great in rendering my Angular controller data on init.
However when I want to conditionally load the next template it doesn't work.
<template id="menuTemplate">

{{ time.now }}

</template>

JS:
socket.on("logon", function ( data ){
//this fails
        $scope.user.name = data.userName;
        var menuTemplate = document.querySelector("#menuTemplate").content;
        document.body.removeChild(document.getElementById("login"));
        document.body.appendChild(menuTemplate.cloneNode(true));
}

This will show me the {{ variables }}.
Loading this menuTemplate first makes it work, but loading it conditionally doesn't.
Maybe Angular doesn't support template-elements, as they have said support will be available in 2.0, but initial load works so maybe someone has it working elsewhere?
Maybe the .clonenode breaks the angular link when performed after load? I dont know.
edit:Have a fiddle but have been unable to make it work as it does in chrome canary.
http://jsfiddle.net/CSK8n/


text:
Q: How can I reproduce the attached bar-chart in Tableau?
I have weeks as dimensions and all other columns as measures.

A: If your data is already in tableau, what you need to do is add weeks to the columns shelf. Drag "measure values" to the rows shelf and "measure names" to the colors mark. This will create the desired result. I entered dummy numbers in the same manner that was shown on your image and this was what I came up with. You can disregard the filter on "measure names" as it is added automatically to deal with the null values.


text:
Q: How to pick video from google photos app? I am trying to pick video from google photos app but I am not getting the correct URI when trying to pick video that is stored in cloud of google photos.
Intent initialization
Intent pickVideoIntent = new Intent(Intent.ACTION_PICK);
                            pickVideoIntent.setType("video/*");
                            pickVideoIntent.addFlags(FLAG_GRANT_READ_URI_PERMISSION);
                            pickVideoIntent.addFlags(FLAG_GRANT_PERSISTABLE_URI_PERMISSION);
                            startActivityForResult(pickVideoIntent, REQ_CODE_PICK_VIDEO);

In the onActivityResult
Uri selectedMediaUri = data.getData();
             if (selectedMediaUri.toString().contains("video")) {
                Uri uri = data.getData();
                String path = getPath(uri, getContext());
                uploadVideoFromUri(uri, path);
            }

public static String getPath(Uri uri, Context context)
    {
        String[] projection = { MediaStore.Video.Media.DATA };
        Cursor cursor = context.getContentResolver().query(uri, projection, null, null, null);
        if (cursor != null) {
            int column_index = cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DATA);
            cursor.moveToFirst();
            return cursor.getString(column_index);
        } else
            return null;
    }

the resulted Uri is
content://com.google.android.apps.photos.contentprovider/0/2/mediakey%3A%2Flocal%253A8941afc5-97e6-437c-8387-b5591f3e1ede/ORIGINAL/NONE/video%2Fmpeg/2022128414

The result of getPath() is always null.


text:
Q: Update ruby version on MAC I'm trying to update ma ruby version.
I'm with ruby 1.8.7 and I would like to install 2.1.0.
I just installed rvm, rbenv, brew and gem.
But when I try to do
$ rbenv install 2.1.0.

I get an error about clang. I don't get the point between clang and ruby
Could you please help me?
Error:
$ rbenv install 2.1.0
Downloading ruby-2.1.0.tar.gz...
Installing ruby-2.1.0...

BUILD FAILED
...
Last 10 log lines:
...
checking build system type... x86_64-apple-darwin12.3.0
checking host system type... x86_64-apple-darwin12.3.0
checking target system type... x86_64-apple-darwin12.3.0
checking for gcc-4.2... no
checking for clang... no
checking for gcc... no
checking for cc... no
./configure: line 3390: -E: command not found
configure: error: clang version 3.0 or later is required

A: You need to install the Developer Tools command-line tools in order to build Ruby. As one option, you can install Xcode from the App Store, and Xcode will let you install the command line tools if they aren't automatically installed with your version.

A: You can install developer command line tools without installing Xcode. Just type the following in the terminal:
xcode-select --install


text:
Q: Can someone help me spot the error in my sql syntax here? I have a syntax error I'm having trouble discerning. Help appreciated!

Schema Creation Failed: You have an error in your SQL syntax; check
  the manual that corresponds to your MySQL server version for the right
  syntax to use near '`i_id` int,     PRIMARY KEY (d_id),     FOREIGN KEY
  (i_id) REFERENCES Indicators (i_id' at line 6:

CREATE TABLE Indicators
(
    `i_id` int AUTO_INCREMENT,
    `i_name` varchar(255),
    PRIMARY KEY (i_id)
);

CREATE TABLE Data
(
    `d_id` int AUTO_INCREMENT,
    `Year` year,
    `Datapoint` float(24,2)
    `i_id` int,
    PRIMARY KEY (d_id),
    FOREIGN KEY (i_id) REFERENCES Indicators (i_id)
);

A: You are missing the comma at the end of the Datapoint line
Also if the default engine of your MySQL instance is not InnoDB you will not be able to create the foreign keys.

A: CREATE TABLE Data
(
    `d_id` int AUTO_INCREMENT,
    `Year` year,
    `Datapoint` float(24,2),
                           ^------ here it is
    `i_id` int,
    PRIMARY KEY (d_id),
    FOREIGN KEY (i_id) REFERENCES Indicators (i_id)
);

you're missing a comma after float(24,2)


text:
Q: What is the difference between component prop and using children in Route? I've been playing with react-router but now I have a question that I've been unable to answer:
I understand that if you use <Route component={SomeComponent}/> the router uses React.createElement to create the new react element (see this link). So if you use the hook useEffect it will get triggered every time right? if that is the case, if I use the recommended approach:
<Route>
  <SomeComponent/>
</Route>

The behavior of the useEffect should be different, shoudln't be?
Anyway, I was trying to see evidence of this with the following example:

// App.js

import { BrowserRouter as Router, Link, Route } from 'react-router-dom';
import { PropComp } from './PropComp';

function App() {
  return (

      <Router>
        <Link to='/uno'>uno</Link>

...

        <Link to='/dos'>dos</Link>
        <Route path='/uno' component={(props) => <PropComp {...props}/>}/>
        <Route path='/dos'>
          <PropComp/>
        </Route>
      </Router>

  );
}

export default App;

// PropComp.js

import React, { useState, useEffect } from 'react'

export const PropComp = () => {

    const [counter, setCounter] = useState(0)

    useEffect(() => {
        console.log('PropComp mounted')
    }, [])

    const onPlus = () => {
        setCounter(x => x + 1)
    }

    const onRemove = () => {
        setCounter(x => x - 1)
    }

    return (

{counter}

            <button onClick={onPlus}>Sum</button>
            <button onClick={onRemove}>Remove</button>

    )
}

So at the end, I don't understand what is the practical difference between the path=/unoand path=/dos.
Also, I was reading this post, so I took the example of the Reac-Router docs and changed the Route component in order to use the prop component and nothing changed... for sure I'm doing/understanding something wrong...

A:  <Router>
    <Link to='/uno'>uno</Link>

...

    <Link to='/dos'>dos</Link>
    <Route path='/uno' component={(props) => <PropComp {...props}/>}/>
    <Route path='/dos'>
      <PropComp/>
    </Route>
  </Router>

here
  <Link to='/uno'>uno</Link>
    //Link simply redirect the control to "/uno" this route. and
    //here:
    <Route path='/uno' component={(props) => <PropComp {...props}/>}/>
   // this Defines the component for this "/uno" route

 //and your second question is that why we use these two approaches:
     <Route path='/uno' component={(props) => <PropComp {...props}/>}/>
      <Route path='/dos'>
         <PropComp/>
       </Route>
// we can use both approaches it's up to you, which one you refer, I used both


text:
Q: How many requests per second should my asp(class) app handle I'm profiling a asp(classic) web service. The web service makes database calls, reads/writes to files, and processes xml. On a windows server 2003 box(2.7ghz, 4 core, 4gb ram) how many requests per second should I be able to handle before things start to fail.
I'm building a tool to test this, but I'm looking for a number of requests per second to shoot for.
I know this is fairly vague, but please give the best estimate you can. If you need more information, please ask.

A: 95% of the performance of any data-driven app is dependent on the database: 1) the way you do your calls, 2) the indexes, 3) the hardware under the database (disk subsystem in particular).
I have seen a machine, like you are describing, handle 40 requests per second (2500/minute), but numbers like 10 per second (600/minute) are more common.  I would expect even lower if you are running your DB on the same machine, and even lower still if that DB is SQLExpress or MSAccess.
Also, at capacity, your app will probably not fail, but IIS will Queue requests, once it is saturated, and may timeout some of those requests if it can't service them before the timeout expires.
Btw, instead of building a tool to test your app, you may want to look into using a test tool such as Microsoft WCAT.  It is pretty smooth and easy to use.

A: How fast should it be? Fast enough.
How fast is fast enough? That's a question that only you and your users can answer. If your service is horrifically inefficient and keeps up with demand, it's fast enough. If your service is assembly-optimized, lightning-fast, and overwhelmed with requests, it's not fast enough.
If the server is handling its actual workload, then don't worry about how fast it "should" be. When the server is having trouble, or when you anticipate that it soon will, then you should look at improving the code or upgrading the hardware. Remember Knuth's Law – premature optimization is the root of all evil. Any work you do now to make it faster may never pay off, and you may be forced to make compromises with flexivility or maintainability. Remember, too, an older adage – if it ain't broke, don't fix it.

A: Yes I would also say 10 per second is a good benchmark. For a high performance app you would want to get more than this, but if you have no specific goal you should generally be able to get at least 10 requests per sec for a general web page with a bunch of database queries.


text:
Q: Empty response on long running query SailsJS I'm currently running SailsJS on a Raspberry Pi and all is working well however when I execute a sails.models.nameofmodel.count() when I attempt to respond with the result I end up getting a empty response.
getListCount: function(req,res)
    {
            var mainsource = req.param("source");

            if(mainsource)
            {
                sails.models.gatherer.find({source: mainsource}).exec(
                        function(error, found)
                        {
                                if(error)
                                {
                                        return res.serverError("Error in call");
                                }
                                else
                                {
                                        sails.log("Number found "+found.length);
                                        return res.ok({count: found.length});
                                }
                        }
                );
        }
        else
        {
                return res.ok("Error in parameter");
        }
},

I am able to see in the logs the number that was found (73689).  However when responding I still get an empty response.  I am using the default stock ok.js file, however I did stick in additional logging to try to debug and make sure it is going through the correct paths.  I was able to confirm that the ok.js was going through this path
if (req.wantsJSON) {
    return res.jsonx(data);
}

I also tried adding .populate() to the call before the .exec(), res.status(200) before I sent out a res.send() instead of res.ok().  I've also updated Sails to 11.5 and still getting the same empty response.  I've also used a sails.models.gatherer.count() call with the same result.

A: You can try to add some logging to the beginning of your method to capture the value of mainsource. I do not believe you need to use an explicit return for any response object calls.
If all looks normal there, try to eliminate the model's find method and just evaluate the request parameter and return a simple response:
getListCount: function(req, res) {
    var mainsource = req.param("source");
    sails.log("Value of mainsource:" + mainsource);

    if (mainsource) {
      res.send("Hello!");
    } else {
      res.badRequest("Sorry, missing source.");
    }
}

If that does not work, then your model data may not actually be matching on the criteria that you are providing and the problem may lie there; in which case, your response would be null. You mentioned that you do see the resulting count of the query within the log statement. If the res.badRequest is also null, then you may have a problem with the version of express that is installed within sailsjs. You mention that you have 11.5 of sailsjs. I will assume you mean 0.11.5.
This is what is found in package.json of 0.11.5
   "express": "^3.21.0",

Check for any possible bugs within the GitHub issues for sailsjs regarding express and response object handling and the above version of express.
It may be worthwhile to perform a clean install using the latest sailsjs version (0.12.0) and see if that fixes your issue.
Another issue may be in how you are handling the response. In this case .exec should execute the query immediately (i.e. a synchronous call) and return the response when complete. So there should be no asynchronous processing there.
If you can show the code that is consuming the response, that would be helpful. I am assuming that there is a view that is showing the response via AJAX or some kind of form POST that is being performed. If that is where you are seeing the null response, then perhaps the problem lies in the view layer rather than the controller/model.
If you are experiencing a true timeout error via HTTP even though your query returns with a result just in time, then you may need to consider using async processing with sailjs. Take a look at this post on using a Promise instead.


text:
Q: Windows CE 6.0 send data via USB-Serial Cable I am developing a WinCE application (.Net 3.5) which allow connection to terminal via TCPIP, Serial Port and USB.
Currently still trying to intergrate USB feature. I have done some research and found that USB connection can be done via SerialPort class in C#.
I tried to connect an USB-Serial cable to WinCE and a new COMPort (COM5) appear.
But when i send data through that port, it always return Write Timeout error.
Below is my code when connecting through SerialPort:
private void SetSerialPort()
{
    try
    {
        string[] a = SerialPort.GetPortNames();
        string port = "COM4";
        if (config.port.Length > 0)
        {
            port = config.port;
        }
        this.sp.PortName = port;
        this.sp.BaudRate = 9600;
        this.sp.DataBits = 8;
        this.sp.Parity = Parity.None;
        this.sp.StopBits = StopBits.One;
        this.StartSerialPort();
    }
    catch (Exception ex)
    {

    }
    finally
    {
        this.Refresh();
    }
}
public void StartSerialPort()
{
    try
    {
        this.sp.Open();
        this.sp.Handshake = Handshake.None;
        this.sp.ReceivedBytesThreshold = 1;
        this.sp.DiscardInBuffer();
        this.sp.DiscardOutBuffer();
        this.sp.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);
    }
    catch (Exception ex)
    {
        throw ex;
    }
    finally
    {
        if (this.sp.IsOpen)
        {
            this.sp.RtsEnable = true;
            this.sp.DtrEnable = true;
            this.sp.WriteTimeout = 5000;
        }
    }
}

Is it possible to send data through this setup?
WinCE USB > USB-Serial (RS232) > DB9 pin.
Thanks in advanced.

A: I have found the problem. It seem that i am using the wrong cable.
My WinCE Tablet is installed with FTDI driver while my cable is based on Prolific USB chipset.
I have buy a FTDI USB chipset cable and i am able to receive data from it.


text:
Q: Problem at the Table of Contents in Lyx I use Lyx 2.1, document class : report.
At the table of Contents, no spacing between "a few" under sections.

A: For some reason you have added some vertical space in the subsection headings, which messes things up. Here is a minimal LaTeX example demonstrating what you've done:
\documentclass{report}
\begin{document}
\tableofcontents
\subsection{First \vspace{0.25cm}}
\subsection{Second \vspace{-0.25cm}}
\subsection{Third }
\end{document}

So all you need to do is to find the subsections where you have added the vertical space, and remove it.
This is how it could appear in LyX. It may not look like the \vspace is part of the subsection heading, but when you place the cursor next to the vspace you'll see that it actually is. As an alternative to removing the space entirely, you could place the cursor just before the vspace, hit enter, and then set the style to Standard.


text:
Q: Separate data with its own label in chartjs I have dynamic data in barchart and it is needed a label dynamically, supposedly it should work but the problem is it displays the number of labels and the number of data refer to this image for the output.
Below is my working code
    let backgroundColor: any = [
      'rgba(255, 99, 132, 0.2)',
      'rgba(54, 162, 235, 0.2)',
      'rgba(255, 206, 86, 0.2)',
      'rgba(75, 192, 192, 0.2)',
      'rgba(153, 102, 255, 0.2)',
      'rgba(255, 159, 64, 0.2)',
      'rgba(255, 99, 132, 0.2)',
      'rgba(54, 162, 235, 0.2)',
      'rgba(255, 206, 86, 0.2)',
      'rgba(75, 192, 192, 0.2)',
      'rgba(153, 102, 255, 0.2)',
      'rgba(255, 159, 64, 0.2)'
    ];

    let borderColor: any = [
      'rgba(255,99,132,1)',
      'rgba(54, 162, 235, 1)',
      'rgba(255, 206, 86, 1)',
      'rgba(75, 192, 192, 1)',
      'rgba(153, 102, 255, 1)',
      'rgba(255, 159, 64, 1)',
      'rgba(255,99,132,1)',
      'rgba(54, 162, 235, 1)',
      'rgba(255, 206, 86, 1)',
      'rgba(75, 192, 192, 1)',
      'rgba(153, 102, 255, 1)',
      'rgba(255, 159, 64, 1)'
    ];

    this.barChart = new Chart(this.barCanvas.nativeElement, {
      type: 'bar',
      data: {
        labels: this.monthcostlabor,
        datasets: this.monthcostlabor.map((elem, i) => ({
          label: elem,
          backgroundColor: backgroundColor[(i % backgroundColor.length)],
          borderColor: borderColor[(i % borderColor.length)],
          borderWidth: 1,
          data: this.monthcostglobal
        })) // the second push() can be included here?
      },
      options: {
        scales: {
          yAxes: [{
            ticks: {
              beginAtZero: true
            }
          }]
        }
      }
    });


text:
Q: Assign custom attribute values to grid collection I have a created a custom grid in admin ,
I want to assign custom attributes from customer to one of the column in the grid , I can get the value of attribute from customer repository but how can I pass it  to collection?
Any help appreciated.
Thank You.

A: I have resolved this by joining my collection with customer_entity_varchar table
 $customerEav = $collection->getTable('customer_entity_varchar');

 $collection->getSelect()->join(
        array('customereav'=>$customerEav),
        '`order`.customer_id = customereav.entity_id AND customereav.attribute_id=214',
        ['custom_attribute' => 'customereav.value']);

hope this helps you as well.
Thank You.


text:
Q: C reverse function wont work with 32 characters To test my skills, I'm trying to write my own version of a few standard library functions. I wrote a replacement for strlen(), strlength():
int strlength(const char *c){
    int len = 0;
    while (*c != '\0') {
        c++;
        len++;
    }
    return len;
}

which doesn't include the null-terminator, and I am trying to write a function to reverse a string. This:
char *reverse(const char *s){
    char *str = (char *)malloc(sizeof(char) * strlength(s));
    int i = 0;
    while (i < strlength(s)) {
        str[i] = s[(strlength(s) - 1) - i];
        i++;
    }
    str[strlength(s)] = '\0';
    return str;
}

works for every string except for one with 32 characters (not including null-terminator) like foofoofoofoofoofoofoofoofoofoofo. It hangs in the reverse() functions while-loop. For all other amounts of characters, it works. Why is this happening?

A: Your buffer for str is off by 1. Your writes are overflowing into the rest of your heap.
As for why it works for values other than 32, my guess is that it has to do with the heap's memory alignment. The compiler is adding extra padding for smaller buffer sizes, but 32 bytes is nicely aligned (it's a power of 2, multiple of 8, etc.), so it doesn't add the extra padding and that's causing your bug to manifest. Try some other multiples of 8 and you'll probably get the same behavior.

A: char *reverse(const char *s){

here you allocate N characters (where N is the length of s without \0):
    char *str = (char *)malloc(sizeof(char) * strlength(s));

then you iterate N times over all characters of s
    int i = 0;
    while (i < strlength(s)) {
        str[i] = s[(strlength(s) - 1) - i];
        i++;
    }

and finally you add \0 at N+1 characters
    str[strlength(s)] = '\0';
    return str;
}

so you should do instead:
    char *str = malloc(sizeof(*str) * strlength(s) + 1); // +1 for final `\0`

and funny thing is that I just tested your code, and it works fine for me (with one character off) and your 32 characters string. As @JoachimPileborg says, "That's the fun thing about undefined behavior"!
As suggested by others, the problem is certainly due to memory alignment, when you get your data aligned with your memory it overflows, whereas when it is not aligned it overwrites padding values.

A: You asked:

But this works for every other string length. Why won't it for 32?

Most likely because the runtime allocates memory in blocks of 32 bytes. So a 1-character buffer overrun when the buffer size is, say, 22 bytes, isn't a problem. But when you allocate 32 bytes and try to write to the 33rd byte, the problem shows up.
I suspect you'd see the same error with a string of 64 characters, 96, 128, etc . . .

A: Replace
malloc(sizeof(char) * strlength(s))

by
malloc(sizeof(char) * (1+strlength(s)));

The line:
str[strlength(s)] = '\0';

works often as the malloc library routine reserves word boundary aligned block and allocates only as much of it as requested in the call, viz. power of 2, but when the overflowing data overwrites beyond the allocated part, then examining the disassembly through debugger is the best hack to understand the build tool-chain specific to target's behavior. As the line is following the while loop rather than within it, so without disassembly how is the while loop mutating into infinite is unpredictable.

A: What everybody else said about buffer overflow and the vagaries of your runtime's memory allocation implementation/strategy. The size of a C-string is 1 more than its length, due to the NUL-termination octet.
Something like this ought to do you (a little cleaner and easier to read):
#define NUL ((char)0) ;

char *reverse( const char *s )
{
  int   len = strlen(s) ;
  char *tgt = ((char*)malloc( 1+len )) + len ;
  char *src = s ;

  *(tgt--) = NUL ;
  while ( *src )
  {
    *(tgt--) = *(src++) ;
  }

  return tgt;
}

Your strlen() implementation is more complicated than it needs to be, too. This is about all you need:
int string_length( const char *s )
{
  char *p = s ;
  while ( *p ) ++p ;
  return p - s ;
}


text:
Q: Visual studio using the wrong template function for chrono::duration division I was converting over some code to use the c++11 chrono library rather than using the ctime library, at least in part to get a better understanding on the chrono library. Most of it has gone great, except for trying to do division by two chrono::durations. I've reduced the offending code down to a simple example and it took me a while to figure out why it was giving me the error it is.
#include <chrono>
using namespace std;

int main()
{
    chrono::milliseconds tickLength(16);
    chrono::milliseconds futureDuration(200);

    auto numTicks = futureDuration / tickLength;
}

This should access the function
template<class _Rep1,
    class _Period1,
    class _Rep2,
    class _Period2> inline
    typename common_type<_Rep1, _Rep2>::type
        operator/(
            const duration<_Rep1, _Period1>& _Left,
            const duration<_Rep2, _Period2>& _Right)

but instead appears to be trying to use
template<class _Rep1,
    class _Period1,
    class _Rep2> inline
    typename enable_if<is_convertible<_Rep2,
        typename common_type<_Rep1, _Rep2>::type>::value
        && !_Is_duration<_Rep2>::value,
        duration<typename common_type<_Rep1, _Rep2>::type, _Period1> >::type
        operator/(
            const duration<_Rep1, _Period1>& _Left,
            const _Rep2& _Right)

and thus is trying to determine a common type between milliseconds and long long. The compiler output is:
1>------ Build started: Project: Playground, Configuration: Debug Win32 ------
1>  playground.cpp
1>c:\program files (x86)\microsoft visual studio 12.0\vc\include\type_traits(1446): error C2446: ':' : no conversion from 'std::chrono::milliseconds' to '__int64'
1>          No user-defined-conversion operator available that can perform this conversion, or the operator cannot be called
1>          c:\users\XXX\documents\visual studio 2013\projects\playground\playground\playground.cpp(9) : see reference to class template instantiation 'std::common_type<__int64,std::chrono::milliseconds>' being compiled
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

Am I doing something wrong in my code?
Is this a visual studio issue?
Is this a c++11 standard issue?

A: Your example code compiles for me using clang/libc++.  And your description of what should be happening sounds right to me.  Further, if I print out numTicks, I get 12, which is 200/16 (integer division).
Sounds like a visual stdio bug to me.  I see nothing wrong with your code.


text:
Q: C++ Using a local variable of a method in another method Does anyone know if there's a way to pass a variable that i have created inside of a method to another method . I am posting part of the code so that it is clearer what i need to do
int Point::trovaLato(Point *spigolo2, Point *sol_p, Point *pvet){
//code
//code
Point* lato=new Point(myvalue1,myvalue2,myvalue3);
return 0;
}

Now i want to use that variable 'lato' inside of
int Rettangolo::interseca(Point *sol_p, Point *pvet){
int ritlat, test;
test = punti[0]->trovaLato(punti[1], sol_p, pvet); //this works
if(test){
    test = punti[1]->trovaLato(punti[2], sol_p, pvet);//ok
    if(!test){
        ritlat = lato->intersecaLato(punti[1], punti[2]); //doesn't know what lato is ofcourse :(
//more code
}

Thanks a lot

A: Change the return type to Point, and return one:
Point Point::trovaLato(Point* spigolo2, Point* sol_p, Point* pvet){
  //code
  //code
  return Point(myvalue1, myvalue2, myvalue3);
}

If you really need to return an int, you can return an std::pair<int, Point>.


text:
Q: Mobile-friendly D3.js bubble chart I am building a force bubble chart with D3.js. I am almost done, the only thing is that when I am simulating on a mobile, the positions of the bubbles are not adjusting to the size of the screen (I don't see any bubble). When I look at examples, it seems to display correctly on mobiles.
What part of the code in D3.js is changing the mobile display ?
You can visualize my project from this link (some things don't work like the background picture but the bubbles are there. We see them in tablet and desktop mode but not on cellphone mode). You can access the github page by following the same path : https://rawgit.com/aubertsigouin/canAi/master/index.html

A: Is your svg bigger than the screen?
You can set the size of the svg based on the window size.
let svg = d3.select('#teck-stack-svg');
svg.attr('width', window.innerWidth);
svg.attr('height', window.innerHeight);


text:
Q: How do you FIND (not prove) an expression that is logically equivalent to another expression? I need to find an expression that is logically equivalent to q ↔ (¬p ∨ ¬q). I have already constructed a truth table for the expression, but it hasn't helped so I'm still unsure on how to find a logically equivalent expression. The truth table has given this output:
F
F
T
F
Thanks for your help!

A: Your truth table indicates that your expression is true in exactly one of the four cases.  That says that this expression is equivalent to one of $p \wedge q$, ${\lnot} p \wedge q$, $p \wedge {\lnot q}$, $\lnot p \wedge \lnot q$: I'll leave it to you to see which one.


text:
Q: Does the word "cheeky" describe me? I want to describe my own sense of humor :-)
I recently sent my friend's mother a thank you note for hosting me. She replied by saying that thank you notes are very important, and my note was very appreciated.
I responded by saying that thank you notes are indeed very important, and I've been trying to teach her son this for a long time. For example, I continued, I recently lent her son my sleeping bag and (as of yet) have received neither the sleeping bag nor a thank you note!
We are all very close, which is why I am able to rib her son in front of his mother like that.
But I want to be able to describe this sense of humor. Could my comment ribbing her son be described as 'cheeky'? I can think of no other word to describe it really. My intention was just to make fun of him in an amusing way... all the more amusing because it's a letter to his mother.
Oh, and the irony here is, it was her own son that reminded me to send a thank you note.

A: So, you could say she sent a thank you note for your thank you note ;)
Yes, 'Cheeky' is an entirely appropriate word to use here.


text:
Q: Make javascript run onclick instead of pageload I have the the following script that runs when the page is loaded:
<script language="JavaScript">
     j=parseInt(Math.random()*ranobjList.length);
     j=(isNaN(j))?0:j;
     document.write(unescape(ranobjList[j]));
</script>

How can I execute it when a button is clicked rather then when it loads?

A: put it in a function, and call it on an onclick event on an element
function myEvent() {
    j=parseInt(Math.random()*ranobjList.length);
    j=(isNaN(j))?0:j;
    document.write(unescape(ranobjList[j]));
}

then in your html
<input type='button' value='Click Me' onclick='myEvent();' />

A: The code example you have isn't actually running on page load. It's running as it's interpreted by the DOM.
But here is a solution to your request.
The HTML button must be above the script tag. So you'll want something just like this:
<input type="button" value="Click me for action" id="actionButton" />

<script type="text/javascript">
    document.getElementById("actionButton").addEventListener("click", function() {
        j=parseInt(Math.random()*ranobjList.length);
        j=(isNaN(j))?0:j;
        document.write(unescape(ranobjList[j]));
    }, false);
</script>


text:
Q: How many distinct graphs with 10 vertices, each of which having an even degree, can be constructed? Suppose G=(V,E) is a simple undirected graph, whose vertices are labelled 1,2,...,10 and degree of each vertex in Vis even. How many such distinct (labelled) graphs with 10 vertices can be constructed?
How to approach this question?

A: This is not a very difficult problem, but it is fairly instructive for a beginner in Graph Theory, especially when broaching the topic of vertex degrees and counting. Recall that there're exactly $2^{n \choose 2}$ labelled graphs on n vertices (to see this, note that there're ${n \choose 2}$ pairs of vertices in an n-vertex graph, and since there're 2 possibilities for each pair (either an edge is present, or it isn't), we get the desired count). Using this, we see that there are exactly $2^{9 \choose 2}$ = $2^{36}$ labelled graphs on 9 vertices. We claim now that there are the same number of labelled graphs on 10 vertices in which every vertex has even degree: For this, it suffices to establish a bijection between our two collections. Let G be a labelled graph on 9 vertices, and let G' be the graph obtained from G by adding the vertex x which is adjacent to every vertex of G which has odd degree. Since G must have an even number of vertices with odd degree (by the Handshaking lemma), x has even degree; moreover, each of the 9 vertices of G' which were from G also clearly have even degree by construction. Hence G' is a unique member of our collection of labelled graphs on 10 vertices corresponding to G (to make uniqueness more precise, you could show our operation has a well-defined inverse, though this is fairly obvious again by construction). This completes the problem.
Remark: Try to generalize your problem for arbitrary n!


text:
Q: Assign consequential values to a DataFrame from a numpy array based on a condition The task seems easy but I've been googling and experimenting for hours without any result. I can easily assign a 'static' value in such case or assign a value if I have two columns in the same DataFrame (of the same length, ofc) but I'm stuck with this situation.
I need to assign a consequential value to a pandas DataFrame column from a numpy array based on a condition when the sizes of the DataFrame and the numpy.array are different.
Here is the example:
import pandas as pd
import numpy as np

if __name__ == "__main__":
    df = pd.DataFrame([np.nan, 1, np.nan, 1, np.nan, 1, np.nan])
    arr = np.array([4, 5, 6])

    i = iter(arr)

    df[0] = np.where(df[0] == 1, next(i), np.nan)

    print(df)

The result is:
     0
0  NaN
1  4.0
2  NaN
3  4.0
4  NaN
5  4.0
6  NaN

But I need the result where consequential numbers from the numpy array are put in the DataFrame like:
     0
0  NaN
1  4.0
2  NaN
3  5.0
4  NaN
5  6.0
6  NaN

I appreciate any help.

A: it's not the very efficient way but it will do the job.
import pandas as pd
import numpy as np

def util(it, row):
    ele = next(it, None)
    return ele if ele is not None else row

df = pd.DataFrame([np.nan, 1, np.nan, 1, np.nan, 1, np.nan])
arr = np.array([4, 5, 6])
it = iter(arr)

df[0] = np.array(list(map(lambda r : util(it, r) if r == 1.0 else np.nan, df[0])))


text:
Q: SQL Query criteria to get data by date I've a doubt on SQL Query.
Actually my problem is I have to retrieve data using date (Criteria).
For Example, lets assume a table named "Plans".  It have columns PLANID and EXPIRY_TIME(plan expiry time in milliseconds).
Both columns are BIGINT datatype.
I have to retrieve all rows, who all are having plan expiry date as today.
Like, today date is 17. Then result must have expiry date as 17 from any month and any year.
For that, I had surfed. I found a way to convert milliseconds to  date. But it was working on "date" datatype only where I have type as "BIGINT".
That Function is FROM_UNIXTIME();
Is there any way to do it?
Advance thanks for the help!

A: You can do something like this:
SELECT `plan`.`PLANID`,
`plan`.`EXPIRY_TIME`,
FROM_UNIXTIME(`plan`.`EXPIRY_TIME`/1000, '%d-%m-%Y') as plan_expiry
FROM `Test`.`plan`;

The important point is dividing by 1000 to get seconds like stated here:
Convert BigInt timestamp to a real Date with row aggregation and operations in mySQL
Result:
PLANID      EXPIRY_TIME       plan_expiry
1           1458211499228     17-03-2016

Regards


text:
Q: Mapping XML to POJO using xstream I'm using XStream to map XML to the corresponding POJO. My XML structure is as below
<myTag>
<TagABC>
   <x> ... </x>
   <y> ... </y>
</TagABC>
    .
    .
    .
<TagABC>
   <x> ... </x>
   <y> ... </y>
</TagABC>
</myTag>

So there are multiple TagABC. I have defined TagABC in my POJO as
private List<TagABCHolder> TagABC;

where TagABCHolder is another POJO that simply contains x, y and their getter, setter
Now when I try to do the mapping using XStream with the code below
xstream.alias("TagABC", TagABCHolder.class);

xstream.fromXML(xml);

This does not recognize the List structure defined in POJO for TagABC and throws the error below
 ---- Debugging information ----
 message             : x: x
 cause-exception     : com.thoughtworks.xstream.mapper.CannotResolveClassException
 cause-message       : x: x
 class               : com.a.b.c.testing.common.TagABCHolder
 required-type       : java.util.ArrayList
 path                : /myTag/TagABC/x
 line number         : 1

Any idea how can I resolve this?

A: I got the solution.
This is just a trick with the annotations.
Here's what I did:
I added @XStreamImplicit annotation in the POJO (TagABCHolder)
@XStreamImplicit(itemFieldName="TagABC")
private List<TagABCHolder> TagABC;

and just processed the annotations placed within the POJO from the code where I was mapping
xstream.processAnnotations(TagABCHolder.class);

That's it!!!


text:
Q: libRestKitThree20 library is getting error I have included restkit in project and when i build restkit, it builds successful. But when I build project, it gives 6 errors:
Undefined symbols for architecture i386:
  "_OBJC_CLASS_$_TTModel", referenced from:
      _OBJC_CLASS_$_RKObjectLoaderTTModel in libRestKitThree20.a(RKObjectLoaderTTModel.o)
  "_OBJC_CLASS_$_TTTableLinkedItem", referenced from:
      _OBJC_CLASS_$_RKMappableObjectTableItem in libRestKitThree20.a(RKMappableObjectTableItem.o)
  "_OBJC_CLASS_$_TTTableViewDataSource", referenced from:
      _OBJC_CLASS_$_RKObjectTTTableViewDataSource in libRestKitThree20.a(RKObjectTTTableViewDataSource.o)
  "_OBJC_METACLASS_$_TTModel", referenced from:
      _OBJC_METACLASS_$_RKObjectLoaderTTModel in libRestKitThree20.a(RKObjectLoaderTTModel.o)
  "_OBJC_METACLASS_$_TTTableLinkedItem", referenced from:
      _OBJC_METACLASS_$_RKMappableObjectTableItem in libRestKitThree20.a(RKMappableObjectTableItem.o)
  "_OBJC_METACLASS_$_TTTableViewDataSource", referenced from:
      _OBJC_METACLASS_$_RKObjectTTTableViewDataSource in libRestKitThree20.a(RKObjectTTTableViewDataSource.o)
ld: symbol(s) not found for architecture i386
collect2: ld returned 1 exit status

kindly help how to rid it off

A: Make sure your project is using the Three20 library. Also make sure your build order makes sense - you may need to reference three20 in your workspace/project before RestKit is compiled or in the RestKit project if you have one.


text:
Q: can we increase the size of embedded google presentation? I am embedding google presentation in my website. But the slides in it are very small and hard to view. Is there some way by I which I could increase the display area of that embedded google presentation. Or, it can't be done at all and I should not waste time searching for it?
Thanks

A: Is this your document? If so just go into google docs and re-publish the presentation, but choose the large player size.
If it's not your presentation (you don't have access to the presentation in google docs) you can tweak the html:
Here's the markup for the (default) small player:
<iframe src="http://docs.google.com/present/embed?id=<your_document_id>" frameborder="0" width="410" height="342">

And here's the markup for the (default) large player:
<iframe src="http://docs.google.com/present/embed?id=<your_document_id>&size=l" frameborder="0" width="700" height="559">


text:
Q: Concating CSV files but Filtering Duplicates by 2 Columns I have a csv I want to update based on certain criteria. Example:
csv:
Name     UniqueID    Status
Apple    1121        Full
Orange   1122        Eaten
Apple    1123        Rotten

New values (also in a csv):
csv1:
Apple    1121        Eaten
orange   1122        Eaten
Pear     1233        Wiggly

the updated csv would look like this:
Name     UniqueID    Status
Apple    1121        Full
Orange   1122        Eaten
Apple    1123        Rotten
Pear     1233        Wiggly
Apple    1121        Eaten

So basically skip the entries that have the same UniqueID and Status. If it's a new UniqueID or an existing UniqueID and a different Status I want it included as a separate row. So from the above example orange   1122  Eaten, was excluded.
I tried converting the csv to a DataFrame and using the drop_duplicates.
data = pd.concat([pd.DataFrame.from_csv(csv, csv1)].drop_duplicates(subset=['Status', 'UniqueID'])
But it predictably dropped all the duplicates. Which resulted in:
    Name     UniqueID    Status
    Apple    1121        Full
    Orange   1122        Eaten
    Apple    1123        Rotten
    Pear     1233        Wiggly
   # Apple    1121        Eaten  <-- this result was excluded

A:
cat csv csv1 | awk '{if (!status[$2] || status[$2]!=$3) {print $0; status[$2]=$3} }'

explanation
print these files in sequence and iterete line by line
cat csv csv1 | awk '{
Keep second column (unique id) in an array key and the third one column as the value. Then check, if the array element doesn't exists (it means this is first occurence of that row) OR value is not equal to the third one (it means that value has changed)
if (!status[$2] || status[$2]!=$3) {
then simply print the row and set the array value
print $0;
status[$2]=$3
if ends
}
awk ends
}'

A: setup
import pandas as pd
from StringIO import StringIO

csv = """Name     UniqueID    Status
Apple    1121        Full
Orange   1122        Eaten
Apple    1123        Rotten"""

csv1 = """Name     UniqueID    Status
Apple    1121        Eaten
Orange   1122        Eaten
Pear     1233        Wiggly """

option 1
set_index + combine_first + reduce
def fruit_status1(f):
    return pd.read_csv(StringIO(f), delim_whitespace=True,
                       index_col=['UniqueID', 'Status'])

def update1(d1, d2):
    return d2.combine_first(d1)

reduce(update1, [fruit_status1(f) for f in [csv, csv1]])

option 2
pd.concat + drop_duplicates
def fruit_status2(f):
    return pd.read_csv(StringIO(f), delim_whitespace=True)

pd.concat([fruit_status2(f) for f in [csv, csv1]]) \
    .drop_duplicates(subset=['UniqueID', 'Status'])


text:
Q: Разворачивание значений в словаре по ключу через функцию У меня есть словарь вида d = {'foo': 'bar', 'spam': ['eggs', 'test']}.
Необходимо с использованием функции (не lambda) осуществить смену местами ключа и значения(ий) таким образом, чтобы из исходных данным получилось такая картина:
d = {'bar':'foo', 'eggs': 'spam', 'test': 'spam'}

Как сделать "разворот" ключа с одним значением мне понятно:
def f(k):
    d[d.pop(k)] = k
    print(d)
f('foo')

Вполне ожидаемо получаем:
{'spam': ['eggs', 'test'], 'bar': 'foo'}

Но вот с несолькими значениями у одного ключа уже возникают проблемы и на вызов функции:
f('spam') мы получаем ошибку:

TypeError: unhashable type: 'list'

Как это можно исправить?

A: Если в лоб, то можно проверять тип данных, который лежит под ключом и если это список, то прогонять по всем значениям данного списка. Как то так:
d = {'foo': 'bar', 'spam': ['eggs', 'test']}

def f(inn:dict) -> dict:
    result = {}
    for key, value in inn.items():
        if isinstance(value, list):
            for item in value:
                result[item] = key
        else:
            result[value] = key
    return result

f(d)

# out
# {'bar': 'foo', 'eggs': 'spam', 'test': 'spam'}

И я все-таки сторонник не использовать внешние переменные в функции, а передавать данные через параметры и возвращать результат. Снимает ответственность с функции за внешними изменения и в дальнейшем ее можно использовать как черный ящик, без привязки к внешним изменениям


text:
Q: Print a structure in a String format in C I one of my assignment, I have a task to print the below whole structure in a string format.
Struct test
{
    int a,
    char char1,char2;
}

output should be: Structure is a=10,char1=b,char2=c;
I know it is very simple by using
printf("Structure is a=%d,char1=%c, char2= %c", s.a,s.char1,s.char2);

But in real-time, I have a lot of big structures and I cannot write printf statements with access specifiers for each element of structure. Is there any other way to print the whole structure with just specifying the structure variable or some other?

A: There's no way to do this in pure C. Some languages support this via a concept called reflection, but it's not available in C.
Code-that-writes-code is your best bet. Write a script that finds all your structs and builds functions to printf them.

A: One possible solution I can think of is that you can take the help of the fread funtion using which you can save the whole content of the structure at once into a, say temporary file. Using:
fread(&STRUCTURE_OBJECT, sizeof(YOUR_STRUCTURE), 1, FILE_POINTER);

Where STRUCTURE_OBJECT is the name of a data element of your strucure.
And then use linux based commands like "cat" and "piping" etc for the quick glance of the output.