text:
Q: ansible YAML regex filter I'm trying to extract guid value of API response, here is a sample of the response:
"api_request.json": {
        "message": "\"Role name 'mgmt-ALERTPUBLISHER-uuid-placeholder' is not compliant. Use 'mgmt-ALERTPUBLISHER-b7d445b08a96e7f19ff0ff005686cddd', or do not use a name of the format <service name>-<roletype>-<arbitrary value>.\""
    }

Here is my regex:
<div>\p{Any}*?</div>|[0-9a-f]{32}

How can I use regex with YAML?
I have only found regex_replace and regex_escape but not pure regex matcher.
http://docs.ansible.com/ansible/playbooks_filters.html#json-query-filter

A: The regex_replace should do the trick.
This is the code. I'm basically searching for the 'ALERTPUBLISHER-' string and cutting the 32-character string behind it, keeping it in a named group (just above the note) and using it afterwards in the output.
I noticed your API is in json, if you have the possibility it might be handy if you ask for an additional field with only the uuid string. That will be much more robust than any regex.
- hosts: localhost
  gather_facts: False

  vars:
    message: "\"Role name 'mgmt-ALERTPUBLISHER-uuid-placeholder' is not compliant. Use 'mgmt-ALERTPUBLISHER-b7d445b08a96e7f19ff0ff005686cddd', or do not use a name of the format <service name>-<roletype>-<arbitrary value>.\""

  pre_tasks:
  - debug:
      msg: "{{ message | regex_replace('^.*ALERTPUBLISHER-(?P<uuid>.{32}).*$', '\\g<uuid>') }}"

This gives me the following output
PLAY [localhost] *********************************************************************************************************************************************************************************************************************************************************************************************************************************************************

TASK [debug] *************************************************************************************************************************************************************************************************************************************************************************************************************************************************************
ok: [localhost] => {
    "msg": "b7d445b08a96e7f19ff0ff005686cddd"
}

PLAY RECAP ***************************************************************************************************************************************************************************************************************************************************************************************************************************************************************
localhost                  : ok=1    changed=0    unreachable=0    failed=0


text:
Q: How do I remove (unpublish) my app from Play Store? Every tutorial, example and even official google description is deprecated. The new layout does not have the feature button at the described position.

A: TL;DR: (As of September 2020)
Open the Play Console. Select an app. Select Release > Setup >Advanced settings. On the App Availability tab, select Unpublish.

From https://support.google.com/googleplay/android-developer/answer/9859350?hl=en&ref_topic=9872026:

When you unpublish an app, existing users can still use your app and
receive app updates. Your app won't be available for new users to find
and download on Google Play.
Prerequisites

*

*You have accepted the latest Developer Distribution Agreement.

*Your app has no errors that need to be addressed, such as failing to fill in the content rating questionnaire or provide details about your app's target audience and content.

*Managed publishing is not active for the app you want to unpublish.

To unpublish your app:
Open the Play Console. Select an app. Select Release > Setup > Advanced settings. On the App Availability tab, select Unpublish.

How to Disable Managed publishing

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to interpret the output of the CPLEX interactive optimizer? I have been using the CPLEX interactive optimizer to solve some linear programming problems. I generate the problem, use the read command from CPLEX, and then run optimize. For some problems, CPLEX produces a solution within an hour and I use write <filename> sol to obtain the complete solution. For some problems, however, it seems to get stuck after a point. The output I see looks like this:
       Nodes                                         Cuts/
   Node  Left     Objective  IInf  Best Integer    Best Bound    ItCnt     Gap
    .        .        .        .        .        .        .        .        .
    .        .        .        .        .        .        .        .        .
    .        .        .        .        .        .        .        .        .
Elapsed time = 816.06 sec. (429933.56 ticks, tree = 8.58 MB, solutions = 13)
   2884  1809       87.6482 12159      201.6200       80.3540  2100428   60.15%
   2938  1863      102.4825 11621      201.6200       80.3540  2149201   60.15%
   3727  2616       93.1194 10858      201.6200       80.3540  2409711   60.15%
   3743  2632       92.6249 11845      201.6200       80.3540  2437316   60.15%
   3767  2656       91.7097 12044      201.6200       80.3540  2466252   60.15%
   3803  2692       91.8088 11972      201.6200       80.3540  2491113   60.15%
   3805  2694      101.4411 10242      201.6200       80.3540  2497951   60.15%
   3827  2716       91.7697 12003      201.6200       80.3540  2522926   60.15%
   3937  2826      102.6357  7167      201.6200       80.3540  2676145   60.15%
   4175  3056       94.0081  9159      201.6200       83.9275  2783878   58.37%
Elapsed time = 930.33 sec. (472066.00 ticks, tree = 20.04 MB, solutions = 13)
   4178  3059       88.0621 11735      201.6200       83.9275  2788962   58.37%
   4190  3071       87.5922 11461      201.6200       83.9275  2809216   58.37%
   4202  3083       87.7980 11585      201.6200       83.9275  2823899   58.37%
   4214  3095       87.9296 11733      201.6200       83.9275  2841065   58.37%
   4215  3096       92.6440 11647      201.6200       83.9275  2844197   58.37%
   4227  3108       94.0457 12069      201.6200       83.9275  2869047   58.37%
   4239  3119       93.3760 11843      201.6200       83.9275  2890566   58.37%
   4251  3131       94.2709 11724      201.6200       83.9275  2916710   58.37%
   4274  3153       92.6187 11640      201.6200       83.9275  2945659   58.37%
   4286  3163       91.6257 11632      201.6200       83.9275  2965344   58.37%
Elapsed time = 998.66 sec. (493988.99 ticks, tree = 20.09 MB, solutions = 13)
   4310  3186       91.8091 10453      201.6200       83.9275  3010401   58.37%
   4323  3199       96.4584 11813      201.6200       83.9275  3034842   58.37%
   4335  3211       96.1343 11849      201.6200       83.9275  3057500   58.37%
   4359  3234       96.8602 11609      201.6200       83.9275  3092422   58.37%

In the beginning, the last column has a higher number (e.g., 99.92%), which starts decreasing quickly. But after a certain point, the last gap column keeps stating 58.37% without further reduction. What does this value signify? My understanding is that this is the percentage difference between the current optimal solution and the global optimum. (i.e., x% means that if I stop the optimization at this point, the solution returned is provably within x% of the global optimum).
Is my understanding correct? Also, what can I do to understand and debug/get-around this phenomenon of "getting stuck"?

A: The % gap is the relative difference between the best solution and the best known bound for a solution.  This is guaranteed to be higher than the gap between the best known solution and the true global optimum.  In your case, the best bound is 83.9275, the best bound is 201.62, and you are minimizing so the gap is
1 - (83.9275 / 201.62)  =  .5837

The "stuck" behavior you see is quite common when solving a difficult mixed-integer problem.  It's possible that the solution you have is actually close to optimal, but the bound isn't tight, or that your solution is truly far the optimal, but CPLEX is unable to find anything better.  There are a lot of methods for trying to solve this problem.  Among them are

*

*Improve your MIP formulation

*Try different parameters (turn up cuts, probing, switch to strong branching, ...)

*See if another solver works better on your problem (gurobi or xpressmp)


text:
Q: Selectively copy ndarray rows with prange in Cython I have a question about a relatively operation I've written in Cython that I'd like to parallelize, but I haven't found any documentation or questions that seem to point in the right direction.
Simply, I want to copy a subset of one array into another array depending on a condition.
I have a large matrix of points, and for each of them I want to check if it's within a certain distance of a center point, and if so, copy it into my results matrix. out_points has been allocated to the same size as the input extent_points, so that I know it will fit. All variables are cdef'ed as ints and ndarrays as appropriate.
for pp in range(extent_points.shape[0]):
    meets_condition = 1
    for ii in range(extent_points.shape[1]): # check if in bounds
        if extent_points[pp,ii] < (epicenter[ii] - radius) or \
           extent_points[pp,ii] > (epicenter[ii] + radius):
            meets_condition = 0; break
    if meets-condition == 1: # if in bounds, then copy to output matrix
        for ii in range(extent_points.shape[1]):
            out_points[out_count,ii] = extent_points[pp,ii]
        out_count += 1
return out_points[:out_count, :]

It seems like it should be embarrasingly parallel to check this condition on each of my many points in parallel, but it's unclear to me how to parallelize the copy. Should I just mark a  column on the input if it shouldn't be copied and then iterate over again and copy? Is there more prange() documentation besides the short Cython user guide page and the wiki page?


text:
Q: How to import file to a custom form with custom DAC in Acumatica I am having trouble importing a CSV to my custom grid containing a custom DAC.
I have managed to get the import functionality and got the process to the point where it imports the first line in the file only. I cannot see why the caches only contain the one entry from the file.
My code:
Graph:
public class MyClassProcess : PXGraph<MyClassProcess>, PXImportAttribute.IPXPrepareItems
{
    [PXImport(typeof(MyDAC))]

    public PXSelect<MyDAC> CustomersView;

    public MyClassProcess()
    {
        PXCache entry = CustomersView.Cache;

        PXUIFieldAttribute.SetVisible<MyDAC.id>(entry, null, false);

        entry.AllowInsert = true;
        entry.AllowUpdate = true;
        entry.AllowDelete = true;

    }

    protected virtual IEnumerable customersView()
    {
        List<MyDAC> list = new List<MyDAC>();

        foreach (MyDACitem in CustomersView.Cache.Inserted)
        {
            list.Add(item);
        }

        return list;
    }

DAC:
[Serializable]
public class MyDAC: IBqlTable
{
    #region Id

    public abstract class id : IBqlField { }
    protected int? _ID;
    [PXDBInt(IsKey = true)]
    [PXUIField(DisplayName = "ID")]
    public virtual int? ID { get; set; }

    #endregion

    #region Selected
    public abstract class selected : IBqlField
    {
    }
    protected bool? _Selected = false;
    [PXDBBool()]
    [PXDefault(false, PersistingCheck = PXPersistingCheck.Nothing)]
    [PXUIField(DisplayName = "Selected")]
    public virtual bool? Selected
    {
        get
        {
            return _Selected;
        }
        set
        {
            _Selected = value;
        }
    }
    #endregion

    #region CustomerID
    public abstract class customerID : IBqlField { }
    protected string _CustomerID;
    [PXDBString(20, IsFixed = true, IsUnicode = true, InputMask = "")]
    [PXUIField(DisplayName = "Account ID")]
    public virtual String CustomerID { get; set; }
    #endregion

    #region CustomerCD
    public abstract class customerCD : IBqlField { }
    protected string _CustomerCD;
    [PXDBString(50, IsFixed = true, IsUnicode = true, InputMask = "")]
    [PXUIField(DisplayName = "Account Name")]
    public virtual String CustomerCD { get; set; }
    #endregion

    #region PaymentMethodID
    public abstract class paymentMethodID : IBqlField { }
    protected string _PaymentMethodID;
    [PXDBString(10, IsFixed = true, IsUnicode = true, InputMask = "")]
    [PXUIField(DisplayName = "Payment method")]
    public virtual String PaymentMethodID { get; set; }
    #endregion

    #region Cashaccount
    public abstract class cashaccount : IBqlField { }
    protected int? _CashAccount;
    [PXDBInt()]
    [PXUIField(DisplayName = "Cashaccount")]
    public virtual int? Cashaccount { get; set; }
    #endregion

    #region Currency
    public abstract class currency : IBqlField { }
    protected string _Currency;
    [PXDBString(10, IsFixed = true, IsUnicode = true, InputMask = "")]
    [PXUIField(DisplayName = "Currency")]
    public virtual String Currency { get; set; }
    #endregion
}

Aspx:
<asp:Content ID="cont1" ContentPlaceHolderID="phDS" Runat="Server">
<px:PXDataSource ID="ds" runat="server" Visible="True" Width="100%"
    TypeName="MyNamespace.MyClassProcess"
    PrimaryView="CustomersView"
    >
    <CallbackCommands>

    </CallbackCommands>
</px:PXDataSource>
</asp:Content>
<asp:Content ID="cont2" ContentPlaceHolderID="phL" runat="Server">
<px:PXGrid ID="grid" runat="server" DataSourceID="ds" Width="100%" Height="150px" SkinID="Primary" AllowAutoHide="false">
    <Levels>
        <px:PXGridLevel DataMember="CustomersView">
            <Columns>
                <px:PXGridColumn Type="CheckBox" TextAlign="Center" DataField="Selected" Width="60" ></px:PXGridColumn>
                <px:PXGridColumn DataField="ID" Width="90" ></px:PXGridColumn>
                <px:PXGridColumn DataField="CustomerID" Width="90" ></px:PXGridColumn>
                <px:PXGridColumn DataField="CustomerCD" Width="150" ></px:PXGridColumn>
                <px:PXGridColumn DataField="PaymentMethodID" Width="90" ></px:PXGridColumn>
                <px:PXGridColumn DataField="Cashaccount" Width="90" ></px:PXGridColumn>
                <px:PXGridColumn DataField="Currency" Width="70" ></px:PXGridColumn>
                <%--<px:PXGridColumn DataField="CurrentBal" Width="70" ></px:PXGridColumn>--%>
            </Columns>
        </px:PXGridLevel>
    </Levels>
    <AutoSize Container="Window" Enabled="True" MinHeight="150" />
    <ActionBar >
    </ActionBar>

<Mode AllowUpload="True" /></px:PXGrid>

Data:
ID,Account ID,Account Name,Payment method,Cashaccount,Currency ID
1,C001,Customer name 1,EFT,8405,ZAR
2,C002,Customer2,EFT,8405,ZAR
3,C003,Customer 3,EFT,8405,ZAR
All customers, payment methods, cashaccounts, currencies exist in the system.
I have a table named the same as MyDAC.
PXCache entry = CustomersView.Cache;

And
foreach (MyDACitem in CustomersView.Cache.Inserted)
        {
            list.Add(item);
        }

Only shows 1 line as inserted even if there are two lines in the file. It imports this one line successfully into my grid, but not the other lines.
What am I missing.

A: Are you missing an IsKey=true in your DAC ?


text:
Q: form validation problems with jquery / javascript This is my first real project which involves form validation. I am experiancing a problem which I can not find the solution to.
The objective is this, there is a continue button which will be activated once all the field inputs have been passed as valid. I am going about this by creating seperate variables, all initially set as false, devoted to checking each input field. When the user has entered correct validation data, the variable is set to true.
I then run an if statement to check if all the variables are set to true, and if so, I activate the continue button which, when clicked, slides the next part of the form into the page.
HTML:

Step 3: Your Details

        <form action="" method="">

                Email:
                <input type="text" placeholder="Email Address" id="email" class="form-control your-details">

                Name:
                <input type="text" placeholder="Full Name" id="name" class="form-control your-details">

                Contact Number:
                <input type="text" placeholder="Contact Number" id="number" class="form-control your-details">

                Date of Birth:
                <input type="date" id="dob" class="form-control your-details">

                        </form>

                <input type="submit" id="submit" value="CONTINUE">

JAVASCRIPT / JQUERY:
//collection of input form fields//
    var formSubmit = $("#submit");
    var emailField = $("#email");
    var nameField = $("#name");
    var numberField = $("#number");

    //Switch to true when each validation has passed//
    emailValidated = false;
    nameValidated = false;
    numberValidated = false;

    //email validation check//
    emailField.on("input",function(){
        var emailInput = $(this).val()
        var testExp = new RegExp(/[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,3}$/);
        if (emailInput < 1) {
            $("#email-warning").html("Email is required!");
            $("#email-warning").css("visibility","visible");
            emailValidated = false;
        }

        else if (!testExp.test(emailInput)){
            $("#email-warning").html("Please enter a valid email");
            $("#email-warning").css("visibility","visible");
            emailValidated = false;

        }   else {
            $("#email-warning").css("visibility","hidden");
            emailValidated = true;
        }

        })

    //name validation check//
    nameField.on("input",function(){
        var nameInput = $(this).val()
        if (nameInput < 1) {
            $("#name-warning").html("Name is required");
            $("#name-warning").css("visibility","visible");
            nameValidated = false;
        } else {
            $("#name-warning").css("visibility","hidden");
            nameValidated = true;
        }

        })

    //contact number validation check//
    numberField.on("input",function(){
        var numberInput = $(this).val()

        if (typeof numberInput !== "number" && numberInput.length < 9) {
            $("#number-warning").html("Please enter a valid number");
            $("#number-warning").css("visibility","visible");
            numberValidated = false;
        } else {
            $("#number-warning").css("visibility","hidden");
            numberValidated = true;
        }

        })

    if (emailValidated && nameValidated && numberValidated){
        alert("correct");
        }

    })

at the moment, I am simply using the alert prompt to test if it is working, but it fails.
As mentioned, this is my first real form validation. Any other tips or advice would be greatly appreciated. Thanks for the help in advance.

A: There were a couple things that I found from copying pasting your snippets of code. 1 there was an ending "})" without a beginning $(document).ready(function(){ ". 2 none of your ".on" statements had an ending semi colon.
Here is my javascript with a small change

$(document).ready(function () {
    //collection of input form fields//
    var formSubmit = $("#submit");
    var emailField = $("#email");
    var nameField = $("#name");
    var numberField = $("#number");

    //Switch to true when each validation has passed//
    emailValidated = false;
    nameValidated = false;
    numberValidated = false;

    //email validation check//
    emailField.on("input", function () {
        var emailInput = $(this).val()
        var testExp = new RegExp(/[a-z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,3}$/);
        if (emailInput < 1) {
            $("#email-warning").html("Email is required!");
            $("#email-warning").css("visibility", "visible");
            emailValidated = false;
        }

        else if (!testExp.test(emailInput)) {
            $("#email-warning").html("Please enter a valid email");
            $("#email-warning").css("visibility", "visible");
            emailValidated = false;

        } else {
            $("#email-warning").css("visibility", "hidden");
            emailValidated = true;
            enableContinue();
        }

    });

    //name validation check//
    nameField.on("input", function () {
        var nameInput = $(this).val()
        if (nameInput < 1) {
            $("#name-warning").html("Name is required");
            $("#name-warning").css("visibility", "visible");
            nameValidated = false;
        } else {
            $("#name-warning").css("visibility", "hidden");
            nameValidated = true;
            enableContinue();
        }

    });

    //contact number validation check//
    numberField.on("input", function () {
        var numberInput = $(this).val()

        if (typeof numberInput !== "number" && numberInput.length < 9) {
            $("#number-warning").html("Please enter a valid number");
            $("#number-warning").css("visibility", "visible");
            numberValidated = false;
        } else {
            $("#number-warning").css("visibility", "hidden");
            numberValidated = true;
            enableContinue();
        }

    });

    enableContinue = function () {
        if (emailValidated && nameValidated && numberValidated) {
            $('#submit').prop('disabled', false);
        }
    }

});

Step 3: Your Details

            <form action="" method="">

                    Email:
                    <input type="text" placeholder="Email Address" id="email" class="form-control your-details">

                    Name:
                    <input type="text" placeholder="Full Name" id="name" class="form-control your-details">

                    Contact Number:
                    <input type="text" placeholder="Contact Number" id="number" class="form-control your-details">

                    Date of Birth:
                    <input type="date" id="dob" class="form-control your-details">

            </form>

            <input type="submit" class="btn btn-primary" id="submit" disabled="disabled" value="CONTINUE">

Your form CONTINUE button becomes enables once all fields have a value. Note: I did not try to improve your javascript any, just made it work.

A: Right now you synchronically check validation variables at script, so they are all false. You have to asynchronically check them after form submit. Just add event listener to form submit to check variables like this:
document.getElementById('#form').addEventListener('submit', function(){
    if (emailValidated && nameValidated && numberValidated){
      alert("correct");
    }
});

Don't forget to set id to your form.

A: You may be able to save a lot of work if you leverage some of the built in HTML5 form validation. https://developer.mozilla.org/en-US/docs/Learn/HTML/Forms/Form_validation
This simple example adds a new field every time you submit the form, as long as the existing fields are valid. You would need to test the state of the form to see if you should be adding another section or submitting.

$('form').on('submit', function() {
  $(this).find('fieldset').append('<input type="text" required />');
  return false;
});

<form>
  <fieldset>
    <input type="text" required />
  </fieldset>
  <input type="submit" id="submit" value="continue" />
</form>


text:
Q: .htaccess 301 redirect and remove .html combined I am trying to redirect all .html files form stripelatice_ui folder to root and remove .html extention
localhost:8089/stripelatice_ui/home.html

to
localhost:8089/home

i have tried using
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^\.]+)$ $1.html [QSA,NC,L]

RewriteRule ^stripelatice_ui/(.*)$ /$1 [R=301,NC,L]

but it is giving be error saying that the page has redirection loop

A: You can use:
RewriteEngine On
RewriteBase /stripelatice_ui/

# To externally redirect /stripelatice_ui/file.html to /file
RewriteCond %{THE_REQUEST} /stripelatice_ui/(.+?)\.html[\s?] [NC]
RewriteRule ^ /%1 [R=301,L,NE]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^([^.]+)/?$ $1.html [L]


text:
Q: How do I ensure that a call to subscribe on the observer initially receives the most recent value? I am using rxjs together with Angular 2 and Typescript. I would like to share a common web-resource (a "project" in the context of my app, essentially a JSON document) between multiple components. To achieve this I introduced a service that exposes an observable, which will be shared by all clients:
/**
 * Handed out to clients so they can subscribe to something.
 */
private _observable : Observable<Project>;

/**
 * Used to emit events to clients.
 */
private _observer : Observer<Project>;

constructor(private _http: Http) {
    // Create observable and observer once and for all. These instances
    // are not allowed to changed as they are passed on to every subscriber.
    this._observable = Observable.create( (obs : Observer<Project>) => {
        this._observer = obs;
    });
}

Clients now simply get a reference to that one _observable and subscribe to it.
/**
 * Retrieves an observable that always points to the active
 * project.
 */
get ActiveProject() : Observable<Project> {
    return (this._observable);
}

When some component decides to actually load a project, it calls the following method:
/**
 * @param id The id of the project to set for all subscribers
 */
setActiveProject(id : string) {
    // Projects shouldn't change while other requests are in progress
    if (this._httpRequest) {
        throw { "err" : "HTTP request in progress" };
    }

    this._httpRequest = this._http.get('/api/project/' + id)
        .catch(this.handleError)
        .map(res => new Project(res.json()));

    this._httpRequest.subscribe(res => {
        // Cache the project
        this._cachedProject = res;
        // Show that there are no more requests
        this._httpRequest = null;
        // Inform subscribers
        this._observer.next(this._cachedProject)

        console.log("Got project");
    });
}

It basically does a HTTP request, transforms the JSON document into a "proper" instance and calls this._observer.next() to inform all subscribers about the change.
But if something subscribes after the HTTP request has already taken place, the see nothing until a new HTTP request is issued. I have found out that there is some kind of caching (or replay?) mechanism in rxjs that seems to adress this, but I couldn't figure out how to use it.
tl;dr: How do I ensure that a call to subscribe on the observer initially receives the most recent value?
Extra question: By "pulling the observer out of the observable" (in the constructor), have I essentially created a subject?

A: That's what BehaviorSubject does
import { BehaviorSubject } from 'rxjs/subject/BehaviorSubject';
...
obs=new BehaviourSubject(4);
obs.subscribe(); //prints 4
obs.next(3); //prints 3
obs.subscribe(); //prints 3

A: I usually achieve this with shareReplay(1). Using this operator with 1 as parameter will ensure that the latest value emitted will be kept in a buffer, so when there is a new subscriber that value is immediately passed on to it. You can have a look at the documentation :
var interval = Rx.Observable.interval(1000);

var source = interval
    .take(4)
    .doAction(function (x) {
        console.log('Side effect');
    });

var published = source
    .shareReplay(3);

published.subscribe(createObserver('SourceA'));
published.subscribe(createObserver('SourceB'));

// Creating a third subscription after the previous two subscriptions have
// completed. Notice that no side effects result from this subscription,
// because the notifications are cached and replayed.
Rx.Observable
    .return(true)
    .delay(6000)
    .flatMap(published)
    .subscribe(createObserver('SourceC'));

function createObserver(tag) {
    return Rx.Observer.create(
        function (x) {
            console.log('Next: ' + tag + x);
        },
        function (err) {
            console.log('Error: ' + err);
        },
        function () {
            console.log('Completed');
        });
}

// => Side effect
// => Next: SourceA0
// => Next: SourceB0
// => Side effect
// => Next: SourceA1
// => Next: SourceB1
// => Side effect
// => Next: SourceA2
// => Next: SourceB2
// => Side effect
// => Next: SourceA3
// => Next: SourceB3
// => Completed
// => Completed
// => Next: SourceC1
// => Next: SourceC2
// => Next: SourceC3
// => Completed

Extra question: By "pulling the observer out of the observable" (in
  the constructor), have I essentially created a subject?

I am not sure what you mean by that, but no. A subject is both an observer and an observable and have specific semantics. It is not enough to 'pull the observer out of the observable' as you say. For subjects semantics, have a look here : What are the semantics of different RxJS subjects?


text:
Q: (FICO Xpress) Is it possible to specify the number of positive and negative results I would like to get via constraints? I am currently trying to create a model where the results of the objective function when applied to all rows in the problem will be used for recommendation purposes.
    !********************************************************************************
! 1. Import Modules
! 2. This part is used to define result format and directories
!********************************************************************************

model "savings portfolio"
    uses "mmxprs", "mmsheet"

parameters
    CAPITAL = 100000000
    INPUTFILE = "C:/Users/Admin/Downloads/201031_SAVINGS_ACCOUNTS3_v1.0.xlsx"! 3. File directory for data file
    RESULTFILE = "C:/Users/Admin/Downloads/201031_SAVINGRESULTS3_v1.0.xlsx"! 4. File directory for result file
end-parameters

!********************************************************************************
! 5. Declare variable types
! 6. Variable types as well as the mpvar must be declared first before importing data
!********************************************************************************
declarations
    INDEX: set of integer
    PRODUCTNAME: array(INDEX) of string
    MONTH: array(INDEX) of integer
    MONTH2: array(INDEX) of integer
    MININVEST: array(INDEX) of integer
    MININVEST2: array(INDEX) of integer
    PRINCIPAL: array(INDEX) of mpvar  ! 7. mpvar refers to the variable that is to be optimized
    PRINCIPAL2: array(INDEX) of mpvar
    INTEREST: array(INDEX) of real
    INTEREST2: array(INDEX) of real
end-declarations

!********************************************************************************
! 8. "XPRS_VERBOSE" settings: Enable to view problem statistics
!********************************************************************************
setparam("XPRS_VERBOSE", true)

!********************************************************************************
! 9. Read data
!********************************************************************************
initializations from "mmsheet.xlsx:"+INPUTFILE
    [PRODUCTNAME,INTEREST,MONTH,MININVEST,INTEREST2,MONTH2,MININVEST2] as "[Sheet1$A2:H501]" !10.Select data from excel sheet excluding headers, must include index column
end-initializations

!********************************************************************************
! 11. Calculating YEAR
!********************************************************************************
forall(i in INDEX) YEAR(i):=MONTH(i)/12
forall(i in INDEX) YEAR2(i):=MONTH2(i)/12

!********************************************************************************
! 12. Objective Function
!********************************************************************************
SUMDIFF:=sum(i in INDEX) (PRINCIPAL(i)*(1+(INTEREST(i)/MONTH(i)))^(MONTH(i)*getsol(YEAR(i))) - PRINCIPAL2(i)*(1+(INTEREST2(i)/MONTH2(i)))^(MONTH2(i)*getsol(YEAR(i))))

!********************************************************************************
! 13. Constraints
!********************************************************************************
sum(i in INDEX) PRINCIPAL(i) = CAPITAL
sum(i in INDEX) PRINCIPAL2(i) = CAPITAL
forall(i in INDEX) PRINCIPAL(i) >= MININVEST(i)
forall(i in INDEX) PRINCIPAL2(i) >= MININVEST2(i)
SUMDIFF >= 0

!********************************************************************************
! 14. Optimization method
!********************************************************************************
maximize(SUMDIFF)

!********************************************************************************
! 15. Calculate variables
!********************************************************************************
forall(i in INDEX) PRINSTANDIFF(i):=(getsol(PRINCIPAL(i))*(1+(INTEREST(i)/MONTH(i)))^(MONTH(i)*getsol(YEAR(i)))) - (getsol(PRINCIPAL2(i))*(1+(INTEREST2(i)/MONTH2(i)))^(MONTH2(i)*getsol(YEAR(i))))
forall(i in INDEX) INVESTMENT1(i):=getsol(PRINCIPAL(i))
forall(i in INDEX) INVESTMENT2(i):=getsol(PRINCIPAL2(i))

initializations to "mmsheet.xlsx:"+RESULTFILE
    [PRODUCTNAME,INVESTMENT1,INVESTMENT2,PRINSTANDIFF] as "grow;[Sheet1$A2:E2]"
end-initializations

end-model

The purpose of this model is to use the values in PRINSTANDIFF to decide which option to invest in. If the resulting value is positive, Option 1 (INVESTMENT1) is the better option whereas if the value is negative, Option 2 (INVESTMENT2) is the better option.
My question is, is there a way to control the number of positive values and negative values I can get from the model via constraints? I would ideally like to keep the number of positives and negatives at a minimum ratio of 6:4 and a maximum ratio of 7:3.

A: Elaborating on my comment and turning it into an answer: Tasks like the one you describe can be achieved by indicator constraints.
The idea is to introduce binary helper variables that are 1 if an expression is positive and 0 if it is negative:
declarations
    SIGN: array(INDEX) of mpvar
end-declarations
forall(i in INDEX) SIGN(i) is_binary

and then connect those with the sign of an expression via indicator constraints
forall(i in INDEX) indicator(1, SIGN(i), EXPR(i) >= 0)
forall(i in INDEX) indicator(-1, SIGN(i), EXPR(i) <= 0)

With this, SIGN(i) is 1 if EXPR(i) is non-negative and SIGN(i) is 0 if EXPR(i) is non-positive.
Now you can write the number of positive expressions as sum(i in INDEX) SIGN(i) and the number of negative expressions as sum(i in INDEX) (1 - SIGN(i)). Thus a ratio on the two can be enforced via
4 * sum(i in INDEX) SIGN(i) >= 6 * sum(i in INDEX)(1 - SIGN(i)) ! minimum ratio: sum_of_positive/sum_of_negative >= 6/4
3 * sum(i in INDEX) SIGN(i) <= 7 * sum(i in INDEX)(1 - SIGN(i)) ! maximum ratio: sum_of_positive/sum_of_negative <= 7/3

The only problem left is to define EXPR(i) appropriately as an expression in mpvars. This may be an issue here since it seems to involve some non-linearities.


text:
Q: Hibernate Session closings with Hadoop I'm an intermediate Hibernate user. I am trying to get some traction with Hadoop at my company. I'm using a library called spring-hadoop (https://github.com/SpringSource/spring-hadoop) to configure my application and inject my dependencies.
I'm having a lot of trouble getting Hadoop to respect my hibernate sessions. I'm hitting the legendary LazyInitializationException.

org.hibernate.LazyInitializationException:
  could not initialize proxy - no
  Session   at
  org.hibernate.proxy.AbstractLazyInitializer.initialize(AbstractLazyInitializer.java:108)
    at
  org.hibernate.proxy.AbstractLazyInitializer.getImplementation(AbstractLazyInitializer.java:150)
    at
  org.hibernate.proxy.pojo.cglib.CGLIBLazyInitializer.invoke(CGLIBLazyInitializer.java:150)
    at
  p.model.ServicePoint$$EnhancerByCGLIB$$181013ec.getReadResolution()
    at
  p.service.ResourceService.getStartDate(ResourceService.java:77)

Resolution is a lazy init field on a ServicePoint object that is retrieved with hibernate in the first part of the map task.
The exception is thrown later on in the map task when I try to work with the ServicePoint object. It is not thrown in the reduce task. Modifying the ServicePoint hibernate mapping is not an option.
I've tried a bunch of approaches suggested by my giant "Java Persistencee with Hibernate" book such as:

*

*Opening a session at the beginning of Map:

Session session =
  this.sessionFactory.openSession();
  session.beginTransaction();

*Adding stuff like this to my sessionFactory bean:

prop key="hibernate.connection.release_mode">on_close < /prop>

Before i pull out all stops and try stuff like Conversation Interceptors, can anyone give me a suggestion ? Nothing works and the exception keeps coming.


text:
Q: Could not find schema information for the attribute - Web.config I've discovered wierd messages in my Error list.
I got 28 messages for different attributes in my Web.config file saying:
Could not find schema information for the attribute '___'

With elements like

*

*configSource

*BaseRestExtensions

*log4net

*security

*settings

*umbracoConfiguration

and more!
I had a problem logging in with Umbraco and my guess is that this could be occouring the problem. What is this? Why is this happening? And how do i solve this?
THANKS


text:
Q: PHP rewrite rule as database values I need to rewrite
www.example.com/folder/35467/title.html onto
www.example.com/folder/?id=35467

id and title comes from the database. I'm gona put the htaccess file into the "folder".

A: .htaccess
<IfModule mod_rewrite.c>

    Options +FollowSymLinks
    RewriteEngine on

############################################
## you can put here your script root folder
## path relative to web root

    RewriteBase /

############################################
## never rewrite for existing files, directories and links

    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-l

############################################
## rewrite everything else to index.php

    RewriteRule .* index.php [L]

</IfModule>

index.php
list (,,$id,$title) = explode('/', $_SERVER['REQUEST_URI']);
$link = 'www.example.com/folder/?id='. $id;

A: If the htaccess file is going to be in /folder/ then you need these rules:
RewriteEngine On
RewriteBase /folder/
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^([0-9]+)/(.*)\.html ?id=$1 [L]

To redirect access with the id query string, you can check the $_SERVER['REQUEST_URI'] variable in your index.php.
if ( !strpos($_SERVER['REQUEST_URI'],'.html') ) {
    // The request that was made wasn't with the nicer looking URL
    header("Location: /folder/$id/$title.html");
    exit();
}


text:
Q: Using Java 8 with LibGDX I'm writing a game in Java using LibGDX, with only desktop as the targeted platform. I just created a new LibGDX project, and imported some existing code into it, but now I'm getting a few errors. Specifically, using the diamond operator. For example, this line of code:
HashMap<String, Integer> connectionsMap = new HashMap<>();

is generating this error:
Error:(20, 37) java: diamond operator is not supported in -source 1.6
(use -source 7 or higher to enable diamond operator)

Ideally, I'd like to use Java 8. The Gradle files in the module I imported were preserved, so I changed the sourceCompatibility line in all the other build.gradle files throughout the project from 1.6 to 1.8, and I made sure that in the Project Structure > Project > Language Level was set to Java 8. However, I'm still getting this issue. What else do I need to change for my project to use Java 8?

A: If you're using IntelliJIDEA, make changes in three places.

*

*sourceCompatibility = 1.8 in build.gradle file of all modules

*Project Structure > Project > Language Level

*Project Structure > Modules > Sources Tab on all modules > Language Level


text:
Q: Visual Studio PowerShell Making Listbox DragDrop files Usable I have set a listbox up in my Windows Form where i can drag and drop files into it, the first thing i want to achieve is to show filename only not the Path, please see below my code block.
$handler = {
  $_.Data.GetFileDropList() | % {
    $listbox1.Items.Add($_)
  }
}
$listbox1.AllowDrop = $true
$listbox1.Add_DragEnter({$_.Effect = [Windows.Forms.DragDropEffects]::Copy})
$listbox1.Add_DragDrop($handler)

the second objective is to be able to run my PowerShell combine .pdf script within the listbox1.

my .pdf combine script is below
$button2_Click = {

$pdftk = "C:\Program Files (x86)\PDFtk Server\bin\pdftk.exe"
$inputFolder = "E:\SIGNEDNOTES"
$outputFolder = "E:\out\"

$IntactScan = Get-ChildItem $inputFolder -File | Measure-Object | % {$_.Count}

If ($IntactScan -gt $maxItems) {

   Get-Childitem $inputFolder -filter *.pdf -Recurse
   pdftk "E:\SIGNEDNOTES\*.pdf" cat Output $outputFolder\Rename.pdf

   Move-Item "E:\SIGNEDNOTES\*.pdf" "E:\Backup\"
}
else {
    exit
}
}

basically i want the user to be able to drag 2 x pdf files into the listBox1 and press the combine button and that outputs the combined .pdf to the second listBox2

A: As mentioned in the comments, the only way to show something different than the actual underlying item value is to use the DataSource/DisplayMember properties rather than adding file names directly to Items:
# Create datatable to hold the dragged files
$droppedFiles = [System.Data.DataTable]::new()
[void]$dt.Columns.Add('Name')
[void]$dt.Columns.Add('Value')

# ...
# Instruct the box to get the items from the datatable and use the `Name` column for displaying entries
$listbox1.DataSource = $droppedFiles
$listbox1.DisplayMember = 'Name'

And then, in your drop handler:
$handler = {
  $_.Data.GetFileDropList() | % {
    $name = (Get-Item $_).Name
    $droppedFiles.Add([pscustomobject]@{Name = $name; Value = $_})
  }
  $listbox1.Refresh()
}

You can still use Items for read-only access to the items provided by the data table

A: Regards to my first question this is on going but the less important one out the 2
i solved the other one question (combine 2 pdfs from listBox) by code below

$pdftk = "C:\Program Files (x86)\PDFtk Server\bin\pdftk.exe"
$inputFolder = $listbox1.Items
$outputFolder = "E:\out"

$CountyCount = Get-ChildItem $inputFolder -File | Measure-Object | % {$_.Count}

If ($CountyCount -gt $maxItems) {

   Get-Childitem $inputFolder -filter *.pdf -Recurse
   pdftk $listbox1.Items cat Output $outputFolder\Combine.pdf

    $listbox1.Items.Clear()

    #Move-Item "E:\SIGNEDNOTES\*.pdf" "E:\Backup\"
}
else {
    exit
}

}```

thank you for your help


text:
Q: Spring Integration - Control sftp polling using a boolean flag for sftp inbound adaptor Is there a way in spring integration sftp adaptor to control the polling based on a boolean flag?
Example

*

*boolean flag = true, then poll the directory, and get the file.

*boolean flag = false, then do not poll the directory.

A: See AbstractPollingEndpoint:
/**
 * Configure a cap for messages to poll from the source per scheduling cycle.
 * A negative number means retrieve unlimited messages until the {@code MessageSource} returns {@code null}.
 * Zero means do not poll for any records - it
 * can be considered as pausing if 'maxMessagesPerPoll' is later changed to a non-zero value.
 * The polling cycle may exit earlier if the source returns null for the current receive call.
 * @param maxMessagesPerPoll the number of message to poll per schedule.
 */
@ManagedAttribute
public void setMaxMessagesPerPoll(long maxMessagesPerPoll) {

It is also explained in docs: https://docs.spring.io/spring-integration/docs/current/reference/html/core.html#conditional-pollers

Starting with version 5.5, a 0 value for max-messages-per-poll has a special meaning - skip the MessageSource.receive() call altogether, which may be considered as pausing for this inbound channel adapter until the maxMessagesPerPoll is changed to a non-zero value at a later time, e.g. via a Control Bus.

You can also do such a control via MessageSourceMutator advice injected into the poller configuration. That one has this method to implement:
/**
 * Subclasses can decide whether to proceed with this poll.
 * @param source the message source.
 * @return true to proceed (default).
 */
default boolean beforeReceive(MessageSource<?> source) {


text:
Q: How to change the size of a Datagrid Scrollbar? I have a Datagrid that displays the  data on Runtime, and as it has lot of data it itself brings scrollbar on it, but the size is smaller. Can anyone tell how to change size of scrollbar and make it bigger ?
<DataGrid x:Name="DgUnitVerReefer" HorizontalAlignment="Center" SelectionMode="Single"      SelectionUnit="FullRow" Margin="20,94,26,0" IsReadOnly="True" AutoGenerateColumns="False"     Visibility="Visible" VerticalAlignment="Top" Height="334"      HorizontalGridLinesBrush="#FFA4C4EA" FontFamily="Microsoft New Tai Lue" AlternatingRowBackground="#FFA4C4EA" MouseDoubleClick="DgUnitVerReefer_MouseDoubleClick" FontSize="16" Width="387">
        <DataGrid.Columns>
            <DataGridTextColumn Header="" Binding="{Binding Path= UNIT_NUMBER}" Width="350" />
        </DataGrid.Columns>
</DataGrid>

and then on window_loaded in load data and assign to datagrid.
   DgUnitVerReefer.DataContext = objVerifyUnit.DtLovReefer.DefaultView;
   DgUnitVerReefer.ItemsSource = objVerifyUnit.DtLovReefer.DefaultView;
   DgUnitVerReefer.DisplayMemberPath = "UNIT_NUMBER";
   DgUnitVerReefer.SelectedValuePath = "UNI_ID";

on running it display scrollbar with smaller size, how to change its size ?

A: King King solution doesn't work if you want to reduce the width of the ScrollBar. In this case you also should set the MinWidth property.
An other solution based on this response is to modify the SystemParameters.VerticalScrollBarWidth property:
<DataGrid.Resources>
    <system:Double x:Key="{x:Static SystemParameters.VerticalScrollBarWidthKey}">5</system:Double>
</DataGrid.Resources>

A: You can apply style for the ScrollBar type at the DataGrid level. We should use a Trigger against the Orientation property to apply style to the vertical scrollbar only:
<DataGrid.Resources>
    <Style TargetType="ScrollBar">
        <Style.Triggers>
            <Trigger Property="Orientation" Value="Vertical">
                <Setter Property="Width" Value="50"/>
            </Trigger>
        </Style.Triggers>
    </Style>
</DataGrid.Resources>

For horizontal scrollbar, we need to set the Height instead, and the Value for the trigger is Horizontal.


text:
Q: Setting rootviewcontoller in AppDelagate after deleting SceneDelegate I deleted SceneDelegate.swift and deleted related entry from .plist file.
Since my project doesn't support iPad, I won't need any SceneDelegate thing. Am I right?
I use SwiftUI so there is also no Storyboard
Now in AppDelegate file
var window: UIWindow?

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {

        self.window = UIWindow(frame: UIScreen.main.bounds)

  if (TegKeychain.get("ISLOGGEDIN") == "1") {

           //present WelcomeScreen.swift

        } else {

            //present Login.Swift
        }

        return true
    }

Other files
struct Login: View {
    var body: some View {
        Text("Login")
    }
}

struct WelcomeScreen: View {
    var body: some View {
        Text("WelcomeScreen")
    }
}

I searched the web and was not able to find any helpful info about how to present a view controller without a storyboard.

A: Here is check-list of what I have done to rollback scenes support from new SwiftUI iOS project created from template:

*

*Remove UIApplicationSceneManifest key from Info.plist

*Remove all scene session related delegate methods from AppDelegate

*Remove SceneDelegate

*Updated AppDelegate as follows
    import UIKit
    import SwiftUI

    @UIApplicationMain
    class AppDelegate: UIResponder, UIApplicationDelegate {

        var window: UIWindow?

        func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
            let contentView = ContentView() // << default Hello World

            // Use a UIHostingController as window root view controller.
            let window = UIWindow(frame: UIScreen.main.bounds)
            window.rootViewController = UIHostingController(rootView: contentView)
            self.window = window
            window.makeKeyAndVisible()

            return true
        }

    }

*Build & Run - works.


text:
Q: In triangle with incircle prove that $\overline{CQ}$ is parallel to $\overline{AB}$
We are given a triangle $ABC$ whose incircle touches side $AB$ at point $D$ and side $AC$ at point $E$.
  Point $P$ lies on segment $AC$ such that segment $IP$ is parallel to the segment $DE$, where $I$ is center of incircle. Lines $DE$ and $BP$ intersect at point $Q$.
Prove that $CQ$ is parallel to $AB$.

I tried angle chasing, then some ideas with new special points, lines etc, but it doesn't give any solution. I would like any advice, any help. No solution.

A:
Let us introduce a couple of additional points: $F$, as the intersection between $BC$ and the incircle; $R$, as the antipode of $D$ in the incircle. $PRI$ and $PEI$ are congruent and it is not difficult to check that $Q,R,F$ are collinear. Can you show $AB\parallel PR\color{red}{\parallel} QC$ by invoking Pascal's (or Brianchon's) theorem?


text:
Q: Replace leading zeros in a string with a maximum of three in Javascript I am currently writing a method to check for the existence of 3 leading zeros in a string and if they exist to strip them from said string. I have the following logic which is pretty straightforward but I need to ensure that anything after the three digits are kept, even if the 4th character is a zero. I am getting passed strings from a message queue which add these 3 zeros on in some circumtances so the existence of a 0 in the 4th position is entirely valid and needed to be kept. What would be the best way of doing this?
const string = '0000443212334';
string.replace(/^0+/, '');

As you can see, this will remove the 4th digit too (as it is a zero) which is unwanted.

A: You can change the regex a bit,
string.replace(/^[0]{3}/, '');


text:
Q: How do I turn an array of strings into property names on the type level? Given the function
function invert(arr: string[]) {
  let result = {};

  arr.forEach((x, i) => {
    result[x] = i;
  })

  return result; // insert type cast here
}

What I'm basically looking for, is a way for intellisense in VSCode to tell me exactly what props are available in the resulting object, so given const example = invert(['foo', 'bar', 'baz'])
The auto-completion should show me this:

My current approach involves casting the result as {[K in T[number]]: K} where T is an alias for typeof arr, but this approach doesn't give me any auto-completion.
What do I write to get TypeScript to do show me this stuff?
The interface {[name]: number} is merely a simplified example (for NDA reasons), the main question of how to map an array to property names is still the core of it all.

A: If you're happy to define your array using as const this is a possible solution
type ArrayToNumberMapType<K extends string, A extends readonly K[]> = {[K in A[number]]: number}

function invert<K extends string, A extends readonly K[]>(arr: A): ArrayToNumberMapType<K, A> {
  let result: ArrayToNumberMapType<K, A> = {} as ArrayToNumberMapType<K, A>;

  arr
    .forEach(
      (x: K, i: number) => {
        result[x] = i;
      }
    )

  return result;
}

const someArray = ['foo', 'bar', 'baz'] as const
const mappedObject = invert(someArray)
mappedObject. // .foo, .bar or .baz

A: As the comments already noted, one way to do this is to make invert generic. Currently arr is only a string[]. That's why your mapped type does not work.
function invert<T extends string>(arr: T[]): Record<T, number> {
  let result = {} as Record<T, number>;

  arr.forEach((x, i) => {
    result[x] = i;
  })

  return result
}

This simply generic implementation produces a Record<T, number> where T consists of the keys inside the array.
const example = invert(['foo', 'bar', 'baz'])
// const example: Record<"foo" | "bar" | "baz", number>

Playground

This works but we could still improve this a bit. As currently, the keys are only typed as number even though we know exactly which number they have.
function invert<T extends string[]>(arr: [...T]): {
    [K in keyof T & `${bigint}` as T[K] & string]: K extends `${infer N extends number}` ? N : never
} {
  let result = {} as any;

  arr.forEach((x, i) => {
    result[x] = i;
  })

  return result
}

In this implementation, we map over the elements of T directly and filter out the number keys. Then we convert the index K to a number.
This results in the following return type:
const example = invert(['foo', 'bar', 'baz'])
// const example: {
//     foo: 0;
//     bar: 1;
//     baz: 2;
// }

Playground


text:
Q: Invalid hook call error when using React function component from npm package I have a React function component, SimpleComponent, exported from library project and published on GitHub packages. This package is consumed in consumer project which simply renders SimpleComponent. If SimpleComponent is using React hook, it fails to render in consumer project and I get the following React hook related error:
Uncaught Error: Minified React error #321; visit https://reactjs.org/docs/error-decoder.html?invariant=321 for the full message or use the non-minified dev environment for full errors and additional helpful warnings.
library project: https://github.com/joshigaurava/library
consumer project: https://github.com/joshigaurava/consumer
Both projects use React, TypeScript and webpack. Package.json, TypeScript and webpack configs included.
library package version 0.0.1 contains SimpleComponent without React hook and it renders and functions fine in consumer project. (SimpleComponent works)
library package version 0.0.2 contains SimpleComponent with React hook and it fails to render in consumer project. (SimpleComponent fails)
I see many others a facing similar issue and I have tried various things so far but nothing has worked:

*

*Ensured that there is a single dependency on react/react-dom in consumer project (npm ls react, npm ls react-dom)

*Ensured none of the issues listed at https://reactjs.org/warnings/invalid-hook-call-warning.html have occurred

*People seem to have solved this issue with npm link or symlinks when using npm file: in dependencies, but in my case, consumer project is using library project by consuming an npm package and so this doesn't apply

*Foolishly tried exporting SimpleComponent in different ways - with or without default etc.

Now I wonder if this has something to do with how webpack is bundling the library project. But I am spending too much time on this issue and any help will be appreciated.

A: webpack config was the issue. React was being bundled in output. For anyone stumbling on this issue, following webpack config helped fix it:
externals = {
  react: {
    root: "React",
    commonjs2: "react",
    commonjs: "react",
    amd: "react",
    umd: "react",
  },
  "react-dom": {
    root: "ReactDOM",
    commonjs2: "react-dom",
    commonjs: "react-dom",
    amd: "react-dom",
    umd: "react-dom",
  },
};


text:
Q: Restore Windows 10 to factory settings? I have a little laptop that originally came with Windows 7. I upgraded to Windows 10.
I now wish to delete everything off the machine so I can give it to a friend, how do I achieve this? I don't have any media.

A: Windows has a feature called Reset since Windows 8. This cleans out all personal data and applications.

A: As Windows 10 is easily available, just download the installation media here, which has an option for "Creating Media for another PC". As you're kicking that off, grab your current license for Windows 10 (should something go wrong) to ensure you have a way to register your install.
To refresh the PC (once you have the installation media), follow the steps listed here for you.
To just re-setup the laptop (which will delete everything on the HDD) follow the steps for creating an install media (just a copy and paste from the above link):

*

*Run the media creation tool.

*Select Create installation media for another PC.

*Select the language, edition and architecture (64-bit or 32-bit) for
Windows 10.

*Follow the steps to create the installation media, then select
Finish when it's done.

*When you're ready to perform a clean installation, turn on your PC,
insert the DVD or USB flash drive you created, then shut down your
PC.

*Restart your PC, then press any key to boot from the DVD or USB
flash drive.
If you restart your PC and your current version of Windows starts, you might have to open a boot menu or change the boot order in your PC's BIOS or UEFI settings so that your PC boots from the media. To open a boot menu or change the boot order, you'll typically need to press a combination of keys (such as F2, F12, Delete or Esc) immediately after you turn on your PC. For instructions on changing the boot order for your PC, check the documentation that came with your PC or go to the manufacturer's website.
If changing the boot menu or order doesn't work, try again by signing in to Windows, shutting down, then starting your PC.

*On the Install Windows page, enter your language and other
preferences, then select Next.

*Select Install Windows.

*On the Enter the product key to activate Windows page, enter your
product key. The product key should be in a purchase confirmation
email if you bought Windows

*It looks like this: PRODUCT KEY: XXXXX-XXXXX-XXXXX-XXXXX-XXXXX.


text:
Q: How do you set binding of ComboBox ItemsSource in UserControl? Here is the combobox in my UserControl:
<Combobox ItemsSource="{Binding ComboItemsProperty}" />

I have tried:
Binding bind = new Binding();
bind.Mode = BindingMode.OneWay;
bind.Source = this;
bind.Path = new PropertyPath("ComboItemsProperty");
this.SetBinding(ComboBox.ItemsSourceProperty, bind);

However, this doesn't work.  I think I am doing the bind.Source wrong, but I'm not sure what to set the Source to.  This code is inside my UserControl.xaml.cs.

A: You can try (Replace this)
Binding bind = new Binding();
bind.Mode = BindingMode.OneWay;
bind.Source = yourCollectionSourceOrClass; //<--Replace with your collection
bind.Path = new PropertyPath("ComboItemsProperty");
this.SetBinding(ComboBox.ItemsSourceProperty, bind);

A: You need to the set context of the instance containing your property ComboItemsProperty. So instead of 'this' u should set it to 'this.DataContext' or other class object instance containing the ItemSource property you have defined..
Try this,
Binding bind = new Binding();
bind.Mode = BindingMode.OneWay;
bind.Source = this.DataContext;
bind.Path = new PropertyPath("ComboItemsProperty");
this.SetBinding( ComboBox. ItemsSource Property, bind);

(posting frm mobile)

A: I have tried a lot of ways to do this, however, nothing seems to work.
I am instead going to serialize the binding when the .xaml file gets saved out.  This seems to be working perfectly.  Binding will no longer have to be set in code.


text:
Q: HTML5 Fullscreen API and DIV's So I am creating a geo locator tool using Google Maps. While you are able to set the marker on the page, I wanted to make the Google Maps div fullscreen.
After some brief research, I came across http://demosthenes.info/blog/708/Introducing-the-HTML5-FullScreen-API, which provided a start for the fullscreen API.
The Javascript I use is the same as provided on that page, which is:
<script>
function cancelFullScreen() {
if (document.exitFullscreen) {
document.exitFullscreen();
} else if (document.mozCancelFullScreen) {
document.mozCancelFullScreen();
} else if (document.webkitExitFullscreen) {
document.webkitExitFullscreen();
} else if (document.msExitFullscreen) {
document.msExitFullscreen();
}
</script>

Now, the Map DIV is set to 50% width, 450px height to make it look decent on screen, and when I go full screen, it's still set to it's parent div's height/width, so the actual size of the div doesn't change.
Is there a way to change the map height/width so that it will use browser height/width instead of the parent div?

A: Do you want in "fullscreen mode" browser will show full MAP ?
Try this code to handle
var elem = document.getElementById("idOfMAP");
if (elem.requestFullscreen) {
  elem.requestFullscreen();
} else if (elem.msRequestFullscreen) {
  elem.msRequestFullscreen();
} else if (elem.mozRequestFullScreen) {
  elem.mozRequestFullScreen();
} else if (elem.webkitRequestFullscreen) {
  elem.webkitRequestFullscreen();
}

Hope it helps you.


text:
Q: New laptop screen issue Hi I just installed my new laptop screen I made sure the cable is connected good I replaced screens before but this is the first time I encounter a problem like this Anyone can explain this, Thank you!

A: Probably you didn't install polarizing film:


text:
Q: SASS variable as style name Is it possible to use a SASS variable in within a style name? If yes, what's the syntax?
I've tried the following:
@mixin bleed($direction) {
    margin-#{$direction}: 10px;
}

and
@mixin bleed($direction) {
    #{'margin-' . $direction}: 10px;
}

with no luck.
For reference, I'm using lib-sass and the error thrown is Unknown word

A: @mixin margin($direction) {
    margin-#{$direction}: 10px;
}

That works for me with the following call
.margin-test{
    @include margin(right);
}

Gives
.margin-test {
  margin-right: 10px;
}


text:
Q: wide-dhcpv6 is failing to start because its using an interface that does not exist I and trying to restart wide-dhcpv6 and I get this in the journalctl
Feb 03 12:09:49 router sudo[1285]: ciaran : TTY=pts/0 ; PWD=/home/ciaran ; USER=root ; COMMAND=/bin/systemctl restart wide-dhcpv6-client
Feb 03 12:09:49 router sudo[1285]: pam_unix(sudo:session): session opened for user root by ciaran(uid=0)
Feb 03 12:09:49 router systemd[1]: Stopped LSB: Start/Stop WIDE DHCPv6 client.
-- Subject: Unit wide-dhcpv6-client.service has finished shutting down
-- Defined-By: systemd
-- Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
--
-- Unit wide-dhcpv6-client.service has finished shutting down.
Feb 03 12:09:49 router systemd[1]: Starting LSB: Start/Stop WIDE DHCPv6 client...
-- Subject: Unit wide-dhcpv6-client.service has begun start-up
-- Defined-By: systemd
-- Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
--
-- Unit wide-dhcpv6-client.service has begun starting up.
Feb 03 12:09:49 router wide-dhcpv6-client[1288]:  * Starting WIDE DHCPv6 client dhcp6c
Feb 03 12:09:49 router dhcp6c[1293]: ifreset: invalid interface(enp0s31f6): No such device
Feb 03 12:09:49 router dhcp6c[1293]: main: failed to initialize enp0s31f6
Feb 03 12:09:51 router wide-dhcpv6-client[1288]:    ...fail!
Feb 03 12:09:51 router systemd[1]: wide-dhcpv6-client.service: Control process exited, code=exited status=1
Feb 03 12:09:51 router systemd[1]: Failed to start LSB: Start/Stop WIDE DHCPv6 client.
-- Subject: Unit wide-dhcpv6-client.service has failed
-- Defined-By: systemd
-- Support: http://lists.freedesktop.org/mailman/listinfo/systemd-devel
--
-- Unit wide-dhcpv6-client.service has failed.
--
-- The result is failed.
Feb 03 12:09:51 router systemd[1]: wide-dhcpv6-client.service: Unit entered failed state.
Feb 03 12:09:51 router systemd[1]: wide-dhcpv6-client.service: Failed with result 'exit-code'.

its trying to use an interface that was in my config file but I renamed it and replaced the name in my config
ciaran@router:/etc/wide-dhcpv6$ cat dhcp6c.conf
##
## This is/etc/wide-dhcpv6/dhcp6c.conf
##
## Replace the existing configuration with this one.

# Send a PD request on the external facing interface
# send ia-pd says ask for a prefix
# the script is run when the prefix is acquired
interface wan0 {
 send ia-pd 2;
 script "/etc/wide-dhcpv6/dhcp6c-script";
};

# Upon receiving a prefix use the
# information to set the internal facing interface
id-assoc pd 2 {
 prefix-interface wlan0 {
  ifid 1;
  sla-id 1;
  sla-len 0;
 };
};

## End of config.

any idea why its attempting to use the wrong interface?

A: there was a file in /etc/defauls setting the address to ask for a prefix on
ciaran@router:/etc/default$ cat wide-dhcpv6-client
# Defaults for dhcpv6 client initscript
# Used by /etc/init.d/wide-dhcpv6-client

# Interfaces on which the client should send DHCPv6 requests and listen to
# answers. If empty, the client is deactivated.
INTERFACES="enp0s31f6"

# Verbose level for syslog. Default is 0 (0: minimal; 1: info; 2: debug)
#VERBOSE=0

after I changed that to wan0 it worked


text:
Q: Git, can't clone new working copy Originally i established a repository on sda3, from the Linux OS on sda7, using user "git". I (user "sbh") work on the cloned files from sda7 in a local working copy and can successfully commit, push, etc.
This was set up from sda7 by
git clone git@sbh-MBP:/mnt/sda3/Repo

On sda8, another Linux OS with the same UID and GID, I ("sbh") want to clone to a working folder on sda8 but
git clone git@sbh-MBP:/media/sda3/Repo

doesn't work. Both OSs have the same hostname too. Both OSs have a user named "git" too. UID/GID of sda8 is 1000/1002; and those for sda7 are the same, both for"git". Both OSs have same UID/GID for "sbh":. 501/20
All the questions I found pertain to actual remote, server side repos. Though I think this will boil down to a simple git answer.
My error when i try to clone is;

ssh: connect to host sbh-MBP port 22: Connection refused
  fatal: Could not read from remote repository.

I am new to git...
Thank you
PS:
It took more than one reboot apparently and now my error is new, as reflected above.
Is something like git-init share=true necessary?
Another Update
I edited my fstab in sda7 so they, the one in sda8, refer to the same space in the SSD. I also ran, as user "sbh" in sda7 in working copy,
git remote set-url origin git@sbh-MBP:/media/sda3/Repo

A: Now with the updated error message, the issue is evident:

ssh: connect to host sbh-MBP port 22: Connection refused fatal: Could not read from remote repository.

(Emphasis mine.)
That means you just don't have a SSH server running on that host. It could also be the firewall denying access, but that's less likely.

A: This is not a Git problem – this happens entirely within SSH.
Also, as the error message says, it has nothing to do with paths but with hostnames – the OS is unable to translate sbh-MBP to an IP address.
If this is the system's own hostname, it's usually resolved via /etc/hosts or using the nss-myhostname module. Make sure at least one of those is set up.


text:
Q: Is the server connected to localhost and is running on port 5432 error I am working on an old rails app (version 2.3) and I'm unable to test my unit models because when I run rake db:test:load I receive this error message:
Is the server running on host "localhost" (10.0.1.245) and accepting
TCP/IP connections on port 5432?

This is my database.yml file for test:
 test:
  db_host: localhost
  db_port: 5432
  db_name: app_test
  db_user: app_user
  db_pass: password

I've tried to trouble shoot using this resource and tried to modify the postgresql.conf and pg_hba.conf files:
 listen_address = "*"

Common Problems for Postgresql
I've also consulted the Postgresql Documentation for the postgresql.conf and pg_hba.conf file but I know that this could not be the problem. Those two files primarily deal with foreign entities such as virtual machines/ssh etc. This has to be a rails problem.
What I don't understand is where localhost (10.0.1.245) is coming from. In my /etc/hosts file, I have these entries.
  1 127.0.0.1 dev.app.net
  2
  3 # The following lines are desirable for IPv6 capable hosts
  4 ::1 ip6-localhost ip6-loopback
  5 fe00::0 ip6-localnet
  6 ff00::0 ip6-mcastprefix
  7 ff02::1 ip6-allnodes
  8 ff02::2 ip6-allrouters
  9 ff02::3 ip6-allhosts

Changing the database.yml file to refer to dev.app.net for db_host does nothing. Neither does adding localhost 10.0.1.245 accomplish anything. How do I fix this?


text:
Q: new KeyValuePair(i, j).GetHashCode(); High Rate of Duplicates In search of a fast composite key for Dictionary I came upon anomaly I cannot understand nor justify.
In limited testing
Dictionary<KeyValuePair<UInt32, UInt32>, string>

is significantly slower (200:1) than
Dictionary<KeyValuePair<UInt16, UInt16>, string>

Test on two loops from 0 to 1000
Populate and then ContainsKey
         Poplulate     ContainsKey
UInt32    92085         86578
UInt16     2201           431

The problem is that
new KeyValuePair<UInt32, UInt32>(i, j).GetHashCode();

yields MANY duplicates.
In looping i and j 1024 only 1024 unique hash values are created.
Based on avalanche comment from CasperOne tried i*31 and j*97 (two prime numbers) and that resulted in 105280 unique on 1024X1024.  Still a lot of duplicates.  CasperOne I know that is not the same as random. But it is not my job to randomize the input.  GetHashCode() is supposed to randomize the output.
Why the high number of duplicates?
Same loop on
new KeyValuePair<UInt16, UInt16>(i, j).GetHashCode();

yields 1024 X 1024 unique hash codes (perfect).
Int32 has the same problem.
These duplicate hash values kill
Dictionary<KeyValuePair<UInt32, UInt32>, string>

Tuple also generates a lot of duplicates it does not degrade at Int32 compared to Int16.
Time for generating the raw KVP and the raw KPV.GetHashCode is similar.
Same anomaly with HashSet.
Dictionary<KeyValuePair<UInt32, UInt32>, string> dKVPu32 = new Dictionary<KeyValuePair<UInt32, UInt32>, string>();
Dictionary<KeyValuePair<UInt16, UInt16>, string> dKVPu16 = new Dictionary<KeyValuePair<UInt16, UInt16>, string>();
KeyValuePair<UInt32, UInt32> kvpUint32;
KeyValuePair<UInt16, UInt16> kvpUint16;
int range = 1000;
Int32 hashCode;
HashSet<Int32> kvpUint32Hash = new HashSet<Int32>();
HashSet<Int32> kvpUint16Hash = new HashSet<Int32>();

Stopwatch sw = new Stopwatch();
sw.Start();
for (UInt32 i = 0; i < range; i++)
{
    for (UInt32 j = 0; j < range; j++)
    {
        kvpUint32 = new KeyValuePair<UInt32, UInt32>(i, j);
    }
}
Console.WriteLine("UInt32  raw " + sw.ElapsedMilliseconds.ToString());
//  7
sw.Restart();
for (UInt16 i = 0; i < range; i++)
{
    for (UInt16 j = 0; j < range; j++)
    {
        kvpUint16 = new KeyValuePair<UInt16, UInt16>(i, j);
    }
}
Console.WriteLine("UInt16  raw " + sw.ElapsedMilliseconds.ToString());
//  6
sw.Restart();
for (UInt32 i = 0; i < range; i++)
{
    for (UInt32 j = 0; j < range; j++)
    {
        hashCode = new KeyValuePair<UInt32, UInt32>(i, j).GetHashCode();
        kvpUint32Hash.Add(hashCode);
    }
}
Console.WriteLine("UInt32  GetHashCode " + sw.ElapsedMilliseconds.ToString() + "  unique count " + kvpUint32Hash.Count.ToString());
//  285   1024
sw.Restart();
for (UInt16 i = 0; i < range; i++)
{
    for (UInt16 j = 0; j < range; j++)
    {
        hashCode = new KeyValuePair<UInt16, UInt16>(i, j).GetHashCode();
        kvpUint16Hash.Add(hashCode);
    }
}
Console.WriteLine("UInt16  GetHashCode " + sw.ElapsedMilliseconds.ToString() + "  unique count " + kvpUint16Hash.Count.ToString());
//  398 1000000
sw.Restart();
Console.ReadLine();
for (UInt32 i = 0; i < range; i++)
{
    for (UInt32 j = 0; j < range; j++)
    {
        dKVPu32.Add(new KeyValuePair<UInt32, UInt32>(i, j), String.Format("{0} {1}", i.ToString(), j.ToString()));
    }
}
Console.WriteLine("hsKVPu32 pop " + sw.ElapsedMilliseconds.ToString());
//  92085
sw.Restart();
for (UInt32 i = 0; i < range; i++)
{
    for (UInt32 j = 0; j < range; j++)
    {
        if (!dKVPu32.ContainsKey(new KeyValuePair<UInt32, UInt32>(i, j))) Debug.WriteLine("Opps"); ;
    }
}
Console.WriteLine("hsKVPu32 find " + sw.ElapsedMilliseconds.ToString());
//  86578
dKVPu32.Clear();
dKVPu32 = null;
GC.Collect();
sw.Restart();
for (UInt16 i = 0; i < range; i++)
{
    for (UInt16 j = 0; j < range; j++)
    {
        dKVPu16.Add(new KeyValuePair<UInt16, UInt16>(i, j), String.Format("{0} {1}", i.ToString(), j.ToString()));
    }
}
Console.WriteLine("hsKVPu16 pop " + sw.ElapsedMilliseconds.ToString());
//   2201
sw.Restart();
for (UInt16 i = 0; i < range; i++)
{
    for (UInt16 j = 0; j < range; j++)
    {
        if (!dKVPu16.ContainsKey(new KeyValuePair<UInt16, UInt16>(i, j))) Debug.WriteLine("Opps"); ;
    }
}
sw.Stop();
Console.WriteLine("hsKVPu16 find " + sw.ElapsedMilliseconds.ToString());
//  431

P.S. The fastest is to pack .E.G. ((UInt32)int1 << 16) | int2;
The hash of first UInt32 column equals hash of  KVP of the next two.
2281371105  8   992
2281371104  8   993
2281371107  8   994
2281371145  0   0
2281371147  0   2
2281371149  0   4
2281371151  0   6
2281371137  0   8
2281371144  0   1
2281371146  0   3
2281371148  0   5
2281371150  0   7
2281371136  0   9
2281371144  1   0
2281371145  1   1
2281371146  1   2
2281371147  1   3
2281371148  1   4
2281371149  1   5
2281371150  1   6
2281371151  1   7
2281371136  1   8
2281371137  1   9
2281371147  2   0
2281371146  2   1
2281371144  2   3
2281371151  2   4
2281371150  2   5
2281371149  2   6
2281371148  2   7
2281371139  2   8
The only pattern I have found is that either the sum or difference or the KVP matches.
But could not find a pattern for when to sum and when to subtract.
It is a bad hash so knowing what it is is of little value.

A: Since GetHashCode returns an Int32, every pair of Int16s (or UInt16s) can easily return a unique value. With a pair of Int32s, you would need to combine the values in some way to be compatible with your design.
KeyValuePair doesn't override GetHashCode(), so you are just using the default implementation of ValueType.GetHashCode(), and the documentation for it says the following:

(from: http://msdn.microsoft.com/en-us/library/system.valuetype.gethashcode.aspx)
If you call the derived type's GetHashCode method, the return value is not likely to
  be suitable for use as a key in a hash table. Additionally, if the value of one or more
  of those fields changes, the return value might become unsuitable for use as a key in a
  hash table. In either case, consider writing your own implementation of the GetHashCode
  method that more closely represents the concept of a hash code for the type.

Since KeyValuePair doesn't override GetHashCode(), I assume it's not intended to be used as a Dictionary key.
Further, according to this question and this C# code, the default implementation of ValueType.GetHashCode() simply selects the first non-static field, and returns the result of its GetHashCode() method. This explains the high number of duplicates for KeyValuePair<UInt32, UInt32>, although it doesn't explain the lack of duplicates for KeyValuePair<UInt16, UInt16>.
My guess would be that for KeyValuePair<UInt32, UInt32>, GetHashCode() does simply return GetHashCode() of the first value, and that for KeyValuePair<UInt16, UInt16>, GetHashCode() is combining the values resulting in a unique hash for each pair of values, since it is possible and straightfoward to do so.

A: Firstly, we can dispense with the timing aspect of this - it feels to me like this is really just about hash collisions, as obviously those will kill the performance.
So, the question is really why there are more hash collisions for KeyValuePair<uint, uint> than KeyValuePair<ushort, ushort>. To help find out a bit more about that, I've written the following short program:
using System;
using System.Collections.Generic;

class Program
{
    const int Sample1 = 100;
    const int Sample2 = 213;

    public static void Main()
    {
        Display<uint, ushort>();
        Display<ushort, ushort>();
        Display<uint, uint>();
        Display<ushort, uint>();
    }

    static void Display<TKey, TValue>()
    {
        TKey key1 = (TKey) Convert.ChangeType(Sample1, typeof(TKey));
        TValue value1 = (TValue) Convert.ChangeType(Sample1, typeof(TValue));
        TKey key2 = (TKey) Convert.ChangeType(Sample2, typeof(TKey));
        TValue value2 = (TValue) Convert.ChangeType(Sample2, typeof(TValue));

        Console.WriteLine("Testing {0}, {1}", typeof(TKey).Name, typeof(TValue).Name);
        Console.WriteLine(new KeyValuePair<TKey, TValue>(key1, value1).GetHashCode());
        Console.WriteLine(new KeyValuePair<TKey, TValue>(key1, value2).GetHashCode());
        Console.WriteLine(new KeyValuePair<TKey, TValue>(key2, value1).GetHashCode());
        Console.WriteLine(new KeyValuePair<TKey, TValue>(key2, value2).GetHashCode());
        Console.WriteLine();
    }
}

The output on my machine is:
Testing UInt32, UInt16
-1888265981
-1888265981
-1888265806
-1888265806

Testing UInt16, UInt16
-466800447
-459525951
-466800528
-459526032

Testing UInt32, UInt32
958334947
958334802
958334802
958334947

Testing UInt16, UInt32
-1913331935
-1913331935
-1913331935
-1913331935

You can obviously try varying the sample values to see where there are collisions.
The results of KeyValuePair<ushort, uint> are particularly worrying, and the results of KeyValuePair<ushort, ushort> are surprisingly good.
In fact, KeyValuePair<ushort, uint> isn't just bad - it's ludicrously bad as far as I can see - I haven't to find any value which doesn't have the same hash code of -1913331935 when running the 64 bit CLR. Running the 32 bit CLR I get a different hash code, but still the same hash code for all values.
It appears that in .NET 4.5 (which is what I'm running) the default implementation of GetHashCode doesn't just take the first instance field of the struct, as previously documented. I suspect that for at least some types, it just uses the first 4 bytes of memory beyond the header in the boxed value (and there will be boxing for every call here), and that ends up sometimes being just the first field (if that field is a uint), sometimes being more than one field (e.g. for ushort, ushort where both fields can fit "inside" 4 bytes) and sometimes being no fields at all (ushort, uint).
(Actually, this doesn't explain why you get 1024 different hash codes in the uint, uint case instead of just 1000. I'm still unsure on that.)
Ultimately, using a value type which doesn't override GetHashCode as a dictionary key seems like it's just a bad idea, unless you've tested to ensure that it's suitable for your specific requirements. There's just too much which is black magic to be confident about it, IMO.

A: As other answerers have mentioned, KeyValuePair does not override GetHashCode, and the default implementation of GetHashCode for structs isn't the best. You can instead use two-element tuples for this, e.g.
var dict = new Dictionary<Tuple<uint, uint>, string>();
dict.Add(Tuple.Create(1u, 2u),"xxx"); // Tuples override GetHashCode

Note however this will add additional overhead for the extra Tuple heap allocation. (it's partially made up for though, since when you call GetHashCode on a struct that doesn't override it you implicitly box it)

A: Bottom rule is to always override GetHashCode if you want a lot of your own stuff put into a has using structure like a dictionary. You can use this extension to see how well a dictionary is filled. It will report empty slots, duplicate keys and such. About to put it on sourceforge, but here it is;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;

// This unit is Freeware. It was developed by Jerremy Koot & Ivo Tops. July 2011
//
// Version  By    Changes
// =======  ===== ==============================================================
// v1.02    Ivo   Removed not-working Hashtable support and simplified code
// v1.01    Ivo   Lowered memory usage
// v1.00    I&J   First Version

namespace FastLibrary
{
/// <summary>
/// Static Extension Methods for Dictionary, ConcurrentDictionary and HashSet
/// </summary>
public static class ExtHashContainers
{
    /// <summary>
    /// Checks a dictionary for performance statistics
    /// </summary>
    public static string Statistics<TKey, TValue>(this Dictionary<TKey, TValue> source)
    {
        return ExamineData(source.Keys, source);
    }

    /// <summary>
    /// Checks a concurrent dictionary for performance statistics
    /// </summary>
    public static string Statistics<TKey, TValue>(this ConcurrentDictionary<TKey, TValue> source)
    {
        return ExamineData(source.Keys, source);
    }

    /// <summary>
    /// Checks a HashSet for performance statistics
    /// </summary>
    public static string Statistics<TKey>(this HashSet<TKey> source)
    {
        return ExamineData(source, source);
    }

    private static string ExamineData<TKey>(ICollection<TKey> source, Object hashContainer)
    {
        if (!source.Any()) return "No Data found.";

        // Find Buckets
        var b = GetBuckets(hashContainer);
        if (b < 0) return ("Unable to get Buckets Field for HashContainer");

        // Create our counting temp dictionaries
        var d = new int[b];
        var h = new Dictionary<int, int>(source.Count);

        // Find Hash Collisions and Bucket Stats
        foreach (var k in source)
        {
            var hash = k.GetHashCode() & 0x7FFFFFFF; // Hashes are stripped of sign bit in HashContainers
            int bucket = hash%b; // .NET Hashers do not use negative hashes, and use % voor bucket selection
            // Bucket Stats
            d[bucket]++;

            // Hashing Stats
            int c;
            if (h.TryGetValue(hash, out c)) h.Remove(hash);
            else c = 0;
            c++;
            h.Add(hash, c);
        }

        // Do some math
        var maxInBucket = d.Max(q => q);
        var maxSameHash = h.Values.Max(q => q);
        var emptyBuckets = d.Count(q => q == 0);
        var emptyStr = b == 0 ? "0" : ((float) (emptyBuckets)/b*100).ToString("0.0");
        var worstHash = (from i in h where i.Value == maxSameHash select i.Key).FirstOrDefault();

        // Report our findings
        var r = Environment.NewLine + hashContainer.GetType().Name + " has " + b + " buckets with " + source.Count +
                " items. " +
                Environment.NewLine + "The Largest bucket contains " + maxInBucket + " items. " +
                Environment.NewLine + "It has " + (emptyBuckets) +
                " empty buckets (" + emptyStr + "%)" + Environment.NewLine + "Each non-empty bucket has on average " +
                ((source.Count/(float) (b - emptyBuckets))).ToString("0.0") + " items." + "The " + source.Count +
                " items share " + h.Count +
                " unique hashes. ";
        if (maxSameHash > 1)
            r += Environment.NewLine + "The largest collision has " + maxSameHash +
                 " items sharing the same hash, which == " + worstHash;
        return r;
    }

    private static Int32 GetBuckets(object dictionary)
    {
        var type = dictionary.GetType();
        while (type != null && !type.IsGenericType) type = type.BaseType;
        if (type == null) return -1;

        string field = null;
        if (type.GetGenericTypeDefinition() == typeof (Dictionary<,>)) field = "buckets";
        if (type.GetGenericTypeDefinition() == typeof (ConcurrentDictionary<,>)) field = "m_buckets";
        if (type.GetGenericTypeDefinition() == typeof (HashSet<>)) field = "m_buckets";
        if (field == null) return -1;

        var bucketsField = type.GetField(field, BindingFlags.NonPublic | BindingFlags.Instance);
        if (bucketsField == null) return -1;

        var buckets = bucketsField.GetValue(dictionary);
        if (buckets == null) return -1;

        var length = buckets.GetType().GetProperty("Length");
        return (int) length.GetGetMethod().Invoke(buckets, null);
    }
}
}


text:
Q: Code-igniter controllers file name can not start with capital letter I was using small letter for controller file name before,
however, recently move the file to other server that need to controller name to be start with capital
=========================================
Here is the rename example :
file name: Home.php
$route['default_controller']: "home";
link: http://example.com/index_folder/
==========================================
it show error of
Unable to load your default controller. Please make sure the controller specified in your Routes.php file is valid.

And when I change the route to
$route['default_controller']: "Home";
it still show the same error,
Only success if I go to
http://example.com/index_folder/Home/

How to fix that? Thanks for helping
Update
Here is the htaccess file, at the root of the project folder:
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L]
</IfModule>

The reason of rename is it seems the new server has problem if my Controller is in lower case

A: Linux is case sensitive, keep the file name and class name same and try again. It will work.
The same code will work fine on  windows but give exception on Linux.

A: As per Documentation,
class Home extends CI_Controller {

        public function index()
        {
                echo 'Hello World!';
        }
}

Then save the file to your application/controllers/ directory.
Important:-

The file must be called 'Home.php', with a capital 'H'.

Now visit the your site using a URL similar to this:
example.com/index.php/home/
CodeIgniter can be told to load a default controller when a URI is not present, as will be the case when only your site root URL is requested.
To specify a default controller, open your application/config/routes.php file and set this variable:
$route['default_controller'] = 'home';

Where 'home' is the name of the controller class you want used.
If you now load your main index.php file without specifying any URI segments you'll see your "Hello World" message by default.


text:
Q: SQL - Searching a table using another table's column as criteria I have table B with bcust(4-digit integer) and bdate(date) columns. I also have table C with ccust(4-digit integer) and cdate(date). I want to show the records from table c where cdate occurred after bdate.

A: I guess, maybe you're looking for this?
SELECT c.*
       FROM c
            INNER JOIN b
            ON b.bcust = c.ccust
               AND b.bdate < c.cdate;

I assumed, that the records are linked via the bcust and ccust columns.

A: Although you did not mention anything on how the records in both tables are related, I guess that records are related if bcust = ccust.
Then something like this should do what you want:
SELECT c.*
FROM tableC c
  INNER JOIN tableB b ON c.ccust = b.bcust
WHERE c.cdate > b.bdate


text:
Q: is setRetainInstance(true) the best way to deal with fragments losing their shown/hidden when configuration change (screen flip)? When the activity gets restarted all the fragments that where hidden show again. By setting this atribute to true the fragment retains its instance. This looks weird to me and I don't understand why this behavior is not set by default.
Is this the best way of doing this?

A: Not sure if there is a single answer to your question of "what is the best way of doing this" but I have commentated on similar 'how does this work' questions. This discussion may assist you in deciding whether to apply setRetainInstance(true) or setRetainInstance(false). Please note that there have been compatibility issues with this method when using the v4.support* libraries. I agree in that retaining the instance isn't the best way forward for a lot of scenarios.


text:
Q: Minimize a Quadratic Cost Function on the Unit Simplex How can I compute
$$ \min_{x \in \Delta_n} \frac{1}{2}\lVert Bx\rVert^2 + x^tAy$$
with $x \in \mathbb{R}^n, y \in \mathbb{R}^m, A_{m \times n}$, $B_{n \times n}$ where $\Delta_n$ is the unit simplex
$$\Delta_n = \{x \in \mathbb{R}^n_+ | \sum_{i=1}^n x_i = 1\}$$
Are there standard algorithms for computing it?

A: You can also solve this by Projected Gradient Descent since the Projection onto the Unit Simplex is known.
The Code:
vX = pinv(mA) * vB;

mAy = mA.' * vY;
mAA = mA.' * mA;

for ii = 1:numIterations
    stepSize = stepSizeBase / sqrt(ii);
    vG = (mAA * vX) + mAy;
    vX = vX - (stepSize * vG);
    vX = ProjectSimplex(vX, simplexRadius, stopThr);
end

objVal = (0.5 * sum((mA * vX) .^ 2)) + (vX.' * mAy);

disp([' ']);
disp(['Projected Gradient Solution Summary']);
disp(['The Optimal Value Is Given By - ', num2str(objVal)]);
disp(['The Optimal Argument Is Given By - [ ', num2str(vX.'), ' ]']);
disp([' ']);

You can even accelerate this using Nesterov / FISTA to get really fast and efficient algorithm.
You can have the Simplex Projection function from  my Ball Projection GitHub Repository.


text:
Q: SOAP from TSQL in SQL Server I like to get some info from this web service: http://www.mnb.hu/arfolyamok.asmx?wsdl
The info I need is the result of the GetCurrentExchangeRates method.
I test it with SoapUI, with this request:
<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:web="http://www.mnb.hu/webservices/">
   <soapenv:Header/>
   <soapenv:Body>
      <web:GetCurrentExchangeRates/>
   </soapenv:Body>
</soapenv:Envelope>

I got the correct response:
<s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/">
   <s:Body>
      <GetCurrentExchangeRatesResponse xmlns="http://www.mnb.hu/webservices/" xmlns:i="http://www.w3.org/2001/XMLSchema-instance">
         <GetCurrentExchangeRatesResult><![CDATA[<MNBCurrentExchangeRates><Day date="2017-01-06"><Rate unit="1" curr="AUD">212,76</Rate><Rate unit="1" curr="BGN">157,05</Rate><Rate unit="1" curr="BRL">90,57</Rate><Rate unit="1" curr="CAD">218,75</Rate><Rate unit="1" curr="CHF">286,65</Rate><Rate unit="1" curr="CNY">41,83</Rate><Rate unit="1" curr="CZK">11,37</Rate><Rate unit="1" curr="DKK">41,32</Rate><Rate unit="1" curr="EUR">307,16</Rate><Rate unit="1" curr="GBP">358,91</Rate><Rate unit="1" curr="HKD">37,36</Rate><Rate unit="1" curr="HRK">40,53</Rate><Rate unit="100" curr="IDR">2,17</Rate><Rate unit="1" curr="ILS">75,42</Rate><Rate unit="1" curr="INR">4,26</Rate><Rate unit="1" curr="ISK">2,56</Rate><Rate unit="100" curr="JPY">249,83</Rate><Rate unit="100" curr="KRW">24,27</Rate><Rate unit="1" curr="MXN">13,58</Rate><Rate unit="1" curr="MYR">64,78</Rate><Rate unit="1" curr="NOK">34,12</Rate><Rate unit="1" curr="NZD">203,58</Rate><Rate unit="1" curr="PHP">5,87</Rate><Rate unit="1" curr="PLN">70,45</Rate><Rate unit="1" curr="RON">68,17</Rate><Rate unit="1" curr="RSD">2,48</Rate><Rate unit="1" curr="RUB">4,88</Rate><Rate unit="1" curr="SEK">32,16</Rate><Rate unit="1" curr="SGD">202,09</Rate><Rate unit="1" curr="THB">8,12</Rate><Rate unit="1" curr="TRY">80,08</Rate><Rate unit="1" curr="UAH">10,74</Rate><Rate unit="1" curr="USD">289,75</Rate><Rate unit="1" curr="ZAR">21,26</Rate></Day></MNBCurrentExchangeRates>]]></GetCurrentExchangeRatesResult>
      </GetCurrentExchangeRatesResponse>
   </s:Body>
</s:Envelope>

I try to read this information from SQL Server this way (I create a procedure for it, see the code below)
CREATE proc [dbo].[spHTTPRequest]
      @URI varchar(2000) = '',
      @methodName varchar(50) = '',
      @requestBody varchar(8000) = '',
      @SoapAction varchar(255),
      @UserName nvarchar(100), -- Domain\UserName or UserName
      @Password nvarchar(100),
      @responseText varchar(8000) output
AS
    SET NOCOUNT ON

    IF @methodName = ''
    BEGIN
      select FailPoint = 'Method Name must be set'
      return
    END

    SET @responseText = 'FAILED'

    DECLARE @objectID int
    DECLARE @hResult int
    DECLARE @source varchar(255), @desc varchar(255)
EXEC @hResult = sp_OACreate 'MSXML2.ServerXMLHTTP', @objectID OUT
IF @hResult <> 0
BEGIN
      EXEC sp_OAGetErrorInfo @objectID, @source OUT, @desc OUT
      SELECT      hResult = convert(varbinary(4), @hResult),
                  source = @source,
                  description = @desc,
                  FailPoint = 'Create failed',
                  MedthodName = @methodName
      goto destroy
      return
END
-- open the destination URI with Specified method
EXEC @hResult = sp_OAMethod @objectID, 'open', null, @methodName, @URI, 'false', @UserName, @Password
IF @hResult <> 0
BEGIN
      EXEC sp_OAGetErrorInfo @objectID, @source OUT, @desc OUT
      SELECT      hResult = convert(varbinary(4), @hResult),
            source = @source,
            description = @desc,
            FailPoint = 'Open failed',
            MedthodName = @methodName
      goto destroy
      return
END
-- set request headers
EXEC @hResult = sp_OAMethod @objectID, 'setRequestHeader', null, 'Content-Type', 'text/xml;charset=UTF-8'
IF @hResult <> 0
BEGIN
      EXEC sp_OAGetErrorInfo @objectID, @source OUT, @desc OUT
      SELECT      hResult = convert(varbinary(4), @hResult),
            source = @source,
            description = @desc,
            FailPoint = 'SetRequestHeader failed',
            MedthodName = @methodName
      goto destroy
      return
END
-- set soap action
EXEC @hResult = sp_OAMethod @objectID, 'setRequestHeader', null, 'SOAPAction', @SoapAction
IF @hResult <> 0
BEGIN
      EXEC sp_OAGetErrorInfo @objectID, @source OUT, @desc OUT
      SELECT      hResult = convert(varbinary(4), @hResult),
            source = @source,
            description = @desc,
            FailPoint = 'SetRequestHeader failed',
            MedthodName = @methodName
      goto destroy
      return
END
declare @len int
set @len = len(@requestBody)
EXEC @hResult = sp_OAMethod @objectID, 'setRequestHeader', null, 'Content-Length', @len
IF @hResult <> 0
BEGIN
      EXEC sp_OAGetErrorInfo @objectID, @source OUT, @desc OUT
      SELECT      hResult = convert(varbinary(4), @hResult),
            source = @source,
            description = @desc,
            FailPoint = 'SetRequestHeader failed',
            MedthodName = @methodName
      goto destroy
      return
END

-- send the request
EXEC @hResult = sp_OAMethod @objectID, 'send', null, @requestBody
IF    @hResult <> 0
BEGIN
      EXEC sp_OAGetErrorInfo @objectID, @source OUT, @desc OUT
      SELECT      hResult = convert(varbinary(4), @hResult),
            source = @source,
            description = @desc,
            FailPoint = 'Send failed',
            MedthodName = @methodName
      goto destroy
      return
END
declare @statusText varchar(1000), @status varchar(1000)
-- Get status text
exec sp_OAGetProperty @objectID, 'StatusText', @statusText out
exec sp_OAGetProperty @objectID, 'Status', @status out
select @status, @statusText, @methodName
-- Get response text
exec sp_OAGetProperty @objectID, 'responseText', @responseText out
IF @hResult <> 0
BEGIN
      EXEC sp_OAGetErrorInfo @objectID, @source OUT, @desc OUT
      SELECT      hResult = convert(varbinary(4), @hResult),
            source = @source,
            description = @desc,
            FailPoint = 'ResponseText failed',
            MedthodName = @methodName
      goto destroy
      return
END
destroy:
      exec sp_OADestroy @objectID
SET NOCOUNT OFF

GO
*/

declare @xmlOut varchar(8000)
Declare @RequestText as varchar(8000);
set @RequestText=
'<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:web="http://www.mnb.hu/webservices/">
    <soapenv:Header/>
    <soapenv:Body>
        <web:GetCurrentExchangeRates/>
    </soapenv:Body>
</soapenv:Envelope>'

exec spHTTPRequest 'http://www.mnb.hu/arfolyamok.asmx?wsdl', 'post', @RequestText,'http://tempuri.org/CreateOrderForMe','', '', @xmlOut out

But I always get an "Internal server" error. Can somebody suggest me a solution?
Thanks!

A: I was facing the same issue while executing my procedure. There seems to be some difference in the MSXML2.HTTP method between Windows 2012 and windows 2007. For example the send works as follows in 2012:
DECLARE @send NVARCHAR(4000) = 'send("' + REPLACE(@requestBody, '"', '''') + '")';
EXEC @hResult = sp_OAMethod @objectID, @send

unlike
sp_OAMethod @objectID, 'send', null, @requestBody

in your procedure.


text:
Q: Installing racket packages as native executables on linux Is there a way to install a racket package either:

*

*as a statically linked native executable?

*have raco install it to specific path where it can be packaged and distributed as native linux distribution package?

A: There are two questions here. The first one being if it's possible to create a racket package as a statically linked native executable. If you mean a single executable with all the libraries statically linked, the answer is no. You can, however, create a racket distribution of your application that you can then install on machines without racket. See https://docs.racket-lang.org/raco/exe-dist.html
The second question is if you can use raco install to install the above mentioned package and the answer is no. raco will install pkgs, libraries into the system, for use with racket but not an application in a system-wide manner.
My advice is to use raco distribute and then use a system installer get it into the target system. For arch linux, I would create a raco distribute of my application and then I would create an AUR to distribute my application to my target users.


text:
Q: QtWebKit or Server side? Can't translate xml: ReferenceError: Can't find variable: XSLTProcessor I need to open a webpage inside a QWebView in my Qt Widgets Application.
The web works fine, except one part, where some files are not downloading from the server.
I inspected the QWebView and I found that error in the title...
It seems weird, because I tried to compile my app in linux with same Qt version and it works fine, no error in Web Inspector console... I tried compiling with MinGW32 and also with MSVC 2013 with same results.
I tried the same webpage with Qupzilla WebBrowser and it works!!, even in Windows (so I am afraid that is Qt setting in my app, that is only needed in Windows environment, but I couldn't find for it in the QupZilla sources...)
Error detail in windows:

(In linux the same action produces no error)
Top: Linux build, processed 45 requests, Windows build(bottom) stopped at 15 requests..., same code:

Another things I tried:
- Changing user agent
- Playing with QWebSettings
- And maybe another unuseful tries.
Any clue to get my page fully loaded into the Windows QWebView?