text:
Q: IBM Worklight Http Adapters I am using IBM worklight and would like to consume a .NET web service using http adapters. getting the error: "errors": ["Runtime:Runtime: Http request failed: java.net.UnknownHostException:
domain inside the xml typed it in full as [http://localhost/Service/Service1.asmx]
function HelloWorld() {
    var input = {
            method : 'get',
            returnedContentType : 'xml',
            path : "HelloWorld",
            transformation : {
                type : 'xslFile',
                xslFile : 'filtered.xsl'
            }
        };
    return WL.Server.invokeHttp(input);
}

A: In adapter's XML
<protocol>http</protocol>
<host>localhost</host>
<port>80</port>
In adapters JS use path:"Service/Service1.asmx"
Also, make sure that your service returns XML and your filtered.xsl contains a valid transformation for returned XML (otherwise just remote transformation property).

A: I think you are doing the same mistake I was doing few minutes ago. Your HelloWorld function is incomplete. I suggest if you refer to the way the client is constructing the message as per this question: IBM Worklight HTTP Adapter SOAP response: XSL transformation failed


text:
Q: Backbone.js TypeError: Cannot call method 'on' of undefined I'm trying to learn Backbone.js. I'm trying to define a model change event in the view but am getting the following javascript error:
    Uncaught TypeError: Cannot call method 'on' of undefined
If I take out the initialize from the view, it displays the text without error.
Do I have the correct basic structure for a Backbone app?
What am I doing wrong?
$(document).ready(function rdy()
{
    var Person = Backbone.Model.extend({
        defaults: {
            name:   'Alex',
            age:    33,
            }
        });

    person = new Person();

    var ContentView = Backbone.View.extend({
      el: '#content',
      initialize: function() {
        this.model.on('change', this.render, this);  //ERROR HERE <----------
        },
    render: function () {
        this.$el.html("Aargh Hello " + person.get('name'));
        return this;
        }
    });

  var NavigationRouter = Backbone.Router.extend({
    routes: {
        "": "defaultRoute"
            },
    initialize: function (options) {
        this.view = new ContentView({});
        return this;
        },
    defaultRoute: function (actions) {
        this.view.render();
        }
  });
  var navigationRouter = new NavigationRouter;
  Backbone.history.start();
 });

A: You need to pass a model into the view. Like:
// Pass in the person you made earlier. Alternatively, you could use
// new Person() instead of creating the person separately
this.view = new ContentView({ model: person });

Then your render function should also be using this.model
You could also put a check in the view, but if the view is going to rely on there being a Person model, you should probably let it fail like that so you don't forget.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Use of GCD Distributive Law in proof of Euclid's Lemma Suppose that c|ab and (b, c) = 1. Then c|a
Proof
(ab, ac) =|a|(b, c) = |a|. But by hypothesis, one has c|ab, which implies that c|(ab, ac).
We thus conclude that c|a. And the proof is complete.
I am sure it is very simple but I cant seem to understand the stage c|ab implies that c|(ab,ac). I would appreciate if someone could show me this.

A: Since $(b,c)=1$ there exist integers $k,l$ with $kb+lc=1$. Now $c\mid ab$ implies $c$ divides $kab=a(1-lc)=a-alc$. Since $c\mid alc$ it follows that $c\mid a$.

A: Greatest common divisior of $x$ and $y$ is a number with a property that $d \mid x$ and $d \mid y$ implies $d \mid \gcd(x,y)$.
In your case we have $c \mid ab$ from assumption and $c \mid ac$ trivially, because $\frac{ac}{c}=a$. Hence, $c \mid \gcd(ab,ac)$.
I hope this helps $\ddot\smile$

A: It uses basic gcd laws. By the GCD Distributive Law $\,\rm\color{#c00}{DL}\, $ we have
$\qquad\ c\mid ab\iff c\mid ab,ac \color{#0a0}\iff c\mid (ab,ac)\overset{\color{#c00}{\rm D\:\!L}} = a(b,c) \iff c/(b,c)\mid a$
Above we employed $\,\ c\mid j,k\color{#0a0}\iff c\mid (j,k),\,$ the GCD Universal Property.


text:
Q: What does it mean to "Provide a table dump" in SQL Server How can I perform a table dump to give to the client?
To try and provide as much info:

*

*I am using both SQL 2005 and 2008

*Existing databases are simple, like POS, Inventory, Tracking types

*I was asked to provide a table dump (of a certain table in a certain database in a certain server)

*No more info provided by client--just that they would like a table dump

*What is a "table dump", what formats are available, how do I create one to send to client?

If I missed more info, please let me know -- I'm really after the generic kind of table dump generation (if possible through T-SQL, better :) )

A: It means to provide a copy of the table's data.
Typically, it means provide a export of the table, including its definition and insert statements, as a script that can be executed to recreate the table from scratch.
However, It could mean a binary and/or proprietary format too, that is written/read by a database utility.
The common concept is that the table's contents may be restored from the dump.

A: I am assuming your client wants the file in a format that they can work with. In my experience this is something that can be opened in Excel either natively or as a CSV. My first suggestion would be to clarify the requirements with the client.
For now, let's assume they want a CSV file. Assuming you have Sql Server Management Studio, you could use the Import/Export wizard to export the contents of a database (selecting a specific table) to a variety of formats including Flat File and Excel. Right click on the database, choose tasks, export data and follow the steps.
This link shows how to use Import/Export wizard and the BCP command line tool. The BCP command line tool would be a more repeatable and scriptable option. http://www.sqlservercurry.com/2011/01/sql-server-export-table-to-csv.html
If you have SSIS running on the server or available, you could use that to create a package which would be another reusable solution.


text:
Q: update via ajax when model property was edited inline How to call knockout models Update(fieldName, newValue) (that calls some api via ajax and  update fieldName = newValue) when knockout model field value was changed via inline-edit?
I am using the following inline editing found at
Knockout Inline Edit Binding
ko.bindingHandlers.hidden = {
    update: function(element, valueAccessor) {
        ko.bindingHandlers.visible.update(element, function() { return !ko.utils.unwrapObservable(valueAccessor()); });
    }
};

ko.bindingHandlers.clickToEdit = {
    init: function(element, valueAccessor) {
        var observable = valueAccessor(),
            link = document.createElement("a"),
            input = document.createElement("input");

        element.appendChild(link);
        element.appendChild(input);

        observable.editing = ko.observable(false);

        ko.applyBindingsToNode(link, {
            text: observable,
            hidden: observable.editing,
            click: observable.editing.bind(null, true)
        });

        ko.applyBindingsToNode(input, {
            value: observable,
            visible: observable.editing,
            hasfocus: observable.editing
        });
    }
};

clickToEdit custom binding allows element to become input box when editing.
Now, I need to implement auto saving.
This would mean to call Update(fieldName, newValue) for value that has been just edited (when focus lost or similar).
I am new to knockout, so do not understand the logic of how to implement this.
EDIT: I was managed to do somethign, but I know that my solution is bad.
I have modified bindingHandlers (found here: http://jsfiddle.net/rniemeyer/8D5aj/)
and added focusout event that calls data save.

*

*Unfourtunately this is called for every field when page is loaded also and I do not need this.

*And also I do not know how to get observable fieldname and value within this event

*And last I am not able to save this only when field was really changed (this is not so important for now)

Script
ko.bindingHandlers.clickToEdit = {
    init: function (element, valueAccessor) {
        var observable = valueAccessor(),
            link = document.createElement("a"),
            input = document.createElement("input");

        element.appendChild(link);
        element.appendChild(input);

        observable.editing = ko.observable(false);

        ko.applyBindingsToNode(link, {
            text: observable,
            hidden: observable.editing,
            click: observable.editing.bind(null, true)
        });

        ko.applyBindingsToNode(input, {
            value: observable,
            visible: observable.editing,
            hasfocus: observable.editing,
            event: {
                keyup: function (data, event) {
                    //if user hits enter, set editing to false, which makes field lose focus
                    if (event.keyCode === 13) {
                        observable.editing(false);
                        return false;
                    }
                        //if user hits escape, push the current observable value back to the field, then set editing to false
                    else if (event.keyCode === 27) {
                        observable.valueHasMutated();
                        observable.editing(false);
                        return false;
                    }

                },
                focusout: function (data, event) {

                    // this is for test as I do not know how to get fieldname and value
                    var d = {
                        Field: "CompanyName",
                        Value: "Value"
                    };
                    var json = JSON.stringify(d)

                    $.ajax({
                        url: "/api/MyObject/PutValue/5",
                        contentType: "text/json",
                        dataType: "json",
                        type: "PUT",
                        data: json,
                        success: function(data) {
                            //
                        }
                    });
                }
            }
        });
    }

    //update: function (element, valueAccessor, allBindings, viewModel, bindingContext) {

    //}

};

A: If you are comfortable using more than one binding in your solution, why don't you try the simple one documented as Example 2: Click-to-edit in the knockoutjs documentation page?
Markup

    Name:
    <input data-bind="visible: editing,
                      value: name,
                      hasFocus: editing,
                      event: { blur: myblurFunction }" />

Click the name to edit it; click elsewhere to apply changes.

Script
function PersonViewModel(name) {
    var self = this;
    self.name = ko.observable(name);
    self.editing = ko.observable(false);
    self.edit = function () {
        this.editing(true);
    }
    this.myblurFunction = function() {
        var newName = self.name();
        alert("Houston! We have lost focus on " + newName);
        // ajax call here.
    }
}

ko.applyBindings(new PersonViewModel("Bert Bertington"));

Fiddle: http://jsfiddle.net/codovations/Q66bQ/

A: I think that the best idea for saving to the database is to subscribe to your observable in your view model and trigger the AJAX call there.
So, in your view model it would look like:
myObservable.subscribe(function(newValue) {
    //call your update here with the field name and newValue
});

You could even add an extension that makes it easy like:
ko.subscribable.fn.withUpdater = function(prop, handler) {
      this.subscribe(handler.bind(this, prop));

      //support chaining
      return this;

};

Now you could use it in your view model like:
this.firstName = ko.observable("Bob").withUpdater("firstName", yourUpdateFunction);

Here is a sample: http://jsfiddle.net/rniemeyer/dy2f5/


text:
Q: Making volatile Executor class in multi-threaded environment In my spring based application we are initializing threadPool using ExecutorService for concurrent task execution.We don't want the threadPool to be initialised multiple times in case of multithreaded environment, for which we are making our factory class as Singleton.
below is the factory implementation which we are using for threadPool initialization. Sonar analysis is giving a Bug warning as "Remove the "volatile" keyword from this field" for below line-
private static volatile ExecutorService executor;
is it required to make our ExecutorService as Volatile to achieve above behavior.
Below is the factory class
public class ThreadPoolExecutorFactory {

    /** The executor. */
    private static volatile ExecutorService executor;

    /**
     * Instantiates a new thread pool executor factory.
     */
    private ThreadPoolExecutorFactory() {
        // preventing Singleton object instantiation from outside
    }

    /**
     * Gets the executor.
     *
     * @return the executor
     */
    public static ExecutorService getExecutor( ) {
        if(executor == null) {
            synchronized (ThreadPoolExecutorFactory.class) {
                if(executor == null) {
                    executor = Executors.newCachedThreadPool();
                    Runtime.getRuntime().addShutdownHook(new Thread() {
                        @Override
                        public void run() {
                            executor.shutdown();
                        }
                    });
                }
            }
        }
        return executor;
    }
}

A: I think you are mixing Java standalone multi-threading concepts with Spring. In Spring, you can define a class as a "Bean" with "singleton" scope (default). You can have an init method and a destroy method which are guaranteed to be called.
In applicationContext.xml, define bean as below:
    <bean id="myExecutor" class="my.package.factories.ThreadPoolExecutorFactory"
                        scope="singleton"
                        init-method = "init"
                        destroy-method = "destroy">

And change class as below:
package my.package.factories

public class ThreadPoolExecutorFactory {

    /** The executor. */
    private static ExecutorService executor;

    public void init() {
        executor = Executors.newCachedThreadPool();
    }

    public void destroy() {
        executor.shutdown();
    }

    /**
     * Gets the executor.
     *
     * @return the executor
     */
    public static ExecutorService getExecutor( ) {
        return executor;
    }
}

Spring will take care rest of the details.


text:
Q: Finding standard deviation $\sigma$ Carton of mlik  can be reserved fresh for $20$ days in average, $\frac13$ from the milk cartons can reserved fresh for $22$ days or more.

Let's assume that the period of fresh is normaly distribued
find the standard deviation $\sigma$

My attempt:
$$X\sim N(\mu,\sigma^2)$$
$$E[X]=\mu=20$$
$$\text{Var}[X]=\sigma^2$$
$$X\sim N(20,\sigma^2)$$
The cumulative distribution function:
$$\Phi\bigg(\frac{x-\mu}{\sigma}\bigg)=\Phi\bigg(\frac{1/3-20}{\sigma}\bigg)\geq22$$

Is it correct so far? I don't know how to proceed and finding $\sigma$

A: Hint:
$$\frac13 = \Pr(X \ge 22) = 1 - \Pr(X < 22) = 1 - \Phi\left(\frac{22-\mu}{\sigma}\right). $$
Now, there are tables for values of $\Phi$ or just ask wolfram alpha.

A: You have $p(X>22)=\frac 13\Rightarrow p(z>\frac{22-20}{\sigma})=\frac 13$
Therefore $$\frac{22-20}{\sigma}=\Phi^{-1}(\frac 23)=0.43$$


text:
Q: Windows 11 context menu, file explorer mysteriously revert back to window 10 I've installed Windows 11 and it's smooth sailing up until some days ago, my context menu and file explorer magically changed into the classic windows 10 style. This is about the time by snip and sketch stopped working, I've made no registry changes whatsoever and would like to revert these back to win11 style and fix my snip and sketch, how can I do this?

A: Use regedit and check if the following key exists:
HKEY_CURRENT_USER\Software\Classes\CLSID\{86ca1aa0-34aa-4e8b-a509-50c905bae2a2.
If it exists, export it for backup and then delete the entire key.
This should restore the Windows 11 context menu.
Software that can do it for you the switch back and forth is
Windows 11 Classic Context Menu.
I don't know why Snip & Sketch stopped working. If it's worrying you,
you may check the following (the following links are for Windows 10
so may require some adjustment):

*

*sfc /scannow

*Repair Install of Windows 10 with an In-place Upgrade


text:
Q: The ith highest jump out of j jumps I have the following problem from strategic practice and homework 8 of Stat110.

Athletes compete one at a time at the high jump. Let $X_{j}$ be how
high the jth jumper jumped, with $X_{1}, X_{2},...$ with a continuous
distribution. We say that the jth jumper set a record if $X_{j}$ is
greater than all of $X_{j-1}, ....,X_{1}$.
(a) Find the variance of the number of records among the first n
jumpers (as a sum).

In the solution, it says

Let $I_j$ be the indicator r.v. for the jth jumper setting a record.
$I_i$ is independent of $I_j$ for all $i$, $j$ with $i<j$. To see
this, compute
$P(I_i=I_j=1) = \frac{\binom{j-1}{j-i-1}(j-i-1)!(i-1)!}{j!}$

I don't understand the binomial term in the nominator. It seems to me that this term means to pick any $j-i-1$ jumps out of the remaining $j-1$ (except the jth one), and put them between the jump $i$ and jump $j$. But the problem is we can't pick any jump before jump $i$ and put them there between. This is because then the jump $i$ won't be the highest for the first $i$ jumps (setting a record).
My point is that the jump i must be the largest among the first $i$ jumps and larger than some of the jumps between $i + 1$ and $j - 1$. I was using summation to list cases but it's quickly getting out of hands.
Can anyone give an intuitive explanation to this equation? I also read the explanation of the nominator in the sample solution but it doesn't make sense to me unfortunately.

A: It's not a matter of picking a jump before jump $i$ and moving it: you're just starting with a collection of $j$ jumps, and you want to know in how many ways they can be ordered so that both the one in position $j$ and the one in position $i$ are records. No matter which jumps end up in the first $i$ positions, one of them is the highest, and putting it in position $i$ ensures that that one is a record.
Thus, after you put the best jump in position $j$, you really can pick any $j-i-1$ jumps out of the remaining $j-1$ jumps and put them in positions $i+1$ through $j-1$ in any order; there are $\binom{j-1}{j-i-1}$ ways to pick them and then $(j-i-1)!$ order them in those positions. That leaves $i$ jumps for the first $i$ spots, and you just have to make sure that you put the highest one in position $i$. Once you've done that, there are $(i-1)!$ ways to arrange the remaining $i-1$ jumps in the first $i-1$ positions.

A: "My point is that the jump i must be the largest among the first i jumps and larger than some of the jumps between i+1 and j−1. I was using summation to list cases but it's quickly getting out of hands."
That is where you got it wrong, the ith jump doesn't need to be higher than any jumps between i+1 and j-1, . The ith jump only needs to be higher than the other i-1 jumps. There can be any other records between i+1 and j-1.


text:
Q: From php table retrieve data from selected checkbox I have below php table, it has row and column. Each row has checkbox, I am trying to retrieve email data from row that checkbox is selected. I can do this with Jquery, but since I can't save in text file. I am trying to do same thing with PHP. I try couple things, but none worked.
<?php
echo "

     <input type='checkbox' id='chk_all' />
    Id
    Email
    Name
    Car
    Phone

";
while($row = mysqli_fetch_array($result))
{
    echo "
";
    echo "  <input type='checkbox' id='chk[]'/> 	";
    echo "" . $row['id'] . "	";
    echo "" . $row['email'] . "	";
    echo "" . $row['name'] . "	";
    echo "" . $row['car'] . "	";
    echo "" . $row['phone'] , "	";
    echo "
";
}
echo "
";
?>

A: You can do this using Hidden fields and some indentity implementation on name= (and id= as well). Here are some inputs from my end but you can modify the code as per your requirements.
while($row = mysqli_fetch_array($result))
{
    echo "
";
    echo "  <input type='checkbox' name='chk_".$row['id']."' id='SHOULD_BE_UNIQUE_ON_THIS_PAGE'/> 	";
    echo "" . $row['id'] . "	";
    echo "" . $row['email'] . "<input type='hidden' name='chk_".$id."_email' value='".$row['email']."' id='SHOULD_BE_UNIQUE_ON_THIS_PAGE' />	";
    echo "" . $row['name'] . "	";
    echo "" . $row['car'] . "	";
    echo "" . $row['phone'] . "	";
    echo "
";
}
echo "
";

Here chk_{ID} is your main identifier while filtering data. When you submit the form, you should get to know whether checkbox is checked or not and if it is checked then you will come to know which hidden input field  has your data. Hidden fields will not appear in HTML page.

A: As PHP is a Hypertext Preprocessor language, you can't detect any client action on your page. So here is the best solution: you must detect changes you need with JavaScript/JQuery, and then send the result to a php file via Ajax and handle the result there (In your case save it in a file);
I hope it would be helpful for you. Let me know if you have any questions


text:
Q: Speeding up intersect query in PostGIS? I would like to count the number of points that intersect with a list of polygons.
The polygons are very complex (county/state boundaries).
I'm using this query:
SELECT gid, county_name,
   (SELECT COUNT(*) FROM points WHERE
     st_intersects(ST_Transform(points.location::geometry, 4326),
     ST_Transform(counties.geom::geometry,4326))
   ) AS c FROM counties;

In a query where there are 630 counties and 100 points, the query takes 290,000ms.
The difficulty is that I have 100,000 points and this query will then take 4 days.
Needless to say, this isn't viable.
The outcome would be:
County    | count
------------------
Wiltshire | 356

Do you have any advice on how to dramatically improve the efficiency of this query?

A: The way to improve it is to ensure you're using spatial indices.
Firstly, are your datasets in the same coordinate reference system? If not, reload the data after transforming or create a table and place the data in there in the same CRS.
Second, make sure you have a spatial index on the geometry columns you're using.
Next, remove the ST_Transforms from your query. If your results are required to be in a different CRS then do the transform on the results. But I think you're just counting, so don't worry about it!
If your data do have the same CRS, change the query to:
SELECT
    gid,
    county_name,
    (SELECT COUNT(*) FROM points WHERE
     ST_Intersects(points.location, counties.geom))
    ) AS count
FROM counties;


text:
Q: Forcing digital LOW

simulate this circuit – Schematic created using CircuitLab
The above schematic is of a digital chip using 5v logic.  This chip is soldered directly to a board which is supplying the power and the chip can't be removed, or permanently altered.  The Input1 pin is driven by the board and is usually HIGH since it is connected to the 5V Power supply.  However, I would like to somehow drop the voltage down enough to have the chip read it as a logical LOW (without cutting the lead)
Would putting a load between input 1 and ground e.g. Lightbulb accomplish this?  Alternatively, could I short INPUT1 and GND to accomplish this?
I'm still rather new to electronics, so please bear with me...Thanks

A: Without inserting a resistor in line with input 1, all you will achieve by shorting that line to ground is shorting the 5V power supply. The black lines in the circuit are regarded as zero ohms schematically and therefore what you do to the input line you also do to the 5V power line.

A: "Would putting a load between input 1 and ground e.g. Lightbulb accomplish this?"
Yep! I believe it should. As it would act as a voltage divider that would lower the voltage read by input 1 for whatever it's cut-off is to register as "LOW". Though you would have to also put in a resistor in series with either to the right of your stated load or the left. It depends on how you would want to implement your voltage divider.
Shorting it would just short the 5v as stated by Andy.


text:
Q: How to test a FileField in Django REST Framework I have this serializer which I am trying to test:
class AttachmentSerializer(CustomModelSerializer):
    order = serializers.PrimaryKeyRelatedField()
    file = FileField()

    class Meta:
        model = Attachment
        fields = (
            'id',
            'order',
            'name',
            'file_type',
            'file',
            'created_at',
        )

My test simply checks whether it is valid or not:
    def test_serializer_create(self):
        self.data = {
            'order': self.order.pk,
            'name': 'sample_name',
            'file_type': 'image',
            'created_at': datetime.now(),
            'file': open(self.image_path, 'rb').read()
        }

        serializer = AttachmentSerializer(data=self.data)

        self.assertTrue(serializer.is_valid())

And I am constantly getting this error:
{'file': ['No file was submitted. Check the encoding type on the form.']}

I tried to create a file in a number of different ways, such as with StringIO/BytesIO, File and etc. to no avail.
What might be wrong?

A: from django.core.files.uploadedfile import SimpleUploadedFile
content = SimpleUploadedFile("file.txt", "filecontentstring")
data = {'content': content}

try smth like that , because if you check FileField serializer's code - it expects UploadedFile that should have name and size:
    def to_internal_value(self, data):
    try:
        # `UploadedFile` objects should have name and size attributes.
        file_name = data.name
        file_size = data.size
    except AttributeError:
        self.fail('invalid')

and StringIO or opened file objects doesn't have size attribute.

A: I ran into a similar problem. It turned out that Django REST Framework FileField cannot be used with a JSON API parser. DRF documentation states that "Most parsers, such as e.g. JSON don't support file uploads."
Your question does not show which parser you configured, but given how common JSON is, it may be the culprit. You can set a different parser either across the board, or for a specific API view, as described here.
Once the parser problem was fixed, I made the test work with a Django File, but perhaps other approaches could work too:
from django.core.files import File

def test_create(self):
    ...
    data = {
        'file': File(open(path_to_test_file, 'rb')),
    }
    ...

A: The thing is that you pass an opened file to the APIClient / APIRequestFactory, not to the view itself. The Django request will wraps the file to an UploadedFile which is what you should use.


text:
Q: Does Django ship with the authentication templates for use with the django.contrib.auth module? I found some under the tests directory but I'm not sure if they are the right ones.
By authentication templates I mean login.htm, password_reset.htm, etc.
Some of the templates can be found at: http://devdoodles.wordpress.com/2009/02/16/user-authentication-with-django-registration/

A: No, it looks for those templates in a "registration" directory within your templates folder.
From the docs:

It's your responsibility to provide the login form in a template called registration/login.html by default.
Password Reset Optional arguments:

template_name: The full name of a template to use for displaying the password reset form. This will default to registration/password_reset_form.html if not supplied.

Docs: login, password_reset

A: By copying the templates located in django.contrib.admin.templates.registration as mentioned by DZPM above  and placing them into your own registration app's templates directory e.g. *your_proj_root/registration/templates/registration/*
IMPORTANT! If you are keeping the same exact filenames for your templates, you have to remember to make sure that your django.contrib.admin app line is placed below your registration app line; otherwise, it will use the django.contrib.admin's registration templates in preference.

A: While the Django documentation explicitly states that "Django provides no default template for the authentication views", I found that it is trivial to use the admin templates. Just enable the admin app, then add this to urls.py:
url(r'^accounts/login/$', 'django.contrib.auth.views.login', {'template_name': 'admin/login.html'}),
url('^accounts/', include('django.contrib.auth.urls')),

All of the authentication urls work now, albeit with the Django admin look-and-feel.

A: You can use the auth templates at django.contrib.admin.templates.registration:
logged_out.html
password_change_done.html
password_change_form.html
password_reset_complete.html
password_reset_confirm.html
password_reset_done.html
password_reset_email.html
password_reset_form.html

Those will have the look and feel of the Django Admin, so I would suggest to customize it.


text:
Q: why is my python if statement is not working so im pretty sure everything is correct but here it is not working, I would really apperciate it if someone could help me, this code is meant to make you choose between 3 doors, and after you choose a door, it will tell you a door that it is not it also that is not the door that you choose, finally this last part is meant to print the code
import random
import time

prize = (random.randint(1,3))
randomDoor = 7
question = 0

door = input ("Choose a door: 1, 2, ou 3")

print ("you chose door...", door)

#########               PRIZE IS 1                  ################################
if (prize == 1 and door == 1):
        print("random door = 3")
        randomDoor = 3

if (prize == 1 and door == 2):
        randomDoor = 3

if (prize == 1 and door == 3):
        randomDoor = 2

#################               PRIZE IS 2             #############################
if (prize == 2 and door == 1):
        randomDoor = 3

if (prize == 2 and door == 2):
        randomDoor = 3

if (prize == 2 and door == 3):
        randomDoor = 1

####################        PRIZE IS 3              ##############################
if (prize == 3 and door == 1):
        randomDoor = 2

if (prize == 3 and door == 2):
        randomDoor = 1

if (prize == 3 and door == 3):
        randomDoor = 1

print (randomDoor, "has nothing in it")

A: import random

prize = (random.randint(1,3))
randomDoor = 7
question = 0

door = int(input ("Choose a door: 1, 2, ou 3"))

print ("you chose door...", door)

#########               PRIZE IS 1                  ################################
if (prize == 1 and door == 1):
        print("random door = 3")
        randomDoor = 3

if (prize == 1 and door == 2):
        randomDoor = 3

if (prize == 1 and door == 3):
        randomDoor = 2

#################               PRIZE IS 2             #############################
if (prize == 2 and door == 1):
        randomDoor = 3

if (prize == 2 and door == 2):
        randomDoor = 3

if (prize == 2 and door == 3):
        randomDoor = 1

####################        PRIZE IS 3              ##############################
if (prize == 3 and door == 1):
        randomDoor = 2

if (prize == 3 and door == 2):
        randomDoor = 1

if (prize == 3 and door == 3):
        randomDoor = 1

print (randomDoor, "has nothing in it")

changes :
door = int(input ("Choose a door: 1, 2, ou 3"))

When you get an input, if you do not specify its type, it is a string by default


text:
Q: Convergence for power series $\sum_{n=0}^{\infty}z^n(5+e^{i\pi n})^n$? Consider the power series
$$\sum_{n=0}^{\infty}z^n(5+e^{i\pi n})^n \tag{1}.$$
Identifiying $e^{i\pi n}$ as $(-1)^n$ for all integers $n$, highlights the problem with using the ratio test or the root test for convergence of series, since $(-1)^n$ does not converge, right?
How can the convergence be determined for this power series? Does it exist?
Does it exist for other than $z=0$? Can it be determined by setting $(-1)^n=-1$ for all $n$ and therefore calculate the "smallest" radius or something like that?

A: Let's set $a_n=(5+(-1)^n)z^n$.
We have $|4z|^n\le|a_n|\le |6z|^n$ so the series converges for sure whenever $|z|<\frac 16$ and diverges for sure whenever $|z|>\frac 14$
What about values in the ring $\frac 16\le |z|\le\frac 14$ ?
To show that $r=\frac 16$ is the actual radius of convergence, we just need to exhibit one value on the border of the convergence disk that makes the series divergent.
Note that it doesn't prevent the series to converge for other values of $z$ in the concerned ring, but the radius of convergence is defined as the larger $r$ such that the series for $|z|<r$ is guaranteed to converge.
So we try with $z=\frac 16$ and the since the series is with all positive terms we can split it to $\displaystyle \sum\limits_{k=0}^{\infty} \left(\frac 46\right)^{2k+1}+\sum\limits_{k=0}^{\infty} \left(\frac 66\right)^{2k}$
The first series is convergence since it is a geometric series with $\left(\frac 46\right)^2<1$ and the second one is trivially divergent since its terms are all equal to $1\not\to0$.
Thus the series for $z=\frac 16$ is divergent, and it fixes the radius of convergence to its lower bound.

A: Yes, $e^{i\pi n}=(-1)^n$. Therefore, your series is$$6+4z+6^2z^2+4^3z^3+\cdots$$And, yes, you can use the root test here:$$\limsup_n\sqrt[n]{\left\lvert z^n\bigl(5+(-1)^n\bigr)^n\right\rvert}=6\lvert z\rvert.$$Therefore, the radius of convergence is $\frac16$.


text:
Q: My Mandelbrot sketching program in c# isn't working I have to make a c# program which creates a form and one of its controls has to be a control that makes a sketch of a Mandelbrot set in which you can zoom in and tell on which point you want to centre. In my opinion i'm doing the right thing, but when I want to start the program, I don't get the desired image of a standard Mandelbrot set. For the Mandelbrot sketch control I've got the next bit of my Mandelbrot class:
class Mandelbrotsketchscreen : UserControl
{
    //a method that draws every point with a certain paint
    //a method that chooses the right colour
    //a method that translates the pixel coordinates of the control to the actual coordinates

    //gives the number how many times the function has to be used
    private static int Mandelnumber(PointF p, PointF middle, double scale, int max, Size size)
    {
        PointF realpoint = new PointF();
        realpoint.X = (float)(middle.X + (p.X - size.Width / 2) * scale);
        realpoint.Y = (float)(middle.Y + (p.Y - size.Height / 2) * scale);
        PointF help = new PointF(0, 0);
        int i;
        for (i = 1; i <= max; i++)
        {
            help.X = help.X * help.X - help.Y * help.Y + realpoint.X;
            help.Y = 2 * help.X * help.Y + realpoint.Y;

            if (Math.Sqrt(help.X * help.X + help.Y * help.Y) > 2)
                break;
        }
        return i;
    }
}

Can someone tell me if I'm doing the calculation wrong or that maybe my loops are wrong?
The result I'm getting now is:

A: The new values for help.X and help.Y need to be calculated based on the previous values of help.X and help.Y.
Your code first calculates the new help.X value based on the previous help.X and help.Y values. So far, so good. But then, your code calculates help.Y using the new help.X value instead of the previous help.X value.
Thus, a solution/fix for your problem can be as simple as:
    for (i = 1; i <= max; i++)
    {
        var newX = help.X * help.X - help.Y * help.Y + realpoint.X;
        var newY = 2 * help.X * help.Y + realpoint.Y;

        help.X = newX;
        help.Y = newY;

        if (Math.Sqrt(help.X * help.X + help.Y * help.Y) > 2)
            break;
    }

(Side note: The newY variable in my example here is not strictly necessary. I chose to use it to clearly illustrate the distinction between previous and new values for help.X and help.Y.)

A different (and shorter) solution has been mentioned by Eric Lippert in the comments: Just create a new help point instead of mutating/modifying the existing help point:
    for (i = 1; i <= max; i++)
    {
        help = new PointF(
            help.X * help.X - help.Y * help.Y + realpoint.X,
            2 * help.X * help.Y + realpoint.Y
        );

        if (help.X * help.X + help.Y * help.Y > 4)
            break;
    }

This shorter solution also eliminates the rather slow square root computation by comparing against the square of 2 (= 4).


text:
Q: Add numpy.get_include() argument to setuptools without preinstalled numpy I am currently developing a python package that uses cython and numpy and I want the package to be installable using the pip install command from a clean python installation. All dependencies should be installed automatically. I am using setuptools with the following setup.py:
import setuptools

my_c_lib_ext = setuptools.Extension(
    name="my_c_lib",
    sources=["my_c_lib/some_file.pyx"]
)

setuptools.setup(
    name="my_lib",
    version="0.0.1",
    author="Me",
    author_email="me@myself.com",
    description="Some python library",
    packages=["my_lib"],
    ext_modules=[my_c_lib_ext],
    setup_requires=["cython >= 0.29"],
    install_requires=["numpy >= 1.15"],
    classifiers=[
        "Programming Language :: Python :: 3",
        "Operating System :: OS Independent"
    ]
)

This has worked great so far. The pip install command downloads cython for the build and is able to build my package and install it together with numpy.
Now I want to improve the performance of my cython code, which leads to some changes in my setup.py. I need to add include_dirs=[numpy.get_include()] to either the call of setuptools.Extension(...) or setuptools.setup(...) which means that I also need to import numpy. (See http://docs.cython.org/en/latest/src/tutorial/numpy.html and Make distutils look for numpy header files in the correct place for rationals.)
This is bad. Now the user cannot call pip install from a clean environment, because import numpy will fail. The user needs to pip install numpy before installing my library. Even if I move "numpy >= 1.15" from install_requires to setup_requires the installation fails, because the import numpy is evaluated earlier.
Is there a way to evaluate the include_dirs at a later point of the installation, for example, after the dependencies from setup_requires or install_requires have been resolved? I really like to have all dependencies resolved automatically and I dont want the user to type multiple pip install commands.
The following snippet works, but it is not officially supported because it uses an undocumented (and private) method:
class NumpyExtension(setuptools.Extension):
    # setuptools calls this function after installing dependencies
    def _convert_pyx_sources_to_lang(self):
        import numpy
        self.include_dirs.append(numpy.get_include())
        super()._convert_pyx_sources_to_lang()

my_c_lib_ext = NumpyExtension(
    name="my_c_lib",
    sources=["my_c_lib/some_file.pyx"]
)

The article How to Bootstrap numpy installation in setup.py proposes using a cmdclass with custom build_ext class. Unfortunately, this breaks the build of the cython extension because cython also customizes build_ext.

A: One (hacky) suggestion would be using the fact that extension.include_dirs is first requested in build_ext, which is called after the setup dependencies are downloaded.
class MyExt(setuptools.Extension):
    def __init__(self, *args, **kwargs):
        self.__include_dirs = []
        super().__init__(*args, **kwargs)

    @property
    def include_dirs(self):
        import numpy
        return self.__include_dirs + [numpy.get_include()]

    @include_dirs.setter
    def include_dirs(self, dirs):
        self.__include_dirs = dirs

my_c_lib_ext = MyExt(
    name="my_c_lib",
    sources=["my_c_lib/some_file.pyx"]
)

setup(
    ...,
    setup_requires=['cython', 'numpy'],
)

Update
Another (less, but I guess still pretty hacky) solution would be overriding build instead of build_ext, since we know that build_ext is a subcommand of build and will always be invoked by build on installation. This way, we don't have to touch build_ext and leave it to Cython. This will also work when invoking build_ext directly (e.g., via python setup.py build_ext to rebuild the extensions inplace while developing) because build_ext ensures all options of build are initialized, and by coincidence, Command.set_undefined_options first ensures the command has finalized (I know, distutils is a mess).
Of course, now we're misusing build - it runs code that belongs to build_ext finalization. However, I'd still probably go with this solution rather than with the first one, ensuring the relevant piece of code is properly documented.
import setuptools
from distutils.command.build import build as build_orig

class build(build_orig):

    def finalize_options(self):
        super().finalize_options()
        # I stole this line from ead's answer:
        __builtins__.__NUMPY_SETUP__ = False
        import numpy
        # or just modify my_c_lib_ext directly here, ext_modules should contain a reference anyway
        extension = next(m for m in self.distribution.ext_modules if m == my_c_lib_ext)
        extension.include_dirs.append(numpy.get_include())

my_c_lib_ext = setuptools.Extension(
    name="my_c_lib",
    sources=["my_c_lib/some_file.pyx"]
)

setuptools.setup(
    ...,
    ext_modules=[my_c_lib_ext],
    cmdclass={'build': build},
    ...
)

A: First question, when is numpy needed? It is needed during the setup (i.e. when build_ext-funcionality is called) and in the installation, when the module is used. That means numpy should be in setup_requires and in install_requires.
There are following alternatives to solve the issue for the setup:

*

*using PEP 517/518 (which is more straight forward IMO)

*using setup_requires-argument of setup and postponing  import of numpy until setup's requirements are satisfied (which is not the case at the start of setup.py's execution)

PEP 517/518-solution:
Put next to setup.py a pyproject.toml-file , with the following content:
[build-system]
requires = ["setuptools", "wheel", "Cython>=0.29", "numpy >= 1.15"]

which defines packages needed for building, and then install using pip install . in the folder with setup.py. A disadvantage of this method is that python setup.py install no longer works, as it is pip that reads pyproject.toml. However, I would use this approach whenever possible.

Postponing import
This approach is more complicated and somewhat hacky, but works also without pip.
First, let's take a look at unsuccessful tries so far:
pybind11-trick
@chrisb's "pybind11"-trick, which can be found here: With help of an indirection, one delays the call to import numpy until numpy is present during the setup-phase, i.e.:
class get_numpy_include(object):

    def __str__(self):
        import numpy
        return numpy.get_include()
...
my_c_lib_ext = setuptools.Extension(
    ...
    include_dirs=[get_numpy_include()]
)

Clever! The problem: it doesn't work with the Cython-compiler: somewhere down the line, Cython passes the get_numpy_include-object to os.path.join(...,...) which checks whether the argument is really a string, which it obviously isn't.
This could be fixed by inheriting from str, but the above shows the dangers of the approach in the long run - it doesn't use the designed mechanics, is brittle and may easily fail in the future.
the classical build_ext-solution
Which looks as following:
...
from setuptools.command.build_ext import build_ext as _build_ext

class build_ext(_build_ext):
    def finalize_options(self):
        _build_ext.finalize_options(self)
        # Prevent numpy from thinking it is still in its setup process:
        __builtins__.__NUMPY_SETUP__ = False
        import numpy
        self.include_dirs.append(numpy.get_include())

setupttools.setup(
    ...
    cmdclass={'build_ext':build_ext},
    ...
)

Yet also this solution doesn't work with cython-extensions, because pyx-files don't get recognized.
The real question is, how did pyx-files get recognized in the first place? The answer is this part of setuptools.command.build_ext:
...
try:
    # Attempt to use Cython for building extensions, if available
    from Cython.Distutils.build_ext import build_ext as _build_ext
    # Additionally, assert that the compiler module will load
    # also. Ref #1229.
    __import__('Cython.Compiler.Main')
except ImportError:
    _build_ext = _du_build_ext
...

That means setuptools tries to use the Cython's build_ext if possible, and because the import of the module is delayed until build_ext is called, it founds Cython present.
The situation is different when setuptools.command.build_ext is imported at the beginning of the setup.py - the Cython isn't yet present and a fall back without cython-functionality is used.
mixing up pybind11-trick and classical solution
So let's add an indirection, so we don't have to import setuptools.command.build_ext directly at the beginning of setup.py:
....
# factory function
def my_build_ext(pars):
     # import delayed:
     from setuptools.command.build_ext import build_ext as _build_ext#

     # include_dirs adjusted:
     class build_ext(_build_ext):
         def finalize_options(self):
             _build_ext.finalize_options(self)
             # Prevent numpy from thinking it is still in its setup process:
             __builtins__.__NUMPY_SETUP__ = False
             import numpy
             self.include_dirs.append(numpy.get_include())

    #object returned:
    return build_ext(pars)
...
setuptools.setup(
    ...
    cmdclass={'build_ext' : my_build_ext},
    ...
)

A: I found a very easy solution in this post:

Or you can stick to https://github.com/pypa/pip/issues/5761. Here you install cython and numpy using setuptools.dist before actual setup:

from setuptools import dist
dist.Distribution().fetch_build_eggs(['Cython>=0.15.1', 'numpy>=1.10'])

Works well for me!


text:
Q: Socket connects to a port on a non existant ip address I have the following code used to socket connect to a server running on Ubuntu 15.10:
    void Connect(std::string address, int port)
    {
            struct addrinfo hints;
            struct addrinfo *result = NULL;
            struct addrinfo *rp = NULL;
            int sfd, s;

            std::cout << "Connecting to address " << address << " port " << port << std::endl;

            std::memset(&hints, 0, sizeof(struct addrinfo));

            hints.ai_family = AF_UNSPEC;        /* Allow IPV4 or IPV6 */
            hints.ai_socktype = SOCK_DGRAM;     /* Datagram socket */
            hints.ai_flags = 0;
            hints.ai_protocol = 0;              /* Any protocol */

            std::string portStr;
            portStr = std::to_string(port);

            s = getaddrinfo(address.c_str(), portStr.c_str(), &hints, &result);

std::cout << "ADDRESS-------------> " << s << std::endl;
            if (s != 0)
            {
                std::stringstream ss;
                ss << "Cannot resolve hostname " << address << gai_strerror(s);
                throw std::runtime_error(ss.str());
            }

            /*
             *  getaddrinfo() returns a list of address structures. We should try each
             *  address until we successfull bind. If socket() or connect() fails, we close the socket
             *  and try the next address until the end.
             */
            for (rp = result; rp != NULL; rp = rp->ai_next)
            {
    std::cout << "loop-----------------> " << rp->ai_family << std::endl;
                sfd = socket(rp->ai_family, rp->ai_socktype, rp->ai_protocol);
    std::cout << "sfd-----------------> " << sfd << std::endl;

                if (sfd == -1)
                    continue;

    /*
                 *  If connect succeed, the address was found.
                 */
                int sts = connect(sfd, rp->ai_addr, rp->ai_addrlen);

    std::cout << "sts-----------------> " << sts << std::endl;

                if (sts == 0)
                    break;

                close(sfd);
            }

            /*
             *  Check for failure
             */
            if (rp == NULL)
            {
                std::stringstream ss;
                ss << "Cannot find server address at " << address << " port " << port;
                throw std::runtime_error(ss.str());
            }

            freeaddrinfo(result); /* Object no longer needed */

    std::cout << "SOCKET-----------------> " << sfd << std::endl;

            currentSocket = sfd;

    }

My problem is that this code is connecting the socket, even if an IP address is not available. Check the results:
Here is the runtime output:
    Connecting to address 192.168.0.185 port 9090
    ADDRESS-------------> 0
    loop-----------------> 2
    sfd-----------------> 5
    sts-----------------> 0
    SOCKET-----------------> 5

$ ping 192.168.0.185
PING 192.168.0.185 (192.168.0.185) 56(84) bytes of data.
From 192.168.0.185 icmp_seq=1 Destination Host Unreachable
From 192.168.0.185 icmp_seq=2 Destination Host Unreachable
From 192.168.0.185 icmp_seq=3 Destination Host Unreachable

I would like to understand what´s going on here ? Why does it connects the socket to a port from a non-existant Ip Address ?

A: You are passing an IPv4 address, not a hostname, to getaddrinfo() (you should be specifying AI_NUMERICHOST in the hints.ai_flags field, though).  It is going to output a single addrinfo containing a sockaddr_in for that IP address as-is, it will not try to validate the IP's existence.  That is why getaddrinfo() is returning 0.
You are telling getaddrinfo() that you are going to be using a UDP (SOCK_DGRAM) socket, not a TCP (SOCK_STREAM) socket.  So the output addrinfo contains information for creating a UDP socket when calling socket().
You are then calling connect() on a UDP socket.  In UDP, connect() does not actually create a physical connection, like it does for TCP.  It merely assigns the specified peer IP to the socket so that send() and recv() can then be used instead of sendto() and recvfrom().  That is why connect() is returning 0 instead of failing.  Doing this allows send() to always send packets to the same IP, and recv() to only accept packets received from the same IP.
You are not actually sending any data yet, so the peer IP is not being validated at any step of your code.  Once you start sending data, the transmitted packets will end up receiving ICMP host unreachable errors from the network, thus causing send() and recv() to start failing.
So, if you want connect() to fail for a non-reachable IP address, create a TCP socket instead of a UDP socket.  Otherwise, if you continue using a UDP socket, you need to send data to the IP so the network will try to physically route it.
BTW, if connect() did fail, you would be leaking the output addrinfo as you are calling freeaddrinfo() only if connect() succeeds.  You need to call freeaddrinfo() anytime getaddrinfo() succeeds, regardless of how you use the addrinfo data.

A: A UDP 'connect' is not a network operation. It sets a condtion in the local API, that filters out datagrams from other hosts and allows you to use send() instead of sendto(). It won't fail, but subsequent sends will.


text:
Q: webrtc - In firefox beta version giving InvalidSessionDescriptionError: Local descriptions must have a=mid attributes error WEBRTC - while setting answer into setLocalDescription getting below error in firefox beta version .63
this.soc.setLocalDescription(answer, function(){}, function(error){ co.handleAnswerLoacalDescError(error); } );
SWRTCAnswerPConn.prototype.handleAnswerLoacalDescError = function (error) {
    console.log("error SWRTCAnswerPConn.prototype.handleAnswerLoacalDescError "+error);
}
Below one is the local sdp
"v=0\r\no=mozilla...THIS_IS_SDPARTA-63.0 6779639364423913043 0 IN IP4 0.0.0.0\r\ns=-\r\nt=0 0\r\n
 a=ice-options:trickle\r\n
 a=msid-semantic:WMS *\r\nm=audio 9 RTP/SAVPF 0\r\nc=IN IP4 0.0.0.0\r\n
 a=sendrecv\r\n
 a=ice-pwd:0c25b6011567fa002a87fw6d36d0c32e\r\n
 a=ice-ufrag:9cba9881\r\n
 a=msid:{342671bf-c92f-4d7e-add6-37228fcaffc4} {6876af26-691b-4beb-9fed-a18e27ea0fe0}\r\n
 a=rtcp-mux\r\n
 a=rtpmap:0 PCMU/8000\r\n
 a=setup:active\r\n
 a=ssrc:127692948 cname:{f7d3d74d-86e0-4a27-a143-79f4703d32cf}\r\n"

*

InvalidSessionDescriptionError: Local descriptions must have a=mid attributes

*
Please, anyone, help to resolve this issue.


text:
Q: Single Web Page Display Issue So I was building a site for a local computer building business, and I designed it as a single page applet. I am essentially done with the html, the CSS is not a great issue. What became a problem was hiding and displaying different parts of the page. For some reason, my script.js won't recognize that I do not want to see all the html at once, but only portions. Any help would be appreciated. All of the files are pasted below.

<title> Name - Home </title>
<link rel="stylesheet" type="text/css" href="public/styles.css">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

 Welcome to Name

    <input id="scheduleButton" class="btn btn-sm scheduleButton" type="button" value="Schedule a phone appointment">
    <input id="reviewsButton" class="btn btn-sm reviewsButton" type="button" value="Reviews">
    <input id="contactButton" class="btn btn-sm contactButton" type="button" value="Contact Us">

        <button class="btn btn-primary dropdown-toggle" type="button" data-toggle="dropdown"> Hours </button>

Sunday: 11:00 am - 8:00 pm

Monday: 2:00 pm - 5:00 pm, 7:00 pm - 9:00 pm

Tuesday: 2:00 pm - 5:00 pm, 7:00 pm - 9:00 pm

Wednesday: 2:00 pm - 5:00 pm, 7:00 pm - 9:00 pm

Thursday: 2:00 pm - 5:00 pm, 7:00 pm - 9:00 pm

Friday: 2:00 pm - 5:00 pm, 7:00 pm - 9:00 pm

Saturday: 11:00 am - 8:00 pm

 Schedule an Appointment

    <form id="appt">

        <input type="text" name="firstname" placeholder="First Name...">

        <input type="text" name="lastname" placeholder="Last Name...">

        <input type="text" name="email" placeholder="Email...">

        <input type="text" name="phone" placeholder="Callback Number...">

        <input type="radio" name="type" value="New"> Schedule an appointment regarding making a computer

        <input type="radio" name="type" value="Old"> Call about a computer we made

        <input type="radio" name="type" value="Current"> Ask about the status of your build

        <input type="radio" name="type" value="Other"> Have a question about something else

        <input type="submit" name="Submit">

    </form>

 Our Contact Information

 Contact us during our office hours by calling: (999) 999-9999

 Feel free to email us any time at: email@gmail.com

 Please enter the specifications you would like in your computer

    <form id="specs">
        <form id="processor">

 Processor:

            <input type="radio" name="AMD"> AMD

            <input type="radio" name="Intel"> Intel
        </form>

        <form id="motherboards">

 Motherboard:

            <input type="radio" name="ASUS"> ASUS

            <input type="radio" name="MSI"> MSI

            <input type="radio" name="Gigabyte"> Gigabyte

            <input type="radio" name="ASRock"> ASRock
        </form>

        <form id="memory">

 Memory (RAM):

            <input type="radio" name="4"> 4 GB

            <input type="radio" name="8"> 8 GB

            <input type="radio" name="16"> 16 GB

            <input type="radio" name="32"> 32 GB
        </form>

        <form id="harddrive">

 Hard Drive Size:

            <input type="radio" name="500 GB"> 500 GB

            <input type="radio" name="1 TB"> 1 TB

            <input type="radio" name="2 TB"> 2 TB

            <input type="radio" name="X TB"> 2+ TB
        </form>

        <form id="tower">

 Tower Type:

            <input type="radio" name="mid"> Mid Tower

            <input type="radio" name="full"> Full Tower

            <input type="radio" name="mini"> Mini Tower

            <input type="radio" name="super"> Super Tower
        </form>

        <form id="graphics">

 Graphics Card:

            <input type="radio" name="evga"> EVGA

            <input type="radio" name="MSI"> MSI

            <input type="radio" name="Gigabyte"> Gigabyte

            <input type="radio" name="ASUS"> ASUS

        </form>

        <input type="submit" name="Submit">

    </form>

And the script:
var currentID;

$(document).ready(function (e) {
    $('#schedulePage').hide();
    $('#formPage').hide();
    $('#contactPage').hide();
    $('#specPage').hide();
});

CSS should be irrelevant. Thanks again.

A: You don't need to use jquery's hide function use bootstrap's hide class
 $(document).ready(function (e) {
    $('#schedulePage').addClass("hide");
    $('#formPage').addClass("hide");
    $('#contactPage').addClass("hide");
    $('#specPage').addClass("hide");
 });

As in bootstrap 3.3.7 they have given CSS for hide class as
    display: none !important;
Just make sure your css is not overriding this property

A: You can use Boostrap CSS Helper Classes for hide and display htm element.
$(document).ready(function (e) {
    $('#schedulePage').addClass("hidden");
    $('#formPage').addClass(".hidden");
    $('#contactPage').addClass("hidden");
    $('#specPage').addClass("hidden");
});

Or
   $(document).ready(function (e) {
        $('#schedulePage').addClass("invisible");
        $('#formPage').addClass(".invisible");
        $('#contactPage').addClass("invisible");
        $('#specPage').addClass("invisible");
    });


text:
Q: Getting the permalink to the latest post from a category What's the best way to get the permalink to the latest post of a chosen category? I have a page that I want to have several links to the latest post from different specified categories.
Simple question, but I'm not sure if it's even possible :)
Thanks!

A: This will work:
$latest_post = get_post( array( 'cat' => YOUR_CAT_ID, 'posts_per_page' => 1) )
if( $latest_post ) {
    echo get_permalink( $latest_post->ID );
}

Or you can do it in bulk for more categories:
$categories = array( 7, 12, 14, 15 );

foreach( $categories as $cat ) {
    $latest_post = get_post( array( 'cat' => $cat, 'posts_per_page' => 1) )
    if( $latest_post ) {
        echo get_permalink( $latest_post->ID );
    }
}


text:
Q: How to send Parameters (some values) from servlet to android on the server side i am doing this and have to send three strings from this class

to the client side in android application
  @Override
  protected void doPost(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException {
        name1 = getParameter(req, "name");
        phone1 = getParameter(req, "phone");
        dob1 = getParameter(req, "dob");
        String regId = getParameter(req, PARAMETER_REG_ID);
        resp.setContentType("text/html");
        Datastore.register(regId);
        Datastore.register_name(name1);
        Datastore.registerPhone(phone1);
        Datastore.registerDob(dob1);
}

And On The Client Side I have to Recieve it
Actually i was doing it to get responses from server to client it has relay simple solution what you want to send from server to client side if you have post method in the do post method u have to make some output stream and what ever you write on the stream you can get easily by reading that output stream

A: yes u can use this way on servlet response
resp.setHeader(java.lang.String name, java.lang.String value)

and at Android end you can get the value from response
    String value =response.getHeaders(name);

I hope u will get into the way i told u .....

A: Your question is not clear ...
Please edit your question and explain in detail
What I have understood is: You want to send some messages / parameters from your back end Server to the Mobile device.
If this is what you need, then have a look at the Google Cloud Messaging : http://developer.android.com/google/gcm/index.html which is designed specifically for this.


text:
Q: How do I keep Score in Python? enter image description hereI don't know how to make python keep score in a game, I saw that I should put score = 0 at the top of code and then after the if statement put score +1 but it comes out blank whenever I run the code:
I tried score +1 and score+=1 after the if statement but when I run it keeps coming out as blank.
Does anyone know how to help?
Thanks

A:     score = 0
    player_input = input("Enter the capital of Greece: ").capitalize()
    if player_input == "Athens":
        score += 1
    print(score)

    # I hope this helps

EDIT: Your use of .upper() will change a string like "text" into "TEXT". Instead I used .capitalize() which changes a string like "text" into "Text". Also instead of writing "score + 1", which doesn't actually add one to your score variable, you should write either "score = score + 1" or "score += 1" for short.


text:
Q: Aggregate periods using recursive queries I need to merge overlapping periods (defined by FROM and TO variables) of sequential events (with identifier NUM) for each group (ID) with a "lookahead buffer", meaning that if the next period starts within the buffer zone, they should be merged.
For instance; in the following example the second event (NUM = 2) starts at time 13, which is within the buffer zone (10 + 5 = 15).
The tricky part here compared to other similar problems I've found is that although the buffer period has a fixed value for each event, this could potentially change if it is merged with an event (only backwards) that has a longer buffer period.
For instance; Event three is also merged to the same periods as event 1 and 2, and because the buffer periods of these events are longer. The following buffer zone should instead be (25 + 5 = 30), rather than (25 + 3 = 28), meaning the following event 4 should also be included in these periods as well.
Once again the buffer period of event 4 is also changed to 5. However, because 40 > 31+5, the last event is a separate observation.
CREATE TABLE MY_TABLE(ID INTEGER, NUM INTEGER, FROM INTEGER, TO INTEGER, LOOKAHEAD INTEGER);
INSERT INTO MY_TABLE VALUES (1, 1, 1,  10, 5);
INSERT INTO MY_TABLE VALUES (1, 2, 13, 20, 5);
INSERT INTO MY_TABLE VALUES (1, 3, 21, 25, 3);
INSERT INTO MY_TABLE VALUES (1, 4, 29, 31, 3);
INSERT INTO MY_TABLE VALUES (1, 5, 40, 50, 3);

Eventually, the result I need are two observations with the two "disjunct" periods;
(ID = 1, FROM = 1,  TO = 31)
(ID = 5, FROM = 40, TO = 50)

Naturally I initially thought I could create this "LOOKHEAD"-variable, by creating a new variable LOOKAHEAD2 that is the maximum of previous value of LOOKAHEAD2 and current value of LOOKAHEAD, conditional on FROM(this record) < (TO + LOOKAHEAD)(previous record) using OLAP functions. This doesn't really work however since it is a reference to itself...
Instead, I tried using recursive queries, where I start with the first event (NUM = 1), and than recursively join the table with the next event (root.NUM+1 = next.NUM) conditional on (root.TO + root.LOOKAHEAD > next.FROM), and also updating the LOOKAHEAD variable accordingly.
But I have never used recursive queries before, and I can't get it to join on the updated value of the LOOKAHEAD-value.
Does anyone know how to solve this with either recursive queries or other?

A: You should use the RESET WHEN window modifier in your analytic functions (LAG in Teradata 16, or MAX in earlier ones); don't use a recursive query.
Update:
DROP TABLE MY_TABLE;
CREATE VOLATILE TABLE MY_TABLE
( id          INTEGER
, num         INTEGER
, from_value  INTEGER
, to_value    INTEGER
, lookahead   INTEGER
) ON COMMIT PRESERVE ROWS;

INSERT INTO MY_TABLE VALUES (1, 1, 1,  10, 5);
INSERT INTO MY_TABLE VALUES (1, 2, 13, 20, 5);
INSERT INTO MY_TABLE VALUES (1, 3, 21, 25, 3);
INSERT INTO MY_TABLE VALUES (1, 4, 29, 31, 3);
INSERT INTO MY_TABLE VALUES (1, 5, 40, 50, 3);

INSERT INTO MY_TABLE VALUES (2, 1, 1, 10, 5);
INSERT INTO MY_TABLE VALUES (2, 2, 20, 30, 15);
INSERT INTO MY_TABLE VALUES (2, 3, 40, 41, 5);
INSERT INTO MY_TABLE VALUES (2, 4, 100, 200, 5);
INSERT INTO MY_TABLE VALUES (2, 5, 300, 400, 3);

SELECT  id, first_from_value, to_value
FROM  ( SELECT  id
              , to_value
              , CASE WHEN overlaps_flag = 1
                  THEN  NULL
                  ELSE  COALESCE
                        ( MIN (from_value)
                            OVER (PARTITION BY id
                                  ORDER BY from_value
                                  RESET WHEN MAX (overlaps_flag)
                                               OVER (PARTITION BY id
                                                     ROWS BETWEEN
                                                          1 PRECEDING
                                                      AND 1 PRECEDING) = 0
                                  ROWS BETWEEN UNBOUNDED PRECEDING
                                           AND 1 PRECEDING)
                        , from_value )
                END AS first_from_value
        FROM  ( SELECT  id, from_value, to_value
                      , MAX (from_value)
                          OVER (PARTITION BY id
                                ORDER BY from_value
                                ROWS BETWEEN 1 FOLLOWING AND 1 FOLLOWING)
                          AS next_from_value
                      , CASE WHEN to_value + lookahead + 1 >= next_from_value
                          THEN 1 ELSE 0
                        END AS overlaps_flag
                FROM  my_table
              ) AS a
      ) AS a
WHERE first_from_value IS NOT NULL
ORDER BY 1, 2

id  first_from_value    to_value
1   1                   31
1   40                  50
2   1                   10
2   20                  41
2   100                 200
2   300                 400


text: Q: What deletes docker images periodically? Every so often I have observed that docker images get deleted from the local repository without an explicit rmi command. Does docker perform a clean up on the images not being used by any of the containers?


text:
Q: Add each element of an ArrayList to each element of another ArrayList I have an ArrayList which has N items. I want to iterate through the ArrayList, and add each item in the ArrayList to the equivalent item in another ArrayList. I have tried this, but it doesn't work:
ArrayList<Integer> arrList1 = new ArrayList<Integer>();

for(String key: myMap.keyValues() {
    ArrayList<Integer> dynArrList = getArrayListFromSomewhereElse();

    for(Integer i : dynArrList) {
       arrList1.set(i, arrList1.get(i) + dynArrList.get(i)); // sum each item
    }
}

I get index out of bounds exception. I have tried to initilise arrList1, but it made no difference. I also tried to set a minimum size for it.

A: You have not provided two lists of integers to sum together. You have dynArrList as an addend, and you have arrList1 for the result. But you don't have a second addend, which should tell you that you don't really understand your problem yet. Either your real task isn't what you think it is, or you haven't correcltly identified where you are getting your data from.
So, suppose you have two List<Integer>s.  Program to the interface where possible.  How would you do an item by item sum?  Write a sum method, and recognize what can happen if the two lists are of different sizes.
public List<Integer> sum(List<Integer> left, List<Integer> right) {
    if (left.size() != right.size()) {
        // A runtime exception you write saying that you can't add two
        // arrays of different sizes.
        throw new VectorShapeException(left.size(), right.size());
    }
    List<Integer> vectorSum = new ArrayList<>();
    for (int i = 0; i < left.size(); ++i) {
        vectorSum.add(left.get(i) + right.get(i));
    }
    return vectorSum;
}

Identify what you want to add, and use this.
Now, suppose you had the assignment to calculate the dot product of two integer array lists. You'd might want two things--a method to sum the elemnts of one list, and a method to get a vector of products. This might be wasteful, as you probably don't need the intermediate list, and you'd be wasting space.  The first task is easy:
public int sum(List<Integer> list) {
    int total = 0;
    for(Integer element: list) {
        total += element;
    }
   return total;
}

The second is easy; just copy and rename things:
public List<Integer> product(List<Integer> left, List<Integer> right) {
    if (left.size() != right.size()) {
        // A runtime exception you write saying that you can't multiply two
        // arrays of different sizes.
        throw new VectorShapeException(left.size(), right.size());
    }
    List<Integer> vectorProd = new ArrayList<>();
    for (int i = 0; i < left.size(); ++i) {
        vectorProd.add(left.get(i) * right.get(i));
    }
    return vectorProd;
}

public int dotProduct(List<Integer> left, List<Integer> right) {
    return sum(product(left, right));
}

But there's a tedious problem here.  The cut and paste and modify is a sign that I wasn't really thinking there.  The only real difference between the 2-argument sum and product methods is the operator and the names. This leads to functional programming, which is probably too much for now.

A: The index out of bounds exception is coming from your loop:
for(Integer i : dynArrList) {
    arrList1.set(i, arrList1.get(i) + dynArrList.get(i));
}

In this case i is not an index into the list. There is no guarantee that any of your lists have i elements. You probably want a standard for loop for this:
for(int i = 0; i < dynArrList.size(); i++) {
    arrList1.set(i, arrList1.get(i) + dynArrList.get(i));
}

Also, if you're going to be calculating any kind of sum, you need to make sure that the two lists have the same number of elements, or that you're only going until the length of the shorter of the two lists.

A: If arrList1 does not have anything on it, how do you set the element to be arrList1.get(i) + dynArrList.get(i)? There must be a missing step where arrList1 values are set. As written in the example, use .add for a growable List instead of .set.
ArrayList<Integer> arrList1 = new ArrayList<Integer>();//has no values and no size

ArrayList<Integer> dynArrList = getArrayListFromSomewhereElse();

for(Integer i : dynArrList) {
   arrList1.add(i); // sum each item
}

or use an intermediate ArrayList to do the merge/final List.
ArrayList<Integer> arrList1 = getArrayFromALocation();//may have values and size
ArrayList<Integer> dynArrList = getArrayListFromSomewhereElse();
ArrayList<Integer> mergedList1 = new ArrayList<Integer>();

for(int i =0; i<  dynArrList.size(); i++) {//assuming larger
if ( i < arrList1 .size() )
   mergedList1.add(new Integer(dynArrList.get(i).intValue()+(arrList1 .get(i).intValue())); // sum each item
else
    mergedList1.add(new Integer(dynArrList.get(i).intValue()+0));
}
}
return mergedList1;


text:
Q: Force PHP to use TLS 1.0 instead of SSL Good day all.
I'm using a payment gateway on a site with a credit card payments, the bank gateway send to all its customers that it will stop all SSL connections starting from the 3rd of January, so I must be sure to doing the right things without tests.
actually I'm using this configuration just before making the connection:
<?php
curl_setopt($curl_handle, CURLOPT_URL,$to_url);
curl_setopt($curl_handle, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER,1);
curl_setopt($curl_handle, CURLOPT_POST, 1);
curl_setopt($curl_handle, CURLOPT_POSTFIELDS, $data);
$buffer = curl_exec($curl_handle);
curl_close($curl_handle);
?>

this is set to false due to debugging needs.
curl_setopt($curl_handle, CURLOPT_SSL_VERIFYPEER, false);

So, I've read that adding:
CURLOPT_SSLVERSION => 1

should force the use of TLS, is that true?
Does adding this option will prevent the gateway to ignore my requests?
Does it needs some other options?

A: You might experience connectivity issues, if you don't specify your TLS version, which often happens.
You need the following options:
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);
curl_setopt($ch, CURLOPT_SSLVERSION, CURL_SSLVERSION_TLSv1_2);
curl_setopt($ch, CURLOPT_CAINFO, 'cacert.crt');
curl_setopt($ch, CURLOPT_SSL_CIPHER_LIST, $array_ciphers);

This way, you will achieve maximum forward secrecy.
You can always remove any of the mentioned parameters, but before you do, make sure you read this detailed explanation of the functions above.
Afterwards you can decide what you would like to do.
Let me know, if you have any questions.


text:
Q: Как произвести миграцию в Alembic? Смотрел здесь туториал http://alembic.zzzcomputing.com/en/latest/tutorial.html
прописал alembic revision -m "create account table" и мне создало скрипт, но поля в нем пусты, я так и не понял мне самому их заполнять или есть чудесная команда которая все сделает. В schema новая таблица есть.
Использую python, alembic, sqlalchemy, postgresql
Подскажите пожалуйста


text:
Q: GraphView cannot resolve symbol addSeries() I'm trying to use Graphview following this tutorial.
But I have some issue with GraphView.addSeries() that cannot be resolve.
So here is my build.gradle
apply plugin: 'com.android.application'

android {
    compileSdkVersion 23
    buildToolsVersion "23.0.3"

    defaultConfig {
        applicationId "com.example.florian.graph2"
        minSdkVersion 15
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.4.0'
    compile files('libs/GraphView-4.0.1.jar')
    //compile 'com.jjoe:graphview:4.0.1'
}

I've tried both using the Maven Central Repository with the line compile 'com.jjoe:graphview:4.0.1', and Download and paste the jar file with the line compile files('libs/GraphView-4.0.1.jar').
I don't know why but the first didn't work at all and with the second one in the line graph.addSeries(series); addSeries cannot be resolve.
My code is Here
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

import com.jjoe64.graphview.GraphView;
import com.jjoe64.graphview.series.DataPoint;
import com.jjoe64.graphview.series.LineGraphSeries;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    GraphView graph = (GraphView) findViewById(R.id.graph);

    LineGraphSeries<DataPoint> series = new LineGraphSeries<DataPoint>(new DataPoint[]{
            new DataPoint(0,1),
            new DataPoint(1,0),
            new DataPoint(2,5),
            new DataPoint(3,2),
            new DataPoint(4,7)
    });

    graph.addSeries(series);
}

If you guys have any idea it will be welcome. Thank you.

A: If anyone in the same case, I put everything in onCreate method and now it's working.

A: Search for dependencies, add libraries, then you can import the classes:


text:
Q: How do I install yum on Redhat Enterprise 4? For historical reasons, one of the machines that I manage has a Redhat Enterprise 4 boot disk (among others).  Every now and then, we have to boot into RHEL4 to bring up some of the legacy software that we support and connect to.  Since it's a fringe system, the Redhat support has long since lapsed and I can't convince myself that it would be worth paying just to get RPMs that I can go and get for myself.
That said, the default RHEL tools are heavily biased against letting you do exactly that.  I would like to install yum and use that as my package discovery and installation.
So, is there an installation guide to integrating yum with an older RHEL 4 system?

A: up2date has support for using yum repositories.  Probably better to use that, than to install additional software you don't necessarily need.
Edit /etc/sysconfig/rhn/sources
Add a line like:
yum EPEL http://rhn.sonoma.edu/pub/mirrors/epel/4/$ARCH

That's a literal "yum", the repository name you'd like up2date to see it as, then the URL, which has some very limited support for variables, such as $ARCH.
You can also do apt and straight directories; there's examples in the file.
If you want to disable the RHN stuff, just comment out the "up2date default" line from the same file.

A: Not too long ago I moved a RHEL 4 system to CentOS for similar reasons.  It was a pretty simple process and has worked very well so far.  I used these instructions:
http://fixlinux.com/2006/04/11/migrate-rhel-to-centos/

A: This repository is run by Redhat.

A: To install yum on RHEL4, use the instructions here. They describe obtaining all yum's dependencies from http://fr2.rpmfind.net/, and configures the system to use that as a yum repository. Check the individual packages for newer versions, but otherwise it worked just fine.

A: Just go on the internet and find a compatible yum rpm.  Then do sudo rpm -ivh [RPM name]. That should do the basic installation.  After that you have to find some repositories with the RPMS you want to be able to install.  I strongly suggest DAG, although I don't know if they continue to maintain libraries for older OSes.  Most repositories will have their own rpms for installing the necessary configs and keys, and if they don't they will have step by step instructions for getting set up.

A: Look into RPMforge.  You can get a yum from there.


text:
Q: How to properly render an embedded Font? I download a True Type Font and I embedded it just as this page explains.
I had to set the UseCompatibleTextRendering property to be able to load it but it looks very weird, I don't know why it looks good in the browser but not in the application.
Just to be clear I added the font to my resources, set it as embedded resource, I used this module:
Imports System.IO
Imports System.Reflection
Imports System.Drawing.Text
Imports System.Runtime.InteropServices

Module ExternalFontType
    Public Function GetFont(aAssembly As Assembly,
      strFontName As String, intFontSize As Integer,
      fsFontStyle As FontStyle) As Font

        Using pcolFonts As New PrivateFontCollection

            Dim bFont() As Byte = ExternalFontType.bRawFontData(aAssembly, strFontName)
            Dim ptrMemFont As IntPtr =
               Marshal.AllocCoTaskMem(bFont.Length)

            Marshal.Copy(bFont, 0, ptrMemFont, bFont.Length)
            pcolFonts.AddMemoryFont(ptrMemFont, bFont.Length)

            Marshal.FreeCoTaskMem(ptrMemFont)

            Return New Font(pcolFonts.Families(0),
               intFontSize, fsFontStyle)
        End Using
    End Function

    Private Function bRawFontData(aAssembly As Assembly, strFontName As String) As Byte()
        Using stFont As Stream =
            aAssembly.GetManifestResourceStream(strFontName)

            If (stFont Is Nothing) Then Throw _
               New Exception(String.Format("Cannot load _
            font '{0}'", strFontName))

            Dim bFontBuffer() As Byte = New _
               Byte(CInt(stFont.Length - 1)) {}

            stFont.Read(bFontBuffer, 0, CInt(stFont.Length))
            Return bFontBuffer
        End Using
    End Function
End Module

and included it in this code
lbl.UseCompatibleTextRendering = True
lbl.Font = ExternalFontType.GetFont(Me.GetType.Assembly, "ProyectName.FontName.ttf", 15, FontStyle.Bold)

A: More than one problem with that code:

*

*The PrivateFontCollection cannot be declared with a Using statement: this collection must be preserved as long as the Fonts it points to are needed. It's usually declared as a Field in the class (Form) that uses it or in a shared class (or Module, here), then disposed of when not needed anymore.

*Marshal.FreeCoTaskMem() cannot be used here; it's a temptation to call it after  Marshal.AllocCoTaskMem(), but not in this occasion. This can (will) compromise the Font data allocation. What you need to do is dispose of the PrivateFontcollection object. The Framework will take care of the COM affair (it will do it for you even if you forget to dispose of the PrivateFontcollection object. You should try not to forget, though).

*The assembly reference is not required: the Font is added to the Project's Resources as a byte array, which is all that's needed. It can then be retrieved either by name, e.g., My.Resources.SomeFontName, or using the ResourceManager.GetObject() method, casting the returned object to Byte():
Dim fontData As Byte() = My.Resources.SomeFontName
Dim fontData As Byte() = DirectCast(My.Resources.ResourceManager.GetObject("SomeFontName"), Byte())

▶ You have already mentioned this but let's say it again: not all controls can use these Fonts. Only controls that can use Fonts drawn by GDI+ can actually use Fonts from the PrivateFontCollection, the Label and Button controls are among of these, in fact both expose a UseCompatibleTextRendering property. A RichTextBox, for example, cannot.

*

*If the Font is created correctly, you can use Graphics.DrawString() to draw strings content using that Font, even when you cannot set it as the Font of a Control.

Private myFontCollection As PrivateFontCollection = New PrivateFontCollection()

In the Form's Constructor, add Font from the Project's Resources.

*

*Here I'm using a helper class, FontManager, which exposes a public shared method AddFontsFromResource(): pass to this method the PrivateFontCollection and a list of resources names corresponding to the Font names.
This method fills the collection with Fonts that can be installed successfully and returns the number of Fonts installed.
Of course you use whatever other method you prefer to reference your Fonts.

*Note. In the example, three Font resources are added to the collection:
{"FontFamily1Regular", "FontFamily1Italics", "OtherFontFamily"}
but two belong to the same FontFamily, so the PrivateFontCollection will contain just two elements, not three.
Public Sub New()
    Dim installedFontsCount = FontManager.AddFontsFromResources(myFontCollection,
        {"FontFamily1Regular", "FontFamily1Italics", "OtherFontFamily"})
    ' The Font can set here or anywhere else
    someLabel.UseCompatibleTextRendering = True
    someLabel.Font = New Font(myFontCollection.Families(0), 10.5F, FontStyle.Regular)
    someButton.UseCompatibleTextRendering = True
    someButton.Font = New Font(myFontCollection.Families(0), 10.5F, FontStyle.Italic)
End Sub

It's important to dispose of the PrivateFontCollection when it's not needed anymore: when the Form that initialized it closes or before the Application closes:
You could also use a shared object to reference a PrivateFontCollection that can be used anywhere in the Project. In this case the collection needs to be disposed of when the Application closes.
Private Sub Form1_FormClosed(sender As Object, e As FormClosedEventArgs) Handles MyBase.FormClosed
    myFontCollection.Dispose()
End Sub

Helper class:
Imports System.Drawing.Text
Imports System.Runtime.InteropServices

Public Class FontManager
    Public Shared Function AddFontsFromResources(fontCollection As PrivateFontCollection, fontNames As String()) As Integer
    If fontNames.Length = 0 Then Return Nothing
    Dim installedFontsCount = 0

    For Each fontName As String In fontNames
        Try
            Dim fontData As Byte() = CType(My.Resources.ResourceManager.GetObject(fontName), Byte())
            If fontData Is Nothing Then Throw New InvalidOperationException()

            Dim data As IntPtr = Marshal.AllocCoTaskMem(fontData.Length)
            Marshal.Copy(fontData, 0, data, fontData.Length)
            fontCollection.AddMemoryFont(data, fontData.Length)
            installedFontsCount += 1
        Catch ex As Exception
            ' Placeholder: Notify User/Log/Whatever
            Debug.Print($"Font installation failed for {fontName}")
        End Try
    Next
    Return installedFontsCount
    End Function
End Class

C# version:
using System.Drawing.Text;
using System.Runtime.InteropServices;

public static int AddFontsFromResources(PrivateFontCollection fontCollection, string[] fontNames)
{
    int installedFontsCount = 0;
    if (fontNames.Length == 0) return 0;

    foreach (string fontName in fontNames) {
        try {
            byte[] fontData = (byte[])Properties.Resources.ResourceManager.GetObject(fontName);
            var data = Marshal.AllocCoTaskMem(fontData.Length);
            Marshal.Copy(fontData, 0, data, fontData.Length);
            fontCollection.AddMemoryFont(data, fontData.Length);
            installedFontsCount += 1;
        }
        catch (Exception) {
            // Placeholder: Notify User/Log/Whatever
            Console.WriteLine($"Font installation failed for {fontName}");
        }
    }
    return installedFontsCount;
}


text:
Q: Modifying a const int in C++ running the following code shows that &x=ptr, so how come x and *ptr are not equal?
const int x=10;
int* ptr =(int*) &x;
*ptr = (*ptr)+1;

cout << &x << " " << x << "  " << ptr <<"  " <<*ptr;  //output : 0012FF60 10  0012FF60  11

A: You're modifying an object declared const. This is undefined behavior; the program is not required to do anything sensible. It could appear to work fine, or give subtly wrong answers, or segfault, or execute arbitrary code supplied by an attacker. The usual hyperbole is that the program is allowed to make demons fly out your nose.

A: The C++ implementation is only required to make a program work if you obey the rules. You violated the rules. The C++ implementation likely behaved this way:

*

*Because x is declared const, the C++ implementation knows its value cannot change as long as you obey the rules. So, wherever x is used, the C++ implementation uses 10 without bothering to check whether x has changed.

*Because *ptr points to a non-const int, stores to it and reads from it are actually performed. These "work" because the memory it points to (where x is represented) is not actually marked read-only by the operating system. Thus, you are able to make modifications in spite of the fact that you are not supposed to.

Observe that the behavior of the C++ implementation would work if you obeyed the rules. If you had not modified x, then using 10 for x wherever it appeared would have worked normally. Or, if you had not declared x to be const, then the C++ implementation would not have assumed it would always be 10, so it would get the changed value whenever x was accessed. This is all the C++ standard requires of an implementation: That it work if you follow the rules.
When you do not follow the rules, a C++ implementation may break in seemingly inconsistent ways.


text:
Q: How do I distribute my Python 3.6 application with all dependencies like in SqueezeTool I have a python application that I built on Kivy for the GUI, and I separated that file from the RNN model. I just import that file directly with:
from keras_network import Network

I tried using the official trick to deploying using pyinstaller, but that doesn't work, as my application crashes, when running the final .exe file generated. I even made appropriate changes to the .spec file.
Isn't there an easier way to package this application in Python 3.6? (like SqueezeTool, which is too old, and isn't working in Python 3.6)
Can I compile the python files to .pyc files and have all dependencies statically linked? And why is this still such a big pain, when Python is so popular?

A: Ok... I finally got it to work.
I came up with this solution after I implemented the whole project in PyQt5, and while trying to package it with PyInstaller.
Here is how I got it to work (for people who could have any problems later):

*

*Used python 3.5

*Install Windows 10 SDK for some missing files that should've been with MSVC 2015.

*Install the dev version PyInstaller from:
pip install https://github.com/pyinstaller/pyinstaller/archive/develop.zip --upgrade

*Used the command to include my data files, as well as including hidden import h5py:
pyinstaller --add-data keras_model.h5;. --add-data TrainingData.txt;. --hidden-import=h5py --hidden-import=h5py.defs --hidden-import=h5py.utils --hidden-import=h5py.h5ac --hidden-import=h5py._proxy project-name.py

*Then edited the .spec file generated. Added "from kivy.deps import sdl2, glew" without the quotes in the beginning of the file after the comment. Also added "*[Tree(p) for p in (sdl2.dep_bins + glew.dep_bins)]," without the quotes in the COLLECT() function call as the 6th argument.

*Then used the following command to rebuild using .spec file:
pyinstaller --add-data keras_model.h5;. --add-data TrainingData.txt;. --hidden-import=h5py --hidden-import=h5py.defs --hidden-import=h5py.utils --hidden-import=h5py.h5ac --hidden-import=h5py._proxy project-name.spec
Then the built application's executable was present in the 'dist\project-name\' directory. Double clicking the application lead to the application executing perfectly.
Hope this helps anyone stuck in the same place.


text:
Q: 'itemImage1' has a SelectedValue which is invalid because it does not exist in the list of items. Parameter name: value I have a problem with this exception in my website itemImage1 has a SelectedValue which is invalid because it does not exist in the list of items.
Parameter name: value.
To summarize the code, I have two radio buttons called guitar and bass. If the admin select guitar, it will then generate the specified file path and look for the images within the location. It will then display the available images in the dropdownlist. Same goes for bass but with a different location.
My first try with the code, as I select the guitar radiobutton, it worked perfectly and displays the available images in the dropdownlist. But when I change to the bass radio button, it is giving me the exception that I have mentioned above.
I have tried unbinding it by setting the datasource and selectedvalue to null, clearing the items and setting the SelectedIndex to -1, but it still isn't working. Where am I going wrong?
Here is the code:
protected void Page_Load(object sender, EventArgs e)
{
    ShowItemImages();
}

private void ShowItemImages()
{
    var imageList = new ArrayList();
    if (itemType1.Checked)
    {
        itemImage1.Items.Clear();
        itemImage2.Items.Clear();
        itemImage1.SelectedIndex = -1;
        itemImage2.SelectedIndex = -1;
        itemImage1.SelectedValue = null;
        itemImage2.SelectedValue = null;
        itemImage1.DataSource = null;
        itemImage1.DataBind();
        itemImage2.DataSource = null;
        itemImage2.DataBind();
        itemselectedValueGuitar1 = itemImage1.SelectedValue;
        itemselectedValueGuitar2 = itemImage2.SelectedValue;
        var images = Directory.GetFiles(Server.MapPath("~/Images/Brands/String Instrument Items/Guitar/"));
        foreach (var image in images)
        {
            var imageName = image.Substring(image.LastIndexOf(@"\") + 1);
            imageList.Add(imageName);
        }
        itemImage1.DataSource = imageList;
        itemImage1.DataBind();
        itemImage2.DataSource = imageList;
        itemImage2.DataBind();
        itemImage1.SelectedValue = itemselectedValueGuitar1;
        itemImage2.SelectedValue = itemselectedValueGuitar2;
    }
    else if (itemType2.Checked)
    {
        itemImage1.Items.Clear();
        itemImage2.Items.Clear();
        itemImage1.SelectedIndex = -1;
        itemImage2.SelectedIndex = -1;
        itemImage1.SelectedValue = null;
        itemImage2.SelectedValue = null;
        itemImage1.DataSource = null;
        itemImage1.DataBind();
        itemImage2.DataSource = null;
        itemImage2.DataBind();
        itemselectedValueBass1 = itemImage1.SelectedValue;
        itemselectedValueBass2 = itemImage2.SelectedValue;
        var images = Directory.GetFiles(Server.MapPath("~/Images/Brands/String Instrument Items/Bass/"));
        foreach (var image in images)
        {
            var imageName = image.Substring(image.LastIndexOf(@"\") + 1);
            imageList.Add(imageName);
        }
        itemImage1.DataSource = imageList;
        itemImage1.DataBind();
        itemImage2.DataSource = imageList;
        itemImage2.DataBind();
        itemImage1.SelectedValue = itemselectedValueBass1;
        itemImage2.SelectedValue = itemselectedValueBass2;
    }
}

Here is the aspx code:

     Item Type:

         <asp:RadioButton ID="itemType1" runat="server" Text="Guitar" AutoPostBack="True" GroupName="ItemType"/>
         <asp:RadioButton ID="itemType2" runat="server" Text="Bass" AutoPostBack="True" GroupName="ItemType"/>

         Item Image1:

         <asp:DropDownList ID="itemImage1" runat="server" Width="300px">
         </asp:DropDownList>

         <asp:FileUpload ID="itemFileUpload1" runat="server" />
         <asp:Button ID="itemUploadImage1" runat="server" Text="Upload Image" OnClick="itemUploadImage1_Click"/>

         Item Image2:

         <asp:DropDownList ID="itemImage2" runat="server" Width="300px"></asp:DropDownList>

         <asp:FileUpload ID="itemFileUpload2" runat="server" />
         <asp:Button ID="itemUploadImage2" runat="server" Text="Upload Image" OnClick="itemUploadImage2_Click"/>


text:
Q: QMessage while waiting for a ping command response I'm doing a ping to an IP address, and I want to show into a QMessageBox that a ping operation is going on. After that, if a response is received or one second timeout happens, I want to close the QMessageBox.
Code:
int status;
QByteArray command;
QMessageBox myBox(QMessageBox::Information, QString("Info"), QString("Checking connection"), QMessageBox::NoButton, this);

command.append("ping -w 1 172.22.1.1");
status=system(command);
myBox.setStandardButtons(0);
myBox.exec();
if (0==status){ // Response received
    // Some stuff here...
    myeBox.setVisible(false);
}
else { // Timeout
    // Some other stuff here...
    myBox.setVisible(false);
}

My guess is that I may need to use threads for this task, but since I am a Qt newbie maybe the problem is anywhere else.
EDIT:
As @atamanroman suggested I've tried to use QProcess, using signal void QProcess::finished ( int exitCode, QProcess::ExitStatus exitStatus ) [signal] as told in Qt reference:
private:
QProcess *process;
//...

      QMessageBox myBox(QMessageBox::Information, QString("Info"), QString("Checking connection"), QMessageBox::NoButton, this);
    QObject::connect(&process, SIGNAL(finished(int, QProcess::ExitStatus)), &myBox, SLOT(close()));
    command.append("ping -w 1 172.22.1.1");
    process.start(comdand);
        myBox.setStandardButtons(0);
        myBox.exec();

And it's not working. myBox is never closed. What's wrong?

A: You should use QProcess (start ping.exe and parse output) or QTcpSocket (do the ping yourself) instead of system() because they are part of Qt and can signal you when the ping has finished. Connect to that signal in order to hide your QMessageBox.

A: In your edit:
First:
QProcess *process; // This is a pointer, you don't need to add "&" in connect
                   // You should have called "process = new QProcess" before...
QMessageBox myBox; // This is an object, you need to add the "&" to connect;

We take out the first &
QObject::connect(process, SIGNAL(finished(int, QProcess::ExitStatus)), &myBox, SLOT(close()));

second:
Using Linux ping will never stop, then you will never have the finished signal. You can provide ping some parameters like count or time to wait. Or start a timer to stop the process.
third:
You need to match the parameters between signals and slots to avoid warnings, etc.
I sugest you to create a local SLOT "processfinished(int, QProcess::ExitStatus)" and then you call to myBox.Close(), but "myBox" must be from class to have reference to this after end the method where you call it.


text:
Q: Canon Registry Keys Remain after Uninstallation I have a Canon printer but have found that with it installed I can't correctly install MySQL (there are threads about this problem).  So I uninstalled the Canon files, reinstalled MySQL and found that the MySQL installation is creating Canon directories.  So I searched the registry and there are keys for Canon still there.
I worry about deleting every key that say Canon when I don't really understand what I'm deleting. Can anyone suggest a way to get the Canon registry keys removed?
Thanks in advance.

A: Typically I use Revo Uninstaller (not sure who makes it and I'm away from my rig, sorry) when removing Windows programs as it searches for both leftover configuration files and registry keys in addition to the standard uninstall process, leaving your machine a bit cleaner than just normally uninstalling.
But, at this point that is too late to help, which is where CCleaner (from Piriform, would link to it but I'm on my phone) can help you. It searches for dead registry keys and can remove them, and can perform a number of useful maintenance tasks as well.

A: I ended up searching the registry for the string 'webprint'.  There were a few entries and I deleted them, reinstalled MySQL and the directory structure looks correct.  I then reinstalled the Cannon files (though I did not install WebPrint) and everything is working fine at the moment.