text:
Q: google Map loads without data connection I'm almost new to android, so I'm trying to make a map activity; for this, I followed the demo from Google: https://developers.google.com/maps/documentation/android/intro
So, the map works without any problem, but I noticed a weird behavior, when I install the map on my cell phone and turn on the airplane mode (Wifi and 4g are off), the map still loads. How is this possible? I thought that the application downloads the map through data (4g or wifi). Is it possible that my application is loading the map from Google play services? Here is the code.
package com.example.startup;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import org.json.JSONObject;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesClient;
import com.google.android.gms.location.LocationClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.OnMapClickListener;
import com.google.android.gms.maps.Projection;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.Polyline;
import com.google.android.gms.maps.model.PolylineOptions;

import android.R.layout;
import android.app.ActionBar;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.Style;
import android.graphics.Path;
import android.graphics.Point;
import android.location.Location;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.NavUtils;
import android.support.v4.view.ViewPager.LayoutParams;
import android.text.Layout;
import android.util.Log;
import android.util.TypedValue;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RadioButton;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.RadioGroup;
import android.widget.TableLayout;
import android.view.View.OnClickListener;

public class Navigation extends FragmentActivity implements
GooglePlayServicesClient.ConnectionCallbacks,
GooglePlayServicesClient.OnConnectionFailedListener  {

    private GoogleMap mMap;
    int ZOOM = 13;
    ArrayList<LatLng> markerPoints;
    ArrayList<Location> MyLocation;
    private RadioButton layer;
    boolean show_statsEnable=false;
    private LocationClient mLocationClient;
    private ActionBar actionBar;
    int navigation_number=4;
    float speed=0;
    float distance=0;
    float elapsed_time=0;
    boolean showing=false;
    Location myLocation = null;
    PopupWindow popwin=null;
    RelativeLayout show_stats=null;
    TextView navigation_speed=null;
    boolean navigation_trackEnable=false;
    List<LatLng> LatLngArray = new ArrayList<LatLng>();
    boolean navigation_ShowStatsEnable=false;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(R.layout.navigation);

        mLocationClient = new LocationClient(this,this,this);
        setUpMapIfNeeded();

    }

        }

    @Override
    protected void onStart() {
        super.onStart();
        // Connect the client.
        mLocationClient.connect();
//        mLocationClient.setMockMode(true);
    }

    @Override
    protected void onStop() {
        // Disconnecting the client invalidates it.
        mLocationClient.disconnect();
        super.onStop();
    }

    @Override
    protected void onResume() {
        super.onResume();
        setUpMapIfNeeded();

    }

    private void setUpMapIfNeeded() {
        if (mMap == null) {
            mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
                    .getMap();
        }
        if (mMap != null)
        {
            setUpMap();
    }
    }

    private void setUpMap() {

        mMap.setMapType(GoogleMap.MAP_TYPE_NORMAL);
        mMap.setMyLocationEnabled(true);
        mMap.getUiSettings().setCompassEnabled(false);
        mMap.getUiSettings().setZoomControlsEnabled(false);
        mMap.getUiSettings().setCompassEnabled(false);
    }
    private void update_map(){
//      Toast.makeText(this, "Zoom "+String.valueOf(ZOOM) , Toast.LENGTH_SHORT).show();

        try{
            myLocation = mLocationClient.getLastLocation();
            double latitude = myLocation.getLatitude();
            double longitude = myLocation.getLongitude();
            LatLng myPosition=null;
            myPosition = new LatLng(latitude, longitude);
//          CameraUpdate yourLocation = CameraUpdateFactory.newLatLngZoom(myPosition, ZOOM);
//          mMap.animateCamera(yourLocation);
            CameraPosition cameraPosition = new CameraPosition.Builder()
                .target(myPosition)      // Sets the center of the map to Mountain View
                .zoom(ZOOM)                   // Sets the zoom
                .bearing(0)                // Sets the orientation of the camera to east
                .tilt(30)                   // Sets the tilt of the camera to 30 degrees
                .build();                   // Creates a CameraPosition from the builder
            mMap.animateCamera(CameraUpdateFactory.newCameraPosition(cameraPosition));
        }
        catch(Exception e){
        }
    }

    @Override
    public void onConnectionFailed(ConnectionResult arg0) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onConnected(Bundle arg0) {
        LocationRequest locationRequest = LocationRequest.create();
        locationRequest.setFastestInterval(0);
        locationRequest.setInterval(0).setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
        mLocationClient.requestLocationUpdates(locationRequest, mLocationListener);
    }
    private LocationListener mLocationListener = new LocationListener() {

        private long mLastEventTime = 0;

        @Override
        public void onLocationChanged(Location myLocation) {
            update_map();

    };

    @Override
    public void onDisconnected() {

    }
}

Any comment will be appreciated! Thanks

A: What you are seeing is Cached map tiles that were downloaded when you first had a connection. If you move the map to a different point on the globe that you have not visited you will see that the map does not load

A: OK, here's the deal...
The map shows because it has been cached by the phone. This means that the phone has downloaded a bit of a map for faster loading (in the same way your browser might download part of a frequently visited website, so that to load the website, it doesn't have to spend so much time downloading the HTML and other stuff). As such, no data connection is needed.
What you may find (personally, I find this cool) is that, even when you are viewing an uncached map (or rather, viewing an empty screen) the map may still be able to locate your position. This is because the phone uses GPS or GLONASS (depending on where you live) to locate you, regardless of whether or not there is data.
By scrolling away from the map part displayed when on airplane mode,  you will probably see a blank screen, confirming that it is cached.
Hope this helps!


text:
Q: Where is Schwarzschild solution valid? The extrinsic Schwarzschild solution is a vacuum solution, meaning that it is valid for regions of spacetime where there is no matter or energy. This seems to imply that the Schwarzschild solution is only valid outside the spherical body. For inside the spherical object, the internal Schwarzschild solution is used, where the stress energy tensor is no longer 0. However, when we use kruskal coordinates, the coordinate system covers the inside of the spherical object (usually taken to be a black hole). How can the kruskal coordinates accurately describe interior region of black hole when it is only derived for when there's a vacuum?
The question linked in the comments does not have an answer to this question, because the answers say that there can be spacetime curvature in a vacuum solution. My question is NOT "how can there be spacetime curvature in a vacuum?". The question is why do we talk about the spacetime INSIDE a black hole (which supposedly has a mass) as Schwarzschild?

A:
However, when we use kruskal coordinates, the coordinate system covers the inside of the spherical object (usually taken to be a black hole).

The interior (by which I mean, $r<r_S$) of a Schwarzschild black hole is also a vacuum, insofar as the stress-energy tensor vanishes there.

But it's a black hole..doesn't it have mass/energy?

The Schwarzschild metric is a vacuum solution to the Einstein equations. It describes the metric in a vacuum ($T_{\mu\nu}=0$) under the assumptions that the metric is spherically symmetric and stationary. If you model a star as a spherical fluid with a sharp boundary with pure vacuum outside it, then the exterior region would be described by the Schwarzschild metric while the interior of the star (where $T_{\mu\nu}\neq 0$) would be described by the interior Schwarzschild metric. In this case, the parameter $M$ which appears in the exterior Schwarzschild solution is the mass of the star.
One could ask, however, what happens when you assume that $T_{\mu\nu}=0$ everywhere.  The most general spherically symmetric, stationary vacuum solution to Einstein's equations is
$$\mathrm ds^2 = -\left(1-\frac{\alpha}{r}\right)c^2\mathrm dt^2 + \left(1-\frac{\alpha}{r}\right)^{-1} \mathrm dr^2 + r^2 \mathrm d\Omega^2$$
where $\alpha$ is an unknown constant. If $\alpha = 0$, then this is just the standard Minkowski spacetime from special relativity. However, it's entirely possible that $\alpha \neq 0$, provided that we remove the set of points with $r=0$ from the spacetime manifold (otherwise, the metric would be undefined there).
One might object immediately by noting that for $r=\alpha$, the metric component $g_{rr}$ is undefined. However, this is what is called a coordinate singularity; it's not actually a problem with the spacetime, just with this choice of coordinates. One can switch to the Kruskal coordinate system to demonstrate this fact. In contrast, the singularity at $r=0$ is a genuine one, and so that set of points must be removed.
So if $\alpha \neq 0$, then what is it? Comparison with the exterior Schwarzschild solution outside of a star provides a physical interpretation - this is what you'd expect to see if a total mass $M\equiv \alpha c^2/2G$ was crushed down to a single point in space (which, to avoid infinities, must be excised from the spacetime manifold).  However, it's important to note that at all points (other than the singularity, which again has been removed), $T_{\mu\nu}=0$. This is true both for $r>\alpha$ and $0<r<\alpha$.

[...] from observations black holes are not a single point. Supermassive black holes have a radius of ~15 million miles.

The 15 million miles you refer to is the event horizon of the black hole - the $\alpha$ which appears in my explanation above.  Again, for a Schwarzschild black hole, $T_{\mu\nu}=0$ both outside the event horizon and inside the event horizon.

[...] For these black holes there is surely mass and energy, so it seems like we cannot speak of geodesics "inside" the black hole if we are still sticking with schwartzchild space time

One of the reasons I keep using the qualifier Schwarzschild to refer to a black hole is because this metric is the simplest possible model for understanding the phenomenon. It is not necessarily a realistic model for an actual black hole, which would generically be e.g. rotating and surrounded by an accretion disk which is slowly falling below the event horizon. Rather, you should think of it as a toy model for understanding the nuances of the event horizon and other highly non-intuitive phenomena. Adding a steady influx of mass or some other more complex features would only obscure these issues.

A: Schwarzschild solution is valid only outside of matter's sphere and it is static - there is no time dependence. In case of black hole it ends on the even horizon. Behind it, time and space change their place and the resulting metric ("extended" Schwarzschild) is no more static - it depends explicitly on time. Hence, the black hole spacetime have two regions, separated by the event horizon, that are described by two different metrics. The use of the name Schwarzschild for both of them is somewhat misleading but due to history. Schwarzschild entitled his paper "On the gravitational field of a mass point according to Einstein's theory". He was not aware of the immense meaning of his result and the fact that in general relativity there is no something like a "mass point".

redpajama_set_name: RedPajamaStackExchange


text:
Q: Relation between postgres and pg-admin can any one help me with this?
How pg-admin is used with postgresql?
How do they work together?
I want to know the working and the realtion between the two.

A: pgAdmin is a GUI client specifically written for PostgreSQL. It is written in Python and uses the PostgreSQL C library libpq via psycopg2 to communicate with the PostgreSQL database server.
You need the PostgreSQL server running before you can connect to it with pgAdmin.
pgAdmin is an independent project, and it is written by different people than PostgreSQL (although there are naturally overlaps).


text:
Q: Paired t-test in testing difference between two classifiers While reading the paper "Approximate Statistical Tests for Comparing Supervised Classification Learning Algorithms", I am confused at Section 3.3 when the authors claim that the paired t-test is not suitable to use to compare two classifiers $A$ and $B$, because the observed proportion of test examples misclassified $p_A$ and $p_B$ by $A$ and $B$ during trial $i$ are not independent. However, according to my understanding, the paired t-test assumes that the samples are paired, thus dependent.
What I reckon is that the test mentioned in the paper is the unpaired t-test. However, I think there is no motivation to consider unpaired t-test to compare two classifiers.
Thank you in advance!

A: We use a paired t-test when we have two measurements on the same sampling unit (dependent observations) AND when sampling units are independent of one another. Observations are paired, not samples.
In the situation in Section 3.3, the sampling units are NOT independent of one another because sampling units are created artificially by resampling the sample dataset (S). A paired t-test is therefore not appropriate.
The test mentioned in the paper uses a formula based on differences (p(i)), so it is referring to a paired t-test.


text:
Q: Inet6Address.getByName() giving odd response for 0:0:0:0:0:ffff:0:0 I'm using the following code to normalise IPv6 IP addresses:
try {
    return Inet6Address.getByName(ipAddress).getHostAddress();
} catch (final UnknownHostException e) {
    return ipAddress;
}

However, when I use IP "0:0:0:0:0:ffff:0:0", I get "0.0.0.0" as the response. I tried this code with "ffff" in each of the other octets, and they seem to be fine:
ffff:0:0:0:0:0:0:0
0:ffff:0:0:0:0:0:0
0:0:ffff:0:0:0:0:0
0:0:0:ffff:0:0:0:0
0:0:0:0:ffff:0:0:0
0.0.0.0
0:0:0:0:0:0:ffff:0
0:0:0:0:0:0:0:ffff

Any thoughts on why this IP in particular wouldn't return an IPv6 format?

A: getHostAddress() is (correctly) displaying an IPv4-mapped IPv6 address.


text:
Q: Getting 200 meter distance difference from the current location in GPS with map This is my Map Activity class and i have to extract the current location lat n long points and have to show them on map.And i also have incorporated a search box which will display the location of an address on map. Its showing the location but at difference of 200 meter. And when i reopen it, it always show the previous traced location or searched location. I want to show the extracted lat n long points on map.Please Help me out. Thanks in advance..
  import java.io.IOException;
  import java.util.List;
  import java.util.Locale;

  import android.app.AlertDialog;
  import android.graphics.drawable.Drawable;
 import android.location.Address;
 import android.location.Criteria;
import android.widget.Button;
 import android.widget.EditText;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapController;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;
import com.google.android.maps.OverlayItem;

public class MapViewActivity extends MapActivity implements LocationListener {

private MapView mapView;
Button search;
EditText address;
 private LocationManager locationManager;
 @Override
 public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

search=(Button)findViewById(R.id.find_loc);
address=(EditText)findViewById(R.id.enter_address);
search.setOnClickListener(new OnClickListener() {

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        address=(EditText)findViewById(R.id.enter_address);
        if (address.getText().toString().trim().length() == 0) {
            showMessage("Error", "Please enter address!");
            return;
        }
        Geocoder geoCoder = new Geocoder(MapViewActivity.this,
    Locale.getDefault());
        try {
            List<Address> addresses = geoCoder.getFromLocationName(
                    address.getText().toString(), 1);
         // Getting latitude
            double latitude = addresses.get(0).getLatitude();

            // Getting longitude
            double longitude = addresses.get(0).getLongitude();

            if (addresses.size() > 0) {
              GeoPoint p = new GeoPoint(
                        (int) ( latitude * 1E6),
                        (int) (longitude * 1E6));
           // Getting MapController
            MapController mapController =
 mapView.getController();

            // Locating the Geographical point in the Map
            mapController.animateTo(p);

            //Applying a zoom
            mapController.setZoom(15);

            // Redraw the map
            mapView.invalidate();

            // Getting list of overlays available in the map
            List<Overlay> mapOverlays = mapView.getOverlays();

            // Creating a drawable object to represent the
 image of mark in the map
            Drawable drawable =
  MapViewActivity.this.getResources().getDrawable(R.drawable.cur_position);

            // Creating an instance of ItemizedOverlay to mark
 the current location in the map
            CurrentLocationOverlay currentLocationOverlay = new
  CurrentLocationOverlay(drawable);

            // Creating an item to represent a mark in the
 overlay
             OverlayItem currentLocation = new OverlayItem(p,
 "Current Location", "Latitude : " + latitude + ", Longitude:" + longitude);

            // Adding the mark to the overlay
            currentLocationOverlay.addOverlay(currentLocation);

            // Clear Existing overlays in the map
            mapOverlays.clear();

            // Adding new overlay to map overlay
            mapOverlays.add(currentLocationOverlay);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        catch(Exception e)
        {
            showMessage("Error", "Address not found!");
            e.printStackTrace();
        }
    }
});
// Getting reference to MapView
mapView = (MapView) findViewById(R.id.map_view);

// Setting Zoom Controls on MapView
mapView.setBuiltInZoomControls(true);

// Getting LocationManager object from System Service LOCATION_SERVICE
locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);

// Creating a criteria object to retrieve provider
//Criteria criteria = new Criteria();
final Criteria criteria = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_FINE);
criteria.setAltitudeRequired(false);
criteria.setBearingRequired(false);
criteria.setCostAllowed(true);
criteria.setPowerRequirement(Criteria.POWER_LOW);

// Getting the name of the best provider
String provider = locationManager.getBestProvider(criteria, true);

// Getting Current Location
Location location = locationManager.getLastKnownLocation(provider);

if(location!=null){
    onLocationChanged(location);
}

locationManager.requestLocationUpdates(provider, 20000, 0, this);

}
 @Override
 public boolean onCreateOptionsMenu(Menu menu) {
  getMenuInflater().inflate(R.menu.activity_main, menu);
  return true;
}

  @Override
 protected boolean isRouteDisplayed() {
// TODO Auto-generated method stub
  return false;
  }
  @Override
 public void onBackPressed() {
    finish();
 }
@Override
public void onDestroy() {
 if (locationManager != null) {
 locationManager.removeUpdates(this);
 }
 super.onDestroy();
  }

 @Override
  public void onLocationChanged(Location location) {
// Getting latitude
double latitude = location.getLatitude();

// Getting longitude
double longitude = location.getLongitude();

// Setting latitude and longitude in the TextView tv_location
//tvLocation.setText("Latitude:" +  latitude  + ", Longitude:"+ longitude
 );

// Creating an instance of GeoPoint corresponding to latitude and longitude
GeoPoint point = new GeoPoint((int)(latitude * 1E6), (int)(longitude*1E6));

// Getting MapController
MapController mapController = mapView.getController();

// Locating the Geographical point in the Map
mapController.animateTo(point);

// Applying a zoom
mapController.setZoom(15);

// Redraw the map
mapView.invalidate();

// Getting list of overlays available in the map
List<Overlay> mapOverlays = mapView.getOverlays();

// Creating a drawable object to represent the image of mark in the map
Drawable drawable =
this.getResources().getDrawable(R.drawable.cur_position);

// Creating an instance of ItemizedOverlay to mark the current location in
 the map
CurrentLocationOverlay currentLocationOverlay = new
 CurrentLocationOverlay(drawable);

// Creating an item to represent a mark in the overlay
OverlayItem currentLocation = new OverlayItem(point, "Current Location",
 "Latitude : " + latitude + ", Longitude:" + longitude);

// Adding the mark to the overlay
currentLocationOverlay.addOverlay(currentLocation);

// Clear Existing overlays in the map
mapOverlays.clear();

// Adding new overlay to map overlay
mapOverlays.add(currentLocationOverlay);

}

  private void showMessage(final String title, final String message) {
runOnUiThread(new Runnable() {

    public void run() {
        AlertDialog.Builder alert = new AlertDialog.Builder(MapViewActivity.this);
        alert.setTitle(title);
        alert.setPositiveButton("OK", null);
        alert.setMessage(message);
        alert.show();
    }
});
}
    @Override
  public void onProviderDisabled(String provider) {
 // TODO Auto-generated method stub
   }

@Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
 }

 @Override
  public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}

 }

   and this is my CurrentLocationOverlay class

package com.ceolution.bhinstitute.crm;

 import java.util.ArrayList;

import android.graphics.drawable.Drawable;
import android.util.Log;

 import com.google.android.maps.ItemizedOverlay;
 import com.google.android.maps.OverlayItem;

 public class CurrentLocationOverlay extends ItemizedOverlay<OverlayItem> {

private ArrayList<OverlayItem> mOverlays = new ArrayList<OverlayItem>();

public CurrentLocationOverlay(Drawable defaultMarker) {
    super(boundCenterBottom(defaultMarker));
}

// Executed, when populate() method is called
@Override
protected OverlayItem createItem(int arg0) {
    return mOverlays.get(arg0);
}

@Override
public int size() {
    return mOverlays.size();
}

public void addOverlay(OverlayItem overlay){
    mOverlays.add(overlay);
    populate(); // Calls the method createItem()
}

@Override
protected boolean onTap(int arg0) {
    Log.d("Tapped", mOverlays.get(arg0).getSnippet());
    return true;
}
 }

A:     // Getting LocationManager object from System Service LOCATION_SERVICE
    locationManager = (LocationManager) getSystemService(LOCATION_SERVICE);

    // getting GPS status
    isGPSEnabled = locationManager
            .isProviderEnabled(LocationManager.GPS_PROVIDER);

    String provider;
    if(!isGPSEnabled)
    {
        provider = LocationManager.NETWORK_PROVIDER;
    }
    else
        provider=LocationManager.GPS_PROVIDER;

    locationManager.requestLocationUpdates(provider, 20000, 0, this);

use above code after
// Setting Zoom Controls on MapView
        mapView.setBuiltInZoomControls(true);

hope this will help and also you can give alert to user to enable gps.


text:
Q: gmail API Users.messages: list is not getting replies If I make a request to the gmail API for Users.messages.list it will return 100 of the newest messages.
If I make another request, 1 minute later and there are no new emails it will return the same 100 most recent messages.
If I make a third request, 2 minutes after the original and there is a reply to one of the 100 most recent messages it will still return the 100 most recent messages.
The problem with this is the it only returns the message id and thread id, not if there is a new reply or not.  That would mean that I would have to check every message that I have locally stored, or every one of the 100 returned messages just to know if there was a reply to it or not.
The way that works, you couldn't "check" your email via the api because if you had stored 10000 messages and you were checking replies on all of them you would use up your entire API "number of requests" allocation in a single day!
What's wrong with you Google?
Sure I could use pop3 or imap but why when I could just use something like /list_recent?

A: You should definitely take a look at this part of the Gmail API documentation: https://developers.google.com/gmail/api/guides/push
Basically, it explains you how you can setup a "watch" over a Gmail account and receive notifications (new e-mail, deleted e-mail, labels added...) through Pub/Sub, the messaging queue protocol from Google.
The notifications will contain an historyId, which is a kind of milestone in the Gmail account. Using the /history endpoint, you'll then get the e-mails that were added and/or deleted since this history point. You have to store the latest historyId you handled somewhere in your app, so that you can query the right changes (and not miss anything) on the next notification.
If you don't need to react to changes in real-time, maybe you can call the /history endpoint periodically, but it will definitely be less efficient at scale.
It takes a bit of work to get this working but at the end of the day you get a very efficient system able to react about changes in real-time.


text:
Q: innerHTML doesn't work, why? I  want  set new  in span,
var email ='ss@ww.net';
document.getElementById('spanEmail').innerHTML=''+email+'';

but  this way not working ,  but this working
document.getElementById('spanEmail').innerHTML='sample text>';

How replace this span content ?

A: You haven't closed your href attribute with a double-quote.
href="mailto:'+email+'>

Should be
href="mailto:'+email+'">

A: You are missing a closing " the code should read:
document.getElementById('spanEmail').innerHTML=''+email+'';


text:
Q: How should this sentence structure be interpreted?
it will be mandatory for you to provide this information in order for
  us to meaningfully be able to respond to your query or provide the
  information or service that you have requested.
  (https://sea.filmbankmedia.com/privacy-notice/)

The bold part is confusing. Does it mean:

(to meaningfully be able to respond to your query) or (to meaningfully
  be able to provide ... )

or

(to meaningfully be able to respond to your query) or (to provide ...)

A: It's unclear, I agree.
I believe it's trying to say that it won't be able to provide a meaningful response to your query, since I don't think one could meaningfully provide the information or service.
However, the sentence could be interpreted either way.


text:
Q: Ошибка сегментирования (сделан дамп памяти) семафоры #include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/ipc.h>
#include <sys/sem.h>
#include <sys/shm.h>
#include <string.h>

union semun{
    int val;
    struct semid_ds* buf;
    unsigned short *array;
    struct seminfo *__buf;
};

int main(int argc, char* argv[])
{
    if(argc != 2)
    {
        printf("no argument, for help %s -h\n", argv[0]);
        return -1;
    }
    if(strcmp(argv[1], "-h") == 0)
    {
        printf("To use, type in the file name as an argument\nExample: '%s file'\n",argv[0]);
        return -1;
    }
    FILE* file = fopen(argv[1], "w");
    if(file == NULL)
    {
        printf("Can't create file\n");
        return -1;
    }
    //открытие буфера
    if(close(open("./SHARED", O_RDWR, S_IRUSR | S_IWUSR)))
    {
        printf("Can't open SHARED\n");
        return -1;
    }
    key_t buff_key = ftok("./SHARED", 1);
    int buff_id = shmget(buff_key, 1024, 0);
    char* buff = (char *)shmat(buff_id, NULL, 0);
    //открыте семафоров
    //0 - свободно сегментов; 1 - занято сегментов
    //2 - защита; 3 - конец файла; 4 - для записи без остатка
    if(close(open("./SEM", O_RDWR, S_IRUSR | S_IWUSR)))
    {
        printf("Can't open SEM\n");
        return -1;
    }
    key_t sem_key = ftok("./SEM", 1);
    int sem_id = semget(sem_key, 0, 0);
    semun init;
    count =5;
    printf("count = %d", count);
    //заготовки структур для semop()
    sembuf sem_wait = {0, -1, 0};
    sembuf sem_post = {0, 1, 0};
    //запись в файл
int last = 0;
    while(semctl(sem_id, 1, GETVAL) != 0 || semctl(sem_id, 3, GETVAL) != 0)
    {
        //дождемся наличия заполенных буферов и уменьшим на 1
        sem_wait.sem_num = 1;
        semop(sem_id, &sem_wait, 1);

        //защита
        sem_wait.sem_num = 2;
        semop(sem_id, &sem_wait, 1);

        //увеличим число пустых буферов на 1
        sem_post.sem_num = 0;
        semop(sem_id, &sem_post, 1);

        //запись нового блока в файл

        if(semctl(sem_id, 4, GETVAL) != 0 && semctl(sem_id, 3, GETVAL) == 0 && semctl(sem_id, 1, GETVAL) == 0)
        {
        }
        else if(semctl(sem_id, 4, GETVAL) != 0 && semctl(sem_id, 3, GETVAL) == 0 && semctl(sem_id, 1, GETVAL) == 1)
        {
            last = semctl(sem_id, 4, GETVAL);
            fwrite(buff, last, 1, file);
        }
        else
        {
            fwrite(buff, 128, 1, file);
        }
        //сдвиг буфера на влево
        memmove(buff, buff+128, 896);

        //защита
        sem_post.sem_num = 2;
        semop(sem_id, &sem_post, 1);
    }

    shmdt(buff);
    fclose(file);
}

От администратора запускается, так не хочет. Не могу понять где он лезет куда не надо..
Поменял всё на советы. Но проблема от этого не уйдет.
Вот думаю правильно ли с правами создаю. Создает эти файлы shared и sem другая программа вот таким способом:
open("./SHARED", O_CREAT | O_RDWR, S_IRUSR | S_IWUSR)

A: Ваша проблема состоит главным образом, в использовании уродливого подхода к обработке ошибок:
Вы пытаетесь заглянуть в хрустальный шар:
if(close(open("./SHARED", O_RDWR, S_IRUSR | S_IWUSR)))
{
    printf("Can't open SHARED\n");
    return -1;
}

После чего, уже безо всякого контроля кодов возврата, делаете свое черное дело:
key_t buff_key = ftok("./SHARED", 1);

Избавьтесь от хрустального шара - анализируйте возвращаемое значение ftok и errorno согласно документации

A: if(close(open("./SHARED", O_RDWR, S_IRUSR | S_IWUSR)))
{
    printf("Can't open SHARED\n");
    return -1;
}

Старайтесь избегать подобных конструкций , такие конструкции часто приводят к непредсказуемым результатам, сложному поиску ошибок и читать трудно.
 int rc;
 rc = open("./SHARED", O_RDWR, S_IRUSR | S_IWUSR);
 if(rc == -1){
   printf("Can't open SHARED\n");
   return -1;
 }

Чуь больше кода, но можно явно локализовать ошибку.


text:
Q: Custom control icons for images in fabric js
This code works fine in fabric js version 1.5 but it doesnt work in
  the latest fabric version 2.4.0.It throws the following error:Uncaught
  TypeError: Cannot read property 'fire' of undefined and Uncaught
  TypeError: Cannot read property 'slice' of undefined.Please refer this
  fiddle link(https://codepen.io/elhoussinelaidi/pen/RRrLzv) this is
  written in fabric version 1.5.but i want this functionality to be
  working fine in fabric version 2.4.0.Could anyone please help me out to solve this problem.

<!DOCTYPE html>

  <title>Custom Control</title>

    <canvas id="canvas" width="400" height="300"></canvas>

A: You need to adapt fabric.Canvas.prototype._performTransformAction and fabric.Canvas.prototype._getActionFromCorner to 2.4 fabric version
Check here:https://codepen.io/anon/pen/WaRaed
You can also use this for custom controls


text:
Q: Несколько join-ов в одно поле Есть таблица с продуктами:
-products
---ID
---NAME

Есть еще таблицы например с ценами продуктов:
-auto_prices
---ID
---PRODUCT_ID
---PRICE_AUTO

-moto_prices
---ID
---PRODUCT_ID
---PRICE_MOTO

Хочу взять результаты с полями ID,NAME,PRICE
SELECT
    ID,
    NAME,
    PRICE_AUTO as PRICE,
    PRICE_MOTO as PRICE
FROM products p
LEFT JOIN  auto_prices ap on  p.ID = ap.PRODUCT_ID
LEFT JOIN  moto_prices mp on  p.ID = mp.PRODUCT_ID

Но тогда появляется два поля PRICE
ID,NAME,PRICE,PRICE
Как сделать чтобы выбиралось одно поле PRICE

A: Попробуйте так:
(SELECT p.ID, p.NAME, ap.PRICE_AUTO as PRICE
FROM products p
JOIN `auto_prices` ap ON p.ID = ap.PRODUCT_ID)
UNION
(SELECT p.ID, p.NAME, mp.PRICE_MOTO as PRICE
FROM products p
JOIN `moto_prices` mp ON p.ID = mp.PRODUCT_ID)

А вообще, если у вас такая структура таблиц и там больше ничего вообще нет, может быть стоит сделать по другому?
Отдельно auto_prices и moto_prices не нужны.  Price можно в одной таблице держать. Прямо в products. В данном случае. При этом добавив колонку category и доп таблицу categories, связав эти две таблицы. Получится, что  соотнесете каждый товар к категории/типу ... что это фото, вело, мото, прото и т.д.  И тогда если захотите выбирать цену, в зависимости от товара, можно будет использовать ту таблицу с категориями. А в данном случае не придется делать лишних движений, достаточно будет написать
SELECT id, name, price FROM products

A: Более стандартный вариант, чем ISNULL.
    SELECT
        ID,
        NAME,
        COALESCE(PRICE_AUTO,  PRICE_MOTO) as PRICE
    FROM products p
    LEFT JOIN  auto_prices ap on  p.ID = ap.PRODUCT_ID
    LEFT JOIN  moto_prices mp on  p.ID = mp.PRODUCT_ID


text:
Q: in direct2d drawing dimensions change after window resizing I am a beginner, and I have made a program in direct2d using c++ in visual studio 2015, just a very basic program that draws a white square on a black background , and it does show the square in a small window. But the problem is that if the user maximizes that window the vertical dimension of the drawing becomes elongated and the square becomes rectangle.
This is the screenshot of the window before maximizing it:
enter image description here
And this is the screenshot of the window after maximizing it:
enter image description here
What am I doing wrong ?
 here is my code and thanks in advance:
ID2D1HwndRenderTarget* pRT = NULL;
ID2D1Factory* pD2DFactory = NULL;
ID2D1SolidColorBrush* pBlackBrush = NULL;
ID2D1SolidColorBrush* pRedBrush = NULL;
HRESULT hr;
RECT rc;
POINT pt;

void draw(){
  pRT->BeginDraw();
  pRT->FillRectangle( D2D1::RectF((FLOAT)rc.left,
     (FLOAT)rc.top,(FLOAT)rc.right, (FLOAT)rc.bottom),pBlackBrush);
  pRT->FillRectangle( D2D1::RectF((FLOAT)pt.x,
     (FLOAT)pt.y,pt.x + 50.0f  ,pt.y + 50.0f),pRedBrush);
  hr = pRT->EndDraw();
}

int APIENTRY wWinMain(/* wWinMain parameters */){

 /*
 ...
 window making
 ...
 */

 hr = D2D1CreateFactory(
   D2D1_FACTORY_TYPE_SINGLE_THREADED,&pD2DFactory );

 // Obtain the size of the drawing area.
 GetClientRect(hWnd, &rc);

 // Create a Direct2D render target

 hr =pD2DFactory->CreateHwndRenderTarget(
    D2D1::RenderTargetProperties(),
    D2D1::HwndRenderTargetProperties(
       hWnd,D2D1::SizeU(rc.right - rc.left, rc.bottom - rc.top)
    ),
    &pRT
 );
 if (SUCCEEDED(hr)){
   pRT->CreateSolidColorBrush(
      D2D1::ColorF(D2D1::ColorF::White),
      &pRedBrush
   );
   pRT->CreateSolidColorBrush(
      D2D1::ColorF(D2D1::ColorF::Black),
      &pBlackBrush
   );
 }
 pt.x = 0;
 pt.y = 0;

 while (1) {
   PeekMessage(&msg, nullptr, 0, 0, PM_REMOVE);
   if (msg.message == WM_QUIT) break;
   if (!TranslateAccelerator(msg.hwnd, hAccelTable, &msg)){
     TranslateMessage(&msg);
     DispatchMessage(&msg);
   }

   draw();
 }
}

A: It seems like you don't resize the render target when your window resizes. I expect you run into similar problems not just from maximizing, but when you resize your window too? See https://learn.microsoft.com/en-us/windows/desktop/LearnWin32/dpi-and-device-independent-pixels#resizing-the-render-target.
Code snippet from the linked document:
void Resize()
{
    if (pRenderTarget != NULL)
    {
        RECT rc;
        GetClientRect(m_hwnd, &rc);

        D2D1_SIZE_U size = D2D1::SizeU(rc.right, rc.bottom);

        pRenderTarget->Resize(size);
        InvalidateRect(m_hwnd, NULL, FALSE);
    }
}

You'll want to call this by catching WM_SIZE.


text:
Q: I want to start Making mods in minecraft and I have a problem when i am trying to run Gradlew setupDecompWorkspace it gives me a error When I open powershell I typed ./gradlew setupDecompWorkspace it gives me that
* What went wrong:
Task 'setupDecompWorkspace' not found in root project 'forge-1.12.2-14.23.5.2859-mdk'.

* Try:
Run gradlew tasks to get a list of available tasks. Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

* Get more help at https://help.gradle.org

Deprecated Gradle features were used in this build, making it incompatible with Gradle 5.0.
Use '--warning-mode all' to show the individual deprecation warnings.
See https://docs.gradle.org/4.9/userguide/command_line_interface.html#sec:command_line_warnings

BUILD FAILED in 8s
PS C:\Users\Ostrov\Desktop\Minecraft Mod Creation\forge-1.12.2-14.23.5.2859-mdk>```

It says BUILD FAILED in 8s because I tried to install it and it installed it for a few minutes but then it says there is an error and build failed

A: Are you using the mdk from Forge's website?
If you're on IntelliJ, you don't have to run this command. It automatically sets up the Gradle project. You should get a UI that looks like this:

Now, instead of typing the command, you can just click genIntellijRuns under the fg_runs section of the Gradle menu.


text:
Q: Updating Datarow from List via for loop. Index was out of bounds I have two string lists:
currentRow = contains the info that the row should have
currentCol = contains the names of the columns that data from currentRow should go in.
each List contains 25(0-24) items, and is ordered in the same way as the dataRow it should be written to.
I am filling the Lists here, from labels and textboxes on a form:
                List<string> currentRow = new List<string>();
                List<string> currentCol = new List<string>();

                foreach (var c in form11.Controls)
                {
                    if (c.GetType() == typeof(TextBox))
                    {
                        var str = c.ToString();
                        var str1 = str.Substring(35);
                        currentRow.Add(str1);
                    }
                    if (c.GetType() == typeof(Label))
                    {
                        var str = c.ToString();
                        var str1 = str.Substring(34);
                        currentCol.Add(str1);
                    }
                }

I then select the row in the dataTable that needs to be updated from the 3rd item in currentRow, which is a unique identifier.
var updateRow = arraysDt.Select("SERIAL =" + "'" + currentRow.ElementAtOrDefault(2) + "'");

Now i try to update the row from the items in the Lists here:
for (int i = 0; i < currentRow.Count; i++)
                {
                    //MessageBox.Show(currentCol.ElementAtOrDefault(i).ToString() + "   " + currentRow.ElementAtOrDefault(i).ToString());
                    updateRow[0][currentCol.ElementAtOrDefault(i)] = currentRow.ElementAtOrDefault(i);
                }

As soon as it gets inside the for loop i throws a "index was out of bounds of the array" error.
As i said, currentCol contains column names and currentRow is the value.
So when it get here i expect it to find the column name and then update it with the value.
updateRow[0][currentCol.ElementAtOrDefault(i)] = currentRow.ElementAtOrDefault(i);

What am i doing wrong?

A: I have found out the issue:
"SERIAL =" + "'" + currentRow.ElementAtOrDefault(2) + "'"

will give me this:
SERIAL=' XXXXX'
What i need is:
SERIAL='XXXXX'
so to fix it i did:
                string SMnum = currentRow.ElementAt(2).ToString().Replace(" ", string.Empty);
                string query = string.Format("SERIAL='{0}'", SMnum.Replace(@"'", "''"));

                var updateRow = arraysDt.Select(query);

This removes any white space in the string that i am looking for.


text:
Q: Shop categories as search results from attributes table Is it normal to create shop categories not in the categories table but as search results from the attributes table?
What are the pitfalls you might encounter? I never did this before, but now when I working on the website with products that have many different attributes I found that creating many categories not very practical (or maybe I wrong), I tried to search this on web but didn't find info about this db design (or I didn't search properly(?), maybe this approach have some name like programming patterns?).
For example:
    Products: Levis[bottoms, jeans, blue], Dockers[bottoms, pants, black], Lee[bottoms, pants, violet]
    Categories:
      Bottoms [query:bottoms]
        Pants [query:pants]
          Violet Pants [query:pants, violet]
        Jeans [query:jeans]

    Products: Abibas[shoes, sport...], SuperBoots[shoes, boots, leather]
    Categories:
      "Shoes"[query:shoes]
        "Leather boots"[query: boots, leather]
        "Sport" [query: sport]

A: Start with a highly normalized design to avoid anomalies and stay DRY. Optimize only if required. Test performance with real world data.
If you're going to use hierarchical or network categories, you should use a database that supports hierarchical ("recursive CTE") queries (i.e. not MySQL).
Use standard data modeling patterns to save time.
For pure hierarchical categories, have a table like this:
create table product_categories (
  category_id int primary key,
  name text not null,
  parent_id int null references categories(category_id),

  unique (name, parent_id)
);

and have a foreign key from your products table to the above table.

A: another way to look at this -- its not always necessary to create separate categories -- sometimes a category is being filtered to make it easier for the customer to find what they want. So in your examples the customer is saying show me only those Boots that are made of Leather, OR show me pants in just the color Violet.
balanced by what your market is -- if people come to your website to buy Leather Boots then having that be its own category would make sense. thats a very specific destination category that could also have lots of sub-categories.
versus violet colored pants -- maybe that is a destination category somewhere :-)
but most likely it would be a search filter that would be applied to a category.
another consideration for categories is they are extremely important for SEO so you want to keep your core category structure consistent so you can get ranked appropriately.


text:
Q: window.stop() execution through selenium is not working I am trying to read elements from the page using selenium but it seems the page is getting loaded infinitely. The element which I want to read is visible on the page (tried xpath and I was able to fetch the element). I tried the below code to execute the javascript command to stop the page load but for some reasons it is getting time out.
driver.executeScript("window.stop());

A: As @pcalkins suggested to use PageLoadStrategy, I used the "none" strategy in the chrome capabilities and it really did work. Below is the chrome capability property which I set.
"pageLoadStrategy" : none


text:
Q: Should binary features be one-hot encoded? I'm working with data that consists of a few dozen binary features about people which basically come down to "person has feature x" [True/False].
From what I can find online categorical data should be one-hot encoded instead of assigning an arbitrary value for each category because you can't say "category 1 is less than category 2". So the solution is to create a dummy variable for each category:
Cat || dummy 1 | dummy 2 | dummy 3
____||_________|_________|________
 1  ||   1     |   0     |   0
 2  ||   0     |   1     |   0
 3  ||   0     |   0     |   1

Now for binary features one can choose between using the variable directly (1 for true, 0 for false) or use two dummy variables ((1, 0) for true, (0, 1) for false.). But I can't find any sources that show/explain what the best approach is.
I myself am conflicted, because on one hand, the dummy variables reduces the importance of each individual variable and it is show that at least in some cases the accuracy of the model suffers, source. But on the other hand, this can also encode missing data (in the form of (0, 0)). Furthermore, is it possible to say "False is less than True"?
I'm actually using a Random Forest in python, and I know that tree-based classifiers such as Random Forests support categorial data, but the Sklearn package hasn't implemented this yet.
I wrote a small test on the Sklearn digits data set. This data set has a number of 8 by 8 images of digits (0-9), each pixel has a value between 0 and 16 and a simple model can use this to learn to recognize the digits.
For my test I change the values of > 8 to True and <= 8 to False. The accuracy ofcourse suffers when compared to the original data, but when I implement one-hot encoding, thus changing True to (1, 0) and False to (0, 1) I can't find a significant difference compared to the binary encoding.
An explanation of the recommended approach would be greatly appreciated!

A: Converting a binary variable that takes the values of [0, 1] into a one-hot encoded of [(0, 1), (1, 0)] is redundant and not recommended for the following reasons (some of them are already mentioned in the comment above but just to expand on this):

*

*It is redundant because the binary variable is already in a form similar to the one-hot encoded, where the last column is dropped as it does not make any difference with or without it, because it can be inferred from the first given column: If I give you [(0, ), (1,)], you can know the complementary column [(, 1), (, 0)].

*Suppose you have more than one binary variable, say 4 for example. If you convert them into one-hot encoded form, the dimension will increase from 4 to 8. The latter is not recommended for the following reasons:

*

*The Curse of Dimensionality: High dimensional data can be so troublesome. That's because a lot of algorithms (e.g. clustering algorithms) use the Euclidean Distance which, due to the squared terms, is sensitive to noise. As a matter of fact, data  points  spread  too thin as the dimensions increase, making data extremely  noisy.  Besides,  the  concept of neighborhood becomes meaningless, and  approaches  that  are  based  on  finding the relative contrast between distances of the data points become unreliable.

*Time & Memory Complexity: It is intuitive that increasing the number of features will cost the algorithm more execution time and memory space requirement. To name a few, algorithms that use the Covariance Matrix in its computation will get affected. Polynomial algorithms will end up with too many terms...and so on. In general, the learning usually is faster with less features especially if the extra features are redundant.

*Multi-Collinearity: Since the last column in the one-hot encoded form of the binary variable is redundant and 100% correlated with the first column, this will cause troubles to the Linear Regression-based Algorithms. For example, since the ordinary least squares estimates involve inverting the matrix, a computer algorithm may be unsuccessful in obtaining an approximate inverse, if a lot of features are correlated, and hence the inverse may be numerically inaccurate. Also, linear models work by observing the changes in the dependent variable y with the unit changes in one independent variable after holding all other independent variables as constants, yet in case independent variables are highly correlated, the latter fails (there are more other consequences of Multi-Collinearity) (although some other algorithms might be less sensitive to this as in Decision Trees).

*Overfitting-prone: In general, too many features (regardless if they're correlated or not) may overfit your model and fail to generalize to new examples, as every data point in your dataset will be fully identified by the given features (search Andrew NG lectures, he explained this in detail)
Summary
In a nutshell, converting a binary variable into a one-hot encoded one is redundant and may lead to troubles that are needless and unsolicited. Although correlated features may not always worsen your model, yet they will not always improve it either.


text:
Q: Fail to import tensorflow on windows I am using windows10, python 3.6 without anaconda. I was trying to install tensorflow for my GTX1060.
After installing it, I found that I cannot import tensorflow and the error message as followed:
Traceback (most recent call last):
  File "C:\Program Files\Python36\lib\site-packages\tensorflow\python\pywrap_tensorflow.py", line 58, in
    from tensorflow.python.pywrap_tensorflow_internal import *
  File "C:\Program Files\Python36\lib\site-packages\tensorflow\python\pywrap_tensorflow_internal.py", line 28, in
    _pywrap_tensorflow_internal = swig_import_helper()
  File "C:\Program Files\Python36\lib\site-packages\tensorflow\python\pywrap_tensorflow_internal.py", line 24, in swig_import_helper
    _mod = imp.load_module('_pywrap_tensorflow_internal', fp, pathname, description)
  File "C:\Program Files\Python36\lib\imp.py", line 243, in load_module
    return load_dynamic(name, filename, file)
  File "C:\Program Files\Python36\lib\imp.py", line 343, in load_dynamic
    return _load(spec)
ImportError: DLL load failed: 找不到指定的模块。
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
  File "", line 1, in
  File "C:\Program Files\Python36\lib\site-packages\tensorflow__init__.py", line 22, in
    from tensorflow.python import pywrap_tensorflow  # pylint: disable=unused-import
  File "C:\Program Files\Python36\lib\site-packages\tensorflow\python__init__.py", line 49, in
    from tensorflow.python import pywrap_tensorflow
  File "C:\Program Files\Python36\lib\site-packages\tensorflow\python\pywrap_tensorflow.py", line 74, in
    raise ImportError(msg)
ImportError: Traceback (most recent call last):
  File "C:\Program Files\Python36\lib\site-packages\tensorflow\python\pywrap_tensorflow.py", line 58, in
    from tensorflow.python.pywrap_tensorflow_internal import *
  File "C:\Program Files\Python36\lib\site-packages\tensorflow\python\pywrap_tensorflow_internal.py", line 28, in
    _pywrap_tensorflow_internal = swig_import_helper()
  File "C:\Program Files\Python36\lib\site-packages\tensorflow\python\pywrap_tensorflow_internal.py", line 24, in swig_import_helper
    _mod = imp.load_module('_pywrap_tensorflow_internal', fp, pathname, description)
  File "C:\Program Files\Python36\lib\imp.py", line 243, in load_module
    return load_dynamic(name, filename, file)
  File "C:\Program Files\Python36\lib\imp.py", line 343, in load_dynamic
    return _load(spec)
ImportError: DLL load failed: 找不到指定的模块。
Failed to load the native TensorFlow runtime.
See https://www.tensorflow.org/install/install_sources#common_installation_problems
for some common reasons and solutions.  Include the entire stack trace
above this error message when asking for help.


text:
Q: Load controller after bootstrap angularjs I am using requirejs and angularjs to load the module inside my application.
The problem I am facing is I dont know how to load the controller after angular has been bootstrapped. Here is my code :
main.js :
require(['app', //all my scripts go here
function(){
 angular.bootstrap(document, ['myApp']);
});

app.js :
define([], function(){
    var myApp = angular.module('myApp', ['ngRoute']);
    $routeProvider.
        when('/home', {
                templateUrl : 'partials/home.html',
                controller : 'UserRegisterCtrl'
            }).
            otherwise({
                redirectTo : '/home'
            })
    return myApp;
})

controller.js
define(['app'], function(app){
    app.controller('MyCtrl', function($scope){});
})

myApp.html
body(ng-app)

  <-- I can not put MyCtrl here
because I think the MyCtrl has been declared before myApp has been bootstrapped

Therefore I really need to know if there is a way to load the MyCtrl controller after myApp has been bootstrapped. I am really new to Angularjs. Any help would be really appreciate.

A: If you are manually bootstrapping your angular app there is no need for ng-app, because this is just a directive that pretty much does the same thing.
This little trap caused some people a headache before:

*

*Why do I need to angular.bootstrap even when I declare ng-app="MyApp" in JSFiddle

*angular bootstrapping issues angular.bootstrap not working on my apps

A: When you use ng-app in your html, the bootstrap happens automatically.  In this case, it depends what you put in the


text:
Q: Find all integers such that there is a number and all elements more than it can be written using the elements of a set in exactly that many ways. Find all integers $r$ such that $\exists$ $p \in \mathbb{Z^{+}}, A \subset \mathbb{Z^{+}}$ and every $q > p$ can be written using distinct elements from $A$ in no more or less than $r$ ways.
I think it is not possible. But I could not generate an example for any number either. Can I get a few examples so I can verify it further?

A: Here is a solution for $r=2$ (which might make the general pattern clear).  Let $$A=\{1,2,3,4,8,16, \cdots , 2^n, \cdots\}$$
That is, $A=\{2^n\}\cup \{3\}$.
In that case, of course, $1,2$ can only be written in one way.  But any greater number has one decomposition that uses $3$ and one which does not.


text:
Q: Hibernate Search @IndexedEmbedded I have a similar situation like this one
@Entity
@Indexed
public class Place {
    @Id
    @GeneratedValue
    @DocumentId
    private Long id;

    @Field( index = Index.TOKENIZED )
    private String name;

    @OneToOne( cascade = { CascadeType.PERSIST, CascadeType.REMOVE } )
    @IndexedEmbedded
    private Address address;
    ....
}

@Entity
public class Address {
    @Id
    @GeneratedValue
    private Long id;

    @Field(index=Index.TOKENIZED)
    private String street;

    @Field(index=Index.TOKENIZED)
    private String city;

    @ContainedIn
    @OneToMany(mappedBy="address")
    private Set<Place> places;
    ...
}

The problem now is the following:
If I change for example the name field in entity Place which entities are going to be re-indexed?
1) Only the name field?
2) The whole Place entity?
3) The whole Place entity and the entities annotated with @IndexedEmbedded?
The one I need for my purpose would be the third. So if it is not standard, could there be any solution to achieve this behaviour?

A: Fortunately it's really the third, so I was lucky and it works as expected

A: You can use the following code to re-index the Place Entity manually
public void updateIndex(T entity){
        FullTextEntityManager fullTextEntityManager = Search.getFullTextEntityManager(em);
        fullTextEntityManager.index(entity);
        fullTextEntityManager.getSearchFactory().optimize(entity.getClass());
    }

Secondly if you are using hibernate you can configure lucene in persistence.xml to automatically update the indexes of the entities that are changed


text:
Q: How to get my Vcard in agsXMPP? I want  to get my Vcard from server.
I send my Vcard to server by this code:
VcardIq viq = new VcardIq(IqType.set, new Jid(XmppCon.Server));
viq.Vcard.Nickname = "Alex";
XmppCon.Send(viq);

And I know from this,that how to get other user's Vcard.But this method don't work for my registered Id.
Can anyone help me to get my Vcard from server in agsXMPP?

A: Here is a sample code
public void GetMyVcard()
{
  VcardIq viq = new VcardIq(IqType.get);
  xmppCon.IqGrabber.SendIq(viq, new IqCB(VcardResult), null);
}

private void VcardResult(object sender, IQ iq, object data)
{
  if (iq.Type == IqType.result)
  {
    Vcard vcard = iq.Vcard;
    if (vcard != null)
    {
      string fullname = vcard.Fullname;
      string nickname = vcard.Nickname;
      string description = vcard.Description;
      Photo photo = vcard.Photo;
    }
  }
}


text:
Q: Changing the Order of Identity Providers in Azure B2C I have been building an Azure B2C Test System and have customised the login page as per the guide here. Is there any way to change the order of the Elements so that the Local Sign-in option is on the top or bottom?
Also is there a way to make a profile edit policy use the Sign-Up/Sign-In login page style? e.g. 3rd Party Identity Providers at the top and a email\username and password button at the bottom.
Here is how it currently Looks:
Identity Provider Order

A: The order in which the buttons for different identity providers are shown in Azure AD B2C is based on the order in which they are saved. If you select multiple identity providers and then save, they will be added in a seemingly random order. However, if you add one (say Facebook), save your changes to the policy, and then add another (say Google) and save. They will be displayed in that order. This also applies for the Local Accounts button in the policies that show such button.
In the case of Sign-up/Sign-in, the section for local accounts will always be displayed at the bottom and there is currently no way to control this via Azure AD B2C.
You can leverage hacky CSS to do flip these two sections, but beware that this is a hack and can break if at any time the html elements change.
div#api { display: table }
.social { display: table-footer-group }
.localaccount { display: table-header-group }

You should probably request this as a first class feature via the Azure AD B2C UserVoice forum


text:
Q: How do you iterate one level at a time? Let's say I have something like this and it can't be changed:
<xml>
<element name="breakfast" type="sandwich" />
<element name="lunch">
  <complexType>
    <element name="meat" type="string" />
    <element name="vegetables" type="vegetable" />
    <element name="chips" type="boolean" />
  </complexType>
</element>
<complexType name="sandwich">
  <element name="bread" type="string" />
  <element name="cheese" type="int" />
  <element name="butter" type="boolean" />
</complexType>
<complexType name="vegetable">
  <element name="tomato" type="int" />
  <element name="lettuce" type="boolean" />
  <element name="carrot" type="boolean" />
</complexType>
<element name="dinner" type="sandwich" />
</xml>

I want some sort of array / object like:
var day = {
  time: {
    breakfast: {
      bread: "string",
      cheese: "int",
      butter: "boolean"
    },
    lunch: {
      meat: "string",
      vegetables: {
        tomato: "int",
        lettuce: "boolean",
        carrot: "boolean"
      },
      chips: "boolean"
    },
    dinner: {
      bread: "string",
      cheese: "int",
      butter: "boolean"
    },
  },
  food: {
    sandwich: {
      bread: "string",
      cheese: "int",
      butter: "boolean"
    },
    vegetable: {
      tomato: "int",
      lettuce: "boolean",
      carrot: "boolean"
    },
  }
}

I don't mind what language, PHP or JavaScript would be great but I really just want to see the logic. I am sure there is a standard pattern for this.
At the moment I have something along the lines of:
$xml = new DOMDocument();
$xml->loadXML($data);

$day = array(
  "time" => array(),
  "food" => array()
);
getLevel1($xml->childNodes[0]);

function getLevel1(DOMNode $domNode) {
  global $day;
  foreach ($domNode->childNodes as $node) {
    if ($node->nodeName == "element") {
      if ($node->hasChildNodes()) {
        $day["time"][$node->getAttribute('name')] = getLevel2($node);
      } else {
        if (isset($day["food"][$node->getAttribute('type')])) {
          $day["time"][$node->getAttribute('name')] = $day["food"][$node->getAttribute('type')];
        } else {
          $day["time"][$node->getAttribute('name')] = $node->getAttribute('type');
        }
      }
    };
    if ($node->nodeName == "complexType") {
      if ($node->hasChildNodes()) {
        $day["food"][$node->getAttribute('name')] = getLevel2($node);
      } else {
        $day["food"][$node->getAttribute('name')] = $node->getAttribute('type');
      }
    };
  }
};

function getLevel2(DOMNode $domNode) {
  $object = array();
  foreach ($domNode->childNodes as $node) {
    if ($node->nodeName == "element") {
      $object[$node->getAttribute('name')] = $node->getAttribute('type');
    };
    if ($node->hasChildNodes()) {
      if ($node->hasAttribute('name')) {
        $object[$node->getAttribute('name')] = getLevel2($node);
      } else {
        return getLevel2($node);
      }
    }
  }
  return $object;
}

print_r($day);

Output: here
I can see why breakfast does not show because it does not exist at the time so I need a better way to iterate.

A: Add one more function that replaces all known types (I called it replaceComplexTypes):
<?php

$data = '<xml>
<element name="breakfast" type="sandwich" />
<element name="lunch">
  <complexType>
    <element name="meat" type="string" />
    <element name="vegetables" type="vegetable" />
    <element name="chips" type="boolean" />
  </complexType>
</element>
<complexType name="sandwich">
  <element name="bread" type="string" />
  <element name="cheese" type="int" />
  <element name="butter" type="boolean" />
</complexType>
<complexType name="vegetable">
  <element name="tomato" type="int" />
  <element name="lettuce" type="boolean" />
  <element name="carrot" type="boolean" />
</complexType>
<element name="dinner" type="sandwich" />
</xml>';
$xml = new DOMDocument();
$xml->loadXML($data);

$day = getLevel1($xml->childNodes[0]);
$day2 = replaceComplexTypes($day['time'], $day['food']);
$day = array('time' => $day2, 'food' => $day['food']);

function getLevel1(DOMNode $domNode) {
  $day = array(
    "time" => array(),
    "food" => array()
  );
  foreach ($domNode->childNodes as $node) {
    if ($node->nodeName == "element") {
      if ($node->hasChildNodes()) {
        $day["time"][$node->getAttribute('name')] = getLevel2($node);
      } else {
          if (isset($day["food"][$node->getAttribute('type')])) {
            $day["time"][$node->getAttribute('name')] = $day["food"][$node->getAttribute('type')];
          } else {
            $day["time"][$node->getAttribute('name')] = $node->getAttribute('type');
          }
      }
    };
    if ($node->nodeName == "complexType") {
      if ($node->hasChildNodes()) {
        $day["food"][$node->getAttribute('name')] = getLevel2($node);
      } else {
        $day["food"][$node->getAttribute('name')] = $node->getAttribute('type');
      }
    };
  }
  return $day;
}

function getLevel2(DOMNode $domNode) {
  $object = array();
  foreach ($domNode->childNodes as $node) {
    if ($node->nodeName == "element") {
      $object[$node->getAttribute('name')] = $node->getAttribute('type');
    };
    if ($node->hasChildNodes()) {
      if ($node->hasAttribute('name')) {
        $object[$node->getAttribute('name')] = getLevel2($node);
      } else {
        return getLevel2($node);
      }
    }
  }
  return $object;
}

function replaceComplexTypes(array $replaceIn, array $replaceWith) {
  $output = array();
  foreach ($replaceIn as $key => $value) {
    if (is_array($value)) {
      $output[$key] = replaceComplexTypes($value, $replaceWith);
    }
    else {
      if (array_key_exists($value, $replaceWith)) {
        $output[$key] = $replaceWith[$value];
      }
      else {
        $output[$key] = $value;
      }
    }
  }
  return $output;
}

print_r($day);


text:
Q: How to display the Json text and image retrieved from web service in horizontal list view? I am developing Android application where I want to display the json format text and image retrieved from web service in horizontal list view. I am storing json formated data into ArrayList

A: The first thing is how to display a horizontal ListView. I want to recommend you use RecyclerView for smoother listView display. So how to display recyclerView in Horizontal? This is my tutorial step by step.
First, in xml file should be like this:
  <android.support.v7.widget.RecyclerView
        android:id="@+id/recyclerView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_alignParentBottom="true"
        android:scrollbars="vertical" />

Second, in the Activity's onCreate should be like this:
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    recyclerViewItem = (RecyclerView) findViewById(R.id.recyclerView);
    LinearLayoutManager itemslayoutManager = new LinearLayoutManager(getApplicationContext());
    itemslayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
    recyclerViewItem.setLayoutManager(itemslayoutManager);
    SampleAdapter sampleAdapter = new SampleAdapter(List<SampleData>);
    recyclerViewItem.setAdapter(sampleAdapter);
    return true;
    }

To parse JSON you should use library called: Retrofit instead of AsyncTask
try this:
Retrofit

A: activity_main.xml
  <android.support.v4.view.ViewPager
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:numColumns="auto_fit"
    android:horizontalSpacing="4dp"
    android:stretchMode="columnWidth"
    android:id="@+id/gallery_child_list"
    android:background="#E4E4E4"
    android:verticalSpacing="4dp" />

Mainactivity
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    // Get the view from activity_main.xml
    setContentView(R.layout.activity_main);
    // Execute DownloadJSON AsyncTask
    new DownloadJSON().execute();
}

// DownloadJSON AsyncTask
private class DownloadJSON extends AsyncTask<Void, Void, Void> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        // Create a progressdialog
        mProgressDialog = new ProgressDialog(MainActivity.this);
        // Set progressdialog message
        mProgressDialog.setMessage("Loading...");
        mProgressDialog.setIndeterminate(false);
        // Show progressdialog
        mProgressDialog.show();
    }

    @Override
    protected Void doInBackground(Void... params) {
        // Create an array
        arraylist = new ArrayList<HashMap<String, String>>();
        // Retrieve JSON Objects from the given URL address
        try {
            HttpClient client = new DefaultHttpClient();
            HttpPost httppost = new HttpPost("YOUR_URL");
            HttpResponse response = client.execute(httppost);
            HttpEntity resEntity = response.getEntity();
            String json = EntityUtils.toString(resEntity);
            JSONObject jObject = new JSONObject(json);
            // Locate the array name in JSON
                HashMap<String, String> map = new HashMap<String, String>();
            JSONObject jsonobject = jObject.optJSONObject("online");
            for (int i = 0; i < jObject.length(); i++) {
                    map.put("date", jsonobject.getString("men"));
                    map.put("flag", jsonobject.getString("kids"));
                    map.put("flag", jsonobject.getString("women"));
                    // Set the JSON Objects into the array
                    arraylist.add(map);
                }
                } catch (Exception e1) {
                e1.printStackTrace();
            }
        return null;
    }
        @Override
    protected void onPostExecute(Void args) {
        viewPager = (ViewPager) findViewById(R.id.pager);
        adapter = new ViewPagerAdapter(MainActivity.this, arraylist);
        viewPager.setAdapter(adapter);
        // Close the progressdialog
        mProgressDialog.dismiss();
        adapter.notifyDataSetChanged();

    }
}

viewpageradapter
public class ViewPagerAdapter extends PagerAdapter {
// Declare Variables
Context context;
LayoutInflater inflater;
ArrayList<HashMap<String, String>> data;
ImageLoader imageLoader;
HashMap<String, String> resultp = new HashMap<String, String>();

public ViewPagerAdapter(Context context, ArrayList<HashMap<String, String>> arraylist) {
    this.context = context;
    data = arraylist;
    imageLoader = new ImageLoader(context);
}

@Override
public boolean isViewFromObject(View view, Object object) {
    return view == ((RelativeLayout) object);
}

@Override
public int getCount() {
    return data.size();
}

        @Override
public Object instantiateItem(ViewGroup container, int position) {

    // Declare Variables
    ImageView imgflag;

    inflater = (LayoutInflater) context
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View itemView = inflater.inflate(R.layout.viewpager_item, container,false);

    // Locate the ImageView in viewpager_item.xml
    imgflag = (ImageView) itemView.findViewById(R.id.flag);
            // Capture position
            resultp = data.get(position);
            // Capture position and set results to the ImageView
            // Passes flag images URL into ImageLoader.class
            imageLoader.DisplayImage(resultp.get(MainActivity.FLAG), imgflag);
            // Add viewpager_item.xml to ViewPager
            ((ViewPager) container).addView(itemView);

    return itemView;
}

@Override
public void destroyItem(ViewGroup container, int position, Object object) {
    // Remove viewpager_item.xml from ViewPager
    ((ViewPager) container).removeView((RelativeLayout) object);

}
}


text:
Q: Structured streaming truncates kafka timestamps to seconds I am reading data from Kafka with Spark Structured Streaming and want to include the Kafka timestamp in the message:
sparkSession.readStream
  .format("kafka")
  .option("kafka.bootstrap.servers", "kafka-broker:10000")
  .option("subscribe", "topicname")
  .option("includeTimestamp", true)
  .load()
  .selectExpr("CAST(topic AS STRING)", "CAST(key AS STRING)", "CAST(value AS STRING)", "timestamp")
  .as[(String, String, String, Long)]

When I then look at the timestamp it is truncated from milliseconds to seconds. Is there any way I can get the millisecond precision back after reading?

A: The truncation happens when the timestamps is read as a Long value. This happens in the last line of:
sparkSession.readStream
  .format("kafka")
  .option("kafka.bootstrap.servers", "kafka-broker:10000")
  .option("subscribe", "topicname")
  .option("includeTimestamp", true)
  .load()
  .selectExpr("CAST(topic AS STRING)", "CAST(key AS STRING)", "CAST(value AS STRING)", "timestamp")
  .as[(String, String, String, Long)]

It does not truncate when you change the last line to:
.as[(String, String, String, Timestamp)]

A: I just tried this quickly in IntelliJ with my local Kafka set-up.
If you are referring to the three dots in the end of the timestamp field as truncation (as in the output below):
Batch: 1
-------------------------------------------
+-----+----+--------+--------------------+
|topic| key|   value|           timestamp|
+-----+----+--------+--------------------+
| test|null|test-123|2018-10-07 03:10:...|
| test|null|test-234|2018-10-07 03:10:...|
+-----+----+--------+--------------------+

Then you just need to add the following line:
.option("truncate", false)
in your writeStream() portion like:
Dataset<Row> df = sparkSession
                .readStream()
                .format("kafka")
                .option("kafka.bootstrap.servers", "localhost:9092")
                .option("subscribe", "test")
                .option("includeTimestamp", "true")
                .load()
                .selectExpr("CAST(topic AS STRING)", "CAST(key AS STRING)", "CAST(value AS STRING)", "CAST(timestamp as STRING)");

try {
    df.writeStream()
          .outputMode("append")
          .format("console")
          .option("truncate", false)
          .start()
          .awaitTermination();
} catch (StreamingQueryException e) {
    e.printStackTrace();
}

This change gave me the full timestamp in the output:
Batch: 1
-------------------------------------------
+-----+----+--------+-----------------------+
|topic|key |value   |timestamp              |
+-----+----+--------+-----------------------+
|test |null|test-123|2018-10-07 03:19:50.677|
|test |null|test-234|2018-10-07 03:19:52.673|
+-----+----+--------+-----------------------+

I hope this helps.


text:
Q: How to store words from the sentence I have the following C++ code that calculates the total number of words and stores the the value in count variable.
So, the question is how can I store those particular words from a sentence in a variable so I can later use them to match the words in the sentence if I pass a word to match with.
Thanks for the help.
#include <iostream>
#include <cstring>
#include <new>
#include <cctype>

int wordsInString(const char* );

int main()
{
    wordsInString("My name is Donnie");
    return 0;
}

int wordsInString(const char* s)
{
    int count = 0;
    int len = strlen(s);
    int i;
    for(i=0;i<len;i++)
    {
        while(i<len && (s[i] == ' ' || s[i] == '\t' || s[i] == '\n'))
        {
            i++;
        }
        if(i<len)
        {
            count++;
            while(i<len && (s[i] != ' ' && s[i] != '\t' && s[i] != '\n'))
            {
                i++;
            }
        }
    }
    std::cout << "The total count: " << count << std::endl;
    return count;
}

A: I can offer another way to solve this problem - using the algorithm Depth first search.
#include <iostream>
#include <string>
#include <cctype>
#include <vector>
using namespace std;
const int maximumSize=40;
string wordsInString="My name is Donnie";
vector<string> words;
string temporary;
vector<int> visitedWords(maximumSize, 0);
template<class Type>
void showContent(Type input)
{
    for(int i=0; i<input.size(); ++i)
    {
        cout<<input[i]<<", ";
    }
    return;
}
void dfsWords(int current, int previous)
{
    if(visitedWords[current]==1)
    {
        return;
    }
    visitedWords[current]=1;
    if(isspace(wordsInString[current])==false)
    {
        temporary.push_back(wordsInString[current]);
    }
    else
    {
        words.push_back(temporary);
        temporary.clear();
    }
    if(current==(wordsInString.size()-1))
    {
        words.push_back(temporary);
        temporary.clear();
    }
    for(int next=current; next<wordsInString.size(); ++next)
    {
        dfsWords(next, current);
    }
    return;
}
void solve()
{
    dfsWords(0, -1);
    cout<<"wordsInString <- ";
    showContent(wordsInString);
    cout<<endl<<"words <- ";
    showContent(words);
    return;
}
int main()
{
    solve();
    return 0;
}

Here is the result:
wordsInString <- M, y,  , n, a, m, e,  , i, s,  , D, o, n, n, i, e,
words <- My, name, is, Donnie,

A: Perhaps I misunderstood the problem in my initial comments, but if you just want to count the number of space-delimited "words" in a string, then I recommend using an std::istringstream for the string, then use a loop extracting the space-delimited "words" one by one using the normal input operator >> into a dummy string variable, and increase a counter in the loop.
Perhaps something like this:
unsigned wordsInString(std::string const& string)
{
    // A stream we can read words from
    std::istringstream stream(string);

    // The word counter
    unsigned word_counter;

    // A dummy string, the contents of the string will never be used
    std::string dummy;

    // While we can read words from the stream, increase counter
    for (word_counter = 0; stream >> dummy; ++word_counter)
    {
        // Empty
    }

    // Return the counter
    return word_counter;
}

This works because:

*

*The result of the >> stream extract operator is the stream itself, and when converted to a boolean value it will be false when we reach the end of the stream, which breaks the loop; And

*The stream extraction operator separates on white-space (space, newline, tab, etc.); And

*For each successful extraction of a word from the stream, we will increase the counter, so the loop counts the "words" in the stream.

A: The question author shows a code that works and counts the number of words. Perfectly fine. The question is, how to store the words now. And not only count.
In a comment at the end, the author says that they are allowed to use the mentioned headers only. Unfortunately, this will invalidate all other answers.
The reference to the headers is not only a restriction, but also a proposal solution.
The OP is obviously taking a C++ class and is building up know-how at the moment. But, of course still far away from mastering one of the most complex programming languages.
But if we start to ignore the requirements, then the problem can always be solved with a one-liner. No complex recursive stuff and nonsense needed.

So, first I will also ignore the requirements and show the one-liner approaches.
Later, I will show what the professor wants to see.

All this relies on the fact that we have container in C++ and iterators to iterate over the elements in those containers. You will find this everywhere. E.g. something with begin() and end(). And there are many iterators for many different purposes.
For example, if you have a string (which is a container for characters), then you can simple use iterators to iterate over all characters in the string.
But there is, since many many years, a special iterator to iterate over patterns, like for example words in a string. This is a dedicated iterator that is specifically designed for this purpose.
And because it is specifically designed for this use case and it is simple to use and very flexible, it should be used.
We are talking about the std::sregex:token_iterator. Please see here for a description. You can simply define a pattern in simple regex language, like for a word, and then iterate over all words. Brutally simple.
OK, now that we know that we have a specific and dedicated iterator, especially designed for our purpose, we can use existing functions for iterators, to get our needed result.
First, the count. There is a function called std::distance. And as its name says, it calculates the distance between 2 iterators. For example, the distance between the first and the last element is of course equal to the count of elements in any container.
And, as with any iterator, also the std::sregex_token_iterator has constructors. Reading here, we can see "begin" iterator will be initialized with the container and a regex. The "end" iterator is the default constructor, without any argument. So, you can simply write {} to get the end iterator.
With that know-how, we can write:
#include <iostream>
#include <string>
#include <regex>
#include <iterator>

// --------------------------------------------------------------------------------
// Some alias name to save typing word and get a more readable text
using Words = std::vector<std::string>;
using WordIter = std::sregex_token_iterator;

// A regex to specify a pattern for words consisting of alpha and digit characters
const std::regex re{ R"(\w+)" };

// Test string with some example data
const std::string test{ " My name is Donnie " };
// --------------------------------------------------------------------------------

int main()
{
    // ---------------------------------------------------------------------------------------
    // One-liner to get the count
    unsigned int count = std::distance(WordIter(test.begin(), test.end(), re), {});
    // ---------------------------------------------------------------------------------------

    std::cout << "\nWe found '" << count<< "' words\n\n";
}

That is ultra-simple, has low complexity and is easy to understand.
I appreciate that regexs have something of an overhead, but I don't think that matters here.

Next: Storing the words.
If we want to store the words, we would typically use a dynamic container, like a std::vector.
And, very nice, the std::vector has a constructor, which takes a pair of iterators and then copies all elements. See constructor number 5.
So, everything pointed to by the iterators will be put into the vector. And, additionally, after adding the words to the std::vector we have also the "count" of words, because the vector knows how many words are in it.
See the next one-liner:
#include <iostream>
#include <string>
#include <vector>
#include <regex>

// --------------------------------------------------------------------------------
// Some alias name to save typing word and get a more readable text
using Words = std::vector<std::string>;
using WordIter = std::sregex_token_iterator;

// A regex to specify a pattern for words consisting of alpha and digit characters
const std::regex re{ R"(\w+)" };

// Test string with some example data
const std::string test{ " My name is Donnie " };
// --------------------------------------------------------------------------------

int main()
{
    // ---------------------------------------------------------------------------------------
    // One-liner to store all words in a vector and get its count
    // Define a container that will contain all words using the range constructor of the vector

    Words words(WordIter(test.begin(), test.end(), re), {});

    // ---------------------------------------------------------------------------------------

    // Output part: Now we have all words and their count. Show result to user
    std::cout << "\nWe found '" << words.size() << "' words\n\nAnd these are:\n\n";
    for (const std::string& w : words) std::cout << w << '\n';
}

Again, an ultra-simple and efficient solution.
By just using the correct container and iterator, we get a compact and very good readable and understandable solution.

But now, back to reality. The OP starts to learn the language. All copy and paste of the above advanced stuff will be rejected by the Prof.
So, we need to follow their requirements.
They only want to see functions from:

*

*iostream  --> Only std::cout

*cstring --> Only C style strings (char *) and C-style string functions

*new --> Handwritten dynamic memory management. No std::vector

*cctype -->We may use std::ispace to search for spaces.

Especially difficult for newbies is dynamic memory management. But this shall be taught here.
First info: A C-string consists of all the characters and a trailing 0 to terminate the string. This means, if we need to allocate dynamic memory for a string, we need to get "number of characters + 1" bytes.
So, if we have a string "ABC", then it has 3 bytes. If we want to copy that to dynamically allocated memory, then we need to write: char* text = new char[3+1];. This needs to be remembered.
Then, if we want to store more than one string, then we need a 2 dimensional array. One dimension for the characters that form the words and the second dimension for the number of words.
So, a char**
There are two possibilities to dynamically allocate such an array. First, we count all words and then allocate an array with this count: char** wordList = new char*[count];.
Or, we follow the full dynamic approach, we define some default capacity for such an array, like for example 1 element. Then, if the array is full, we double the capacity (so, getting 1,2,4,8,16,…) and allocate a new array. Something like:
if (count >= capacityOfArray) {
    // Not enough capacity. Get more. Double capacity
            capacityOfArray = capacityOfArray * 2;

            // Create new array with bigger capacity
            char** temp = new char* [capacityOfArray] {};

And then copy all data from the old array to the new array. We must not forget to release the memory of the old array after we copied all the elements.
Anyway. All dynamically allocated memory must be released!
With that, we get the following code, which fulfils all requirements:
#include <iostream>
#include <cstring>
#include <new>
#include <cctype>

int wordsInString(const char * s, char **& wordList)
{
    int count = 0;
    int beginOfWord = 0;
    int endOfWord = 0;

    // Create an array that can hold a number of string. InitialCapacity will be 1
    int capacityOfArray = 1;
    // Create the array. Allocate memory, Initialize with nullptr
    wordList = new char *[capacityOfArray] {};

    // How many characters do we have in the string.
    int len = strlen(s);

    // Check each character in the string
    for (int i = 0; i < len; i++)
    {
        // Search the beginning of a word, so the first non white space character
        while (i < len && std::isspace(s[i]))
        {
            i++;
        }
        // We remember the start position of the word
        beginOfWord = i;
        if (i < len)
        {
            // Look for the end of the word, either a white space or end of string
            while (i < len && !std::isspace(s[i]))
            {
                i++;
            }
            // Here we have the end position of the word
            endOfWord = i;

            // What is the length of the word that we just found
            int wordLength = endOfWord - beginOfWord;
            if (wordLength) {

                // Allocate new space for the newWord variable
                char* newWord = new char[wordLength + 1]{ '\0' };

                // Copy the current evaluated word into our variable
#pragma warning(suppress : 4996)
                strncpy(newWord, &s[beginOfWord], wordLength);

                // Check, if we have enough capacity in our array for this new word
                if (count >= capacityOfArray) {
                    // NOt enough capacity. Get more. Double capacity
                    capacityOfArray = capacityOfArray * 2;

                    // Create new array with bigger capacity
                    char** temp = new char* [capacityOfArray] {};

                    // Copy all pointers from old array to new array
                    for (int k = 0; k < count; k++) {
                        temp[k] = wordList[k];
                    }
                    // Release old memory for words
                    delete[] wordList;

                    // And assign new array to wordlist
                    wordList = temp;
                }
                // Store the latest word in our wordlist
                wordList[count] = newWord;

                // Now, we have one word more
                count++;
            }
        }
    }
    return count;
}

int main()
{
    // This array will hold all words
    char** wordList = nullptr;
    int count = 0;

    // Get all words in string and their count
    count = wordsInString(" My name is Donnie ", wordList);

    // Show result on the screen
    std::cout << "\nThe number of words is: " << count << "\n\n";

    // Now show all extracted words on the screen
    for (int i = 0; i < count; ++i)
       std::cout << wordList[i] << '\n';

    // Release all dynamically allocated memory
    for (int k = 0; k < count; ++k)
        // First delete word by word
        delete[] wordList[k];

    // Delete word list
    delete[] wordList;

    return 0;
}

Please note: Such a code is OK for academic purposes. But in C++, we would never use pointers for owned memory or C-Style strings and arrays.


text:
Q: Keeping leading spaces in C I'm having this simple problem that I can't get over with.
int B;
char *a = (char*)malloc(1000*sizeof(char);

scanf("%[^\n]s", a);
printf("%c\n", a[0]);
B = strlen(a);
printf("%d\n", B);

If I put an entry like:
"   abc  "

a[0] = 'a' and B = 5 (the "abc" plus the last two spaces).  I want to count the first three spaces, how do I do it?

A: You could simply read the entire line using fgets() instead of using scanf(), which generally skips whitespace unless you explicitly capture it.
int B;
char *a = malloc(1000 * sizeof*a); /* don't cast malloc */

if (fgets(a, 1000, stdin) == NULL) {
    fputs("Could not read input\n", stdout);
}
else {
    printf("%c\n", a[0]);
    B = strlen(a);
    printf("%d\n", B);
}

A: If you want to trim the leading space, you can try this:
void trim_left(char *p);
int main()
{
  int B;
  char *a = (char*)malloc(1000*sizeof(char));

  scanf("%[^\n]s", a);
  printf("%c\n", a[0]);
  trim_left(a);
  B = strlen(a);
  printf("%d\n", B);
  printf("a = %s\n", a);
  return 0;
}

void trim_left(char *p) {
  int i = 0;
  while (p[i] && isspace(p[i])) {
    i++;
  }
  memmove(p, p+i, strlen(p+i));
  p[strlen(p+i)] = '\0';
}


text:
Q: Paging received information from table in php How can I page info that is received from mysql table..
I want to show on every page 4 rows
I have this code :
<?php
    include_once "config.php";
    $sql_select_product = "SELECT * FROM product ORDER BY date DESC;";
    $result_select_product = mysqli_query($connection, $sql_select_product);
    if (mysqli_num_rows($result_select_product) > 0) {
        while ($row_select_product = mysqli_fetch_assoc($result_select_product)) {
            echo "

$row_select_product[price]

$row_select_product[name]

$row_select_product[weight]

$row_select_product[work_type]

";
        }
    }
    $connection->close();
?>

A: If you call servername/path/script_name.php?page=[page_number]the script will return only 4 elements of the query.
<?php
$page_number = fiter_input(INPUT_GET,'page',FILTER_VALIDATE_INT,1,1);
$rows_per_page = 4;
$offset = ($page_number - 1) * $rows_per_page;
include_once "config.php";
$sql_select_product = sprintf("SELECT * FROM product ORDER BY date DESC LIMIT %d OFFSET %d;",
  $rows_per_page,$offset);
$result_select_product = mysqli_query($connection, $sql_select_product);
if (mysqli_num_rows($result_select_product) > 0) {
  while ($row_select_product = mysqli_fetch_assoc($result_select_product)) {
    echo "

$row_select_product[price]

$row_select_product[name]

$row_select_product[weight]

$row_select_product[work_type]

";
    }
}

A: Use limit in your query. Something like this:
select * from table_name order by column_name asc limit $offset,$startfrom;


text:
Q: What is BLOB filetype? I've got upload.php file with these file types allowed:
$allowedExtensions = array("mp3","mp4","jpg","jpeg","gif","png");

It performs upload correctly but when uploaded file is larger than 5mb (chunk size is set to 5mb) then it stops working unless I extend my array with BLOB (Javascript console returned this error as response from upload.php - that's how I know what was the problem):
$allowedExtensions = array("mp3","mp4","jpg","jpeg","gif","png","blob");

Can anyone explain me what that BLOB is? It's some kind of upload PART/CHUNK stored on server? Are there any other surprises I should include in allowedExtensions?
My upload.php is the one from Plupload.com: https://github.com/downloads/moxiecode/plupload/plupload_1_5_4.zip (unzip, go to /examples/ and open upload.php). I only extended it by adding this:
foreach($_FILES as $file){
    if($file['tmp_name'] > ''){
        if(!in_array(end(explode(".", strtolower($file['name']))), $allowedExtensions)){
            die($file['name'].' is not an allowed file type!');
        }
    }
}

A: BLOB = Binary Large OBject. Its a database field type for storing binary data.
Without starting a war, IMHO pictures do not belong in a database. Store them on disk and keep a reference to them in a database table.

A: foreach($_FILES as $file){
    if(isset($file['tmp_name']) &&  $file['tmp_name'] != ''){ <--- HERE IS THE CHANGE
        if(!in_array(end(explode(".", strtolower($file['name']))), $allowedExtensions)){
            die($file['name'].' is not an allowed file type!');
        }
    }
}

I modified your loop to help avoid warnings.


text:
Q: Import Fields from One Model into another Model I am consolidating several models (ideas, questions, etc...) into one topic model in the console and I thought something like this might work:
Question.find_each do |q|
  t = Topic.new
  t.create(:title=q.title, :description=q.description, :kind="Question")
end

But I'm getting an error:
 SyntaxError: (irb):24: syntax error, unexpected tIDENTIFIER, expecting ')'
 t.create(:title=q.title,:description=q.description,:kind='question')

Wondering if anyone has ever tried transferring data between models like this and if there's a "right" way to do it.
[edit]
This works:
Question.find_each do |q|
@qt=q.title
@qd=q.description
@q='Question'
@ca=q.created_at
@ui=q.user.id
@uvt=q.user_votes_total
Topic.create!({:title => @qt, :description => [@qd], :kind => @q, :created_at=>@ca, :user_id=>@ui, :user_votes_total=>@uvt })
end

A: Replace = with =>
t.create(:title => q.title, :description => q.description, :kind => 'Question')


text:
Q: Reuse of JAXB bindings in multiple projects I'm looking for a way to reuse bindings in order to avoid re-generation of classes each time I use types from XSDs of other projects.
I'm using maven and the maven-jaxb2-plugin.
Let say I have two projects A and B.
Project A defines a.xsd and is configured with the maven-jaxb2-plugin to generate the classes A1, A2, ... from a.xsd
Project B depends on project A and defines b.xsd, which uses some types defined in a.xsd. B in configured with the maven-jaxb2-plugin to generate the classes B1, B2, ... from a.xsd
To avoid the generation of the classes A1, A2, ... when building B, I included a section like the following in the binding configuration used in project B.
<jaxb:bindings scd="x-schema::tns" xmlns:tns="http://somedomain/A">
  <jaxb:schemaBindings map="false"/>
  <jaxb:bindings scd="~tns:A1">
    <jaxb:class ref="com.example.A1"/>
  </jaxb:bindings>
  <jaxb:bindings scd="~tns:A2">
    <jaxb:class ref="com.example.A2"/>
  </jaxb:bindings>
</jaxb:bindings>

This work fine.
Now suppose I have project C also depending on project A and defining c.xsd which uses types from a.xsd.
To avoid regeneration, I could include the above configuration in the binding configuration of project C, but this will lead me to configure the same binding block multiple times.
Is it possible to configure the common bindings somewhere and include it in the binding configuration of B and C in order to avoid redundancy?


text:
Q: Rails 3: Why isn't my Time attribute being saved to the DB correctly? I have a model with a Time attribute named start_date.  When I create a new object in my controller and initialize the time value, the object looks to be created correctly when I view it in the debugger...
(rdb:75) p @tourney
#<Tournament id: nil, created_at: nil, updated_at: nil, start_date: "2011-04-22 20:05:00", duration_in_mins: 30, winners_name: nil>

but after it's been saved to the db, the start_date value is wrong and is set at the default value....
#<Tournament id: 5, created_at: "2011-04-22 20:07:56", updated_at: "2011-04-22 20:07:56", start_date: "2000-01-01 01:05:00", duration_in_mins: 30, winners_name: nil>

Here's my controller code...
def create

    @tourney = Tournament.new(params[:tournament])
    @tourney.start_date = Time.new(params[:date][:year],
                         params[:date][:month],
                         params[:date][:day],
                         params[:date][:hour],
                         params[:date][:minute])

    debugger
    if @tourney.save
      redirect_to dashboard_path, :notice => "Tournament Created Successfully"
    else
      redirect_to dashboard_path, :notice => "Tournament Creation Failed"
    end

  end

Thanks so much for your wisdom!
My model code...
# Table name: tournaments
#
#  id               :integer         not null, primary key
#  created_at       :datetime
#  updated_at       :datetime
#  start_date       :time
#  duration_in_mins :integer
#  winners_name     :string(255)
#

class Tournament < ActiveRecord::Base

  has_many :participants, :dependent => :destroy

  attr_accessible :start_date, :duration_in_mins

  validates :start_date, :presence => true

end

A: Ok. I got it.
You have got
start_date       :time

But you should store it as a DateTime. So only time was stored without date!
Plus time was saved with default offset (+0000) and not in your local timezone.

A: Three things :
1) It seems that you have no attr_accessible anywhere, but bear in mind that it can cause this.
2) Try to save with save! instead of save. This will present possible model validation errors explicitly. Most times, when a model is not saved, it's because there are validation errors.
3) In your case, i would also check what Time.new(params[:tournament].... gets evaluated to, probably using rails console.

A: Do you need the attr_accessible :start_time in your model?


text:
Q: How do I change my view back to normal? I was mucking around with the options menu and I changed my view on the game so it went all bendy and weird. It was fun for a few days but now I want to change it back to normal and I don't know how!
Please help!

A: You most likely changed your Field of View (FOV). A low FOV will look zoomed in, whereas a high FOV may distorted.
You can change it back (70 is the default) with the upper left slider in your options menu.

A: Its the FOV, change it up and it zooms in, if you change it back it zooms out so you can make it to your standards.