text:
Q: Web service call from android using DataDroid library not returning data to activity Below I've listed my activity code, call out to the web service, and the json parsing class I created to parse the web service results.  I'm trying to pass a user object back to the activity to determine what they can/can't do, however, I'm not getting past the "after execute" log statement.  onRequestFinished never gets called which is where I would have expected it to end up.  Any help would be greatly appreciated as there doesn't seem to be much activity with DataDroid...
LoginActivity.java
package com.motosho.ui;

import com.foxykeep.datadroid.requestmanager.Request;
import com.foxykeep.datadroid.requestmanager.RequestManager.RequestListener;
import com.motosho.R;
import com.motosho.data.model.User;
import com.motosho.data.requestmanager.RequestFactory;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import android.content.Intent;

public final class LoginActivity extends DataDroidActivity implements RequestListener,
    OnClickListener {

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        bindViews();
    }

    protected void onResume() {
        super.onResume();
        for(int i=0; i < mRequestList.size(); i++) {
            Request request = mRequestList.get(i);

            if(mRequestManager.isRequestInProgress(request)) {
                mRequestManager.addRequestListener(this, request);
                setProgressBarIndeterminateVisibility(true);
            } else {
                mRequestManager.callListenerWithCachedData(this, request);
                i--;
                mRequestList.remove(request);
            }
        }
    }

    protected void onPause() {
        super.onPause();
        if(!mRequestList.isEmpty()) {
            mRequestManager.removeRequestListener(this);
        }
    }

    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
    }

    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
    }

    private void bindViews() {
        ((Button) findViewById(R.id.sign_in_button)).setOnClickListener(this);
    }

    private void callLoginWS(String username, String pin, String eventId) {
        Log.i("LOGIN", "in callLoginWS - username=" + username + ", pin=" + pin + ", eventid=" + eventId);
        setProgressBarIndeterminateVisibility(true);
        Request request = RequestFactory.getLoginRequest(username, pin, eventId);
        mRequestManager.execute(request, this);
        Log.i("LOGIN", "after execute");
        mRequestList.add(request);
    }

    public void onClick(View view) {
        switch(view.getId()) {
        case R.id.sign_in_button:
            EditText emailText = (EditText) findViewById(R.id.email);
            EditText pinText = (EditText) findViewById(R.id.pin);
            Log.i("LOGIN","set email and pin text");
            callLoginWS(emailText.getText().toString(), pinText.getText().toString(),"9");
            break;
        }
    }

    @Override
    public void onRequestFinished(Request request, Bundle resultData) {
        Log.i("LOGIN", "inside onRequestFinished");
        if(mRequestList.contains(request)) {
            setProgressBarIndeterminateVisibility(false);
            Log.i("LOGIN", "request found");
            mRequestList.remove(request);

            Toast toast = Toast.makeText(this, "request finished", Toast.LENGTH_SHORT);
            toast.show();
            User user = resultData.getParcelable("user");
            if(user != null) {
                startActivity(new Intent(this, MainActivity.class).putExtras(resultData));
            }
        }
    }

    @Override
    public void onRequestConnectionError(Request request, int statusCode) {
        Log.i("LOGIN", "onRequestConnectionError");
        if(mRequestList.contains(request)) {
            setProgressBarIndeterminateVisibility(false);
            //show error
            Toast toast = Toast.makeText(this, "connection error", Toast.LENGTH_SHORT);
            toast.show();
            mRequestList.remove(request);
        }
    }

    @Override
    public void onRequestDataError(Request request) {
        Log.i("LOGIN", "onRequestDataError");
        if(mRequestList.contains(request)) {
            setProgressBarIndeterminateVisibility(false);
            mRequestList.remove(request);

            //show error
            Toast toast = Toast.makeText(this, "data error", Toast.LENGTH_SHORT);
            toast.show();
        }
    }

    @Override
    public void onRequestCustomError(Request request, Bundle resultData) {
        // Never called
    }

    public void connectionErrorDialogRetry(Request request) {
        Log.i("LOGIN", "connectionErrorDialogRetry");
        String username = request.getString("username");
        String pin = request.getString("pin");
        String eventId = request.getString("eventid");
        callLoginWS(username,pin,eventId);
    }
}

LoginOperation.java
package com.motosho.data.operation;

import java.util.HashMap;

import android.content.Context;
import android.os.Bundle;

import com.foxykeep.datadroid.exception.ConnectionException;
import com.foxykeep.datadroid.exception.CustomRequestException;
import com.foxykeep.datadroid.exception.DataException;
import com.foxykeep.datadroid.network.NetworkConnection;
import com.foxykeep.datadroid.network.NetworkConnection.ConnectionResult;
import com.foxykeep.datadroid.network.NetworkConnection.Method;
import com.foxykeep.datadroid.requestmanager.Request;
import com.foxykeep.datadroid.service.RequestService.Operation;
import com.motosho.config.WSConfig;
import com.motosho.data.factory.LoginJsonFactory;

public final class LoginOperation implements Operation {

    @Override
    public Bundle execute(Context context, Request request)
        throws ConnectionException, DataException, CustomRequestException {
        HashMap<String, String> params = new HashMap<String, String>();
        params.put("username", request.getString("username"));
        params.put("pin", request.getString("pin"));
        params.put("eventid", request.getString("eventid"));

        NetworkConnection networkConnection = new NetworkConnection(context, WSConfig.WS_LOGIN_URL);
        networkConnection.setMethod(Method.POST);
        networkConnection.setParameters(params);
        ConnectionResult result = networkConnection.execute();

        return LoginJsonFactory.parseResult(result.body);
    }
}

LoginJsonFactory.java
package com.motosho.data.factory;

import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.os.Bundle;
import android.util.Log;

import com.foxykeep.datadroid.exception.DataException;
import com.motosho.config.JSONTag;
import com.motosho.data.model.User;

public final class LoginJsonFactory {
    private static final String TAG = LoginJsonFactory.class.getName();

    private LoginJsonFactory() { }

    @SuppressWarnings("null")
    public static Bundle parseResult(String wsResponse) throws DataException {
        User user = new User();

        try {
            JSONObject parser = new JSONObject(wsResponse);
            JSONObject jsonRoot = parser.getJSONObject(JSONTag.USER_ELEM);
            user.firstName = jsonRoot.getString(JSONTag.USER_ELEM_FIRST_NAME);
            user.lastName = jsonRoot.getString(JSONTag.USER_ELEM_LAST_NAME);
            user.phoneNumber = jsonRoot.getString(JSONTag.USER_ELEM_PHONE_NUMBER);
            user.role = jsonRoot.getString(JSONTag.USER_ELEM_ROLE);
            JSONArray jsonPositionsArray = jsonRoot.getJSONArray(JSONTag.USER_ELEM_LIST_POSITIONS);
            int size = jsonPositionsArray.length();
            List<String> tempPositionsArray = null;

            for (int i=0; i < size; i++) {
                tempPositionsArray.add(jsonPositionsArray.getString(i));
            }
            user.positions = tempPositionsArray;

            JSONArray jsonCapabilitiesArray = jsonRoot.getJSONArray(JSONTag.USER_ELEM_LIST_CAPABILITIES);
            size = jsonCapabilitiesArray.length();
            List<String> tempCapabilitiesArray = null;

            for(int i=0; i < size; i++) {
                tempCapabilitiesArray.add(jsonCapabilitiesArray.getString(i));
            }
            user.capabilities = tempCapabilitiesArray;
        } catch (JSONException e) {
            Log.e(TAG, "JSONException", e);
            throw new DataException(e);
        }

        Bundle bundle = new Bundle();
        bundle.putParcelable("user", user);
        return bundle;
    }
}


text:
Q: Display flex not working on Material UI's box item I've created a create-react-app project, where I'm using Material UI. Here I've used Box  item with display="flex"; inline style. But the flex is not working at all. Here is an image.

When I add add display: flex on the inspect element. It works.
I've uploaded the project to github pages. Funny thing is, it works fine on there. Here is the link of the uploaded page. Why is it not working as intended in the local host server?

<AppBar position="static">
            <Toolbar className={classes.toolbar}>
                <Typography variant="h5" className={classes.title}>
                    Travel Advisor
                </Typography>
                <Box display="flex">
                    <Typography variant="h6" className={classes.title}>
                        Explore new places
                    </Typography>

                            <SearchIcon />

                        <InputBase placeholder="Search..." classes={{ root: classes.inputRoot, input: classes.inputInput }} />

                </Box>
            </Toolbar>
        </AppBar>

redpajama_set_name: RedPajamaStackExchange


text:
Q: Sidenav not showing when i minimise the browser I am trying to do the Sidenav, when i have a full screen, the menu displays but when i minimize the browser the menu button shows but when i click it, it doesn't display anything. I don't know why. I am using Materialize css. http://jsfiddle.net/xdrL9e83/8/. When i run it in Jsfiddle it shows the Toggle icon being outside Navbar. I don't know why

    Booking

Patients

Patients History

Bookings

Notes

Add Patient

Patients

Patients History

Bookings

Notes

Add Patient

The Javascript

A: Put the menu toggle icon (mdi-navigation-menu) at the top..

    Booking

Patients

Patients History

Bookings

Notes

Add Patient

Patients

Patients History

Bookings

Notes

Add Patient

Demo: http://codeply.com/go/mMvlUnsNRT

A: Your DIV is closed in the wrong place. It needs to close after the content of your Nav.

    Booking

Patients

Patients History

Bookings

Notes

Add Patient

Patients

Patients History

Bookings

Notes

Add Patient

http://jsfiddle.net/aaronfranco/xdrL9e83/14/


text:
Q: GPG Keys and Emails I have been testing out GPG keys and were studying the changes of the keys when adding/removing users on the key. If I add a user Alice upon key generation. I export the key pairs's public and private key. And then add the user Bob to the same key. And Finally export the same key except with Bob added as a user. Then I compare the Alice and Alice/Bob keys. The Alice public key has a huge chunk similar to the Alice/Bob public keys and also has a few differences in many spots. The Alice/Bob public key is considerably longer than the Alice key. I notice the same applies for the private keys. What I find interesting is that if I encrypt using the Alice Public Key and decrypt using the Alice/Bob private key, I get the same message.
Here are the questions I have:

*

*Does email/User ID affect the public and private key?

*Can you extract the user id from the public key? If yes, how does it work?

*How does the encryption with Alice and decryption with Alice/Bob work?

*Is a certain part of each key used for encryption/decryption and other parts left for the user id and emails?

A:
And then add the user Bob to the same key

Most importantly, this is not what PGP key "user IDs" are for.
User IDs are only labels. They cannot be used for access control of any sort – they only inform others about the owner of the key. There should be only one owner of a key, and all user IDs on a single key should describe the same person.
(The reason you can add multiple user IDs is simply because the same person can have multiple email addresses, and indeed even multiple names.)
If multiple people need to use PGP, each of them should create their individual keys. Then you will list all of their keys when encrypting (e.g. use multiple --recipient options).

*How does the encryption with Alice and decryption with Alice/Bob work?

When you add a second user ID, it's still literally the same RSA key material, you only changed the label that's written on it. User IDs are not for access control.

*

*Does email/User ID affect the public and private key?

*Can you extract the user id from the public key? If yes, how does it work?

*Is a certain part of each key used for encryption/decryption and other parts left for the user id and emails?

When you talk about "public keys" and "private keys" in PGP, that does not usually mean just the raw public key data (e.g. just the RSA parameters) like it does in some other systems. Instead, what you actually get from gpg --export is the OpenPGP keyblock or certificate containing the public keys together with various metadata (user IDs, signatures, etc.).
So when you add a User ID, it doesn't really change the actual key parameters – it is added as a metadata packet next to the public-key packet.
And when people share their "PGP public keys" they share the whole bundle of key+metadata packets as a single unit. Overall the whole idea is very similar to X.509 certificates, which have a 'Subject' field alongside the key itself.
You can use such tools as pgpdump or gpg --list-packets to show the exported data in text format.


text:
Q: Force Identity Server child application to refresh claims I have a parent web application which uses identity server to authenticate users across a suite of other web applications which act as children of that parent app.
We utilize a profile service within the parent application to set user claims which can be used with the child application. This profile service is registered with Identity Server on startup by using IdentityServerBuilderExtensionsAdditional.AddProfileService.
Within the user claims we store some user preferences for easy access within our child applications. Recently we added functionality within the parent application to allow users to directly update these preferences.
Unfortunately these updates do not seem to apply until the user's token is refreshed. This can be up to 5 minutes. There doesn't seem to be any way for me to broadcast to the child applications that something has changed within the parent.
How can I, within the parent application, force the child applications to refresh their claims by making them call that user profile service?

I have tried logging the user out then back in e.g.
await SignOut();
await SignIn(user, rememberMe);

Interestingly this actually seems to work locally on my development machine, but once deployed to production environments this does not work. But I have not been able to determine any difference between my configuration and the production configuration. So, I am looking for a more robust way to force child apps to call this user profile service early.


text:
Q: How can I install all my python 2 packages for python 3? I installed Anaconda with Python 2.7 and then later installed the Python 3.6 kernel. I have lots of Python 2 packages and I don't want to have to manually install all of the packages for Python 3. Has anyone written, or does anyone know how to write, a bash script that will go through all my Python 2 packages and just run pip3 install [PACKAGE NAME]?

A: In your Python 2 pip, run pip freeze > requirements.txt. This will write all your installed packages to a text file.
Then, using your Python 3 pip (perhaps pip3), run pip install -r /path/to/requirements.txt. This will install all of the packages as listed in the requirements.txt file.


text:
Q: having problem with unlimited depth in tree structure i have a list of categories with they parent's id, i want to create a tree structure for them.
then i created this but problem is it's limited to depth level
this is categories:
$categories =
[
    [id => 1, parent_id => 0],
    [id => 2, parent_id => 0],
    [id => 3, parent_id => 0],
    [id => 4, parent_id => 0],
    [id => 5, parent_id => 1],
    [id => 6, parent_id => 1],
    [id => 7, parent_id => 1],
    [id => 8, parent_id => 2],
    [id => 9, parent_id => 2],
    [id => 10, parent_id => 3],
    [id => 11, parent_id => 3],
    [id => 12, parent_id => 4],
    [id => 13, parent_id => 5],
    [id => 14, parent_id => 5],
    [id => 15, parent_id => 5],
    [id => 16, parent_id => 13],
    ...
];

this is my code and it works:
$main = [];
foreach ($categories as $cat) {
    if ($cat->parent_id == 0) {
        $item = $cat;
        $item->subs = [];
        foreach ($all as $sub_cat) {
            if ($sub_cat->parent_id == $cat->id ) {
                $sub_item = $sub_cat;
                $sub_item->subs = [];
                foreach ($all as $sub2_cat) {
                    if ($sub2_cat->parent_id == $sub_cat->id ) {
                        $sub2_item = $sub2_cat;
                        $sub2_item->subs = [];
                        foreach ($all as $sub3_cat) {
                            if ($sub3_cat->parent_id == $sub2_cat->id ) {
                                $sub3_item = $sub3_cat;
                                $sub3_item->subs = [];
                                $sub2_item->subs[] = $sub3_item;
                            }
                        }
                       $sub_item->subs[] = $sub2_item;
                    }
                }
                $item->subs[] = $sub_item;
            }
        }
         $main[] = $item;
    }
}

output is like this:
[
   [
       id=>1,
       parent_id=>0,
       subs=>[
           [
               id=>5,
               parent_id=>1,
               subs=>[
                   [
                       id=>13,
                       parent_id=>5
                       subs=>[...]
                    ],
                    ...
               ]
           ]
       ]
    ],
    [

    ],
    ...
]

output is fine but my categories array may change and may have unlimited depth,
because of that i need a recursive function to do this until there is no children.

A: This will help you
function getTree(array $categories, $parentId = 0) {

    $branch = array();

    foreach ($categories as $category)
    {
        if ($category['parent_id'] == $parentId)
        {
            $subs = getTree($categories, $category['id']);

            if ($subs)
            {
                $category['subs'] = $subs;
            }

            $branch[] = $category;
        }
    }

    return $branch;
}
$categories = [
    ['id' => 1, 'parent_id' => 0],
    ['id' => 2, 'parent_id' => 0],
    ['id' => 3, 'parent_id' => 0],
    ['id' => 4, 'parent_id' => 0],
    ['id' => 5, 'parent_id' => 1],
    ['id' => 6, 'parent_id' => 1],
    ['id' => 7, 'parent_id' => 1],
    ['id' => 8, 'parent_id' => 2],
    ['id' => 9, 'parent_id' => 2],
    ['id' => 10, 'parent_id' => 3],
    ['id' => 11, 'parent_id' => 3],
    ['id' => 12, 'parent_id' => 4],
    ['id' => 13, 'parent_id' => 5],
    ['id' => 14, 'parent_id' => 5],
    ['id' => 15, 'parent_id' => 5],
    ['id' => 16, 'parent_id' => 13],
];
$categoryTree = getTree($categories);

Here is the demo link


text:
Q: Scraping dynamically rendered links from an infinite scrollbar in CasperJS I'm trying to scrape the links on the left sidebar of this page using CasperJS.
The page has hundreds of links in the sidebar, but only loads 20 at a time when you scroll down. This code successfully grabs the first 20 (needs casperjs and phantomjs globally installed to run):
var casper = require('casper').create();
// helper function that gets all of the resume links on the page:

  var getAllLinks = function() {
    var linksOnThisPage = []
    $("a[href^='/ResumeB']").each(function(index, linkDiv) {
      $linkDiv = $(linkDiv)
      linksOnThisPage.push('http://www.super-resume.com' + $linkDiv.attr('href'))
    });
   return linksOnThisPage
  };

//start casper, go  to page, run helper function:
casper.start('http://www.super-resume.com/ResumeBuilder.jtp?query=Database+Administrator', function() {
  allLinks=casper.evaluate(getAllLinks)
  console.log('number of links found:', allLinks.length);
});

casper.run();

I can make the page scroll down in the actual browser with this:
$('#search-left-inner').scrollTop(10000);

10000 is an arbitrarily big number; every time you run that code in the browser, it loads 20 more links. (Ideally I'd like to be able to grab all at once without having to keep reloading 20 at a time, but that's less pressing for now.)
If I put that line inside the getAllLinks function like so:
var getAllLinks = function() {
    $('#search-left-inner').scrollTop(10000);

    var linksOnThisPage = []
    //etc, etc,

it still only loads 20 links. Many similar posts discuss synchronicity issues, so I've I've tried to get the it to wait for the sidebar to finish loading a few ways, including this:
var getAllLinks = function() {
    casper.then(function () {
        $('#search-left-inner').scrollTop(100000);
    });
    casper.then(function () {

    var linksOnThisPage = []
    //etc. etc.
}

but now for some reason it only finds one link instead of 20.

A: I presume that if you scroll, it doesn't immediately load the next items, because loading takes time. You need to wait a little after scrolling before you can attempt to scrape all of the elements again.
casper.start(url)
    .thenEvaluate(scroll)
    .wait(5000, function(){
        var links = this.evaluate(getAllLinks);
        this.echo(links.length);
    })
    .run();

If this produces more links, then you can try the next step and that is infinite scrolling until no new elements are loaded. This can be done with asynchronous recursion in CasperJS:
var linkCount = -1;

function getAllLinks() {
    var linksOnThisPage = []
    $("a[href^='/ResumeB']").each(function(index, linkDiv) {
        $linkDiv = $(linkDiv)
        linksOnThisPage.push('http://www.super-resume.com' +   $linkDiv.attr('href'))
    });
    return linksOnThisPage
}

function scroll() {
    $('#search-left-inner').scrollTop(10000);
}

/**
 * Returns true if more elements were loaded that were before
 */
function checkMore(){
    var newLinks = this.evaluate(getAllLinks);
    var newCount = newLinks.length;
    if (linkCount === -1) {
        linkCount = newCount;
    }
    return linkCount < newCount
}

/**
 * Executes the a single iteration step and waits for a change in numbers.
 * Terminates if there are no changes in 6 seconds.
 */
function step(){
    this.thenEvaluate(scroll)
        .waitFor(check, step, function _onTimeout(){
            var links = this.evaluate(getAllLinks);
            this.echo("finished with " + links.length + " links\n\n"+links.join("\n"));
        }, 6000);
}

casper.start(url, step).run();

Keep in mind that it makes only sense to use jQuery in the DOM context (page context) which is inside of casper.evaluate(). I suggest that you also read the PhantomJS documentation of that function.


text:
Q: Angular 2 custom composite control I'm trying to create a custom composite control for Angular 2. My requirements are I need to create a generic file-picker control that allows users to select a file either using a html5 input[type=file] or by inputing a url to a file.
I've decided to create generic form controls that implement the ControlValueAccessor interface for a both the sub-controls, as they are going to be used elsewhere individually.
I'm trying to wrap them both inside a file-picker-local-or-remote (for lack of a better word) control. This outer control should be responsible for emitting the contents of the file chosen, without caring how the file was picked.
Propagating the value all the way to the consuming form is easy. Every time the subcontrols propagates a value to the intermediary control, the intermediary control relays it further up the chain to the consumer, using the registerChange callback.
However, I'm having trouble propagating validation errors that might occur in the subcontrols. I need to propagate the errors all the way to the consuming form so that they may be localised.
E.g. If a user enters an invalid url in the remote-file-picker subcontrol, that subcontrol's validation function fires with the correct error. This error is given to the intermediary control. How can I propagate this invalid-url error all the way to the consuming form?
More broadly, is there specific guidance about how to create composite controls in Angular 2? I can't find any examples of custom controls that wrap other custom controls, so I'm not really sure I'm doing it correctly.
Put differently, given:
Form:
outerForm = new FormGroup({
    file: new FormControl(null, Validators.required)
});

<form [formGroup]="outerForm">
    <File-Picker-Local-Or-Remote formControlName="file"></File-Picker-Local-Or-Remote>
    ******???******
</form>

File-Picker-Local-Or-Remote
innerForm = new FormGroup({
    local: new FormControl(),
    remote: new FormControl(null, Validators.pattern('http://...'))
});

<input type="file" formControlName="local" />
<input type="text" formControlName="remote" />

When the remote subcontrol fails validation, it gives its error codes to the innerForm. How do I propagate those error messages to the outer form, so that I can replace ******???****** with the appropriate validation message?
Edit: I should note that there are quite a fews ways for me to hack a solution or bypass this problem, including building my own solution using event emitters, not having a composite control in the first place, etc.
What I'm actually interested in is the Angular 2 way of creating reusable and extensible form controls that consumers can interact with just like any other form control, and can be further built upon by other developers to create even more high-level controls.

A: A colleague and I figured this out a while ago but here is the solution for anyone else stumbling across this.
The key is to implement both ControlValueAccessor and Validator interfaces in the composite component.
E.g.
Custom date control, implements ControlValueAccessor
@Component({
  ...
  providers: [{
    provide: NG_VALUE_ACCESSOR,
    useExisting: CustomDateControl),
    multi: true
  }]
})
export class CustomDateControl implements ControlValueAccessor {
  // implement ControlValueAccessor
}

Custom time control, implements ControlValueAccessor
@Component({
  ...
  providers: [{
    provide: NG_VALUE_ACCESSOR,
    useExisting: CustomTimeControl),
    multi: true
  }]
})
export class CustomTimeControl implements ControlValueAccessor {
  // implement ControlValueAccessor
}

Custom composite control dateTime, implements both ControlValueAccessor and Validator
@Component({
  ...
  providers: [{
    provide: NG_VALIDATORS,
    useExisting: CustomDateTimeControl,
    multi: true
  }, {
    provide: NG_VALUE_ACCESSOR,
    useExisting: CustomDateTimeControl,
    multi: true
  }]
})
export class CustomDateTimeControl implements OnInit, ControlValueAccessor, Validator {
  private propagateChange = function (change) { };
  private propagateTouched = function () { };

  // Inner controls (you can also use an internal FormGroup for this)
  public date = new FormControl();
  public time = new FormControl();

  constructor() {}

  ngOnInit() {
    this.date.valueChanges
      .subscribe(value => {
        this.propagateChange(value + ' ' + this.time.value);
        this.propagateTouched();
      }

    this.time.valueChanges
      .subscribe(value => {
        this.propagateChange(this.date.value + ' ' + value);
        this.propagateTouched();
      }
    }

  writeValue(value) {
    // Need to update the inner controls, but don't use setValue / patchValue,
    // as that will trigger valueChanges in the above subscriptions,
    // incorrectly calling touched
  }

  registerOnChange(fn) {
    this.propagateChange = fn;
  }

  registerOnTouched(fn) {
    this.propagateTouched = fn;
  }

  validate(control) {
    // Custom logic to validate the parent control. In this case,
    // we may choose to union all childrens' errors.

    let errors = Object.assign(this.localControl.errors || {}, this.remoteControl.errors || {});
    return Object.keys(errors).length ? errors : null;
  }
}

To my answer my own initial question, a good way to bubble errors up a chain of composite controls is to implement Validator in those composite controls, and have their validate function return some combination of the child controls' errors.
I hope this is useful for others.


text:
Q: Converting date to a day of week in R
Possible Duplicate:
Find the day of a week in R

I have a data for days like 11-01-2011 etc. But I want to add the data corresponding
the date as Monday, Tuesday etc. Is there any R package that contains the information of the dates with days?

A: weekdays(as.Date('16-08-2012','%d-%m-%Y'))
[1] "Thursday"

A: The lubridate package is great for this sort of stuff.
> wday(as.Date('16-08-2012','%d-%m-%Y'))
[1] 5
> wday(as.Date('16-08-2012','%d-%m-%Y'), label=TRUE)
[1] Thurs
Levels: Sun < Mon < Tues < Wed < Thurs < Fri < Sat
> wday(as.Date('16-08-2012','%d-%m-%Y'), label=TRUE, abbr = FALSE)
[1] Thursday
Levels: Sunday < Monday < Tuesday < Wednesday < Thursday < Friday < Saturday

A: Here is some information to create your own library or routine
Constants:
day_of_month
    the day of the month
    e.g. if input mm-dd-yyy then dd

month:
march = 1
april = 2
may = 3
...

year
yy[yy]  (last to digits from yyyy)
   *subtract 1 if month jan or feb
    e.g. if input date is 02-01-2012 (mm-dd-yyyy)
         year =  (12-1) = 11

century
[yy]yy  (first two digits from yyyy)
     e.g. if input year is 2012 then 20 = century
     * year 2000, 1900, ... are 20-1, 19-1 respectively

ALGORITHM
step1: floor(century / 4)

step2: year

step3: floor(year/4)

step4: floor(month*2.6 -0.2)  #this is the leap year correction

step5: day_of_month

step6: add step1...step5

step7: divide by 7  # modulo 7 in codespeak

step8: the remainder is the day of the week

To Interpret Results:
Sun = 0, Mon = 1, Tues = 3, etc..

Not a library, but as the public service jingle goes...
"Read: The More you Know"
Ref: http://www.faqs.org/faqs/sci-math-faq/dayWeek/


text:
Q: Usar un array en una consulta sql con php lo que quiero lograr con esta consulta es que no me muestre los productos que ya están en la sucursal para esto tango un array de los productos de mi sucursal y lo quiero comprar con todos los productos que existen (que están en otra tabla) y los que si se encuentren en este array no los muestre solo los que no aparecen lo estoy haciendo de esta manera
                <form action="asignar_productos_sucursal.php" method="post">

                    <input type="submit" name="cambiar" class="btn btn-primary position-realtive end-50" value="cambiar" >

                            #
                            Producto
                            Familia
                            Existencias
                            Cantidad para Sucursal
                            Sucursal
                            Precio Por Sucursal

                        <?php
                            $Productos_Sucursal = array();

                            $Productos_Sucursal_sql = "SELECT * FROM productos_sucursales WHERE sucursal = '$sucursal' ORDER BY id ASC";
                            $Sucursal_result = mysqli_query($con, $Productos_Sucursal_sql);
                            while ( $Productos_Sucursal_row = mysqli_fetch_array($Sucursal_result) ) {
                            $Productos_Sucursal[] = $Productos_Sucursal_row['producto'] ;

                            }

                            $productos_sucrusales_existentes = implode(",",$Productos_Sucursal);
                            echo $productos_sucrusales_existentes;

                        include('my_function.php');
                        $currency = getCurrency();
                        $sql = "SELECT * FROM catalogo WHERE nombre NOT IN ('$productos_sucrusales_existentes') ORDER BY codigo ASC";
                        $result = mysqli_query($con, $sql);
                        $i = 1;
                        while ($row = mysqli_fetch_array($result)) {
                            echo "
";
                            echo "".$row['codigo']."	";
                            echo " <input type='text' name='producto[]' value='".$row['nombre']."' readonly >	";
                            echo " <input type='text' name='familia[]' value='".$row['departamento']."' readonly  >	";
                            echo "<input type='text' value=".$row['existencia']. " name='region' readonly  >	";
                            echo "<input type='text' value='$cantidad' placeholder='0' name='ExistenciasSucursal[]'  >	";
                            echo "<input type='text' value='$precio' placeholder='$0' name='PrecioSucursal[]' >	";
                            echo "<input type='text' value='$sucursal'  placeholder='' name='Sucursal[]' >	";
                            echo "
 ";
                        }
                        echo "
";
                        echo "
";
                        ?>

                </form>

mi array con los productos existentes en la sucursal es $productos_sucrusales_existentes; y solo para verlos le hago un echo, pero al momento de  querer hacer una consulta de sql con esta  variable no me muestra ningún resultado, y lo que quiero lograr es que solo me muestre los productos que no están en el array anterior

A: Recorre el array $productos_sucrusales_existentes  con un foreach concatenas en un string  separados por  ,
Luego utilizas la siguiente consulta select * from tabla fron codigo in ("lista")
codigo
$productos = "",

foreach($productos_sucrusales_existentes as $k => $value){
 if($productos == "") $productos .= $value->codigo;
 else $productos .= ",".$value->codigo;
}

//creamos la consulta

 $query = "SELECT * from productos where codigo IN ($productos)";


text:
Q: time complexity for array search i am writing the function to check if the given value is included in the matrix in . This matrix has the following properties:
•Integers in each row are sorted in ascending from left to right.
•Integers in each column are sorted in ascending from top to bottom
public static boolean searchMatrix(int target, int[][] matrix)
{
    for(int i = 0;i <= matrix[0].length;i++)
    {
        for (int j=i; j<matrix.length;j++)
        {
        if(target == matrix[i][j])
        return true;
        }
    }
    return false;
}

i want to know weather this program has time complexity of O(N).
if not what changes should i make to get into O(N).

A: I think the search can be done in linear time.  Consider the following 4×4 matrix as a visual:
1 2 4 6
2 3 5 7      ascending from left to right
3 4 6 8      and from top to bottom
4 5 6 9

If we were searching for the value 5 we could begin in the upper left, and then walk to the right until we have either found the value, or encountered a number which is greater than the target of 5.  In this case, we hit 6.  Then, we can rollback to 4, and advance down to a higher row.  It is guaranteed that every previous value in the first row is less than the target and that every value in the next row from that column onwards is greater than the value on the first row.
This is a roughly linear approach.  A good analogy would be walking around the perimeter of a mountain, looking for a certain elevation.  If at each spot we either don't find the height we want, or find only points too high, we keep walking.

A: The way you have it written (brute force computation) has a worst case time complexity of O(N^2).  Since you say that the arrays are sorted, you can instead implement binary search which will have a worst case time complexity of N(2*log(N)).

A: Assuming a n x m matrix, your algorithm is O(n * m), because it (potentially) iterates all rows and columns (ie all elements).
However, there exists an algorithm that is O(log(m + n)).
Because this is for an on-line coding interview (I am psychic), I will give you hints only:

*

*Given elements at coordinate (x, y), what can know about where the target might be?

*What could you do if you treated x and y separately?

A: As stated your algorithm is O(N*M) or O(N^2) for a square matrix.
You can do it with a single loop:
Basically starting from the top right you check the cell if the number is too big move left if the number is too small move down. If you fall off the edge on either side the number's not there.
boolean searchMatrix(int target, int[][] mat)
{
   int i = 0, j = mat[0].length;
   while (i < mat.length && j >= 0)
   {
      if (mat[i][j] == target)
      {
         return true;
      }
      else if (mat[i][j] < target)
      {
         i++;
      }
      else
      {
         j--;
      }
   }
   return false;
}

A: you say the matrix is sorted ,may you can use binary search to find the target . and use two individual one layer loop , firstly search row ,then column.it's o(N/2).


text:
Q: pausing game in dead space 3 Is there any way that I can pause dead space 3 while checking the inventory (by TAB ).  It is very annoying that the game keeps running in background while reading text logs or mission descriptions  And it is also dangerous as you may be attacked by an enemy with inventory description on your face

A: No, there is no way to check inventory and pause game at the same time. It is suppose to add to the horror element of the game.
Single-Player
I would clear the room (killing all the enemies) before using the inventory. I wouldn't really worry about it since the only time you need to manage the inventory is when you want to pick something up or craft more health packs.
Since in either of these circumstances you wouldn't require a pause button I wouldn't worry about it.
It is best to manage inventory also at places where you can store your items (crafting spots) instead of dropping them because they are valuable for the most part.
Ammo drops for the weapon you are currently using, so you don't need to really worry about having junk ammo in your inventory unless you changed weapons and didn't put ammo in safe that you can't currently use.
Multi-Player
In multi-player you can actually trade items with your partner which is helpful if he or you have extra health packs/ammo needed.
Sources:
http://www.computerandvideogames.com/181756/no-pause-option-for-dead-space/


text:
Q: unable to manually change hdmi resolution when using a tv as a monitor Recently i hooked up an old tv for use in my home studio. It is a 32" JVC LCD screen...pretty old: http://www.cnet.com/products/jvc-lt-32g80su-32-lcd-tv/specs/
What I want to do is to connect this TV with hdmi, from my desktop using ATI radeon HD 3600 series video card..as my main monitor. The screen works perfect on resolution 1280x720..which is a little below the native resolution on the tv (1366x768).Except, the screen becomes just a notch too big for the physical size on the tv.(about 1cm outside in both directions..so i can barely see the toolbar). Btw i am running linux, which is a Mint cinnamon 17 3.13.0-24 generic kernel. Anyway, I tried connecting with a windows laptop and i made it fit the screen perfectly above and below the native resolution of the tv.
So i tried adding manual resolutions using the xrandr as shown in this tutorial:
http://community.linuxmint.com/tutorial/view/877
For me it worked for DVI or VGA connections, but with the hdmi (which is the alternative on the Tv) the tv only became black.
So now i am wondering what's going on here. Could it be the video driver installed not supporting the requested hdmi resolutions ? Do i need to install the proprietary drivers provided by the amd perhaps ?

A: Solution: by compensating for overscanning in linux solved the problem, using the 1280x720 resolution.
xrandr --output HDMI-1 --set underscan on
xrandr --output HDMI-1 --set "underscan hborder" 30 --set "underscan vborder" 18

Depending on your screen, but 30 and 18 worked perfectly for the JVC. Found on this post https://bbs.archlinux.org/viewtopic.php?id=145639

A: Not sure about the HDMI resolutions and your driver, but for the part where the edges of the picture get cut off on the TV, check your overscan settings. http://www.engadget.com/2010/05/27/hd-101-overscan-and-why-all-tvs-do-it/


text:
Q: Python CSV read row by row and insert new data I have a csv file, from which I will read row by row and for certain field the data need to be processed and insert the results into another field in the same row before moving on to the next field.
I tried various methods like:
w = open('test.csv', 'w+')
csv_r = csv_reader(w)
csv_w = csv.writer(w)

for row in csv_r:
    row[10] = results
    csv_w.writerows(row)

But I am getting blank. Is there any other way doing this?
Basically i need to read a specific element in a row and then process the data and the result will be appended into another element in the same row.

A: w+ empties/truncates your file so you have nothing to iterate over. It is r+ for reading and writing.
To update the file either store all the updated rows, reopen the file and write or a much better approach is use a tempfile.NamedTemporaryFile to write to then replace the original with shutil.move.
from tempfile import NamedTemporaryFile
from shutil import move
import csv

with open("test.csv") as f, NamedTemporaryFile("w",dir=".", delete=False) as temp:
    # write all updated rows to out tempfile
    csv_w = csv.writer(out)
    csv_r = csv.reader(f)
    for row in csv_r:
       row[10] = results
       csv_w.writerows(row)
# replace original file with updated
move(temp.name,"test.csv")

A: Seems like you are openning both reader and writer on the same file -
csv_r = csv_reader(w)
csv_w = csv.writer(w)

Is that expected? Shouldn't you be openning them on different files?
If you intentionally did it, try using different files, when you open a file with w+ mode, if the file exists it gets overwritten.

w+    Opens a file for both writing and reading. Overwrites the existing file if the file exists. If the file does not exist, creates a new file for reading and writing.

Try openning the file with r+ mode.


text:
Q: How to implement Publishing subscriber Replication topology in SQL? How to implement Publishing subscriber Replication topology in SQL?

A: First, work out what kind of replication you want, and so on.
Also, read through something like the Help system (SQL Books Online) to understand the various Agents that will play a part. Such as the Log Reader agent, the Distribution Agent, and so on. Think about what users you want to use for these.
Then just go into SQL Management Studio, connect to your source, go to the Replication bit and use the New Publisher wizard. Once that's done, go to your Subscriber and set up Subscribers in a similar way.

A: What do you mean by "Publishing subscriber Replication topology"?
In one sense (the "traditional" sense), SQL Server doesn't support a pub / sub model for replication, where a single publisher multicasts data out to many subscribers.
In another sense, all forms of replication are pub / sub, in that there is a central Publisher that provides data to one or more Subscribers, by way of a Distributor and Agents (but it's actually serial unicast).


text:
Q: Analyze_Compensation in oracle Can anyone please tell me for what purpose analyze_compensation is used in oracle?
I got this term in a code in bulk collect. PFB the link:
http://www.oracle.com/partners/campaign/o28plsql-095155.html

A: Suppose you want to print all the rows and columns of table i.e(Select * from table_name;
) in PL/SQL
THEN in that case :-
dbms_output.put_line() wont be able to print the table data when there is more than one row... Hence we use analyze_compensation() .
It is a procedure , which you need to declare in DECLARE BLOCK of PL/SQL
analyze_compensation is used to print the whole table data i.e Select * from table_name;


text:
Q: How to customize the open graph object description position in the news feed? On the news feed, where the image is rendered at 200x200, I'd like the description to appear on the right and not below the image.
Here is what I have:

The description is long and gets clipped in that small one-line space. That's why I'd like it to be on the right side of the image.
This is how I configure the render, but it only seems to configure the appearance in the user wall, not in the news feed of other's wall:

Thanks

A: Unfortunately Facebook does not currently support displaying the description to the right of large image format stories.
If the description needs to be featured more prominently you will need to reduce the size of the image to below 200x200 to force Facebook to use the standard story format.


text:
Q: How to create the query to get correct result with pluralization? This is my table I need to get results like:
in 560038 two hospitals, one temple, zero masjid, zero company, one church and
in 560049 one schools, one masjid, one company, zero temple, zero hospitals, and
in 562129 one high school, zero hospitals, zero company, zero masjid , zero temple.

604=hospital,
1306=temple,
1302=church,
204=school,
1305=masjid,
102=company.

Is it possible to get from a single query in mysql? Here I can give city_id only.
id  |cat_id|poi_id |addr                    |pincode|city_id
1   |6     |604     |Amrutha  Hospital      |560038 |284
2   |13    |1306    |Temple             |560038 |284
3   |13    |1302    |Resurrection Church    |560038 |284
4   |2     |204     |Lake Montfort School   |560049 |284
5   |6     |604     |Garden City Hospital   |560038 |284
6   |13    |1305    |Bilal Masjid           |560049 |284
7   |1     |102     |Grindwell Limited      |560049 |284
8   |2     |204     |Citizen High School    |562129 |284

A: You can use CASE expressions within COUNT() to conditionally aggregate poi_ids to differentiate the counts, grouped by pincode.
You want:
SELECT   pincode,
         COUNT(CASE poi_id WHEN 604  THEN 1 END) AS hospital_cnt,
         COUNT(CASE poi_id WHEN 1306 THEN 1 END) AS temple_cnt,
         COUNT(CASE poi_id WHEN 1302 THEN 1 END) AS church_cnt,
         COUNT(CASE poi_id WHEN 204  THEN 1 END) AS school_cnt,
         COUNT(CASE poi_id WHEN 1305 THEN 1 END) AS masjid_cnt,
         COUNT(CASE poi_id WHEN 102  THEN 1 END) AS company_cnt
FROM     tbl
GROUP BY pincode

Edit: As per your comments, you can get a row format of the counts of each possible poi_id per pincode:
SELECT     a.pincode,
           b.poi_id,
           COUNT(c.pincode) AS cnt
FROM       (SELECT DISTINCT pincode FROM tbl) a
CROSS JOIN poi b
LEFT JOIN  tbl c ON a.pincode = c.pincode AND b.poi_id = c.poi_id
GROUP BY   a.pincode, b.poi_id

Where poi is the name of the table that poi_id links to. Make sure the column names are consistent too.
If you still want one row per pincode, you can use GROUP_CONCAT to bring the counts all into one delimited string:
SELECT   a.pincode,
         GROUP_CONCAT(CONCAT(a.poi_id, ': ', a.cnt) SEPARATOR ' / ') AS poi_cnts
FROM     (
         SELECT     a.pincode,
                    b.poi_id,
                    COUNT(c.pincode) AS cnt
         FROM       (SELECT DISTINCT pincode FROM tbl) a
         CROSS JOIN poi b
         LEFT JOIN  tbl c ON a.pincode = c.pincode AND b.poi_id = c.poi_id
         GROUP BY   a.pincode, b.poi_id
         ) a
GROUP BY a.pincode

A: I think this is what you are looking for:
SELECT pincode, poi_id, COUNT(1) AS place_cnt
FROM table_name
GROUP BY pincode, poi_id;

A: select pincode, addr, count(id) from YourTable group by pincode, addr

A: If I've understood correctly, you want a resultset where each row is the pincode followed by the numver of each type of point of interest.
The target results you specified look like the need to be a long, natural english string. I'm not going to get you that far but I will give you something that you can work with in code.
Here's the end result that you'll end up with:
pincode | hospitals | temples | masjids | companies | churches | schools
560038  |     2     |    1    |    0    |     0     |    1     |    0
560049  |     0     |    0    |    1    |     1     |    0     |    1
562129  |     0     |    0    |    0    |     0     |    0     |    1

NOTE: I don't think requiring the results in this way is ideal.  If new types of points of interest are added later you'll have to rewrite the query. But since this is the question, here's the answer:
There's two ways to do this and both use sub queries that do count(*) for each type of point of interest.  The first option is the embed the sub queries in the SELECT part of the query.  The second option is to make derived tables out of the sub queries and join them together.
Here's option 1:
SELECT
mainTbl.pincode,
(SELECT count(*) FROM myTable WHERE pincode = mainTbl.pincode AND city_id = mainTbl.city_id AND poi_id = 604) as hospitals,
(SELECT count(*) FROM myTable WHERE pincode = mainTbl.pincode AND city_id = mainTbl.city_id AND poi_id = 1306) as temples,
(SELECT count(*) FROM myTable WHERE pincode = mainTbl.pincode AND city_id = mainTbl.city_id AND poi_id = 1305) as masjids,
(SELECT count(*) FROM myTable WHERE pincode = mainTbl.pincode AND city_id = mainTbl.city_id AND poi_id = 1302) as churches,
(SELECT count(*) FROM myTable WHERE pincode = mainTbl.pincode AND city_id = mainTbl.city_id AND poi_id = 204) as schools,
(SELECT count(*) FROM myTable WHERE pincode = mainTbl.pincode AND city_id = mainTbl.city_id AND poi_id = 102) as companies
FROM myTable mainTbl
WHERE mainTbl.city_id = ?

And option2:
SELECT
mainTbl.pincode,
hospitalsTbl.hospitals,
templesTbl.temples,
masjidsTbl.masjids,
churchesTbl.churches,
schoolsTbl.schools,
companiesTbl.companies

FROM myTable mainTbl
JOIN (SELECT count(*) as hospitals, pincode FROM myTable WHERE pincode = mainTbl.pincode AND city_id = mainTbl.city_id  AND poi_id = 604) hospitalsTbl ON hospitalsTbl.pincode = mainTbl.pincode
JOIN (SELECT count(*) as temples, pincode FROM myTable WHERE pincode = mainTbl.pincode AND city_id = mainTbl.city_id AND poi_id = 1306) templesTbl ON templesTbl.pincode = mainTbl.pincode
JOIN (SELECT count(*) as masjids, pincode FROM myTable WHERE pincode = mainTbl.pincode AND city_id = mainTbl.city_id AND poi_id = 1305) masjidsTbl ON masjidsTbl.pincode = mainTbl.pincode
JOIN (SELECT count(*) as churches, pincode FROM myTable WHERE pincode = mainTbl.pincode AND city_id = mainTbl.city_id AND poi_id = 1302) churchesTbl ON churchesTbl.pincode = mainTbl.pincode
JOIN (SELECT count(*) as schools, pincode FROM myTable WHERE pincode = mainTbl.pincode AND city_id = mainTbl.city_id AND poi_id = 204) schoolsTbl ON schoolsTbl.pincode = mainTbl.pincode
JOIN (SELECT count(*) as companies, pincode FROM myTable WHERE pincode = mainTbl.pincode AND city_id = mainTbl.city_id AND poi_id = 102) companiesTbl ON companiesTbl.pincode = mainTbl.pincode
WHERE mainTbl.city_id = ?

As you can see the queries are quite verbose.  It's much better to have something like this:
SELECT count(*) as num_poi, poi_id, pincode
FROM myTable
WHERE city_id = ?
GROUP BY poi_id, pincode

and then build your one line rows in code.


text:
Q: Одинаковые строки не совпадают Я получаю с сервера ответ о регистрации. Если ответ 1 то логин свободен, если 0 то нет. В приложении проверяю этот ответ. Но то что мне приходит никак не хочет сравниваться.
` String resp = null;
        try {
            db.execute("registration.php", newacc);
            resp = db.get();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        //test.setText(resp);
        if (!resp.equals("0")) {
            startActivity(new Intent(Registration.this, Login.class));
        } else toast4.show();`

Я уже перепробовал все что мог но ничего не работает. Если приходит 0, то приложение все равно заходит в блок if и переходит на другую активити.
Вот еще PHP код
<?php
require "conn.php";
mysqli_set_charset($conn,"utf8");
if (isset ($_POST['login'],$_POST['password'],$_POST['salt'],$_POST['reg_date'],$_POST['name'],$_POST['number'])){
    $login= $_POST['login'];
    $pass= $_POST['password'];
    $salt= $_POST['salt'];
    $reg_date= $_POST['reg_date'];
    $name= $_POST['name'];
    $number= $_POST['number'];
    $querry0 = mysqli_query($conn,"SELECT login FROM account WHERE login = '$login'");
    if(mysqli_num_rows($querry0) == 0){
        $querry1 = mysqli_query($conn,"INSERT INTO account (login, password,salt, registration_date) VALUES ('$login', '$pass','$salt', '$reg_date')") or die(mysqli_error($conn));
        $querry2 = mysqli_query($conn,"INSERT INTO client (client_name, phone_number, email) VALUES ('$name', '$number','$login' )") or die(mysqli_error($conn));
        echo "1";
    }else echo "0";
}else echo "err";
?>

Перевел строки в HEX: строка с сервера - efbbbf30, а с которой сравниваю - 30.При чем везде стоит кодировка в UTF-8. Как с этим быть?

A: В общем я теперь просто сравниваю строки в HEX. Костыль, но работает.

A: php добавляет BOM(Byte Order Mark) в Юникод.
Java, а следовательно Андроид при декодировании не удаляет его (уж не знаю почему) и надо это делать самому.
В Вашем случае нужен один символ (как я понял) и можно сравнить только его:
    if (resp.charAt(resp.length() - 1) != '0')) {
        startActivity(new Intent(Registration.this, Login.class));
    } else toast4.show();


text:
Q: how to prove if $m^{2}|n^{2}$ then m|n just hint please. How to prove the following?:  Let $m,n\in \mathbb{N}$ ; $ \;m^{2}\mid n^{2}\Longrightarrow \;\;m\mid n$
Just a hint please. I tried two ways but did not work.

A: Prime factorization is the natural way to go. Another way is to let $d$ be the greatest common divisor of $m$ and $n$, and let $m=ad$, $n=bd$. Note that $a$ and $b$ are relatively prime.
Then from $m^2$ divides $n^2$ we conclude that $a^2$ divides $b^2$. We now show that $a^2=1$. To do this, note that if $a^2\gt 1$ then there is a prime $p$ that divides $a^2$. Use this to contradict the fact that $a$ and $b$ are relatively prime.

A: Assume that $m^2 \mid n^2$ but $m\not\mid n$. Decompose $m$ and $n$ into their prime factors and exponents, i.e. $m = p_1^{a_1}\ldots p_N^{a_N}$, $n = p_1^{b_1}\ldots p_N^{b_N}$. If $m\not\mid n$, what can you say about these prime factors? And what can you say about the prime factors of $m^2$ and $n^2$? And then infer from these answers whether it is indeed possible that $m^2 \mid n^2$ but $m\not\mid n$.

A: Another way is to note that the integer $n^2/m^2$ is the square of a rational (namely, $n/m$), so we need to show that if $k$ is a positive integer and $\sqrt k$ is rational, then it is actually an integer. There are many proofs of this fact. Here is one that does not use prime factorizations:
If $\displaystyle \sqrt k=\frac nm$, we may start by assuming that $n,m$ have no common factors (else, divide both of them by their gcd. This does not change their quotient). Now, also
 $$ \sqrt k=\frac k{\sqrt k}=\frac k{\frac nm}=\frac {mk}n. $$
Since  $n,m$ have no common factors, then there are integers $x,y$ with $nx+my=1$. Simple algebra verifies that since
 $$ \frac nm=\frac{km}n, $$
then also
 $$ \frac nm=\frac{km}n=\frac{ny+kmx}{my+nx}, $$
but the latter is an integer, since $nx+my=1$.


text:
Q: In C++/cli, should a ref class have a destructor(=Dispose) to manage native memory? I've seen the following pattern in our code base:
public ref class FooWrapper {
public:
    FooWrapper(); // does m_p(new NativeFoo)
    ~FooWrapper(); // calls !FooWrapper(), does nothing else (doesn't close any non-memory resource)

    // ... DoStuff() ...

protected:
    !FooWrapper(); // does delete m_mp;

private:
    NativeFoo* m_mp;
    // possibly more (managed/native) members
};

What this achieves is that:

*

*The native pointer will be freed when the managed object is collected by the GC - through the Finalizer (!FooWrapper())

*If you Dispose() of the object (e.g. using), the native memory will be reclaimed immediately, not waiting for garbage collection of the containing object.

After thinking about this for a while, I think this is actually neither needed nor helpful, as we don't actually need the IDisposable interface on this type.
Would it be safe and OK to have the native pointer only be freed on Finalization and do away with the "destructor"?
Would the destructor (~FooWrapper()) be ever (implicitly) needed in in the C++/CLI code, or can I create a ref class only with gcnew anyway?

A: Sure, a destructor is optional.  Unfortunately there's a lot of cargo cult surrounding it, but C++/CLI makes it very easy to hide and avoids anybody from getting nervous.  Omitting is quite reasonable if the native object being wrapped only requires a small amount of memory and no handles.  Up to you to define "small", it can be quite large if your C++/CLI wrapper isn't small or is used in the kind of program where you can expect a healthy garbage collections rate.  Strings help a lot, they chew through gen#0 heap quickly.
Happens a lot already, Runtime Callable Wrappers don't have a destructor.  Which is the other strong motivation to not add it, if it is hard to call then adding it just causes pain and suffering and a lot of support calls.  Compare to the Thread class: a megabyte of VM and 5 operating system handles, but no destructor.  Exceedingly difficult to call the destructor of course.  Nobody notices either, they don't create threads that often.  C++/CLI wrappers often fit that mold.
If it is very easy to call, very short lifetime and just a using statement in C# in a method body then always add it.
This way, that way, only you can make the call.

A: The main purpose of defining a destructor (aka Dispose pattern) is to allow for deterministic finalisation.  It's technically optional but there's never any reason to not include one if you have some unmanaged members or some managed members that are also disposable.
At the end of the day, if you don't think it's worthwhile to destroy these deterministically, then you can simply never call it (via stack semantics or delete from C++, or using or Dispose() from C# and other languages).
Whether it's worthwhile or not will depend on what is contained in the object and how often you create instances.  (Don't forget the latter: it's perfectly valid for the GC to never delete anything during the lifetime of your app, and even small allocations will add up over time.  And remember that it's also valid for the finaliser to never be called.)
Generally speaking, any of the below should be disposable (and actually disposed):

*

*holding large chunks of memory

*holding limited resources (such as OS handles)

*holding processing resources (such as threads)

*holding shared resources (such as files or locks)

*native types using the RAII pattern

*native types that have side effects when destroyed (eg. smart ptrs, some fluent-style objects)

*objects created very frequently

A: Ah yes. A destructor is optional, just like Hans says.
However, MS implemented a very (un?)helpful Level 1 warning:

C4461 - 'type' : this class has a finalizer 'finalizer' but no destructor
  'dtor'
The presence of a finalizer in a type implies resources to delete.
  Unless a finalizer is explicitly called from the type's destructor,
  the common language runtime determines when to run the finalizer,
  after your object goes out of scope.

So for my case I have the choice of either:

*

*Adding a dtor==IDisposable that essentially doesn't do anything helpful beyond cleaning up memory (calling the finalizer) deterministically iff the object is used in a using statement (or IDisposable is otherwise triggered -- foreach, etc.)

*Removing the warning with a pragma.

*Implement the dtor, but male it a noop, which would allow the object to be still used after it has been disposed (noop dispose). It's not actually possible to have the dtor as noop, because if you have a dtor, and it's called, your finalizer will automatically be suppressed. (see also GC::SuppressFinalize)


text:
Q: How to checkout a git repo under linux with wrong charset? I have a simple (but hopefully fast solvable) problem. I created a git archive under windows using the msys/tortoiseGit tools. All right. Now I copied the repo to a USB stick and walked it over to a linux machine.
Unfortunately there are files in the repo that contain German Umlauts etc (äöüß). Under pure windows there is no problem and I know that under pure linux there is also no problem with that.
When I now clone the repo locally the umlauts are replaced by other characters that are not displayable on my machine (results in a ?). At the moment I am not able to reach the windows machine to modify anything. Also it should work soon as I will no more be able to access the windows machine soon.
Therefore:

*

*Can I (somehow) modify the archive to ensure correct character set?

*Can I avoid this situation when I create new archives?

*Can I (only using linux) clone the repo suh that it works transparently?

*[edit] How to reweite the repo such that (at least) the file names get into the right charset?

A: *

*Aside from rewriting the archive, not that I know of.

*Make sure your Windows editors use UTF-8 instead of a local codepage.
See below.

*Your Linux might ship with non-UTF-8 locales.  To a certain extent,
LANG=de_DE.iso88591@euro

will request that your programs read and write in the same encoding.  However, this is not a complete fix; for example Gtk+ assumes filenames are in UTF-8 regardless of the content encoding.

*The usual way to rewrite a Git repo is using git-filter-branch.  Here is an example I made just now that should re-encode filenames, file contents, and commit messages from ISO-8859-1 to UTF-8.
CONVERT='iconv -fiso8859-1 -tutf-8'
git filter-branch \
    --index-filter '
        git ls-files -z --stage |
        while read -d "" mode ref stage name; do
            [[ "$stage" = 0 || "$stage" = 1 ]] &&
            printf "0 0000000000000000000000000000000000000000\t%s\0" "$name"
            newname="$(echo "$name" | '"$CONVERT'")"
            newref="$(
                git cat-file blob "$ref" |
                '"$CONVERT"' |
                git hash-object -w --stdin)"
            printf "%s %s %s\t%s\0" "$mode" "$newref" "$stage" "$newname"
        done |
        git update-index -z --index-info' \
    --msg-filter "$CONVERT" \
    $(git for-each-ref --format='%(refname)' refs/heads refs/tags)

Be careful: I haven't tested this in the presence of merges or binary files, and it's easy to destroy a lot of history with git-filter-branch.  In case something goes wrong, git keeps backups of all positive refs (rewritten or not) in the refs/original namespace.

Just found an amazing answer by VonC: On Windows, use msysgit≥1.7.10, and to fix up an existing repository, there's recodetree binary (filenames only, unlike the above).

A: Git stores files as binary blobs, so you cannot fix it without rewriting the whole history. It is not about modifying the repo, but modifying the files.


text:
Q: Memory increases rapidly to a high value when the keyboard shows up I have two textfields within a uitableview. I create them as follows:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *MyIdentifier = @"MyIdentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:MyIdentifier];
if (cell == nil)
{
    cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:MyIdentifier] autorelease];

    if ([indexPath row] == 0) {
       // text = [[UITextField alloc] initWithFrame:CGRectMake(5, 5, 300, 30)];
        text.delegate=self;
        text.userInteractionEnabled=NO;
        text.contentVerticalAlignment=UIControlContentVerticalAlignmentCenter;
        if(qNum-1==53)
            text.placeholder=@"Category";
        [cell.contentView addSubview:text];
        [text release];

    }
    if ([indexPath row] == 1) {
      //  text2 = [[UITextField alloc] initWithFrame:CGRectMake(5, 5, 300, 30)];
        text2.delegate=self;
        text2.userInteractionEnabled=NO;
        if(qNum-1==53)
            text2.placeholder=@"Subcategory";
        text2.contentVerticalAlignment=UIControlContentVerticalAlignmentCenter;
        [cell.contentView addSubview:text2];
        [text2 release];
    }

}

cell.accessoryType = UITableViewCellAccessoryNone;
cell.selectionStyle = UITableViewCellSelectionStyleNone;
return cell;

}
My problem is when the keyboard shows up and when i start typing characters inside the textfield memory increases rapidly. Is this normal or wat is that i am missing ? Thanks in advance.


text:
Q: workflow custom service host using service activation I'm trying to add a custom service host to a workflow hosted in IIS using the service activations tag in the web.config. However I keep getting this error:
BuildManager returned an invalid compiled string for the virtual path /DefaultTest/TestWorkflow.xamlx.
my web.config looks like this:

serviceActivations
       add service="~/TestWorkflow.xamlx" relativeAddress="TestWorkflow.xamlx" factory="ServiceFactory.TestWorkflowServiceHost"
  serviceActivations

If I set a break point in the constructor of the custom service host, it hits it, and the exception is thrown on the base.CreateServiceHost line.
Any ideas what could be wrong?

A: Try this:
<add factory="ServiceFactory.TestWorkflowServiceHost"
             relativeAddress="./TestWorkflow.xamlx"
             service="TestWorkflow.xamlx"/>


text:
Q: How to echo user data using a second model I want to display the name of a user alongside his notes. I have two models the user and the Notes Model. The Notes Model has the id of the user and the relationship is good.
How do I fetch the name of a user using their id in the view?
I have used plain php between the  tags
@foreach($notes as $note)

            <?php $userid=$note->user_id;
             $user = App\User::find($userid);
             $name = $user->name;
             echo $name;?>:::
            {{$note->note_title}}

 {!! html_entity_decode($note->note_body)!!}

        @endforeach

Am getting the correct name but I guess that's not the correct way in laravel.

A: If your model relationships are configured correctly the user model doesn't need to be fetched in view.
You can get the users name through the one to many relationship.
Take a look here
https://laravel.com/docs/5.8/eloquent-relationships#one-to-many-inverse

A: Looking at my own question two years later and I cannot believe that was me, anyway its progress.
Actually that`s easy {{$note->user->name}}


text:
Q: Swift parse json to struct I have a struct like
struct Channel {
    var id : Int = 0
    var name = ""
}

and I am getting json from URL as
{"channel_list":[{"channel_id":0,"channel_name":"test1"},{"channel_id":0,"channel_name":"test2"}]}

However I am not able to get data as
func parseJson(anyObj:AnyObject) -> Array<Channel>{
    var list:Array<Channel> = []
    if  anyObj is Array<AnyObject> {
        var b:Channel = Channel()
        for json in anyObj as! Array<AnyObject>{
            b.id  =  (json["channel_id"]  as AnyObject? as? Int) ?? 0
            b.name = (json["channel_name"] as AnyObject? as? String) ?? ""
            list.append(b)
        }
    }
    return list
}

//read code
let anyObj: AnyObject? = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions(0),error: nil) as AnyObject?
        println(anyObj)
        if let myobj=anyObj["channel_list"] as AnyObject {
            self.Channellist=self.parseJson(anyObj!)
        }

Whats wrong with this?

A: First, instead of using AnyObject, you should cast the JSON response as a Dictionary: [NSObject:AnyObject] then safe cast the result of anyObj["channel_list"] to an Array of Dictionaries [[NSObject:AnyObject]], because this is your JSON response format.
Then you need to use this type in your parseJSON function. We're also simplifying it while we're at it, because there's no need to do weird castings anymore.
Also, you were passing the wrong argument to your function (you used anyObj instead of myObj).
struct Channel {
    var id : Int = 0
    var name = ""
}

func parseJson(anyObj: [[NSObject:AnyObject]]) -> Array<Channel>{
    var list: Array<Channel> = []
    var b: Channel = Channel()
    for json in anyObj {
        b.id  =  (json["channel_id"] as? Int) ?? 0
        b.name = (json["channel_name"] as? String) ?? ""
        list.append(b)
    }
    return list
}

if let anyObj = NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions(0),error: nil) as? [NSObject:AnyObject] {
    if let myobj = anyObj["channel_list"] as? [[NSObject:AnyObject]] {
        self.Channellist=self.parseJson(myobj)
    }
}

There's still room for improvement: you could create an initializer for your Struct, for example, and also create a typealias for the response types, use map to create the list, etc.

A: Here's how I would do it with Swift 2:
struct Channel {
    var id : Int
    var name: String
    init?(JSON: [NSObject: AnyObject]?) {
          guard let channelID = json["channel_id"] as? Int, let channelName = json["channel_name"] as? String
          else { name = ""; id = 0; return nil }
          name = channelName
          id = channelID
    }
}
func parseJSON(array: [[NSObject:AnyObject]]) -> [Channel?] {
    return array.map { Channel(JSON: $0) }
    // If you don't want to return optionals to channel you can do this instead:
   // return array.map { Channel(JSON: $0) }.filter { $0 != nil }.map { $0! }
}
// And in the caller
do {
     guard let dict = try NSJSONSerialization.JSONObjectWithData(data!, options: []) as? [NSObject : AnyObject]
     else { throw NSError(domain ... // Setup error saying JSON wasn't parsed. }
     guard let arrayContents = dict["channel_list"] as? [[NSObject:AnyObject]]
     else  { throw NSError(domain ... // Setup error saying array wasn't found. }
     let channels = parseJSON(arrayContents)
}
catch {
    print(error)
}


text:
Q: Number of HBase region servers vs data nodes When configuring a HBase cluster alongside Hadoop HDFS, is it a good choice to deploy one region server per HDFS data node, or the ratio between region servers and data nodes should be different from 1:1 ?

A: You can use any ratio you want but the rule of thumb is 1:1. The less regions a RS has the better, more RS means less regions per server and less regions to reassign if the node fails which will improve the recovery time (by a lot, although there has been progress since 0.95: http://hortonworks.com/blog/introduction-to-hbase-mean-time-to-recover-mttr/)


text:
Q: Angular application stops when subscribing to api response I'm at my wits end trying to work out what I've done wrong in my Angular 6 application.  The problem with the below code is that it 'should' work, but my angular application just stops and won't continue.
Note that all my other API calls and similar code is working ok.
I've added in console logs to try to find out what's going on:
I have a form that I'm submitting:
submit(f) {
  console.log('2')
  // Now I'm saving the data, this works
  this.userService.completeProfile(this.model)
    .pipe(first())
    .subscribe(
      data => {
        console.log('3')
        // this is to get a new token
        this.authService.getNewToken(this.model.id)
          .pipe(first())
          .subscribe(() =>
            data => {
              // I never get to 8
              console.log('8')
              this.router.navigateByUrl('/register/profile/complete');
            },
            error => {
              console.log('9')
            }
          );

      },
      error => {
          console.log('10')
      });

}

This is my auth service:
private currentUserSubject = new BehaviorSubject<LoggedInUser>({} as LoggedInUser);
currentUser = this.currentUserSubject.asObservable();

setCurrentUser(): void {
    if (localStorage.getItem("auth_token")) {
        let jwtData = localStorage.getItem("auth_token").split('.')[1]
        let decodedJwtJsonData = window.atob(jwtData)
        let decodedJwtData = JSON.parse(decodedJwtJsonData)

        this.currentUserSubject.next(
            {
                name: decodedJwtData.name,
                id: decodedJwtData.id,
            }
        );
    }
}

getNewToken(id: String) {
    return this.http.post<any>(this.baseUrl + '/GetNewToken', { id: id })
    .pipe(map(user => {
        console.log(user)
        if (user && user.auth_token) {
            console.log("4")
            //localStorage.setItem('auth_token', user.auth_token);
            console.log("5")
            //this.setCurrentUser();
            console.log("6")
        }
        console.log("7")
        return user;
    }));
}

The console output stops at 7

A: I think you have the wrong subscribe(...) implementation. Its parameters are functions (next, error, complete) that are immediately invoked when the related events occur, but you are passing a function that returns an object with data and error inner functions that will never be invoked.
Try changing the section like this:
this.authService.getNewToken(this.model.id)
          .pipe(first())
          .subscribe(data =>
            {
              // I never get to 8
              console.log('8')
              this.router.navigateByUrl('/register/profile/complete');
            },
            error => {
              console.log('9')
            }
          );


text:
Q: Deploying PhoneGap Applications to Web instead of to App Store I've built a web platform where one small feature allows users to contribute data to the system. Now that smartphones are so common, I want to build an app that allows people to submit some information, along with a camera photo and their GPS location.
As our users use varying phones, I'd like to build a single universal app to accomplish that task. I found PhoneGap online for that very purpose, but I have a question: can PhoneGap applications be deployed to the web instead of to app stores? By that, I'm asking whether camera and geolocation functionality will still work if the HTML and Javascript files are placed on a web server.
If not, I've also seen JQTouch. Can I use JQTouch instead for such camera and GPS functionality?

A: *

*I believe that a PhoneGap application is running inside an "interpreter" that will let you access the Camera Accelerometer and so on... So this means that it cannot run outside an Application. So no web deployement

*jQTouch is a UI framework, so no access to Camera or GPS

*You can use HTML5 to access location via web

A: yes, you can deploy phonegap apps with the market.
At least, if it's not an iPhone.
You should still compile the applications and make the user download them.
jQTouch is just for the GUI, much like sencha and jQuery Mobile.
HTML5 would give you a gps functionality, but that doesn't work on most phones yet (symbian and BB and WP make up about 50% of the market if not more).

A: Great Idea Maxim,
Maxim you can deploy your app outside the app store and it can access the native feature, but in that case it will be a webApp And it will be accessible from every mobile platform.
If you want that as an app(Native), You have a submit it into AppStore (For IOS) and for android you can deploy it on other markets also.


text:
Q: I have a code to simulate a data but when I check the results of the output results are not matching for data set Y I have inputted mean as 10 but when I try to check the mean after creating the data set its giving me mean as 0.09038462 could I know the reason plz
set.seed(22)
x   <- seq(5,15,length=1000)
y   <- dnorm(x,mean=10, sd=3)

mean(y)


text:
Q: Trying to CRTP. Why does this produce strange results? This is basic CRTP code.
When I run this code, the output is "world" and not "hello". Why is that?
#include <iostream>

template<typename Derived>
struct A {
    void foo()
    {
        static_cast<Derived*>(this)->bar();
    }
};

struct B : A<B>{
    void bar()
    {
        std::cout << "hello" << std::endl;
    }
};

struct C : A<C> {
    void bar()
    {
        std::cout << "world" << std::endl;
    }
};

int main() {
    void* b = new B();
    auto c = static_cast<A<C>*>(b);
    c->foo();
    return 0;
}

I'm using gcc 5.4.
The main problem is that A<B> and A<C> are different types. I would like to store them in a vector and use it like I would a polymorphic inheritance type with virtual functions. I was trying to see what void* storing would happen and I don't understand what is going on.

A:
void* b = new B();
auto c = static_cast<A<C>*>(b);
c->foo();

This yields undefined behavior. You are accessing an object of type B through a pointer to an unrelated type A<C>. That violates strict aliasing.
If you want to store pointers to different object types in a vector, then you should be using regular old virtual functions and inheritance. The CRTP is for taking common functionality and applying it to different types. It's not for treating two distinct types the same.

A: You dont need CRTP to see that there is something fishy in your example. Lets simplify it a lot:
#include <iostream>

struct B {
    void bar()
    {
        std::cout << "hello" << std::endl;
    }
};

struct C {
    void bar()
    {
        std::cout << "world" << std::endl;
    }
};

int main() {
    void* b = new B();
    auto c = static_cast<C*>(b);
    c->bar();
    return 0;
}

This prints world. We just called a C method on a B instance. How could this happen? Using void* allows you to bypass some rules, but the rules still exists. You shall not treat an instance as something it is not. If you do, you get undefined behaviour.

A:
The main problem is that A<B> and A<C> are different types. I would like to store them in a vector and use it like I would a polymorphic inheritance type with virtual functions.

You can do that by defining a regular class that can be the base class of the class template A.
struct Base
{
    virtual ~Base{} {}
    virtual void foo() = 0;
};

template<typename Derived>
struct A : Base {
    void foo() override
    {
        static_cast<Derived*>(this)->bar();
    }
};

Now you can use:
std::vector<Base*> baseObjects;
baseObjects.push_back(new B());
baseObjects.push_back(new C());

baseObjects[0]->foo();
baseObjects[1]->foo();


text:
Q: How to do DELETE request in MongoJS? I am just making a simple contactlist app, and this is what I did for deleting a record, It stops the server on pressing the delete button but the next time I start the server, it has deleted the record(i.e shows the correct list)
The other requests GET and POST work fine.
In server.js
app.delete('/contactlist/:id',function (req,res) {
var id = req.params.id;

console.log(id);

db.contactlist.remove({'_id' : mongojs.ObjectId(id)},function (err,docs) {
    res.json(doc);
   })
});

In controller.js
$scope.remove = function (id) {
    console.log(id);

    $http.delete('/contactlist/' + id).then(function(response){
        refresh();
    });
};

In index.html
<button class="btn btn-danger" ng-click="remove(contact._id)">Delete</button>

On pressing the delete function it shows this
Possibly unhandled rejection: {"data":null,"status":-1,"config":{"method":"DELETE","transformRequest":[null],"transformResponse":[null],"jsonpCallbackParam":"callback","url":"/contactlist/596bbb440b53b7584765b490","headers":{"Accept":"application/json, text/plain, */*"}},"statusText":""}

Please help! The server stops working, though the next time I start it deletes the record and shows list without the deleted record.

A: Error in server.js , it should be doc and not docs
Rest all fine! Works Well!


text:
Q: To check if a list of numbers is arithmetic or geometric with python Below is the code i have written which only check the 1st and the last patter and not in the middle.
Any help is much appreciated.
def arith_geo(list_n):
    if len(list_n) == 0:
        return 0

    for n in range(len(list_n) - 1):
        if (list_n[n + 1] - list_n[n]) == (list_n[n-1] - list_n[n-2]):
            return 'Arithmetic'
        elif (list_n[n + 1] / list_n[n]) == (list_n[n -1 ] / list_n[n - 2]):
            return 'Geometric'
        else:
            return -1
print(arith_geo([1, 2, 3, 8, 5, 6]))

A: 1) Make special treatment for length 0,1,2  (is length 2 sequence valid AP or GP?)
2) Make Arith_Counter and Geom_Counter variables.
3) Make loop for indexes n in range 1..length-2
4)  At every step.
  check if AP property valid -
  if yes, increment Arith_Counter

  check if GP property valid
  if yes, increment Geom_Counter.

5) At the end check that
Arith_Counter = length - 2
or
Geom_Counter = length - 2
(or both)

This is simple approach without early return (you can add checking counters after every step)

A: Thanks @MBo and @Jeremy Kahan, your answers were awesome directives and with them i managed to solve the question.
Here is what i have done:
 def arith_geo(list_n):
    if len(list_n) == 0:
        return 0
    diff = list_n[1] - list_n[0]
    div = list_n[1] / list_n[0]
    for num in range(1, len(list_n)):
        if list_n[num] - list_n[num - 1] == diff:
            counter = 'Arithmetic'
        elif list_n[num] / list_n[num-1] == div:
            counter = 'Geometric'
        else:
            counter = -1
            break
    return counter
print(arith_geo([2,4,8,16]))
print(arith_geo([1,2,3,4]))
print(arith_geo([1,2,8,3]))

A: With the all built-in function and sequential elimination of possible states it could be implemented pretty straightforward:
def arith_geo(list_n):

    if len(list_n) < 2:
        return "Not a progression - the list is too short"

    # ---------------------------------------------
    states = ['Arithmetic', 'Geometric'] # possible states of list_n

    b1, b2 = list_n[:2]
    adj_elements = list(zip(list_n[1:], list_n[2:]))

    # ---------------------------------------------
    # arithmetric part:
    # ---------------------------------------------

    if not all(y - x == b2 - b1 for x,y in adj_elements):
        states.remove('Arithmetic')

    # ---------------------------------------------
    # geometric part:
    # ---------------------------------------------
    # according to the definition of geometric progression:
    # b1 != 0
    # q != 0 <=> b2 != 0
    # ---------------------------------------------

    if b1 * b2 == 0 or not all(y / x == b2 / b1 for x,y in adj_elements):
        states.remove('Geometric')

    # ---------------------------------------------
    state_message = {0:"Neither arithmetic nor geometric",
                     2:"Both arithmetic and geometric",
                     1:(states+[''])[0]}

    return state_message[len(states)]

Results:
print(arith_geo([])) # Not a progression - the list is too short
print(arith_geo([0])) # Not a progression - the list is too short

print(arith_geo([1, 2])) # Both arithmetic and geometric
print(arith_geo([7, 7])) # Both arithmetic and geometric
print(arith_geo([7, 7, 7])) # Both arithmetic and geometric

print(arith_geo([0, 0])) # Arithmetic
print(arith_geo([0, 1])) # Arithmetic
print(arith_geo([1, 0])) # Arithmetic
print(arith_geo([0, 2, 4])) # Arithmetic
print(arith_geo([7, 5, 3])) # Arithmetic

print(arith_geo([1, 2, 4])) # Geometric
print(arith_geo([1, -0.5, 0.25])) # Geometric

print(arith_geo([0, 2, 3, 8])) # Neither arithmetic nor geometric
print(arith_geo([1, 2, 3, 8])) # Neither arithmetic nor geometric

Note that the function distinguishes between pairs [0, 0] and [7, 7], as well as [0, 1] and [1, 2] - according to the definition of geometric progression.


text:
Q: How to insert multiple rows wih QT Sqlite? I have the following code (it is a function), and I want to insert 500 values to my database whenever I call it.
QSqlDatabase::database().transaction();
query.prepare("INSERT INTO datatable (Name, age, data1, data2, data3, data4, data5)"
              "VALUES (?, ?, ?, ?, ?, ?, ?)");
for (int i = 0; i<500; i++){
    query.bindValue(0,Name[j]);
    query.bindValue(1,age[j]);
    query.bindValue(2,data1[j]);
    query.bindValue(3,data2[j]);
    query.bindValue(4,data3[j]);
    query.bindValue(5,data4[j]);
    query.bindValue(6,data5[j]);
    query.next();   //just trying to go for the next row
}
qDebug() << "Finish" << QSqlDatabase::database().commit();

The problem is that this is only inserting the data from the values when j=500, I mean, this only stores the last data, and the other 499 doesn't get stored.
Can anyone help me? I have tried to put the query, prepared for loop inside but this didn't work as well.

A: You have to use the exec() method instead of next():
QSqlDatabase db = QSqlDatabase::database();

if(db.transaction()){

    QSqlQuery query;
    query.prepare("INSERT INTO datatable (Name, age, data1, data2, data3, data4, data5) VALUES (?, ?, ?, ?, ?, ?, ?)");
    for (int i = 0; i < 500; i++){
        query.bindValue(0, Name[i]);
        query.bindValue(1, age[i]);
        query.bindValue(2, data1[i]);
        query.bindValue(3, data2[i]);
        query.bindValue(4, data3[i]);
        query.bindValue(5, data4[i]);
        query.bindValue(6, data5[i]);
        if(!query.exec()){
            qDebug() << query.lastError().text();
        }
    }

    if(!db.commit()){
        qDebug() << db.lastError().text();
    }
}

A: query.next() is usually used to iterate through rows of a data reader. You should be using query.exec() to insert data with your transaction.
Here is a pretty good tutorial: https://katecpp.wordpress.com/2015/08/28/sqlite-with-qt/

A: This is exactly what QSqlQuery::execBatch is for.
query.prepare("INSERT INTO datatable (Name, age, data1, data2, data3, data4, data5)"
              "VALUES (?, ?, ?, ?, ?, ?, ?)");
QVariantList names;
QVariantList ages;
QVariantList data[5];
for (int i = 0; i<500; i++) {
    names << Name[j];
    ages << age[j];
    data[0] << data1[j];
    data[1] << data2[j];
    data[2] << data3[j];
    data[3] << data4[j];
    data[4] << data5[j];
}
query.addBindValue(names);
query.addBindValue(ages);
for (int i=0; i < 5; ++i)
    query.addBindValue(data[i]);

if (!query.execBatch())
   qDebug() << q.lastError();


text:
Q: Server cannot append header after HTTP headers have been sent Below shown is my code after creating the CSV file, i want to download the file so i am using below code. but its throwing error " Server cannot append header after HTTP headers have been sent" at "Response.AddHeader("Content-disposition", "attachment; filename=" + fileCSV + "\"");" place. Its downloading but browser not redirecting to same page.
string[] header = { "Error Occurred On", "Controller Name", "Action Name", "Exception Occurred", "Stack Trace Description", "InnerException Occurred", "Stack Trace InnerException Occurred " };

The code:
DataTable dt = new DataTable();
for (int e = 0; e < header.Length; e++)
{
    dt.Columns.Add(header[e], typeof(string));
}
StringBuilder sb = new StringBuilder();
IEnumerable<string> columnNames = dt.Columns.Cast<DataColumn>().Select(column => column.ColumnName);
sb.AppendLine(string.Join(",", columnNames));
dt.DefaultView.RowFilter = "[Exception Occurred] LIKE '%" + keyword + "%'";
DataTable dtFilter = new DataTable();
dtFilter = dt.DefaultView.ToTable();
foreach (DataRow row in dtFilter.Rows)
{
    IEnumerable<string> fields = row.ItemArray.Select(field => field.ToString());
    sb.AppendLine(string.Join(",", fields));
}
System.IO.File.WriteAllText(fileCSV, sb.ToString());

byte[] bytes = Encoding.ASCII.GetBytes(sb.ToString());
if (bytes != null)
{
    Response.Clear();
    Response.ContentType = "text/csv";
    //Response.AddHeader("Content-Length", bytes.Length.ToString());
    Response.AddHeader("Content-disposition", "attachment; filename=" + fileCSV);
    Response.BinaryWrite(bytes);
    Response.Flush();
    Response.End();
}

A: You cannot redirect after downloading the File, you are attempting to perform 2 actions where you can only do the first.
I suggest that you download the file in a new (popup) window and redirect the main page if required.
Edit:-
You could force the download by opening the file-download action using window.open.
Example:-
Download File

A: In HTTP there is a single response for each request. So this error means that you've already send something to response.

A: Not sure you are still looking for an answer, but rather than Response.Flush & Response.End, try HttpContext.ApplicationInstance.CompleteRequest(). It has solved a lot of my problems when trying to write directly to request stream.

A: Some few minutes ago I had the the same problem with a file download. I want to share what worked for me.
The most important thing add:
Response.ClearHeaders();

in the begin of action result.
And, to be honest, I read it here https://www.codeproject.com/Questions/1038819/How-to-resolve-this-error-Server-cannot-append-hea


text:
Q: Using pd.concat to add null valued columns from list if not in dataframe? I got the below performance warning

PerformanceWarning: DataFrame is highly fragmented. This is usually the result of calling frame.insert many times, which has poor performance. Consider using pd.concat instead. To get a de-fragmented frame, use newframe = frame.copy()

when I tried to add columns to a dataframe from a list.
The warning asks me to consider using pd.concat. But it looks like pd.concat does not take lists.
I am trying to create a set of dataframes from Excel with the same columns and rows. Each file I'm working with has a slightly different set of numbered columns. I tried iterating over a list to add the columns that are missing.
But since that throws a performance warning, I'd like to improve performance. A sample of my code is below.
missing_columns = list(map(str, [*range(1900, 2022, 1)]))

for f in files:
    data = pd.read_excel(f)
    cols = data.columns.values.tolist()
    new_cols[0] = 'Company'
    data.columns = new_cols
    for missed in missing_columns :
        if missed not in new_cols:
            data[missed] = np.NAN
    data = data.set_index('Company')
    data = data.reindex(sorted(data.columns), axis = 1)

Any help is appreciated!

A: I am trying to process a set of Excel files that have different sets of columns, and I want to add any missing columns to the dataframes so that they all have the same set of columns.
One issue with my code was that it used a for loop to iterate over the missing cols list and add missing columns to the dataframes. This approach can be inefficient because it requires the code to iterate over the entire missing cols list for each dataframe, which can take a long time if the list is large and the dataframes are large.
One way to improve the efficiency of the code is to use the reindex method to add missing columns to the dataframes, rather than using a for loop. The reindex method can add missing columns to a dataframe and fill them with a specified value, such as NaN, which is what I tried in the for loop. By using the reindex method, I can avoid the need to iterate over the years list and add missing columns one at a time, which can improve the performance of the code.
Here how I used the reindex method to add missing columns to the dataframes:
# Get the complete set of columns for the dataframes
all_columns = ['Company'] + missing_columns

# Reindex the dataframes to include all columns
data = data.reindex(columns = all_columns, fill_value = np.NAN)


text:
Q: Deleting ECS services with Ansible I am trying to delete four ECS services with Ansible 2.9.13. I know Ansible can't delete ECS services with running tasks, so I tried setting desired_count to "0" and then deleting it:
- name: Set Service Tasks to 0
  ecs_service:
    name:  "{{service}}"
    state: present
    desired_count: 0
    cluster:  "{{cluster_name}}"
    task_definition: "{{service_data.services[0].taskDefinition}}"
    region: "{{region}}"

- name: Delete OLD ECS service
  ecs_service:
    state: absent
    name:  "{{service}}"
    cluster:  "{{cluster_name}}"
    region: "{{region}}"

It worked for the first service but failed on the second one with this error:
"msg": "It is not possible to update the load balancers of an existing service"

Has anyone run across this issue? Any suggestions on getting around it?

A: Okay, I think I figured it out. It kept thinking I'm trying to change the load balancer, but I was not. No idea why. So I opted to grab all the ALB info and just feed it to the module directly. That did the trick.
Since only two out of the four services actually have a load balancer, this posed another problem. It would fail on the ones WITHOUT. Got around that by adding a conditional. So here's the final mess:
- name: Get Service Data
  ecs_service_info:
    cluster: "{{cluster_name}}"
    region: "{{region}}"
    service: "{{service}}"
    details: true
  register: service_data

- set_fact: with_lb=true
  when: service_data.services[0].loadBalancers|length == 1

- set_fact: with_lb=false
  when: service_data.services[0].loadBalancers|length == 0

- name: Set Tasks with ALB to 0
  ecs_service:
    name: "{{service}}"
    state: present
    desired_count: 0
    cluster: "{{cluster_name}}"
    load_balancers:
      - containerPort: "{{service_data.services[0].loadBalancers[0].containerPort | int}}"
        containerName: "{{service_data.services[0].loadBalancers[0].containerName}}"
        targetGroupArn: "{{service_data.services[0].loadBalancers[0].targetGroupArn}}"
    task_definition: "{{service_data.services[0].taskDefinition}}"
    region: "{{region}}"
  when: with_lb|bool

- name: Set Remaining Tasks to 0
  ecs_service:
    name: "{{service}}"
    state: present
    desired_count: 0
    cluster: "{{cluster_name}}"
    task_definition: "{{service_data.services[0].taskDefinition}}"
    region: "{{region}}"
  when: not with_lb|bool

- name: Delete OLD ECS service
  ecs_service:
    state: absent
    name:  "{{service}}"
    cluster:  "{{cluster_name}}"
    region: "{{region}}"

Cheers!


text:
Q: Passing hidden field value along with textbox value through an array I wrote this function to push values in text boxes which is inside a <p> tag to an array and it is working all good.
$(document).ready(function(){

 $("#form_timesheet").submit(function(e){
    var arr=[];
    var i=0;
    $("#addedRows p").find("input[type=text]").each(function(){
    arr.push($(this).val());
    i++;
 });
 });

now i want to pass a hidden field value along with this text box values through the same array. how can i do that by editing the line '   $("#addedRows p").find("input[type=text]").each(function()'

A: You just need to add
$("#addedRows p").find("input[type=hidden]").each(function(){
arr.push($(this).val()); // and add whatever value in it

A: Standej is mostly right , just modify his answer as following:
$("#addedRows p").find("input[type=hidden], input[type=text]").each(function(){


text:
Q: Xtend: evaluate expression directly from a string Is there a possibilty in the Xtend language to evaluate an expression directly from a string, e.g. like Eval in Groovy. I want to do something like this in Xtend (the example is from Groovy):
import groovy.util.Eval

assert Eval.me('2*5') == 10

If there is no built-in way to do this, what would be the most similar alternative to achieve this (if any)?
P.S. Just to be clear: the expression is of course not just a simple math operation (like in the example); in particular, I would like to call my own Xtend function doing some transformation on a list.

A: I think there isn't anything like this in Xtend, so you should probably look for Java libraries that do this.
For example Java EL seems like a good standard way for evaluating strings. Since EL 3 there is the ELProcessor which doesn't require JSP anymore and it seems quite easy to use:

ELProcessor elp = new ELProcessor();
elp.defineBean("employee", new Employee("Charlie Brown"));
String name = elp.eval("employee.name");

Here is nice article about the latest features of EL, like lambda expression. The article also contains some examples about collections and how to call external methods.


text:
Q: parse rows and conditionally delete a delimiter or token my background is in c/c++... I'm still pretty new to VBA, so please forgive me. I'm pulling latitude data into an excel spreadsheet from a database, but I'm getting an unwanted decimal. Below is a fragment I have copied out of the spreadsheet.
Example of invalid data (inserting a decimal after the minutes value that I don't want):

*

*38'5.'48.189

*38'5.'48.023

*38'5.'48.023

*38'5.'48.023

Example some valid data:

*

*38'10'51.881

*38'10'51.881

*38'10'51.881

*38'10'52.000

*38'10'52.000

*38'10'52.000

How can I go through row by row and delete all the .'s that I don't want? Note that I want to keep the actual decimal places of the seconds values. This data is stored in column K of my spreadsheet.
Edit: I know I can convert to a .csv and I know how to write a program in c++ that will do this, but  a vba script would be great for the sake of simplicity. Thanks!

A: Take your pick :)
I am assuming that the Data is in Column A
Using an Excel Formula
Paste this in Cell B1 and copy it down.
=REPLACE(A9,FIND(".'",A9,1),2,"'")

Using VBA
Replace Sheet1 with the relevant sheet.
Sheets("Sheet1").Replace What:=".'", Replacement:="'", LookAt:=xlPart, _
SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, ReplaceFormat:=False

HTH
Sid


text:
Q: How to end the fixed element using the .offset.top I am using the Javascript code .offset.top to fix an element, but I want to end it when reaching another element.

this is the html

Does anyone know how to fix it?

A: There is a lot of related questions about this subject, you will find a lot of tricks, some works, others not so well, but when is about scroll to fixed, I always use this jquery plugin, created to solve this exact problem.
Demos:
http://jsfiddle.net/ZczEt/167/
http://jsfiddle.net/y3qV5/434/
http://jsfiddle.net/k2R3G/81/
Plugin and source
https://github.com/bigspotteddog/ScrollToFixed
Usage:
$(document).ready(function() {
  $('#mydiv').scrollToFixed();
});

EDIT:
If you are just looking for that line, you should use this to calculate the .single-content top.
$(document).ready(function (){
    var auxtop = $('.single-content').offset().top
    var margintop = parseFloat($('.single-content').css('margin-top').replace(/auto/, 0));
    var sidebartop = auxtop - margintop;
    $(window).scroll(function (event){
        var y = $(this).scrollTop();
        if ( y>= sidebartop ){
            $('#sharing-links').addClass('fixed');
        } else {
            $('#sharing-links').removeClass('fixed');
        }
    });
});