text:
Q: Hidden right sidebar using position only Hi  I have build 2 sidebars. One left sidebar which is hidden by offsetting the element off the screen and giving him negative values for left attribute.
The right side menu in the other hand, doesn't disappear correctly and I can still scroll over horizontally and see this menu.
How can I hide the right sidebar without using display:none or visibility:hidden.
I am adding the code.

   $(function () {
        $("#arrow_btn").click(function () {
            $("#navbar, .upper_menu").toggleClass('active');
            $("#upper_left_menu").toggleClass('open_left_menu');
            console.log("look for arrow btn element");
            console.log("upper_left_menu", $("#upper_left_menu"));
            console.log('$("#navbar")', $("#navbar"));
        });

        $(".project_item").click(function (event) {
            var list = $(this).siblings();
            var i = $(this).find('i');
            $(list).toggleClass('closed_nested_list');
            if ($(i).hasClass('fa-plus')) {
                $(i).removeClass('fa-plus');
                $(i).addClass('fa-minus');
            } else {
                $(i).addClass('fa-plus');
                $(i).removeClass('fa-minus');
            }
            console.log('traverse over all project items');
            console.log('i', i);
            console.log('list', list);
        });

        $("#email").click(function(){
          console.log("you clicked email ya ya ");
          $("#right-navbar").css("display",'inline-block');
          $("#right-navbar, .upper_menu").toggleClass('active');
            $("#upper_right_menu").toggleClass('open_right_menu');
        });

     $(".list_item").click(function(){
       console.log('you clicked list item');
       $("#chatWrapper").toggleClass('active');
$("#right-navbar").toggleClass('aside');
       $("#upper_right_menu").toggleClass('aside_right_menu');
     });

    });
#arrow_btn{
        font-size: 30px;
        font-weight:normal;
    }

    #arrow_btn:hover{
        color: #3983C4;
    }

    .upper_menu {
        display: block;
        background-color: #F2F6F7;
        width: 100%;
        top: 0;
        right: 0;
    }
    #upper_left_menu {
        width: 30px;
        height: 30px;
        z-index: 1;
        -webkit-transition: all 600ms ease;
        -moz-transition: all 600ms ease;
        -ms-transition: all 600ms ease;
        -o-transition: all 600ms ease;
        transition: all 600ms ease;
    }

#upper_right_menu{
        z-index: 1;
        -webkit-transition: all 600ms ease;
        -moz-transition: all 600ms ease;
        -ms-transition: all 600ms ease;
        -o-transition: all 600ms ease;
        transition: all 600ms ease;
}

    .open_left_menu {
        margin-left: 223px;

    }

 .open_right_menu {
        margin-right: 223px;
   -webkit-transition: all 600ms ease;
        -moz-transition: all 600ms ease;
        -ms-transition: all 600ms ease;
        -o-transition: all 600ms ease;
        transition: all 600ms ease;
    }
.aside_right_menu{
  margin-right: 43.5%;
}
    #upper_right_menu {
        position: absolute;
        top: 0px;
        right: 0px;
    }

    #exclamation-triangle,
    #envelope {
        font-size: 24px;
    }

    .warning,
    .email {
        margin: 10px;
    }

 #navbar {
        position: absolute;
        left: -16em;
        top: 0;
        bottom: 0;
        background-color: white;
        box-shadow: 4px 0 5px rgba(0, 0, 0, 0.2);
        z-index: 1;
        cursor: pointer;
        animation: 10s;
        overflow-y: auto;
        overflow-x: hidden;
    }

    #navbar ul {
        width: 224px;
        list-style-type: none;
        margin: 0;
        padding: 1em;
    }

#right-navbar{

  position: absolute;
        right: -16em;
        top: 0;
        bottom: 0;
        background-color: white;
        box-shadow: 0 5px 5px rgba(0, 0, 0, 0.2);
        z-index: 1;
        cursor: pointer;
        animation: 10s;
        overflow-y: auto;
        overflow-x: hidden;
}

#chatWrapper{
  display:none;
  position: absolute;
        right: -32em;
        top: 0;
        bottom: 0;
        width:338.667px;
        background-color: white;
        box-shadow: 0 5px 5px rgba(0, 0, 0, 0.2);
        z-index: 1;
        cursor: pointer;
        animation: 10s;
        overflow-y: auto;
        overflow-x: hidden;
}

#right-navbar ul {
        width: 224px;
        list-style-type: none;
        margin: 0;
        padding: 1em;
    }
/* hovering */
    #chatWrapper,
    #chatWrapper *
    #right-navbar,
    #right-navbar *,
    #navbar,
    #navbar * {
        -webkit-transition: all 600ms ease;
        -moz-transition: all 600ms ease;
        -ms-transition: all 600ms ease;
        -o-transition: all 600ms ease;
        transition: all 600ms ease;
    }

    #navbar.active {
        left: 0px;
    }

  #right-navbar.active{
      right: 0px;
    -webkit-transition: all 600ms ease;
        -moz-transition: all 600ms ease;
        -ms-transition: all 600ms ease;
        -o-transition: all 600ms ease;
        transition: all 600ms ease;
  }
 #right-navbar.aside{
      right: 26.5%;
  }
#chatWrapper.active{
  right:0%;
}

    .nested_list {
        display: inline-block;
        visibility: visible;
    }

    .closed_nested_list {
        display: none;
    }

    .project_item {
        font-family: 'Segue UI', Calibri, arial, verdana, sans-serif;
        font-size: 18px;
    }

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css" rel="stylesheet"/>

        2
        5

                FDR Project

     Unit01

     Unit02

     Unit03

              Niagara Project

     Unit01

     Unit02

     Unit03

              Jarvis Plant

     Unit01

     Unit02

     Unit03

              Jarvis Plant

     Unit01

     Unit02

     Unit03

                FDR Project

     Unit01

     Unit02

     Unit03

              Niagara Project

     Unit01

     Unit02

     Unit03

              Jarvis Plant

     Unit01

     Unit02

     Unit03

              Jarvis Plant

     Unit01

     Unit02

     Unit03

  Hello Chat Warpper

A small piece of the original code without the left menu and only the right menu

   $(function () {

        $("#email").click(function(){
          console.log("you clicked email ya ya ");
          $("#right-navbar").css("display",'inline-block');
          $("#right-navbar, .upper_menu").toggleClass('active');
            $("#upper_right_menu").toggleClass('open_right_menu');
        });

     $(".list_item").click(function(){
       console.log('you clicked list item');
       $("#chatWrapper").toggleClass('active');
$("#right-navbar").toggleClass('aside');
       $("#upper_right_menu").toggleClass('aside_right_menu');
     });

    });
#arrow_btn{
        font-size: 30px;
        font-weight:normal;
    }

    #arrow_btn:hover{
        color: #3983C4;
    }

    .upper_menu {
        display: block;
        background-color: #F2F6F7;
        width: 100%;
        top: 0;
        right: 0;
    }

#upper_right_menu{
        z-index: 1;
        -webkit-transition: all 600ms ease;
        -moz-transition: all 600ms ease;
        -ms-transition: all 600ms ease;
        -o-transition: all 600ms ease;
        transition: all 600ms ease;
}

    .open_left_menu {
        margin-left: 223px;

    }

 .open_right_menu {
        margin-right: 223px;
   -webkit-transition: all 600ms ease;
        -moz-transition: all 600ms ease;
        -ms-transition: all 600ms ease;
        -o-transition: all 600ms ease;
        transition: all 600ms ease;
    }
.aside_right_menu{
  margin-right: 43.5%;
}
    #upper_right_menu {
        position: absolute;
        top: 0px;
        right: 0px;
    }

    #exclamation-triangle,
    #envelope {
        font-size: 24px;
    }

    .warning,
    .email {
        margin: 10px;
    }

#right-navbar{

  position: absolute;
        right: -16em;
        top: 0;
        bottom: 0;
        background-color: white;
        box-shadow: 0 5px 5px rgba(0, 0, 0, 0.2);
        z-index: 1;
        cursor: pointer;
        animation: 10s;
        overflow-y: auto;
        overflow-x: hidden;
}

#chatWrapper{
  display:none;
  position: absolute;
        right: -32em;
        top: 0;
        bottom: 0;
        width:338.667px;
        background-color: white;
        box-shadow: 0 5px 5px rgba(0, 0, 0, 0.2);
        z-index: 1;
        cursor: pointer;
        animation: 10s;
        overflow-y: auto;
        overflow-x: hidden;
}

#right-navbar ul {
        width: 224px;
        list-style-type: none;
        margin: 0;
        padding: 1em;
    }
/* hovering */
    #chatWrapper,
    #chatWrapper *
    #right-navbar,
    #right-navbar * {
        -webkit-transition: all 600ms ease;
        -moz-transition: all 600ms ease;
        -ms-transition: all 600ms ease;
        -o-transition: all 600ms ease;
        transition: all 600ms ease;
    }

    #navbar.active {
        left: 0px;
    }

  #right-navbar.active{
      right: 0px;
    -webkit-transition: all 600ms ease;
        -moz-transition: all 600ms ease;
        -ms-transition: all 600ms ease;
        -o-transition: all 600ms ease;
        transition: all 600ms ease;
  }
 #right-navbar.aside{
      right: 26.5%;
  }
#chatWrapper.active{
  right:0%;
}

    .nested_list {
        display: inline-block;
        visibility: visible;
    }

    .closed_nested_list {
        display: none;
    }

    .project_item {
        font-family: 'Segue UI', Calibri, arial, verdana, sans-serif;
        font-size: 18px;
    }

<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css" rel="stylesheet"/>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>

        2
        5

                FDR Project

     Unit01

     Unit02

     Unit03

              Niagara Project

     Unit01

     Unit02

     Unit03

              Jarvis Plant

     Unit01

     Unit02

     Unit03

              Jarvis Plant

     Unit01

     Unit02

     Unit03

  Hello Chat Warpper

A: Moving answer from comments...
Add overflow-x: hidden; to the nav bar's parent element (in this example, the parent would be body).
This will keep the horizontal scroll bar from coming up when the nav bar moves off the right side of the screen.


text:
Q: How to get distinct/unique attributes in xsl variable <xsl:variable name="Rows" select=" .. some stmt .." />
<xsl:for-each select="$Rows">
    <xsl:value-of select="@ATTRNAME"/>
</xsl:for-each>

Would like to know how to find 'Rows' with unique/distinct attribute 'ATTRNAME' [ in XSLT 1.0 ].

A: Grouping in XSLT 1.0 is done using xsl:key. The following prints only the unique elements of the root element:
<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
    <xsl:output method="text" omit-xml-declaration="yes"/>
    <xsl:key name="attrByVal" match="/*/@*" use="."/>
    <xsl:template match="/">
        <xsl:apply-templates select="/*/@*"/>
    </xsl:template>
    <xsl:template match="@*[generate-id()=generate-id(key('attrByVal', .)[1])]">
        <xsl:value-of select="concat(name(), ': ', ., '
')"/>
    </xsl:template>
    <xsl:template match="@*"/>
</xsl:stylesheet>

Explanation: First, we group all attributes of the root element by value:
<xsl:key name="attrByVal" match="/*/@*" use="."/>

Then, create a template that matches only the first element for each key in the group:
<xsl:template match="@*[generate-id()=generate-id(key('attrByVal', .)[1])]">

And ignore all the others:
<xsl:template match="@*"/>

Example input:
<root one="apple" two="apple" three="orange" four="apple"/>

Output:
one: apple
three: orange

A: XSLT 2.0 solution :
<xsl:for-each-group select="$Rows" group-by="@ATTRNAME">
 <!-- Do something with the rows in the group. These rows
 can be accessed by the current-group() function. -->
    </xsl:for-each-group>

redpajama_set_name: RedPajamaStackExchange


text:
Q: ssl android certificate with volley i have implemented the certificate and keystore to my app and succeeded in making request to my server , but now i want to accept another server's HTTPS (for online payment) to be able to integrate it in my app but volley says that it doesn't accept it , can i accept this domain without their keystore
and this is my code for accepting my server's certificate
private SSLSocketFactory newSslSocketFactory() {
    try {
        // Get an instance of the Bouncy Castle KeyStore format
        KeyStore trusted = KeyStore.getInstance("BKS");
        // Get the raw resource, which contains the keystore with
        // your trusted certificates (root and any intermediate certs)
        InputStream in = getApplicationContext().getResources().openRawResource(R.raw.keystore);
        try {
            // Initialize the keystore with the provided trusted certificates
            // Provide the password of the keystore
            trusted.load(in, KEYSTORE_PASSWORD);
        } finally {
            in.close();
        }

        String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
        TrustManagerFactory tmf = TrustManagerFactory.getInstance(tmfAlgorithm);
        tmf.init(trusted);

        SSLContext context = SSLContext.getInstance("TLS");
        context.init(null, tmf.getTrustManagers(), null);

        SSLSocketFactory sf = context.getSocketFactory();
        return sf;
    } catch (Exception e) {
        throw new AssertionError(e);
    }
}


text:
Q: Why speed = distance/time? Is it merely an arbitrarily chosen definition that we created in order to quantitatively measure the speed of an object or is it some other way around. I want to know what's the reason behind such a relation?
NOTE : I'm considering the fundamental case wherein the motion is uniform and is along a straight line.

A:
Italian physicist Galileo Galilei is usually credited with being the first to measure speed by considering the distance covered and the time it takes. Galileo defined speed as the distance covered per unit of time.[3] In equation form, that is

$v=\frac{d}{t}$

where $v$ is speed, $d$ is distance, and $t$ is time. A cyclist who covers 30 metres in a time of 2 seconds, for example, has a speed of 15 metres per second. Objects in motion often have variations in speed (a car might travel along a street at 50 km/h, slow to 0 km/h, and then reach 30 km/h).

https://en.wikipedia.org/wiki/Speed#Historical_definition

A: Ask yourself how one goes about measuring speed: you always measure the distance and the time and divide the former by the latter. Notice that you don't need to consider the speed of an object to know how far it's traveled from some point, nor do you need the speed of the object to measure the time it takes for the object to travel from one point to another. It is in this sense that length and time are more fundamental than speed.
Because speed cannot be measured in a simpler, more fundamental way, it makes sense to define it as distance divided by time. Loosely speaking, quantities are defined by how we go about measuring them.

A: If you consider how such a quantity may have come about, you could believe that it would be most useful to the average person when making comparisons between every day occurrences involving movement.
My assumption is that the concept of speed would have arisen in an "every day" context rather than coming into being as a pure mathematical definition.
A related answer in Stack Exchange states that the concept of speed predated Galileo by a long way which supports this assumption.
For example, consider an historical era predating free access to basic education, pre-calculus,  where a horse travels 10 leagues in a day, whilst another travels 6 leagues in half of a day.  How might someone in some historical, compare which is fastest?
You need an averaged quantity that describes the rate at which the horse travels i.e. you would have to long it takes each horse to travel the same distance.  To my (admittedly biased) mind, this leads naturally to the concept of speed but without the definition we now use without hesitation.
Obviously, we know that, in this example, one horse travels 10 L/day whereas the other travels 12 L/day, and we, without modern educations, interpret those quantities as speeds.
Therefore, I believe the concept of speed is simply a result of we humans wanting to make simple comparisons of moving objects in Nature, which has eventually been made rigorous in its meaning, and even been extended through calculus to the concept of instantaneous speed.


text:
Q: POST or PUT when sending data with Fetch API to check on server I'm writing a quiz app, where the frontend GETs a question from the server database using Fetch API, then sends both question and answer again via Fetch API to django on the server, which then is supposed to check against the data base if the answer is correct or not. As of now the checking doesn't change anything on the server (though in the future it'll change points for the user depending on if the answer was correct). Should I then be using PUT or POST as method?
I cannot use GET, because a GET method cannot have a body for parameters.
const setup = {
   credentials: "same-origin",
   method: 'PUT' or 'POST'?,
   body: JSON.stringify({
      "answer": 'is answer',
      "question": 'is question'
   }),
   headers: {
      "X-CSRFToken": getCookie("csrftoken"),
      "Accept": "application/json",
      "Content-Type": "application/json",
      "X-Requested-With": "XMLHttpRequest"
   },
};
const response = await fetch('/exercises/get_exercise', setup);

that's my fetch request. Also happy to hear any other comments on the code!

A: Even though you're not creating actual record on your database, I'd suggest you use POST. Think of it as you're creating a submission, or an answer record.
Possible duplicate: PUT vs. POST in REST


text:
Q: What is the difference in localhost (Apache server) and live web server I'm trying to host my site on live server, and it gives me an error.
But when I'm running that site on localhost it runs perfectly.
My question is what is main difference in live server and localhost server.
Any one please explain me. Thanks in advance.

A: There is no difference but might be you have not configured the settings of your live server. In localhost it takes the normal settings automatically. Please mention your error to have better solution to your problem.

A: Thanks friends for your help. The problem is solved now. I made some changes in .htaccess file (rewrite rule), and it gonna works.
But I didn't get one thing that the .htaccess file on localhost is not working on live server. What is the reason, any one can explain. My server settings are same for localhost and live server.


text:
Q: Perl OLE document visible I try to open and modify an Excel document with a Perl script, and I want this document to be still open after. I use the following code :
unless (defined $ex) {
$ex = Win32::OLE->new('Excel.Application', sub{$_[0]->Quit;})
or die "Cannot start Excel";
}

$ex->{Visible} = 1;

The Excel document briefly appears, then vanishes. The work is correctly done, but Excel closes down after. Is there a way to keep Excel open?

A: Just remove your destructor construct from the new method:
$ex = Win32::OLE->new('Excel.Application')
or die "Cannot start Excel";


text:
Q: Unity Value Assigned in Inspector Throws Null in Code I'm a beginner at Unity with a problem for which I've not been able to find an answer on any of the boards.  Creating a very basic Unity C# script, I have the following lines of code in my Awake() function:
Assert.IsNotNull(sfxJump);
Assert.IsNotNull(sfxDeath);
Assert.IsNotNull(sfxCoin);

The third assertion "
Assert.IsNotNull(sfxCoin) throws as null, even though the coin AudioClip is set in the Inspector:
Inspector script values:

However -- and this is the part that has me baffled -- for some reason sfxCoin is not null when invoked in the same script from an OnCollisionEnter() routine
So it appears Unity does register the object with the code -- eventually -- but the assertions fail with the initial Awake(), Start(), and Update() methods.
And this only is happening with sfxCoin.  sfxJump and sfxDeath do not have this issue.
Any help would be appreciated
Entire script is below:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Assertions;

public class Player : MonoBehaviour
{
    [SerializeField] private float jumpForce = 100f;
    [SerializeField] private float forwardMomentum = 5f;
    [SerializeField] private AudioClip sfxJump;
    [SerializeField] private AudioClip sfxDeath;
    [SerializeField] private AudioClip sfxCoin;

    private Animator anim;
    private Rigidbody Rigidbody;
    private bool jump = false;
    private AudioSource audioSource;

    private void Awake()
    {
        Assert.IsNotNull(sfxJump);
        Assert.IsNotNull(sfxDeath);
        Assert.IsNotNull(sfxCoin);
    }

    // Start is called before the first frame update
    void Start()
    {
        anim = GetComponent<Animator>();
        Rigidbody = GetComponent<Rigidbody>();
        audioSource = GetComponent<AudioSource>();
    }

    // Update is called once per frame
    void Update()
    {
        if (!GameManager.instance.GameOver() && GameManager.instance.GameStarted())
        {
            if (Input.GetMouseButton(0))
            {
                GameManager.instance.PlayerStartedGame();

                anim.Play("Jump");
                audioSource.PlayOneShot(sfxJump);
                Rigidbody.useGravity = true;
                jump = true;
            }
        }
    }

    private void FixedUpdate()
    {
        if (jump)
        {
            jump = false;
            Rigidbody.velocity = new Vector2(0, 0);
            Rigidbody.AddForce(new Vector2(forwardMomentum, jumpForce), ForceMode.Impulse);
        }
    }

    private void OnCollisionEnter(Collision collision)
    {
        switch (collision.gameObject.tag)
        {
            case "obstacle":
                Rigidbody.AddForce(new Vector2(-50, 20), ForceMode.Impulse);
                Rigidbody.detectCollisions = false;
                audioSource.PlayOneShot(sfxDeath);
                GameManager.instance.PlayerCollided();
                break;
            case "coin":

                audioSource.PlayOneShot(sfxCoin);
                GameManager.instance.Score(1);
                print("GOT COIN");
                break;

        }
    }
}

A: sorry, I found out what the problem was.
There was a second instance of a game object that was also using the same script that did not have sfxCoin set.  It was hidden under a node in the hierarchy so I didn't see it.
Like I said, I'm a beginner at this.


text:
Q: Replacing special character with jquery i need to replace the special character "[" and "]" in this syntaxe:
var Data = "[{\tst??}]";
It's a json format and i need to show all the information individually so i need a tip in jquery to replace or delete the "[" and "]" they causing me troubles when i whant to show the information.
Thank you.

A: var Data = "...."; // here is your data
var obj = JSON.parse(Data);

after this, obj will contain:
[ { AccountNumber: '664009500',
    AccountNumberLong: '230100950070',
    Autorizations: [],
    AvailableBalance: 0,
    Balance: 2243.93,
    BeneficiaryList: [ [Object], [Object], [Object], [Object], [Object] ],
    CanCreditAccount: true,
    CanDebitAccount: true,
    CodeOffre: 'CPTCHQ11',
    Currency: 'MAD',
    EligibleServiceList: [ '300014', '300018', '300013', '300016' ],
    Entitled: 'MONSIEUR HOUSSAM MOUBTAHIL',
    IsDemat: 'true',
    LstClientidTuteur: null,
    OpeningDate: '/Date(1408662000000+0000)/',
    OperationDate: '/Date(-62135596800000+0000)/',
    OperationLastDate: '/Date(1465776000000+0000)/',
    OperationOAA: null,
    OperationOSD: null,
    Operations: null,
    RelationType: null,
    SitexAccountList: [],
    SitexTierList: null,
    TotalBalance: 0,
    TotalCredit: 32151.26,
    TotalDebit: 29255.77,
    legalSituation: 'MJ' } ]

nothing to change :)
you have a list of objects, if your list will have only one element - take obj[0], if more - just loop through them (using, for loop or jQuery's .each)..

A: Use slice to remove the first and the last char (i.e, [ and ])
CleanData=Data.slice(1, -1);

Use this to remove all [ followed by { in order to get only { and the same is for }] that are replaced with }. In this way, something like [] is not replaced
var res = Data.replace("[{","{");
var CleanData=res.replace("}]","]");

A: try to use : Data.toString().trim().replace("[", anotherCharacter)


text:
Q: What does 'function(){ return this }()' do as an argument? Taken from nanoajax (https://github.com/yanatan16/nanoajax). Why not just pass in this, what does the self execution function returning this do?
!function(e, t) {
    function n() {
        if (t.XMLHttpRequest) return new t.XMLHttpRequest;
        try {
            return new t.ActiveXObject("MSXML2.XMLHTTP.3.0")
        } catch (e) {}
    }
    t.nanoajax = e, e.ajax = function(e, t, r) {
        r || (r = t, t = null);
        var u = n();
        return u ? (u.onreadystatechange = function() {
            4 == u.readyState && r(u.status, u.responseText)
        }, t ? (u.open("POST", e, !0), u.setRequestHeader("X-Requested-With", "XMLHttpRequest"), u.setRequestHeader("Content-Type", "application/x-www-form-urlencoded")) : u.open("GET", e, !0), void u.send(t)) : r(new Error("no request"))
    }
}({}, function() { return this }());

A: It ensures the argument is really the global object (window in a browser or root on node/iojs), which could be different if this in the external scope weren't.
Example :
function A(){
}
A.prototype.doIt = function(){
  !function(a){
    console.log(a);
  }(function() { return this }()); // passing this would pass the instance of A
};
(new A).doIt();

Here, passing this would not pass the global object.
Note that this code is the product of an automated minification operation.


text:
Q: Expected weight of n non-identical balls with given probability distribution We have n balls with weights chosen from a gives set {w1, w2, ..., wc} with probabilities {Pr1, Pr2, ..., Prc} respectively. I am looking for a closed-form formula for the expected weight of total balls. As an example, I think for n=3 and c=2 the result should be like this:
'Expected Weight = 3*w1*(Pr1)^3+(2*w1+w2)*(Pr1)^2*Pr2+(w1+2*w2)*Pr1*(Pr2)^2+3*w2*(Pr2)^3'

A: Well if you only care about the weights expectation, you can use the additivity of the expectation. The expected weight of 1 ball is $w_1Pr_1 + w_2Pr_2+...+w_cPr_c$ therefore the expected weight of $n$ balls is that same number times $n$


text:
Q: Closed non-intersecting geodesics on a compact hyperbolic surface are finite I recently came across this exercise.
Let $S$ be a closed orientable surface of genus strictly greater than one and let $g$ be a Riemannian metric on S with constant negative curvature. Then, given any infinite family of simple closed geodesics on S, there are at least two geodesics in this family that intersect in a point (in other words, a family of closed simple geodesics that are disjoint two by two must be finite).
So far, I only managed to prove that, if $(\gamma_n)_{n\in\mathbb{N}}$ is a sequence of simple closed geodesics, $\gamma_n : S^1 \to S  $, then
$$
\inf_{n,m\in\mathbb{N}}\mathrm{d}(\gamma_n,\gamma_m)=0,
$$
where $\mathrm{d}$ is the distance induced by $g$ on $S$. This infimum must be zero because, for any $t\in S^1$, the sequence $(\gamma_n(t))_{n\in\mathbb{N}}$ is contained in $S$, which is compact, so it admits a converging subsequence $(\gamma_{n_k}(t))_{k\in\mathbb{N}}$, which is a Cauchy sequence, and thus the equality above holds. Now, my (qualitative) idea is that the limit point is very near to all the geodesics in the sequence (for $k$ sufficiently big) and, since on a surface there is not much room, the geodesics are forced to meet in a point. Anyway, I do not how to make it rigorous nor if my idea is correct.
I am also aware of some basic results concerning hyperbolic manifolds, for example Cartan-Hadamard Theorem or the one to one corrispondence between closed geodesics and free homotopy loop classes, but I am not really familiar with them, so I do not know how to apply these theorems.
Any hint will be really appreciated.

A: Suppose that $S$ is a closed connected oriented surface of genus $g\ge 2$ and $L$ is a 1-dimensional submanifold in $S$ such that the complement $S-L$ contains no components which are annuli or disks. Prove (using the Euler characteristic) that the number of components of $L$ is $\le 3g-3$.
Now, if $S$ is equipped with a Riemannian metric of negative curvature, then a closed geodesic in $S$  cannot be null-homotopic and two such geodesics cannot be homotopic unless their images are the same. Use these observation to conclude that if $L\subset S$ is a submanifold each component of which is geodesic then the number of components is at most $3g-3$.


text:
Q: Unable to import module 'handler': No module named 'werkzeug' I suddenly started getting this error on a Django + AWS lambda setup with zappa. I'm using ubuntu 18.04 image on bitbucket pipelines to trigger the deployment.

Unable to import module 'handler': No module named 'werkzeug'

It was working fine for python3.6 on zappa==0.42.2 until the last deployment in 25-July-2019. I thought it was due to some code changes on the app that's causing it (even though the code changes are not related to pip modules - just some updates on the application's codebase) but even reverting to previous deployments are throwing this error now.
My zappa config has a slim_handler: true
{
    "staging": {
        "project_name": "myapp",
        "slim_handler": true,
        "runtime": "python3.6",
        "log_level": "WARNING",
        "timeout_seconds": 300
    }
}

I have tried some suggested solutions in Zappa's GitHub issues but without success.

*

*https://github.com/Miserlou/Zappa/issues/64

*https://github.com/Miserlou/Zappa/issues/1549
I've also tried some SO solutions from questions related to import issues in zappa and haven't been successful. I would highly appreciate any pointers for debugging or workarounds for this zappa issue in AWS lambda with python3.6.

A: For people who are facing similar issue
I fixed it by install zappa in the venv itself.
So, follow the steps (assuming you have venv in env folder locally)
$ source ./env/bin/activate
$ pip install zappa
$ zappa deploy or zappa update


text:
Q: Why windows 10 won't install? I just got an notification that win10 is available and downloaded it. Everything went fine and at last when probably at 48%, (installing drivers and features), it just rebooted and told that restoring your previous version of windows. It restored and a popup told that error code is 80070004-3000D. What to do now? Please help.
Now, it shows that my copy of windows is not genuine..
Huh.. Please help..
Edit: I'm using Asus x200ma. I'm pretty sure that the problem is due to my BIOS. Because I have an option in my BIOS to choose OS (Win7 or win8.1). Should I try using the option. As after selection win8.x, win 7 won't work. Please help. My OS is windows7 ultimate x32. Please help. And also, I can't use media creation tool or ISO image. Please help.

A: I had this issue recently as well as I upgraded to Windows 10 from Windows 7 Ultimate. You will have to do a clean installation of 10 through the BIOS and boot to a removable media (USB or disc). Make sure you have your product key handy. You can go to Microsoft's website and use the updater there to make a removable media OS update. Its about 3 GB.


text:
Q: How do I make my app use less storage? I am making a launcher. Currently it takes up about 20 mb. What can I use to drop it to at most 9 mb?

A: Compress all your images with pngquant. It will reduce the size significantly atleast 30% i think.

A: Did you try to profile your apk?
I recommend you to figure out the problem by profiling apk.
Android Studio (2.2 Preview 1)  has nice APK Analyzer.
http://android-developers.blogspot.jp/2016/05/android-studio-22-preview-new-ui.html
If the problem is classes.dex size, let's try Proguard to reduce the java classes.
https://developer.android.com/studio/build/shrink-code.html


text:
Q: Adding a slave to jenkins I am trying to add a slave in Jenkins. I followed the steps as in https://wiki.jenkins-ci.org/display/JENKINS/Step+by+step+guide+to+set+up+master+and+slave+machines .
I added a new node on the Master. But inorder to connect my slave machine, I am not able to find the added node on the slave.
Any ideas on what might be going wrong?
I checked and I do have connect permissions.

A: The easiest way to add a new Jenkins slave node is

*

*Adds a new node on master (you can do it on the Jenkins web UI)

*Once step 1 is done, it will show that the node is offline.

*Remote desktop to slave machine. Browse the URL that says the node is offline on slave.

*Clicks Lunch on the page, wait until it shows a confirmation dialog to download/execute slave-agent.jnpl file.

*Wait until it shows this popup.

*Clicks File and selects Install as a Windows Service


text:
Q: Cannot get started with Vpython I am a new to python. I am have installed Python27 and Vpython on my windows 64-bit W8.1 laptop.
The python version was Py27 32-bits and Vpython 32-bits. After installation I thought I could directly run an example program from the VIDLE (File -> Open -> bounce). But I realized there is lot more to install to get this working.
So I googled the errors and found that I has to install Numpy and WxPython which I was able to complete successfully. But now I have this error shown below
"The Polygon module is not installed,
   so the text and extrusion objects are unavailable.
The ttfquery and/or FontTools modules are not installed,
   so the text object is unavailable."
I googled for this but was not able to arrive at anything.
Should I install Polygon module, FontTools and ttfquery module?
I was not able to fond a proper link to do any of the above. Kindly help me out. I have a hit a wall.
Thanks!!

A: Hopefully was able to solve the issue.
The problem was with the way how I installed Vpython. I should have accidentally selected "custom installation" instead of "full installation".
Also the version of numpy that comes with default set-up did not support for me. Hence I used the pip to update the version and now everything is up and running.
I am able to get the example programs to work.
Also the 64-bit version is not working still. So its always safe to stick on to 32-bit version even if your machine is 64-bit

A: You're working with an older version of VPython that is no longer supported. See the first page of vpython.org.


text:
Q: PHP POST ARRAY to json_encode I want to use JSON to store the value into Mysql cuz I am making a quiz and there are many answers. But it doesn't go well. Please tell me what's wrong.THX!
<form  method="post" action="resultme.php">

   Q1

      <input name="a[0][]" type="radio"  value="1" />Yes
      <input name="a[0][]" type="radio"  value="2" />maybe
      <input name="a[0][]" type="radio"  value="3" />No

   Q2

        <input name="a[1][]" type="radio"  value="1" />Yes
         <input name="a[1][]" type="radio" value="2" />Maybe
         <input name="a[1][]" type="radio" value="3" />No

 Q3

Language

<input name="a[2][]" type="checkbox"  value="11" />English

<input name="a[2][]" type="checkbox"  value="12" />Chiness

Sport

<input name="a[2][]" type="checkbox" value="21" />swim

<input type="submit" value="click" name="submit" />

How to get the POST thing?
Here is my thought below to get each answer then I can json with {}
But it' no use.
$ans   =array(  "q1"=> $_POST['a[0]'],
        "q2"=> $_POST['a[1]'],
        "q3"=> $_POST['a[2]'],
            )
print_r json_encode( $ans );

A: *

*to debug, just print_r($_POST); after you submit so you will see the structure

*try

$ans = array();
foreach($_POST['a'] as $idx => $answer)
{
$ans['q'.($idx+1)] = $anwser;
}
$ans = json_encode( $ans );


text:
Q: Update customer Password in Magento I am trying to update customer password but its not updating,other customer related information is updating like as username and email. I am getting true in the response after updating the password. below is the code.
env = new SoapSerializationEnvelope(SoapEnvelope.VER11);
env.dotNet = false;
env.xsd = SoapSerializationEnvelope.XSD;
env.enc = SoapSerializationEnvelope.ENC;
SoapObject customerEntity = new SoapObject(NAMESPACE, "customerCustomerEntityToCreate");
customerEntity.addProperty("email",email);
customerEntity.addProperty("customer_id",customerId);
customerEntity.addProperty("firstname",firstName);
customerEntity.addProperty("lastname",lastName);
customerEntity.addProperty("password",password);
request = new SoapObject(NAMESPACE, "customerCustomerUpdate");
request.addProperty("sessionId", sessionId);
request.addProperty("customerId", customerId);
request.addProperty("customerData", customerEntity);

env.setOutputSoapObject(request);
androidHttpTransport = new HttpTransportSE(URL);
androidHttpTransport.debug = true;
(new MarshalHashtable()).register(env);
try {
    androidHttpTransport.call("", env);
} catch (IOException | XmlPullParserException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}
try {
    result = env.getResponse();
    System.out.println(result);
} catch (SoapFault e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

A: I tried this already then I study about this, As according to my knowledge its unable to set password for the customer from API. Because in magento they are using a filter inside the customer create methode like this $data = $validator->filter($data);   . So here the password which we sent is filtered. To avoid this I get the password before filter and set it after the filter as shown below. I am using REST Api I think you have the same problem in your SOAP Api, just change the SOAP Api customer create method/customer update method in magento like this, it may solve your problem.
protected function _create(array $data)
    {
        $password = $data['password'];
        $validator = Mage::getResourceModel('api2/validator_eav', array('resource' => $this));
        $data = $validator->filter($data);
        $data['password'] = $password;
        if (!$validator->isValidData($data))
        {
            foreach ($validator->getErrors() as $error)
            {
                $this->_error($error, Mage_Api2_Model_Server::HTTP_BAD_REQUEST);
            }
            $this->_critical(self::RESOURCE_DATA_PRE_VALIDATION_ERROR);
        }

        $customer = Mage::getModel('customer/customer');
        $customer->setData($data);

        try
        {
            $customer->setPassword($data['password']);      //added
            $customer->setWebsiteId(1)->save();

        }
        catch (Mage_Core_Exception $e)
        {
            $this->_error($e->getMessage(), Mage_Api2_Model_Server::HTTP_INTERNAL_ERROR);
        }
        catch (Exception $e)
        {
            $this->_critical(self::RESOURCE_INTERNAL_ERROR);
        }
    }


text:
Q: Rails3 omniauth google authentication on Returns User Identity My Omniauth integration works on local development but fails for google on staging.
require 'omniauth/openid'
require 'openid/store/memcache'

Rails.application.config.middleware.use OmniAuth::Builder do
  OmniAuth.config.full_host = "http://xx.xx.xxx/"

  # dedicated openid
   provider :open_id, OpenID::Store::Memcache.new(Dalli::Client.new), :name => 'google', :identifier => 'https://www.google.com/accounts/o8/id'

end

I get a this error message:
Started GET "/auth/failure?message=invalid_credentials" for 58.71.19.178 at 2011-12-01 02:22:20 +0000
  Processing by ErrorsController#routing as HTML
  Parameters: {"message"=>"invalid_credentials", "a"=>"auth/failure"}
Rendered public/404.html (0.1ms)
Completed 404 Not Found in 1ms (Views: 0.6ms | ActiveRecord: 0.0ms)
Also the ip in for is not the same in my OmniAuth.config.full_host maybe that could be causing the issue?

A: The culprit was that apache sending and returning on different ips
This monkey patch fixed the issue.
module OmniAuth
  module Strategies
    # OmniAuth strategy for connecting via OpenID. This allows for connection
    # to a wide variety of sites, some of which are listed [on the OpenID website](http://openid.net/get-an-openid/).
    class OpenID
      protected
      def callback_url
        uri = URI.parse(request.url)
        uri.path += '/callback'

        # by KirylP: to overcome hosting subdomain forwarding to rails port
        uri.port = '' if request.env.has_key? 'HTTP_X_FORWARDED_SERVER'

        uri.to_s
      end
    end
  end
end

module Rack
  class OpenID
    SERVER_PORT_TO_AVOID = 12002

    private
    def realm_url(req)
      url = req.scheme + "://"
      url << req.host

      scheme, port = req.scheme, req.port
      if scheme == "https" && port != 443 ||
          scheme == "http" && port != 80
        url << ":#{port}" if port != SERVER_PORT_TO_AVOID # KirylP
      end

      url
    end
  end
end

module OpenID
  class Consumer
    def complete(query, current_url)
      message = Message.from_post_args(query)

      current_url.sub!(":#{Rack::OpenID::SERVER_PORT_TO_AVOID}", '') # KirylP

      mode = message.get_arg(OPENID_NS, 'mode', 'invalid')
      begin
        meth = method('complete_' + mode)
      rescue NameError
        meth = method(:complete_invalid)
      end
      response = meth.call(message, current_url)
      cleanup_last_requested_endpoint
      if [SUCCESS, CANCEL].member?(response.status)
        cleanup_session
      end
      return response
    end
  end
end

A: I had a similar problem. Seems like your google authentication fails (can be for different reasons - invalid credentials, or user denied access), therefore you receive callback to /auth/failure -- and then you get 404.
Did you implement a route for /auth/failure in your routes.rb? In my current project:
in routes.rb
match '/auth/failure', :to => 'sessions#failure'

in sessions_controller
def failure
   redirect_to session[:return_uri] || root_path, alert: "Sorry, we were not able to    authenticate you using your chosen sign on method"
end


text:
Q: Use client-side script to set Business Process Flow Stage on Opportunity in Dynamics CRM I'm working in Dynamics CRM 2015 Online and need to apply some conditional rule to the Opportunity when it is first created from a Lead qualification.  Under certain conditions we need to automatically advance the Business Process Flow stage to the second stage in the flow.  I've already tried this using variations of a plugin on Opportunity Create to set the stage id, but it seems that any value I assign there is ignored when the Opportunity is created from a Lead.  Right now I'm trying to fire a javascript function during the Opportunity Form OnLoad event.  One catch here is I'm also working against a field that is business required but not filled in when the Opportunity is created from a Lead so I can't do a simple Xrm.Page.data.process.moveNext() in the script.  Instead I am updating the Opportunity using the JQuery SDK function updateRecord that is part of the CRM SDK scripts. Here's the important bits of the code:
opp = {
   OpportunityId: oppId,
   StageId: newProcessStageId
}

SDK.JQuery.updateRecord(
   oppId,
   opp,
   "Opportunity",
   function () {
      // success, refresh the form
      Xrm.Page.data.refresh();
   },
   function (error) {
      alert("An error occurred while updating the opportunity: " + error.description);
   }
);

This does work to change the stage, however the problem is on the form the Business Process Flow still shows the first stage as the selected stage, even though it moved the flag indicating the active stage is stage 2, as seen in this screenshot:

After the update, I do a refresh of the form data, but I don't see any way to set the "selected" stage to match the new active stage.  I've scoured the SDK docs and searched around but can't find anything that will do this.  Any help is much appreciated!

A: Unrequire the the required field on load in order to change the stage.  Then try to move to the next stage.

A: What if you do a Xrm.Utility.openEntityForm() call instead of a data.refresh?  (BTW, I've been trying to find a way to set selected stage in JS for a while as well, and haven't found anything either.  I do think if you completely reload the form instead of just the data, though, it should set the selected to the active.)


text:
Q: Javascript Canvas edge detection I would like to achieve this kind of image processing effect in Canvas :
WebGL image processing
What i need is an edge detection algorithm or explanation to draw only black pixels or border element ( such as a face for example ) of the image that an user can submit.
cheers

A: Following your idea, the first step is the Edge detection. The example below shows hot to detect edges using MarvinJ. Having the edges, you might get the object contour.
Input Image:

Edge Detection:

var canvas = document.getElementById("canvas");

image = new MarvinImage();
image.load("https://i.imgur.com/ZHgkM9w.jpg", imageLoaded);

function imageLoaded(){
  var imageOut = new MarvinImage(image.getWidth(), image.getHeight());

  // Edge Detection (Prewitt approach)
  Marvin.prewitt(image, imageOut);
  // Invert color
  Marvin.invertColors(imageOut, imageOut);
  // Threshold
  Marvin.thresholding(imageOut, imageOut, 220);
  imageOut.draw(canvas);
}
<script src="https://www.marvinj.org/releases/marvinj-0.7.js"></script>
<canvas id="canvas" width="500" height="344"></canvas>

A: I used JsFeat as suggested by markE, cheers !
http://inspirit.github.io/jsfeat/


text:
Q: callback causing memory leak Model.GetData(function (args,jsonData) {
    RenderData(jsonData);
});

I am passing a callback to my model class,
var Model = (function () {
    function GetData(args,callback) {
       // do all math works.

       var HTTPClient;

       HTTPClient.onload = function () {
           callback(this.responseText);
       };
    }

})();

Will my callback cause memory leak in my view page.

A: Yes. The onload global variable will store a reference to your function, which is in the same scope as your args and callback.


text:
Q: No visible @interface declares the selector I have a SSLYFoodDetailViewController.h whose contents are
#import <UIKit/UIKit.h>

@interface SSLYFoodDetailViewController : UIViewController

@property(nonatomic, weak) NSString *foodItem;
@property(nonatomic, weak) NSString *restaurantName;

- (void) setFoodItem:(NSString *)foodItem;
- (void) setRestaurantName:(NSString *)restaurantName;

@end

In another file SSLYTableViewController.m inside the prepareForSegue method, I try to do the following -
SSLYFoodDetailViewController *sslyFoodDetailViewController = [segue destinationViewController];
[sslyFoodDetailViewController setFoodItem:@"Pasta"];

XCode is giving me an error that there is No visible @interface for 'SSLYFoodDetailViewController' declares the selector 'setFoodItem'.
At the top of the SSLYTableViewController.m, I have the import statement -
#import "SSLYFoodDetailViewController.h"

What is it that I am missing?

A: That doesn't make any sense, except that setFoodItem: is implied by the foodItem @property declaration.
Try removing the declarations for setFoodItem: and setRestaurantName: in your header - that definitely won't hurt anything because they're redundant.
If that doesn't work, try the property accessor notation:
sslyFoodDetailViewController.foodItem = @"Pasta";

Also of note, you're probably getting a warning on the line:
SSLYFoodDetailViewController *sslyFoodDetailViewController = [segue destinationViewController];

You should add an explicit cast in that line, as follows:
SSLYFoodDetailViewController *sslyFoodDetailViewController = (SSLYFoodDetailViewController *) [segue destinationViewController];


text:
Q: Adding two Model Class In Category Model, getAll method is used for returning all category data. First Active Record in below method $roots have all roots category and $categories have roots category's descendants category. How to add these two Category. Following is getAll Method:
   public function getAll()
    {
      $roots = Category::model()->roots()->findAll();
      foreach($roots as $root)
      {
        $category = Category::model()->findByPk($root->root);
        $categories = $category->descendants()->findAll();
      }
      return $category + $categories;  // this does not concatenate, causes error
    }

A: Two problems here:

*

*You are only going to get the category and descendants of the last root in your table because the foreach loop will overwrite the variables each time.  To prevent this, you will need to make $categoriy and $categories arrays, and assign like $category[] = ... and $categories[] = .... Or maybe better you could merge them into a composite array at the end of the loop.  Maybe something like this:
foreach($roots as $root)
  {
    $category = Category::model()->findByPk($root->root);
    $categories[] = $category;
    $categories = array_merge($categories, $category->descendants()->findAll());
  }
return $categories;

You now have an array of all root and descendent categories stored as root category, then its descendents, then the next root category, then its descendents, etc.

*$category is a Category object as written, and $categories is an array of descendants().  I am hoping that these are Category objects as well.  But you can't concatenate an object with an array, you have to use array_merge(), see my example above.


text:
Q: Pinch Zoom with gallery I'm trying to combine the capability of doing image zoom/panning
inside of a Gallery view. The problem is controlling which touch
events are processed by each. In a horizontal drag on the image, the
ImageView needs to process the drag in order to pan, up until the edge
of the image is reached then the gallery view needs to process the
touch event so that it can swipe over to the next photo.
It seems that if I return false from the imageview's ontouchevent,
then I won't be notified of the panning-drag move events.
What I tried to do was return true from the imageview's ontouchevent
until the edge of the image was hit then return false. However I
believe that this doesn't cause the Gallery to begin processing these
events, as it missed the initial touchdown event.
My next thought is to somehow turn the containing activity into the
touch handler, and somehow stop the Gallery and ImageView from getting
touch events normally, and have the activity forward the touch event's
manually. Not sure if this is possible or if there is an example.
My last resort will be to simply not use the android.widget.Gallery,
which I want to avoid because I want the widget to "feel" the same as
other places on the phone, and I like code re-use. Unfortunately I
might have to do this, as I see all other apps that have this zoom/pan
capability don't seem to use the Gallery widget (Gallery3D etc).
My question is, what's the best way to design for this situation where
motionevents need to split between two views? Any ideas would be
greatly appreciated thank you.

A: please follow the links here.
http://jmsliu.com/138/android-infinite-loop-gallery.html


text:
Q: Limpiar campos marcados por has-error Tengo un formulario donde al querer registrar, manda una alerta marcando el contorno de los campos en rojo ademas de mostrar un mensaje, todo esto creado por la clase has-error.
Este es el codigo que uso para hacer lo anterior dicho.

$("#itemDes").parent().addClass('has-error');
 $("#price").parent().addClass('has-error');
 $("#manufacturer").parent().addClass('has-error');
 $("#model").parent().addClass('has-error');
 $("#min").parent().addClass('has-error');
 $("#max").parent().addClass('has-error');
 $("#engineer").parent().addClass('has-error');
 $("#category").parent().addClass('has-error');
 $("#location").parent().addClass('has-error');
 $("#supplier").parent().addClass('has-error');
 $("#unit").parent().addClass('has-error');
 $("#item").parent().addClass('has-error');
 document.getElementById("errorMessage").style.display = "block";
 document.getElementById("errorMessage").innerHTML = "No puedes dejar campos en blanco, completa la informacion.";
 document.location.href="#errorMessage";

Mi problema es que cuando se marcan en rojo y demas, doy cancelar,vuelvo abrir el formulario, estos siguen en rojo, necesito que esto no suceda mas, y que aparezca como la primera vez que se abrio.


text:
Q: How use pagination and .filter in django How use pagination and filtering together? I have problem because they dont want to work eachother, without filter pagination work but with filter my app have crashes. I know they are some examples how do this on stack overrflow, and it seems thaat problem is in html file but this examples arent fully understandable for me, i would be appreciate if someone would show me what i must change in my code then i would understand this better. I am currently learning Django and still i have problems with understanding someones else code, i understand very well what ive done in my code but when i see someone else code that looks diffrent than mine then i dont know whats going on.
views.py
def Product_list(request, category_slug=None):
 category=None
 categories=Category.objects.all()
 products=Product.objects.all()
 paginator=Paginator(products, 6)
 page=request.GET.get('page')
 products=paginator.get_page(page)

if category_slug:
    category=get_object_or_404(Category, slug=category_slug)
    products=products.filter(category=category)

return render(request, 'shop/product/Product_list.html',
                  {'products':products, 'category':category,
                   'categories':categories,})

product_list.html

 {% if products.has_previous %}
  <<
  <
 {%endif%}
 {%for num in products.paginator.page_range%}
  {% if products.number == num %}
   {{num}}
  {%elif num > products.number|add:'-3' and num < products.number|add:'3' %}
   {{num}}
  {%endif%}
 {%endfor%}
 {% if products.has_next %}
  >>
  >
 {%endif%}

A: You can only filter a QuerySet. But in your view, you're first paginating (so products is now a Page) and then trying filter that Page object. You should only paginate after you've got your final QuerySet with all filters applied.

A:

    {% if ordered_by %}

        <input type="hidden" id="pre-order" value="{{ ordered_by }}" disabled>
    {% endif %}

    {% if is_paginated %}
        <input type="hidden" id="page-no" value="{{ page_obj.number }}" disabled>
    {% endif %}
    <input type="hidden" id="current-url" value="{% url 'InvoiceList' %}" disabled>

        {% if is_paginated %}
            {% if page_obj.has_previous %}

            {% endif %}

            {% for num in page_obj.paginator.page_range %}
                {% if page_obj.number == num %}
                    {{ num }}
                {% elif num > page_obj.number|add:'-3' and num < page_obj.number|add:'3' %}
                    {{ num }}
                {% endif %}
                {% if num > page_obj.number|add:'-1' and num < page_obj.number|add:'1' %}
                     of {{ paginator.num_pages }}
                {% endif %}
            {% endfor %}

            {% if page_obj.has_next %}

            {% endif %}
        {% endif %}

See this html template
here i get a context data on the top inside a container class hidden from get_context_data method to change the "href" of the sorter button.
var pagehref = null;
const pre_order = $("#pre-order").val();
const url = $("#current-url").val();

if($("#page-no")) {
    const page_no = $("#page-no").val();
    pagehref = `page=${page_no}&`;
}

$('#sort-name').ready(function() {
    var $this, addClass, href;

    if(pre_order == "customer_id") {
        href = `${url}?${pagehref}ordering=-customer_id`;
        addClass = "fa-solid fa-sort-up";
        $this = $(this);
    } else if(pre_order == "-customer_id") {
        href = `${url}?${pagehref}`;
        addClass = "fa-solid fa-sort-down";
        $this = $(this);
    } else {
        href = `${url}?${pagehref}ordering=customer_id`;
        addClass = "fa-solid fa-sort";
        $this = $(this);
    }
    $('#sort-name').find('.fa-solid').removeClass().addClass(addClass);
    $('#sort-name').attr('href', href);
});

$('#sort-date').ready(function() {
    var $this, addClass, href;

    if(pre_order == "created_date") {
        href = `${url}?${pagehref}ordering=-created_date`;
        addClass = "fa-solid fa-sort-up";
        $this = $(this);
    } else if(pre_order == "-created_date") {
        href = `${url}?${pagehref}`;
        addClass = "fa-solid fa-sort-down";
        $this = $(this);
    } else {
        href = `${url}?${pagehref}ordering=created_date`;
        addClass = "fa-solid fa-sort";
        $this = $(this);
    }
    $('#sort-date').find('.fa-solid').removeClass().addClass(addClass);
    $('#sort-date').attr('href', href);
});

This my jQuery code to change the href link when ever the page load it get the paginator data and ordered by data and combine it with & to pass multiple parametes in url.
def get_context_data(self, **kwargs):
    context = super(InvoiceListView, self).get_context_data(**kwargs)
    context['total_invoices'] = self.model.objects.all().count()
    context['ordered_by'] = self.get_ordering()
    return context

def get_ordering(self):
    order = self.request.GET.get('ordering', None)
    return order

This is my ListView mehtods


text:
Q: Avoid repetitive coding when disposing of objects With a purpose of memory optimization we've been adding these lines of code:
public class Whatever: IDisposable

private bool disposed = false;

protected virtual void Dispose(bool disposing)
{
    if (!this.disposed)
    {
        if (disposing)
        {
            context.Dispose();
        }
    }
    this.disposed = true;
}

public void Dispose()
{
     Dispose(true);
     GC.SuppressFinalize(this);
}

To every single of our repositories, then are updating tests for each repo as well.
I am wondering, since copy+paste isn't really encouraged in coding isn't there a better way to implement this? Especially annoying since, depending on a project, we have 10-40 repositories...

A: Perhaps simpler - use the context itself to track disposal:
protected virtual void Dispose(bool disposing)
{
    if (disposing) context?.Dispose();
    context = null;
}

public void Dispose()
{
     Dispose(true);
     GC.SuppressFinalize(this);
}

Note that I also think it is vanishingly unlikely that you have a finalizer involved here (and if you do, that is probably a big mistake), so honestly: you can simplify further:
public void Dispose()
{
    context?.Dispose();
    context = null;
}

A: To expand on the base-class approach that Franz hints at; something like:
// common base class that handles the shared details
public abstract class MyCommonBase : IDisposable
{
    protected SomeContext Context { get; private set; }

    public MyCommonBase(SomeContext context)
        => Context = context ?? throw new ArgumentNullException(nameof(context));

    public virtual void Dispose()
    {
        // your choice of dispose code here, via Context
    }
}

// specific implementation class
public class MySomething : MyCommonBase
{
    public MySomething(SomeContext context) : base(context) {}

    // your *extra* code here; can read Context from base
}

Note that in MySomething you don't need to deal with any of the disposal bits - that's all handled by the base class (although you can still override the Dispose() method to add additional cleanup features).


text:
Q: Questions on a formula for the Mertens function The Mertens function $M(x)$ is defined as follows.
(1) $\quad M(x)=\sum\limits_{n=1}^x\mu(n)$
I've noticed the Merten's function can also be evaluated as follows which is related to OEIS entry A087003 and the Collatz conjecture.
(2) $\quad M(x)=\sum\limits_{n=\left\lfloor\frac{x-2}{4}\right\rfloor+1}^{\left\lfloor\frac{x-1}{2}\right\rfloor}\mu(2\,n+1)$
I've verified formula (2) above for the first $10,000$ positive integer values of $x$.
Question (1): Has formula (2) above been proven (or disproven) and if not, can it be?
I've read the following conjecture on the growth of $M(x)$ for any $\epsilon<1/2$ is equivalent to the Riemann hypothesis (see Weisstein, Eric W. "Mertens Conjecture." From MathWorld--A Wolfram Web Resource).
(3) $\quad M(x)=O\left(x^{1/2+\epsilon}\right)$
Question (2): Assuming formula (2) above is correct, does it show any promise with respect to improving upon the fastest known algorithm for computing $M(x)$ and/or the tightest known error bound on the growth of $M(x)$?

A: There is nothing special happening here. Let $$F(s) = \sum_{n=0}^\infty \mu(2n+1)(2n+1)^{-s}, \qquad \frac{1}{\zeta(s)} = (1-2^{-s}) F(s)$$
$$f(x) = \sum_{2n+1 \le x} \mu(2n+1), \qquad M(x) = f(x)-f(x/2)$$


text:
Q: Convert the class of one dataframe based on another dataframe classes I have two data frames , which I am trying to compare using <assert_frame_equal> . The comparison is failing over few columns which have timestamp values.The value seems to be same :
     DF1     TIME    1970-01-01 02:00:00
             Name: 4, dtype: object
             ----
     DF2     TIME    1970-01-01 02:00:00
             Name: 4, dtype: object

I checked the class of this column :
    DF1  :    <class 'pandas._libs.tslibs.timestamps.Timestamp'>
        ---
    DF2:      <class 'str'>

Error Message from using assert_frame_equal:
DataFrame Expected type <class 'pandas.core.frame.DataFrame'>, found <class                         'pandas._libs.tslibs.timestamps.Timestamp'> instead
Can somebody please help , how can I make the classes of two dataframes same. My end goal is just to verify data , (no data types/classes etc). I can't give column name specifically as I have to use this function for multiple data frames , where column names for Date values vary.

A: you could avoid dataframe class comparison by turning this flag off : check_frame_type
for more info check this out:
https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.testing.assert_frame_equal.html


text:
Q: Getter in a Behavior cakephp 3 I've just created a tag behavior to manage tags in an input text field (all keywords are separate by a comma). To do that I name my input "tag_string".
So I need to use a getter to handle the string.
I didn't understand how implement a _getTagString() method directly in the behavior.
If I use my getter (getTagString) in each entities file that use my behavior all my code works fine.
So to avoid write the same getter in each file I want to put it in my behavior file. But it doesn't work.
Here is my method:
public function _getTagString() {
    if (isset($this->_properties['tag_string'])) {
        return $this->_properties['tag_string'];
    }
    if (empty($entity->tags)) {
        return '';
    }
    $tags = new Collection($entity->tags);
    $str = $tags->reduce(function ($string, $tag) {
        return $string . $tag->name . ', ';
    }, '');
    return trim($str, ', ');
}

Thanks for your help

A: After several searches I didn't find anything to implement accessors directly in the behavior.
I use trait, and It works fine.


text:
Q: Export to Excel as a response in web API I am using Web API 4.5.1. I am generating API in C# code and passing this API to front end, where the front end is built on HTML and AngularJS JavaScript. My requirement is to create an API for export to Excel to the front end. I am a kind of stuck here. I am receiving request from front end people with fromdate and todate. Based on that I will query the database to get the data and if I am successful, get the HTML format out of it. I am unable to go further as I am new to this. Below is the code which I am trying to achieve this with:
[HttpPost]
public HttpResponseMessage ExportToExcel(string fromTimeStamp, string toTimeStamp)
{
    DateTime fromDate = new DateTime(1970, 1, 1, 0, 0, 0, 0, System.DateTimeKind.Utc);
    fromDate = fromDate.AddMilliseconds(Convert.ToDouble(fromTimeStamp)).ToLocalTime();
    fromDate.AddDays(1);

    DateTime toDate = new DateTime(1970, 1, 1, 0, 0, 0, 0, System.DateTimeKind.Utc);
    toDate = toDate.AddMilliseconds(Convert.ToDouble(toTimeStamp)).ToLocalTime();
    toDate.AddDays(1);

    var fromDate1 = fromDate.AddDays(1).ToString("yyyy-MM-dd");
    var toDate1 = toDate.AddDays(1).ToString("yyyy-MM-dd");

    var bal = new AdminBAL();
    var ExportData = bal.ExportToExcel(fromDate1, toDate1);
    //where Exportdata is the html format for the data required.
    // unable to find the solution here
}

How can I complete this operation?

A: Can you try this?
 var response = new HttpResponseMessage(System.Net.HttpStatusCode.OK);
        //If you have Physical file Read the fileStream and use it.
        response.Content = new StreamContent(fileStream);
        //OR
        //Create a file on the fly and get file data as a byte array and send back to client
        response.Content = new ByteArrayContent(fileBytes);//Use your byte array
        response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment");
        response.Content.Headers.ContentDisposition.FileName = fileName;//your file Name- text.xls
        response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/ms-excel");
        //response.Content.Headers.ContentType  = new MediaTypeHeaderValue("application/octet-stream");
        response.Content.Headers.ContentLength = fileStream.Length;
        response.StatusCode = System.Net.HttpStatusCode.OK;

I got this works fine.Please let me know if you have any doubts on this.


text:
Q: Fullcalendar save record in mysql I'm trying to create a drag & drop calendar(Fullcalendar) and saving  the new or edited items in a MySQL database.
But I'm having 2 problems at the moment.
First:
I can't drag & drop more then 1 item in the month view:
http://snag.gy/SF9wI.jpg
But if I drag a new one in the Week view ,It works : http://snag.gy/0tW2m.jpg
and if I go back to the Month view the ones I just created in the Week view are still there.
Second:
I'm new in ajax,jquery and I don't really know how to use $_post, so I can save my records in my MySQL database. I tried a few guides but no success.
MySQL database:
name: tblEvent
idEvent INT auto_increment PRIMARY KEY
fiTask INT
fiUser INT
dtStart DATETIME
dtEnd DATETIME
dtUrl VARCHAR(255)
dtAllDay TINYINT(1)

index.php:
<?php
include_once './Includes/functions.php';
?>
<!DOCTYPE html>

        <meta charset='utf-8' />
        <link href='../fullcalendar.css' rel='stylesheet' />
        <link href='../fullcalendar.print.css' rel='stylesheet' media='print' />

Aufgaben

                <?php
                foreach (SelectTask() as $x) {
                    echo "
" . $x['dtTask'] . "
";
                }
                ?>

event.php:
    <?php

// List of events
$json = array();

// Query that retrieves events
$requete = "SELECT * FROM tblEvent";

// connection to the database
try {
    $dbc = new PDO('mysql:host=10.140.2.19;dbname=dbcontrol', 'ymartins', 'a15370430x');
} catch (Exception $e) {
    exit('Unable to connect to database.');
}
// Execute the query
$resultat = $dbc->query($requete) or die(print_r($dbc->errorInfo()));

// sending the encoded result to success page
echo json_encode($resultat->fetchAll(PDO::FETCH_ASSOC));
?>

add_event.php:
    <?php

// Values received via ajax
$title = $_POST['title'];
$user = $_POST['user'];
$start = $_POST['start'];
$end = $_POST['end'];
$url = $_POST['url'];
// connection to the database
try {
    $dbc = new PDO('mysql:host=10.140.2.19;dbname=dbcontrol', '****', ****);
} catch (Exception $e) {
    exit('Unable to connect to database.');
}

// insert the records
$sql = "INSERT INTO tblEvent (dtTitle, dtStart, dtEnd, dtUrl) VALUES (:title, :start, :end, :url)";
$q = $dbc->prepare($sql);
$q->execute(array(':title' => $title, ':start' => $start, ':end' => $end, ':url' => $url));
?>

What am I doing wrong and how can I improve my script?

A: You may want to expand your question to include exactly what is going wrong/not working?
I see one issue at least:
your AJAX call should look like this:
$.ajax({
    url: '/add_event.php',
    data: {'title': title, 'start': start ...}
    type: "POST",
    success: function (json) {
        alert('Added Successfully');
    }
});

complete the 'data:' line... its a dict, not a GET Url encoded string when using POST.
you may also want to add a failure section to catch errors, or at least print out the value of the 'json' in case your php page throws an error (it will be in that variable of the success callback).


text:
Q: converting a graph to a bipartite graph I am reading the application of BFS algorithm. One of the application which i read is to check weather a give graph is bipartite graph or not.Now I want to know, is there any algorithm to convert a graph into bipartite set/graph.
For example we have give a set of edges as

E={ (4, 1),( 1 ,2), (2 ,3),( 7, 2),( 1 ,5),( 8 ,4), (5 ,8),( 8, 9)}

and set of vertices

V= { 1,2,3,4,5,6,7,8}

we have to create bipartite set/graph.
Expected output as :-

s1={1 ,4, 8, 1 ,7 ,3}
   s2={2, 5, 6, 9}

A: The general BFS algorithm to check if a graph is bipartite is:

*

*Start from a vertex v_0, and label it s1.

*Mark all v_0's neighbours as s2, and queue them.

*Mark all the neighbour's neigbours as s1, and queue them

If, at any point, you get to mark as s2 a vertex already marked as s1 or vice versa, the graph is not bipartite. If, instead, you end up with an empty queue, you are done, and you have your partition.
EDIT
If what you want to know, instead,  is how you can build a bipartite graph from a general one, you should first add a metric to compare two different solutions : otherwise, removing all the edges and assigning randomly the vertices to two groups, will always generate a ( trivial ) bipartite graph from any given one.

A: The edge bipartization problem, that is, deleting the minimum number of edges to make a graph bipartite, is NP-hard. Here are slides of a talk about how to solve it as efficiently as possible.


text:
Q: Changing the DOCUMENT_ROOT or a better approach Is there a better way to take set the path for my local environment. Here is what i am trying to do
<?php
if ($_SERVER['SERVER_NAME'] == 'localhost') {
    define("URL", "/mysite");
}else{
    define("URL", "");
}
?>

the only problem with this approach is I need to litter my code with stuff like this
<link rel="stylesheet" href="<?php echo URL; ?>/css/main-style.css" type="text/css" media="all" />
<link rel="stylesheet" href="<?php echo URL; ?>/css/home.css" type="text/css" />
<script src="<?php echo URL; ?>/js/jquery.js?v=1.5.2" type="text/javascript"></script>
<?php include($_SERVER['DOCUMENT_ROOT'] . URL . '/inc/header-inc.php'); ?>

And i have to find every absolute path in my site and add the URL in front which is cluttering the code with this. I am on MAc osx and my DOCUMENT_ROOT is /Users/alex/Sites
I can change it to /Users/alex/Sites/mysite but what happens when I need mysite2

A: Try this approach


text:
Q: referencing the latest state in useInterval that uses useRef As Dan Abramov introduced, I wrote an interval using useRef so it does not get created on every render. My code below saves the redux store into local storage every 20 seconds. However, the store inside of setInterval does not get updated which leads to saving the same initial store every 20 seconds.
import { useRef, useState } from "react";
import { useSelector } from "react-redux";

import styles from "./AutoSaveButton.module.scss";
import LOCAL_STORAGE_KEY from "../../../constants/localStorage";

const TWO_SECONDS = 2000;
const TWENTY_SECONDS = 20000;

function AutoSaveButton() {
  const store = useSelector((state) => state);

  const interval = useRef(null);

  const [isAutoSaveOn, setIsAutoSaveOn] = useState(false);
  const [isSavedMsgDisplayed, setIsSavedMsgDisplayed] = useState(false);

  const toggleAutoSave = () => {
    if (isAutoSaveOn) {
      setIsAutoSaveOn(false);
      clearInterval(interval.current);
      return;
    }

    setIsAutoSaveOn(true);

    interval.current = setInterval(() => {
      localStorage.setItem(LOCAL_STORAGE_KEY, JSON.stringify(store)); <-- how to update?
      setIsSavedMsgDisplayed(true);
      setTimeout(() => {
        setIsSavedMsgDisplayed(false);
      }, TWO_SECONDS);
    }, TWENTY_SECONDS);
  };

  return (

      {isAutoSaveOn ? "auto save off" : "auto save on"}
      {isAutoSaveOn && (

          done

      )}

  );
}

export default AutoSaveButton;

A: since closure will always capture the variable store each time it's reinitialized. use [YOUR STORE].getState().[your reducer] instead

const { useRef, useState } = React
const { useSelector,Provider,useDispatch } = ReactRedux
const { configureStore,createSlice } = window.RTK

//import styles from "./AutoSaveButton.module.scss";
const LOCAL_STORAGE_KEY = "XXX"

const slice = createSlice({
  name: 'data',
  initialState: {
    value: 0,
  },
  reducers: {
    setData: (state, action) => {
      state.value += action.payload
    },
  },
})
const mystore=configureStore({
  reducer: {
    data: slice.reducer
    },
})

const TWO_SECONDS = 2000;
const TWENTY_SECONDS = 20000;

function AutoSaveButton() {
  const store = useSelector((state) => state.data);

  const interval = useRef(null);

  const [isAutoSaveOn, setIsAutoSaveOn] = useState(false);
  const [isSavedMsgDisplayed, setIsSavedMsgDisplayed] = useState(false);

  const toggleAutoSave = (store) => {
    if (isAutoSaveOn) {
      setIsAutoSaveOn(false);
      clearInterval(interval.current);
      return;
    }

    setIsAutoSaveOn(true);
    console.log("store outside", store);

    interval.current = setInterval(() => {

      setIsSavedMsgDisplayed(true);
      console.log("store inside", mystore.getState().data);
      setTimeout(() => {
        setIsSavedMsgDisplayed(false);
      }, TWO_SECONDS);
       //localStorage.setItem(LOCAL_STORAGE_KEY, JSON.stringify(mystore.getState().data)); //<-- how to update?
    }, 1000);
  };

  return (
    toggleAutoSave(store)}
    >
      {isAutoSaveOn ? "auto save off" : "auto save on"}
      {isAutoSaveOn && (
        <span
          className={`material-symbols-outlined `}
        >
          done

      )}

  );
}
const App=()=>{

return <Provider store={mystore}>
    <AutoSaveButton />

  </Provider>
}
const B=()=>{
const dispatch=useDispatch()
return <button onClick={()=>dispatch(slice.actions.setData(12))}>
    setData
    </button>
    }
ReactDOM.render(<App/>,document.getElementById("App"))

second way watchc store with useEffect and put it to ref

const { useRef, useState, useEffect} = React
const { useSelector,Provider,useDispatch } = ReactRedux
const { configureStore,createSlice } = window.RTK

//import styles from "./AutoSaveButton.module.scss";
const LOCAL_STORAGE_KEY = "XXX"

const slice = createSlice({
  name: 'data',
  initialState: {
    value: 0,
  },
  reducers: {
    setData: (state, action) => {
      state.value += action.payload
    },
  },
})
const mystore=configureStore({
  reducer: {
    data: slice.reducer
    },
})

const TWO_SECONDS = 2000;
const TWENTY_SECONDS = 20000;

function AutoSaveButton() {
  const store = useSelector((state) => state.data);

  const interval = useRef(null);
  const mystore = useRef(store);
  useEffect(()=>{
    mystore.current=store
  },[store])

  const [isAutoSaveOn, setIsAutoSaveOn] = useState(false);
  const [isSavedMsgDisplayed, setIsSavedMsgDisplayed] = useState(false);

  const toggleAutoSave = () => {
    if (isAutoSaveOn) {
      setIsAutoSaveOn(false);
      clearInterval(interval.current);
      return;
    }

    setIsAutoSaveOn(true);
    console.log("store outside", store);

    interval.current = setInterval(() => {

      setIsSavedMsgDisplayed(true);
      console.log("store inside", mystore.current);
      setTimeout(() => {
        setIsSavedMsgDisplayed(false);
      }, TWO_SECONDS);
       //localStorage.setItem(LOCAL_STORAGE_KEY, JSON.stringify(mystore.current); //<-- how to update?
    }, 1000);
  };

  return (

      {isAutoSaveOn ? "auto save off" : "auto save on"}
      {isAutoSaveOn && (
        <span
          className={`material-symbols-outlined `}
        >
          done

      )}

  );
}
const App=()=>{

return <Provider store={mystore}>
    <AutoSaveButton />

  </Provider>
}
const B=()=>{
const dispatch=useDispatch()
return <button onClick={()=>dispatch(slice.actions.setData(12))}>
    setData
    </button>
    }
ReactDOM.render(<App/>,document.getElementById("App"))

A: I think I found an answer myself, but if any of you find this dumb, please leave a comment. I am open to discussions!
import { useEffect, useRef, useState } from "react";
import { useSelector } from "react-redux";

import styles from "./AutoSaveButton.module.scss";
import LOCAL_STORAGE_KEY from "../../../constants/localStorage";

const TWO_SECONDS = 2000;
const TWENTY_SECONDS = 5000;

function AutoSaveButton() {
  const store = useSelector((state) => state);

  const interval = useRef(null);

  const [isAutoSaveOn, setIsAutoSaveOn] = useState(false);
  const [isSavedMsgDisplayed, setIsSavedMsgDisplayed] = useState(false);

  const toggleAutoSave = () => {
    if (isAutoSaveOn) {
      setIsAutoSaveOn(false);
      clearInterval(interval.current);
      return;
    }

    setIsAutoSaveOn(true);

    interval.current = setInterval(() => {
      localStorage.setItem(LOCAL_STORAGE_KEY, JSON.stringify(store));
      setIsSavedMsgDisplayed(true);
      setTimeout(() => {
        setIsSavedMsgDisplayed(false);
      }, TWO_SECONDS);
    }, TWENTY_SECONDS);
  };

  /* I added below useEffect and got desired result! */
  useEffect(() => {
    if (!interval.current) return;

    clearInterval(interval.current);

    interval.current = setInterval(() => {
      localStorage.setItem(LOCAL_STORAGE_KEY, JSON.stringify(store));
      setIsSavedMsgDisplayed(true);
      setTimeout(() => {
        setIsSavedMsgDisplayed(false);
      }, TWO_SECONDS);
    }, TWENTY_SECONDS);
  }, [store]);

  return (

      {isAutoSaveOn ? "auto save off" : "auto save on"}
      {isAutoSaveOn && (

          done

      )}

  );
}

export default AutoSaveButton;


text:
Q: Problems converting Docker run to Kubernetes I am having some trouble converting my docker setup to kubernetes. I have read the kubectl for docker users, have set up minikube and am trying to autoscale my docker application with kubernetes.
But I am having some trouble just running it.
I am trying to make a container with a python flask application on centos image that uses a database that I have setup in the cloud
In docker I would just use the docker build . -tag and then use docker run to setup my container. like so:

This would give me a container on port 5000 (For the Database I have to use the hostnetwork als it needs an ip to work with. setting localhost 127.0.0.1:5000 doesnt seem to work, but that is another issue in itself)
When I read the Kubectl documentation for docker users it would seem like i can do almost the same I do with docker in Kubernetes. So I am trying this.
I haven't figured out how to use --network host in kubernetes but I thought just running it and see if it gave an error. And it did. It seems not to be able to pull the image. but docker can. What is going wrong here?

after a while it just goes to.

I haven't even tried horizontal autoscaling yet, nor do I understand the docker-file convert yet. But i should be able to just run the container right?
EDIT:
I used windows to generate the screenshots.
Commands I am running:
docker run --network host -d hu-simple:latest
output I am getting:
a docker deamon string because it created a docker container for me
Commands in Kubernetes I am trying:
kubectl run --image=hu-simpel:latest hu-simpel --port=5000
output i am getting:
deployment.apps/hu-simpel created
But when I try kubectl get all:
I get: ErrImagepull and ImagePullBackOff after a while.
I don't think I am using a kubernetes deployment yaml as I am just trying to run a docker image on kubernetes. I didnt create it in kubernetes using a docker-compose but just tried to run the docker image. But do tell me if I am mistaken.

A: This happens because your minikube instance is not able to reach your Docker daemon. In other words, your Kubernetes doesn't know anything about the images you built using your host Docker.
To solve this, you have this command: minikube docker-env. This will export everything from Docker to your minikube instance, meaning that you'll be able to reuse the images you build in your host.
When you finish you can do docker-machine env -u.


text:
Q: Assign certain number of values to cells I created a data frame with 20 observations, an extra column with all NAs. I'm wondering if there's a way to randomly assign for example 15 "YES" and 10 "NO" or randomly assign for example 15 "1" and 10 "0" for column "A". I would appreciate all the help there is. Thanks in advance!
dt <- data.frame(ID <- 1:20)
dt <- dt %>%
  add_column(A = NA)%>%
  rename(ID = ID....1.20)

A: The function you're looking for is sample, which will select at random elements of a vector (with its default replace=FALSE argument). I'd suggest you use tibble which has many advantages over a data.frame.
#If you want the reproducible results, use set.seed
set.seed(1)

#create a vector with the desired answers
yesnovector<-c(rep("Yes",15), rep("No", 10))

#create tibble and add randomly selected elements from the yes/no vector
tibble(ID=1:length(yesnovector))%>%
add_column(A=sample(yesnovector))


text:
Q: Using avconv to get a single frame from h264 video at set time I want to use avconv to get a single image at a specified time out of a video file.
I've read just enough about libav to think I know what I'm doing, but not enough to actually know.
I've tried:
avconv -ss 00:00:01.786 -r 25 -i input_video.h264 -frames 1 output_image.jpg

as well as using t to avoid the 'frames' parameter:
avconv -ss 00:00:01.786 -r 25 -i input_video.h264 -t 0.01 output_image.jpg

and passing in seconds rather than using the hh:mm:ss.xxx format:
avconv -ss 1.786 -r 25 -i input_video.h264 -t 0.01 output_image.jpg

What I see is when ss is set to 0 (that's '0', '00:00:00.000', '0.0', etc.) the output_image is just the first frame of the video. As expected.
Any other value for ss - even 0.0001 - gives me the last frame of the video.
I'm using the latest avconv from the Raspbian wheezy repo. This behaviour feels like a bug to me, but I don't know the other intricacies of video streaming well enough to be sure.
Does anyone have any idea what I'm doing wrong?

Bonus question: I'd actually like to get a whole bunch of these images out of the same video. Stringing commands together seemed to work before, ie:
avconv -ss 1.786 -r 25 -i input_video.h264 -t 0.01 output_image1.jpg
-ss 3.454 -r 25 -i input_video.h264 -t 0.01 output_image2.jpg
-ss 5.823 -r 25 -i input_video.h264 -t 0.01 output_image3.jpg
-ss etc,etc.

but I switched back to single images to debug this problem. Assuming the first issue gets solved, is that the best way to structure this command or is there a better one?

A:
Edit: As Mulvya noted, ffmpeg will always seek accurately with -ss. This issue is exclusive to avconv.

If you specify the -ss option before the -i option then avconv will inaccurately calculate the frame position.
You need to specify the -i option first so that avconv knows it needs to "seek" through the stream until it accurately finds the correct timestamp.
Also, your example time 1.786 is not aligned to the frames per second -r 25 that you specify in your example.
Since 1/25=0.04 any value for -ss should be divisible by 0.04 in order to specify an individual frame precisely.
The following should get the 46th frame of your video:
avconv -i input_video.h264 -r 25 -ss 1.8 -frames:v 1 output_image.jpg
If you want to get a specific frame by it's index then you will need to employ bc:
avconv -i input_video.h264 -r 25 -ss 0$(echo "scale=2;1000/25" | bc -l) -frames:v 1 output_image.jpg
Where 1000 is the 1001st frame of the video (since 0/25 is the 1st frame).
Note that unlike @hamboy75's example we pass -l (lower case L) to bc so that it performs a floating point calculation (and doesn't round to the nearest integer). scale=2 is used to produce a number accurate to 2dp.
Also note that bc has the "feature" of outputting  numbers less than 1 without the leading zero (i.e. .04) which avconv does not understand. Therefore we also need to insert a leading zero prefixed to the calculation 0$()
When using this command you will get output that looks like the following
frame=    0 fps=  0 q=0.0 size=       0kB time=10000000000.00 bitrate=   0.0kbit
frame=    0 fps=  0 q=0.0 size=       0kB time=10000000000.00 bitrate=   0.0kbit
frame=    0 fps=  0 q=0.0 size=       0kB time=10000000000.00 bitrate=   0.0kbit
frame=    0 fps=  0 q=0.0 size=       0kB time=10000000000.00 bitrate=   0.0kbit
frame=    0 fps=  0 q=0.0 size=       0kB time=10000000000.00 bitrate=   0.0kbit

This is because avconv is seeking through the file to find the specific frame you requested accurately. So frames with a larger index will take longer to extract because avconv will always "seek" through the stream from the stream's beginning.
It may therefore be more desirable to extract a range of frames:
avconv -i input_video.h264 -r 25 -ss 0$(echo "scale=2;7500/25" | bc -l) -t 0$(echo "scale=2;250/25" | bc -l) output_image_%04d.jpg
This example extracts 10 seconds worth of frames from 5 minutes within the video. Of course you could also just use:
avconv -i input_video.h264 -r 25 -ss 300.0 -t 10.0 | bc -l) output_image_%04d.jpg
However, remember that for any duration less than a second the value should be divisible by the frame rate for the video (i.e. 0.04 for 25 fps).
The images for each frame will be named output_image_0001.jpg, output_image_0002.jpg, output_image_0003.jpg, etc. If you are looking to perform image comparison on the extracted frames you may want to consider using png over jpg for greater fidelity.
Note that if you specify a frame index larger than the number of frames present in the video, avconv will simply extract the last frame it finds. You may want to calculate the number of frames in a video by looking at the Duration: part of the output of avconv -i input_video.h264.

A: in my case i wanted an image each 60 seconds the first 3 minutes...
for i in {0..3} ; do avconv -ss echo $i*60.0 | bc -i input_video.h264 -frames:v 1 -y out$i.jpg ; done
If you need it a certain times you can change this a bit :9.


text:
Q: Why are there extra spaces in the file after copying text from one file to another in C? char c, cp;

FILE *input_file, *output_file;

input_file = fopen("d:\\input.txt","r");
output_file = fopen("d:\\output.txt", "w");

if(input_file==NULL){
    printf("cannot open the input.txt file.");
    exit(0);
}

if(output_file == NULL){
    printf("cannot open the output.txt file.");
    exit(0);
}

cp = fgetc(input_file);
while(cp!=EOF){
    fputc(cp,output_file);
    cp=fgetc(input_file);
}

c = fgetc(output_file);
while(c!=EOF){
    printf("%c",c);
    c=fgetc(output_file);
}

fclose(input_file);
fclose(output_file);
getch();

This is the code that I used while copying a text file.
In the input.txt file I have written "Hello how are you".
After executing the code, the text "Hello how are you" is copied to the output.txt file
but there are more than a hundred spaces after the copied text.
After the code below the program is not working:
cp = fgetc(input_file);
while(cp!=EOF){
    fputc(cp,output_file);
    cp=fgetc(input_file);
}

Code below the above code is not working.
What is happening? Please explain in detail. I am a beginner in C.

A: You must define c and cp as int not as char. EOF is defined as an integer value which is distinguishable from any char which may e.g. be read by fgetc(), which returns a value in the unsigned char range or EOF, not necessarily a value in the char range. (credits to @chux).
So while( cp != EOF ) might not become true if cp is a char.
And for the second issue: if you want to read what you have written you must

*

*open output.tx with mode "w+". "w" only permits writing, "w+" allows reading too but like "w" creates the file if it doesn't exist and truncates it if it does. See the man page for further options and details.

*call rewind(output_file) or fseek(output_file, 0, SEEK_SET) between reading and writing.

A: you must close your output file to commit changes and be able to read a second time:
cp = fgetc(input_file);
while(cp!=EOF){
    fputc(cp,output_file);
    cp=fgetc(input_file);
}

fclose(output_file);
// .....
c = fgetc(output_file);


text:
Q: $(document).ready() executes before it is ready? consider a simplified version of what I'm running:

There is obviously much more to this, but this is the basic jist.  Within content.js, I have several functions that load markup into my div based on json data included in the data.js.  In addition to these functions is the following line:
$(document).ready(function()
{
    loadContent();
});

for all intents and purposes, load content is loading just fine, but within that code is a call to perform a jquery .show() of the first div among several divs that get loaded in after they all get appended to the container element.  That code doesn't executing, almost as if the divs don't yet exist.  So I tried late loading:

sure enough, both result in the first panel being displayed.  Why would late loading the file that has the $(document).ready() function in it make a difference if .ready() is supposed to wait until the DOM is loaded anyway?

A: You are appending extra DOM elements with Javascript after the DOM is ready. $(document).ready() fires after the initial DOM is loaded. That means what is sent in the initial request. It doesn't know about your dynamic appends in an external Javascript.
Furthermore, scripts included in the  section get loaded synchronously before the  section gets loaded.

A: Try to wait for the entire document is ready, more or less like this:
$(window).load(function() {
  //code
});


text:
Q: Name or service not known [tcp://redis-slave:6379] Running the Guestbook Kubernetes app with the Kube-Sky add-on. On the guestbook app page I get this error in the JavaScript console:
Fatal error:  Uncaught exception 'Predis\Connection\ConnectionException' with message 'php_network_getaddresses: getaddrinfo failed: Name or service not known [tcp://redis-slave:6379]' in /vendor/predis/predis/lib/Predis/Connection/AbstractConnection.php:141

The following are the all the changes (vs. the provided templates) relating to DNS I can find in my setup:
diff -r sample-configs/unmodified/cloud-init/node.yaml sample-configs/defaults/cloud-init/node.yaml
88a91,92
>         --cluster_dns=10.100.88.88 \
>         --cluster_domain=cluster.local \

diff -r sample-configs/unmodified/skydns-controller.yaml sample-configs/defaults/skydns-controller.yaml
11c11
<   replicas: {{ pillar['dns_replicas'] }}
---
>   replicas: 3
50c50,51
<         - -domain={{ pillar['dns_domain'] }}
---
>         - -domain=cluster.local
>         - -kube_master_url=http://$(KUBERNETES_MASTER_IPV4):8080
62c63
<         - -domain={{ pillar['dns_domain'] }}.
---
>         - -domain=cluster.local.
91c92
<         - -cmd=nslookup kubernetes.default.svc.{{ pillar['dns_domain'] }} 127.0.0.1 >/dev/null
---
>         - -cmd=nslookup kubernetes.default.svc.cluster.local 127.0.0.1 >/dev/null
diff -r sample-configs/unmodified/skydns-service.yaml sample-configs/defaults/skydns-service.yaml
13c13,14
<   clusterIP:  {{ pillar['dns_server'] }}
---
>   clusterIP:  10.100.88.88
>   type: NodePort
17a19
>     nodePort:
20a23
>     nodePort:
\ No newline at end of file

./sample-configs/unmodified/cloud-init/master.yaml:        --service-cluster-ip-range=10.100.0.0/16 \

NAMESPACE     NAME                 READY     STATUS    RESTARTS   AGE       NODE
default       frontend-jw0ud       1/1       Running   0          48m       $publicip.23
default       frontend-mwu18       1/1       Running   0          48m       $publicip.23
default       frontend-o33ei       1/1       Running   0          48m       $publicip.26
default       redis-master-ubpga   1/1       Running   0          46m       $publicip.23
default       redis-slave-7aqp9    1/1       Running   0          46m       $publicip.97
default       redis-slave-w6rn3    1/1       Running   0          46m       $publicip.26
default       redis-slave-wny9v    1/1       Running   0          46m       $publicip.26
kube-system   kube-dns-v9-jek26    4/4       Running   0          50m       $publicip.23
kube-system   kube-dns-v9-ua150    4/4       Running   0          50m       $publicip.26
kube-system   kube-dns-v9-ycloq    4/4       Running   0          50m       $publicip.97
NAMESPACE     NAME           CLUSTER_IP       EXTERNAL_IP   PORT(S)         SELECTOR            AGE
default       frontend       10.100.221.197   nodes         80/TCP          name=frontend       46m
default       kubernetes     10.100.0.1       <none>        443/TCP         <none>              1h
default       redis-master   10.100.151.114   <none>        6379/TCP        name=redis-master   46m
default       redis-slave    10.100.223.227   nodes         6379/TCP        name=redis-slave    46m
kube-system   kube-dns       10.100.88.88     nodes         53/UDP,53/TCP   k8s-app=kube-dns    46m
NAMESPACE     CONTROLLER     CONTAINER(S)   IMAGE(S)                                             SELECTOR            REPLICAS   AGE
default       frontend       php-redis      kubernetes/example-guestbook-php-redis:v2            name=frontend       3          48m
default       redis-master   master         redis                                                name=redis-master   1          46m
default       redis-slave    worker         kubernetes/redis-slave:v2                            name=redis-slave    3          46m
kube-system   kube-dns-v9    etcd           gcr.io/google_containers/etcd:2.0.9                  k8s-app=kube-dns    3          50m
                             kube2sky       gcr.io/google_containers/kube2sky:1.11
                             skydns         gcr.io/google_containers/skydns:2015-10-13-8c72f8c
                             healthz        gcr.io/google_containers/exechealthz:1.0

$ rkubectl  exec busybox -- nslookup kubernetes
Server:    10.100.88.88
Address 1: 10.100.88.88

nslookup: can't resolve 'kubernetes'
error: error executing remote command: Error executing command in container: Error executing in Docker Container: 1
$ rkubectl  exec busybox -- ping -w 1 10.100.88.88
PING 10.100.88.88 (10.100.88.88): 56 data bytes

--- 10.100.88.88 ping statistics ---
1 packets transmitted, 0 packets received, 100% packet loss
error: error executing remote command: Error executing command in container: Error executing in Docker Container: 1

$ rkubectl  exec busybox -- route -n
Kernel IP routing table
Destination     Gateway         Genmask         Flags Metric Ref    Use Iface
0.0.0.0         172.17.42.1     0.0.0.0         UG    0      0        0 eth0
172.17.0.0      0.0.0.0         255.255.0.0     U     0      0        0 eth0

$ rkubectl  exec busybox -- ifconfig
eth0      Link encap:Ethernet  HWaddr 02:42:AC:11:00:1A
          inet addr:172.17.0.26  Bcast:0.0.0.0  Mask:255.255.0.0

$ rkubectl  exec busybox -- cat /etc/resolv.conf
nameserver 10.100.88.88
nameserver 8.8.8.8
nameserver 8.8.4.4
search default.svc.cluster.local svc.cluster.local cluster.local
options ndots:5