text:
Q: Cron job to delay a form post So say I have a form like this:
<form target="_blank" action="submit.php" method="post">
what it should say:<input name="info" type="text" />

When (24hour.day.month.year)<input placeholder="24.13.04.95" name="date" type="text" />

<input name="" type="submit" />
</form>

Where you type what you want it to say. And choose the date at which the form posts†.
†So that when you submit the form it creates a cron job of the post to the submit.php page which send an email with what it should say at the time that is inputed.
like this:
$message = $_POST['info'];
mail('example@hotmail.com', 'Subject', $message);

Is this possible? And is this right way to go about delaying a form post for a substantial amount of time?

A: You need to "edit" your logic.
You can do a POST programmatically, but it's not needed in your case.
Pseudo:
1. User submit the form

2. Save data to database, along with a timestamp:

    $stamp = time() + ( 3600 * 24 * 30 );
    // $stamp is 30 days in the future

3. Create a cron job to run hourly, to trigger the sender code:

    1. Select from database where timestamp is less than current time()
    2. If row(s) found, send the mail. No POST involved
    3. Delete rows from database

A: You have to store $_POST data and schedule a single cron every minute that check if there are messages to send.


text:
Q: Помогите с кодом FlexBox
Как сделать что-бы они шли ровно в ряд
html
        <title>
            Name
        </title>
        <link href="style.css" rel="stylesheet">

                NameStudio

css
@import url('https://fonts.googleapis.com/css?family=Roboto+Condensed:400,700');
*{
    padding: 0px;
    margin: 0px;
}
header{
height: 850px;
width: 100%;
background-color: #1E1E2A;
display: flex;
justify-content: center;
flex-direction: row;

}
logo{
margin-top: 50px;

}
Text{
font-family: 'Roboto Condensed', sans-serif;
font: bold;
font-size: 80px;
color: white;
margin-top: 600px;
display: block;

}

A: Трэш какой-то вы наваяли. И вопрос хорошо бы задать по-человечески.

* {
  padding: 0px;
  margin: 0px;
  box-sizing: border-box;
}

#header {
  height: 100vh;
  width: 100vw;
  background-color: #1E1E2A;
  display: flex;
  justify-content: center;
  align-items: center;
}

#logo {
  width: 75px;
  height: 75px;
  border: 8px solid white;
  border-radius: 50%;
  margin-right: 1em;
}

#text {
  font-family: sans-serif;
  font-weight: bold;
  font-size: 200%;
  color: white;
}

NameStudio

redpajama_set_name: RedPajamaStackExchange


text:
Q: Using the template in 404, 403, 500, etc error pages I'm just thinking if I can made this work in a cool, DRY way.. but i'm pretty new to rails and have no idea of how can I do that..
Any help?
thanks in advance.

A: Just figured it out:
rescue_from Foo::BarException do |exception|
    render file: "#{Rails.root}/public/403", formats: [:html], status: 403, layout: true
end

Then do the 403.html like a boss, and it should work.
But, I still not knowing how to made the automatic 404 use the template too... it always shows the exception, even if I add the rescue in my application controller.


text:
Q: Unity: "Set as Layer Default State" does not show whenever I right-click on an animation I'm currently in Lesson 3.3 of Unity's "Junior Programmer Pathway" - I've run into an issue, the "Set as Layer Default State" does not show whenever I right-click on an animation. The only options are shown in the SS. Any help appreciated.
Version: 2020.3.31f1

A: I found a workaround.
Right-click Entry and select Set StateMachine Default State, this will disconnect the connection to Idle now click on Run_Static


text:
Q: How to call a condition on a view? I have two activities in first activity, I have two text views fromLocation and toLocation. On click of from and to text view I am calling next activity in which I have a map and I choose a location which I am storing in string and showing on text view. This choose location I want to show on fromLocation text view of first activity onClick of a layout of useLocation in second activity on the basis of which text view is choose. If onClick of fromLocation the address should show on fromLocation text view and onClick of toLocation address should show on toLocation. This will be onResume method of first activity.
Now I am getting the address on both text views when I choose address for first time onClick on fromLocation text view.
How to do this..?
GoSendActivity(FirstActivity)
 public class GoSend extends AppCompatActivity implements com.google.android.gms.location.LocationListener, GoogleApiClient.ConnectionCallbacks,
        GoogleApiClient.OnConnectionFailedListener {
    private LocationRequest mLocationRequest;

    private GoogleApiClient mGoogleApiClient;
    boolean mUpdatesRequested = false;
    private GoogleMap mGoogleMap;
    private MarkerOptions markerOptions;
    private LinearLayout ll;
    private TextView additionalContactFrom,additionalContactTo,txt_from,txt_to;

    private LinearLayout linearLayoutFrom,linearLayoutTo;
    private ImageView next;
    private Toolbar toolbar;
    private EditText locdetailsFrom,locdetailsTo,itemDetails;
    private Intent i;
    private LatLng currentLocation,curentpoint,center;
    private GPSTracker gps;
    double latitude,longitude;

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

        setUI();

        int status = GooglePlayServicesUtil
                .isGooglePlayServicesAvailable(getBaseContext());

        if (status != ConnectionResult.SUCCESS) { // Google Play Services are
            // not available

            int requestCode = 10;
            Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, this,
                    requestCode);
            dialog.show();

        } else { // Google Play Services are available

            // Getting reference to the SupportMapFragment
            // Create a new global location parameters object
            mLocationRequest = LocationRequest.create();

            /*
             * Set the update interval
             */
            mLocationRequest.setInterval(GData.UPDATE_INTERVAL_IN_MILLISECONDS);

            // Use high accuracy
            mLocationRequest
                    .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);

            // Set the interval ceiling to one minute
            mLocationRequest
                    .setFastestInterval(GData.FAST_INTERVAL_CEILING_IN_MILLISECONDS);

            // Note that location updates are off until the user turns them on
            mUpdatesRequested = false;

            /*
             * Create a new location client, using the enclosing class to handle
             * callbacks.
             */
            mGoogleApiClient = new GoogleApiClient.Builder(this)
                    .addApi(LocationServices.API).addConnectionCallbacks(this)
                    .addOnConnectionFailedListener(this).build();

            mGoogleApiClient.connect();

        }
    }

    public void setUI() {

        toolbar = (Toolbar) findViewById(R.id.toolbar);
        toolbar.setTitle("COURIER");
        setSupportActionBar(toolbar);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        locdetailsFrom = (EditText) findViewById(R.id.editText_from_details);
        locdetailsFrom.setText(GoSendData.instance.getmFromLocationDetails());

        locdetailsTo = (EditText) findViewById(R.id.editText_to_details);
        locdetailsTo.setText(GoSendData.instance.getmToLocationDetails());

        itemDetails = (EditText) findViewById(R.id.editText_ItemDetail);

        txt_from = (TextView) findViewById(R.id.Text_from);
        txt_to = (TextView) findViewById(R.id.Text_to);
        additionalContactFrom = (TextView) findViewById(R.id.contactDetailsFrom);
        additionalContactTo = (TextView) findViewById(R.id.contactDetailsTo);
        linearLayoutFrom = (LinearLayout) findViewById(R.id.LinearLayoutFrom);
        linearLayoutTo = (LinearLayout) findViewById(R.id.LinearLayoutTo);
        next = (ImageView) findViewById(R.id.imageView_next);

        txt_from.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                i = new Intent(getApplicationContext(), PickLocationActivity.class);
             ///   GoSendData.instance.addressType=0;
                startActivity(i);
            }
        });

        txt_to.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                i = new Intent(getApplicationContext(), PickLocationActivity.class);
                //GoSendData.instance.addressType=1;
                startActivity(i);
            }
        });

        additionalContactFrom.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                if (linearLayoutFrom.getVisibility() == View.GONE) {

                    linearLayoutFrom.setVisibility(View.VISIBLE);

                } else {
                    linearLayoutFrom.setVisibility(View.GONE);

                }
            }
        });

        additionalContactTo.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View v) {

                if (linearLayoutTo.getVisibility() == View.GONE) {

                    linearLayoutTo.setVisibility(View.VISIBLE);

                } else {
                    linearLayoutTo.setVisibility(View.GONE);

                }
            }
        });

        next.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                i = new Intent(getApplicationContext(), GoSendDetailsActivity.class);
                startActivity(i);
            }
        });

    }

    @Override
    public void onResume() {
        int LocationClick;
        super.onResume();  // Always call the superclass method first

            txt_from.setText(GoSendData.instance.mFromLocation);
            txt_to.setText(GoSendData.instance.mToLocation);

        }

    private void setupMap() {
        try {

            mGoogleMap = ((MapFragment) getFragmentManager().findFragmentById(
                    R.id.map)).getMap();

            // Enabling MyLocation in Google Map
            mGoogleMap.setMyLocationEnabled(true);
            mGoogleMap.getUiSettings().setZoomControlsEnabled(true);
            mGoogleMap.getUiSettings().setMyLocationButtonEnabled(true);
            mGoogleMap.getUiSettings().setCompassEnabled(true);
            mGoogleMap.getUiSettings().setRotateGesturesEnabled(true);
            mGoogleMap.getUiSettings().setZoomGesturesEnabled(true);

            gps = new GPSTracker(this);

            gps.canGetLocation();

            latitude = gps.getLatitude();
            longitude = gps.getLongitude();
            curentpoint = new LatLng(latitude, longitude);

            CameraPosition cameraPosition = new CameraPosition.Builder()
                    .target(curentpoint).zoom(19f).tilt(70).build();

            mGoogleMap.setMyLocationEnabled(true);
            mGoogleMap.animateCamera(CameraUpdateFactory
                    .newCameraPosition(cameraPosition));

            mGoogleMap.addMarker(markerOptions);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onLocationChanged(Location location) {
        // TODO Auto-generated method stub

    }

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

    }

    @Override
    public void onConnected(Bundle arg0) {
        // TODO Auto-generated method stub
        setupMap();

    }

          @Override
          public void onConnectionSuspended(int arg0) {
              // TODO Auto-generated method stub

          }

}

ChooseFromMapActivity(second activity)
public class ChooseFromMapActivity extends AppCompatActivity implements
        LocationListener, GoogleApiClient.ConnectionCallbacks,
        GoogleApiClient.OnConnectionFailedListener {

    private LocationRequest mLocationRequest;
    GoogleMap mGoogleMap;

    private GoogleApiClient mGoogleApiClient;
    boolean mUpdatesRequested = false;
    private LatLng center,curentpoint;
    private LinearLayout markerLayout,useLocation;
    private Geocoder geocoder;
    private List<Address> addresses;
    private TextView Address;
    double latitude,longitude;
    private GPSTracker gps;

    Intent intent;
    double x, y;
    StringBuilder str;

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

        SetUpUI();

        int status = GooglePlayServicesUtil
                .isGooglePlayServicesAvailable(getBaseContext());

        if (status != ConnectionResult.SUCCESS) { // Google Play Services are
            // not available

            int requestCode = 10;
            Dialog dialog = GooglePlayServicesUtil.getErrorDialog(status, this,
                    requestCode);
            dialog.show();

        } else { // Google Play Services are available

            // Getting reference to the SupportMapFragment
            // Create a new global location parameters object
            mLocationRequest = LocationRequest.create();

            /*
             * Set the update interval
             */
            mLocationRequest.setInterval(GData.UPDATE_INTERVAL_IN_MILLISECONDS);

            // Use high accuracy
            mLocationRequest
                    .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);

            // Set the interval ceiling to one minute
            mLocationRequest
                    .setFastestInterval(GData.FAST_INTERVAL_CEILING_IN_MILLISECONDS);

            // Note that location updates are off until the user turns them on
            mUpdatesRequested = false;

            /*
             * Create a new location client, using the enclosing class to handle
             * callbacks.
             */
            mGoogleApiClient = new GoogleApiClient.Builder(this)
                    .addApi(LocationServices.API).addConnectionCallbacks(this)
                    .addOnConnectionFailedListener(this).build();

            mGoogleApiClient.connect();
        }

        useLocation.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                intent = new Intent(ChooseFromMapActivity.this,GoSend.class);

                startActivity(intent);

            }
        });
    }

        private void SetUpUI(){

            Address = (TextView) findViewById(R.id.textShowAddress);
            markerLayout = (LinearLayout) findViewById(R.id.locationMarker);
            useLocation = (LinearLayout)findViewById(R.id.LinearUseLoc);

            Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
            toolbar.setTitle("CHOOSE FROM MAP");
            setSupportActionBar(toolbar);

            toolbar.setNavigationIcon(R.drawable.ic_arrow_back_white_24dp);

            toolbar.setNavigationOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    onBackPressed();
                }
            });

            if (Build.VERSION.SDK_INT >= 21) {
                getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
                getWindow().setStatusBarColor(getResources().getColor(R.color.colorPrimaryDark));
            }

}
    private void stupMap() {
        try {

            mGoogleMap = ((MapFragment) getFragmentManager().findFragmentById(
                    R.id.map)).getMap();

            // Enabling MyLocation in Google Map
            mGoogleMap.setMyLocationEnabled(true);
            mGoogleMap.getUiSettings().setZoomControlsEnabled(true);
            mGoogleMap.getUiSettings().setMyLocationButtonEnabled(true);
            mGoogleMap.getUiSettings().setCompassEnabled(true);
            mGoogleMap.getUiSettings().setRotateGesturesEnabled(true);
            mGoogleMap.getUiSettings().setZoomGesturesEnabled(true);

            gps = new GPSTracker(this);

            gps.canGetLocation();

            latitude = gps.getLatitude();
            longitude = gps.getLongitude();
            curentpoint = new LatLng(latitude, longitude);

            CameraPosition cameraPosition = new CameraPosition.Builder()
                    .target(curentpoint).zoom(19f).tilt(70).build();

            mGoogleMap.setMyLocationEnabled(true);
            mGoogleMap.animateCamera(CameraUpdateFactory
                    .newCameraPosition(cameraPosition));

            mGoogleMap.setOnCameraChangeListener(new OnCameraChangeListener() {

                @Override
                public void onCameraChange(CameraPosition arg0) {
                    // TODO Auto-generated method stub
                    center = mGoogleMap.getCameraPosition().target;

                    mGoogleMap.clear();
                    markerLayout.setVisibility(View.VISIBLE);

                    try {
                        new GetLocationAsync(center.latitude, center.longitude)
                                .execute();

                    } catch (Exception e) {
                    }
                }
            });

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    public void onLocationChanged(Location location) {
        // TODO Auto-generated method stub

    }

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

    }

    @Override
    public void onConnected(Bundle arg0) {
        // TODO Auto-generated method stub
        stupMap();

    }

    private class GetLocationAsync extends AsyncTask<String, Void, String> {

        // boolean duplicateResponse;

        public GetLocationAsync(double latitude, double longitude) {
            // TODO Auto-generated constructor stub

            x = latitude;
            y = longitude;
        }

        @Override
        protected String doInBackground(String... params) {

            try {
                geocoder = new Geocoder(ChooseFromMapActivity.this, Locale.ENGLISH);
                addresses = geocoder.getFromLocation(x, y, 1);
                str = new StringBuilder();
                if (Geocoder.isPresent()) {

                    if ((addresses != null) && (addresses.size() > 0)) {
                        Address returnAddress = addresses.get(0);

                        String localityString = returnAddress.getLocality();
                        String city = returnAddress.getCountryName();
                        String region_code = returnAddress.getCountryCode();
                        String zipcode = returnAddress.getPostalCode();

                        str.append(localityString + "");
                        str.append(city + "" + region_code + "");
                        str.append(zipcode + "");

                    }
                } else {
                }
            } catch (IOException e) {
                Log.e("tag", e.getMessage());
            }
            return null;

        }

        @Override
        protected void onPostExecute(String result) {
            try {
                Address.setText(addresses.get(0).getAddressLine(0)
                        + addresses.get(0).getAddressLine(1) + " ");
                GoSendData.instance.mFromLocation=addresses.get(0).getAddressLine(0)
                        + addresses.get(0).getAddressLine(1) + " ";
                GoSendData.instance.mToLocation=addresses.get(0).getAddressLine(0)+addresses.get(0).getAddressLine(1)+"";

            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        @Override
        protected void onProgressUpdate(Void... values) {

        }
    }

    @Override
    public void onConnectionSuspended(int arg0) {
        // TODO Auto-generated method stub

    }
}

A: If i understand correctly.. You should launch second activity as startActivityForResult and after choosing location on map return it as a result.
The first activity should now this value from the method onActivityResult
http://developer.android.com/training/basics/intents/result.html

*

*Click on first textview launch second activity with requestcode

*Second activity after choosing location finishes with setResult, where you store chosen location

*Get the result in onActivityResult of first activity and set it to textView

the same for second textview. Use different requestcodes for different textview, which you should check in onActivityResult to determine which textView data was chosen in second activity


text:
Q: What does 'the timeless' imply in this paragraph?
The very best the Eternal City has to offer, from the timeless to new kids on the block, including a next-generation trattoria and a friendly microbrewery. Select your favorites for a perfect weekend away.
Source: Pick-n-mix Rome

A: I'm quite sure that it refers to people/beings who don't age,  i.e. are immortal.
It could perhaps  also  refer to those who've been there ever since the founding of the city, as it's eternal.
P.S. What book is this? Reads like something right up my alley.
Edit: Read the linked article, now I bet that it refers to the various buildings, and other architectural fancies.


text:
Q: What is the mechanism behind strip() function followed by a slice notation in python? For example
sentence = "hello world"
stripped1 = sentence.strip()[:4]
stripped2 = sentence.strip()[3:8]
print (stripped1)
print (stripped2)

Output:
hell
lo worl

Here strip( ) is a function object. So it should either take parameters or be followed by another object using dot notation. But how is it possible that the function is simply followed by slice notation ? How does strip( ) and slicing work together here ? what is the syntax rule supporting this format ?

A: Python executes _result = sentence.strip()[:4] as several separate steps:
_result = sentence       # look up the object "sentence" references
_result = _result.strip  # attribute lookup on the object found
_result = _result()      # call the result of the attribute lookup
_result = _result[:4]    # slice the result of the call
stripped1 = _result      # store the result of the slice in stripped1

so [:4] is just more syntax, just like a () call, that can be applied to the outcome of another expression.
There is nothing special about the str.strip() call here, it just returns another string, the stripped version of the value of sentence. The method works fine without passing in any arguments; from the documentation for that method:

If omitted or None, the chars argument defaults to removing whitespace.

so there is no requirement here to pass in arguments.
In this specific example, sentence.strip() returns the exact same string, as there is no leading or trailing whitespace in "hello world":
>>> sentence = "hello world"
>>> sentence.strip()
'hello world'
>>> sentence.strip() == sentence
True

so the output of sentence.strip()[:4] is exactly the same as for sentence[:4]:
>>> sentence.strip()[:4] == sentence[:4]
True

You appear to have missed the call there, as you appear to be confused by the output of just the attribute lookup; sentence.strip (no call), produces a built-in method object:
>>> sentence.strip
<built-in method strip of str object at 0x102177a80>


text:
Q: Parse Server Logs in Docker? So I need to dockerize my parse server for a project and im a bit new to Docker.
I'm used to Heroku where I just could use heroku logs or connect papertrial to see the parse logs to help debug things but I have no clue how to see my parse specific logs when its running in a docker container.
I'm able to do test curl and get data back so I know its working but no idea how to find log data.
Searching around really doesn't lead to any results that are more specific to Docker.  I also tried to figure out how to write to the logs folder but the folder alway seems empty.. ?

A: Docker collects the logs of each container from stdout and stderr of a container. As described in 12-factor application, an application should send its logs to stdout (it is standardized by heroku):

A twelve-factor app never concerns itself with routing or storage of its output stream. It should not attempt to write to or manage logfiles. Instead, each running process writes its event stream, unbuffered, to stdout. During local development, the developer will view this stream in the foreground of their terminal to observe the app's behavior.

That being said, everything you stream to stdout of a container will be stored in /var/lib/docker/containers/<container id>/<container id>-json.log directory. You can see the container id using docker ps command. You don't have to see the file always. You can do docker logs <container-id> to see the logs stored in the container's directory.
If you have to have logs in the filesystem, you can store logs inside the container and mount that directory on your host machine to see log files. You can do something like this:
docker run -v <host directory>:<log directory in container> ...

Hope it helps.


text:
Q: Using REGEX in Visualforce I want to be able to render an element if my custom field matches a certain pattern.
Custom Field Name: Code__c
Pattern: (any character)19-10-11-12(any character)
How can this be achieved in Visualforce?
The rendered condition in my below code does not evaluate true. Please help.
My code below -
<apex:outputPanel rendered="REGEX(Code__c, '[a-zA-Z]+19-10-11-12[a-zA-Z]+')">

...

</apex:outputPanel>

A: You have to use the expression syntax when calling the functions
<apex:outputPanel rendered="{!REGEX(Code__c, '[a-zA-Z]+19-10-11-12[a-zA-Z]+')}">

But the REGEX function is not available in Custom Formula Fields or
Visualforce. check this reference
So you have to either move this logic into the controller or try using javascript to render this.


text:
Q: concat of multiple elements in xforms I have the following data instance.
<xhtml:html xmlns:xhtml="http://www.w3.org/1999/xhtml"
xmlns:xs="http://www.w3.org/2001/XMLSchema"
xmlns:xxforms="http://orbeon.org/oxf/xml/xforms"
xmlns:exforms="http://www.exforms.org/exf/1-0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<xhtml:head>
    <xforms:instance id="instanceData">
        <form xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
            xmlns:xsd="http://www.w3.org/2001/XMLSchema">
            <fruits>
                <fruit>
                    <fruit-name>Mango</fruit-name>
                </fruit>
                <fruit>
                    <fruit-name>Apple</fruit-name>
                </fruit>
                <fruit>
                    <fruit-name>Banana</fruit-name>
                </fruit>
            </fruits>
            <all-fruits></all-fruits>
        </form>
    </xforms:instance>
</xhtml:head>
</xhtml:html>

i would like to have all the fruit names in all-fruits tag as below
<all-fruits>Mango Apple Banana</all-fruits>

Please suggest some way to achieve the same. It didn't work for me when tried with xxforms:iterate and concat.

A: The following does the trick:
<xforms:bind nodeset="all-fruits"
             calculate="string-join(../fruits/fruit/fruit-name, ' ')"/>

And here is the full source so you can run it:
<xhtml:html xmlns:xhtml="http://www.w3.org/1999/xhtml"
            xmlns:xs="http://www.w3.org/2001/XMLSchema"
            xmlns:xxforms="http://orbeon.org/oxf/xml/xforms"
            xmlns:exforms="http://www.exforms.org/exf/1-0"
            xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
            xmlns:xforms="http://www.w3.org/2002/xforms">
    <xhtml:head>
        <xforms:model>
            <xforms:instance id="instanceData">
                <form xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
                      xmlns:xsd="http://www.w3.org/2001/XMLSchema">
                    <fruits>
                        <fruit>
                            <fruit-name>Mango</fruit-name>
                        </fruit>
                        <fruit>
                            <fruit-name>Apple</fruit-name>
                        </fruit>
                        <fruit>
                            <fruit-name>Banana</fruit-name>
                        </fruit>
                    </fruits>
                    <all-fruits></all-fruits>
                </form>
            </xforms:instance>
            <xforms:bind nodeset="all-fruits" calculate="string-join(../fruits/fruit/fruit-name, ' ')"/>
        </xforms:model>
    </xhtml:head>
    <xhtml:body/>
</xhtml:html>


text:
Q: Match strings wrapped in square brackets not containing $ I'm trying to match a tag that's inside brackets and does not contain a dollar sign, for example [title]
I have tried:
\[[^\$]\]

and
\[[^\$]+\]

But it's not matching it correctly. Any tips on this?

A: You will need to include a ] in your negated character class so that greedy matching performs as intended:
/\[[^\$\]]+\]/

To remove unnecessary escaping, use:
/\[[^$\]]+]]/

Pattern Demo:  https://regex101.com/r/ePmTRm/1/
*Note, you should not be using regex to handle html.


text:
Q: Why do we use the term DPI for matters involving images on computers I'm told that DPI and Points are no longer relevant in terminology involving graphical displays on computer screens and mobile devices yet we use the term "High DPI Aware" and in Windows you can set the various DPI levels (96, 120, 144, 192).
Here is my understanding of the various terms that are used in displaying images on computer monitors and devices:
DPI = number of dots in one linear inch.  But DPI refers to printers and printed images.
Resolution = the number of pixels that make up a picture whether it is printed on paper or displayed on a computer screen. Higher resolution provides the capability to display more detail. Higher DPI = Higher resolution, however, resolution does not refer to size, it refers to the number of pixels in each dimension.
DPI Awareness =  an app takes the DPI setting into account, making it possible for an application to behave as if it knew the real size of the pixels.
Points and Pixels:  (There are 72 points per inch.)
At 300 DPI, there are 300 pixels per inch. So 4.16 Pixels = 1 point.
At 96 DPI there are 1.33 pixels in one point.
Is there a nice way to "crisply" describe the relationship between DPI, PPI, Points, and Resolution?

A: You are correct that DPI refers to the maximum amount of detail per unit of physical length.
Computer screens are devices that have a physical size, so we speak of the number of pixels per inch they have. Traditionally this value has been around 80 PPI, but now it can be up to 400 PPI.
The notion of "High DPI Aware" (e.g. Retina) is based on the fact that physical screen sizes don't change much over time (for example, there have been 10-inch tablets for more than a decade), but the number of pixels we pack into the screens is increasing. Because the size isn't increasing, it means the density - or the PPI - must be increasing.
Now when we want to display an image on a screen has more pixels than an older screen, we can either:

*

*Map the old pixels 1:1 onto the new screen. The physical image is smaller due to the increased density. People start to complain about how small the icons and text are.

*Stretch the old image and fill in the extra details. The physical image is the same size, but now there are more pixels to represent the content. For example, this results in font curves being smoother and photographs showing more fine details.

A: The term DPI (Dots Per Inch) to refer to device or image resolution came into common use well before the invention of printers that could print multiple dots per pixel. I remember using it in the 1970's. The term PPI was invented later to accommodate the difference, but the old usage still lingers in places such as Windows which was developed in the 1980's.
The DPI assigned in Windows rarely corresponds to the actual PPI of the screen. It's merely a way to specify the intended scaling of elements such as fonts.

A: DPI vs. resolution – What's the difference?
The acronym dpi stands for dots per inch. Similarly, ppi stands for pixels per inch. So, why have two different acronyms for measuring roughly the same thing? Because there is a key difference between the two and if you don't understand this difference it can have a negative impact on your digital signage project.
Part of the confusion between the two terms stems from the fact that many people who use them are lazy and tend to use the terms interchangeably. The simplest way of thinking about them is that one is digital (ppi) and represents what you see on the computer screen and the other is physical (dpi) for example, how an image appears when you print it out on a piece of paper.
I suggest you to check this in-depth article talking about the technicality of this topic.
https://blog.viewneo.com/blog/72-dpi-resolution-vs-300-dpi-for-digital-solutions/


text:
Q: Nested datagrid column visibility based on the contents of its inner datagrid I have a nested datagrid and I want to hide outer datagrid column when the inner datagrid doesn't have any data. I am using MVVM pattern. Model fills the data in the collections which is binded to the view.
Filled Datagrid
The list of Component1, 2 and 3 are displayed through a datagrid inside the outer datagrid. Each label family will have two collections left and right.
When the Model doesn't have any components for left label collection, then I want the Left column to be hidden completely. As in below image. Similarly for Right column.
Left Column Hidden
Please help me in achieving this.
I searched for similar situations on this site and google, but couldn't find anything similar to this.
Here is the XAML code:
    <DataGrid ItemsSource="{Binding Labels}"
          CanUserAddRows="False"
          CanUserDeleteRows="False">
    <DataGrid.Columns>
        <DataGridTemplateColumn Width="10*" >
            <DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <TextBlock Text="{Binding LabelFamily}" />
                </DataTemplate>
            </DataGridTemplateColumn.CellTemplate>
        </DataGridTemplateColumn>
        <DataGridTemplateColumn Header="Right" Width="25*">
            <DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <DataGrid ItemsSource="{Binding LeftLabel.Components}"
                              CanUserAddRows="False"
                              CanUserDeleteRows="False">
                    </DataGrid>
                </DataTemplate>
            </DataGridTemplateColumn.CellTemplate>
        </DataGridTemplateColumn>
        <DataGridTemplateColumn Header="Left" Width="25*">
            <DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <DataGrid ItemsSource="{Binding RightLabel.Components}"
                              CanUserAddRows="False"
                              CanUserDeleteRows="False">
                    </DataGrid>
                </DataTemplate>
            </DataGridTemplateColumn.CellTemplate>
        </DataGridTemplateColumn>
    </DataGrid.Columns>
</DataGrid>

I am not posting the model code to keep the post short as much as possible.

A: You can create converter like this (I used ObservableCollection for testing, you should use your container):
public class NoElementVisibilityConverter : MarkupExtension, IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (value == null)
            return Visibility.Collapsed;
        ObservableCollection<int> ienum = value as ObservableCollection<int>;
        return ienum == null || ienum.Count() == 0 ? Visibility.Collapsed : Visibility.Visible;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }

    public override object ProvideValue(IServiceProvider serviceProvider)
    {
        if (_converter == null)
            _converter = new NoElementVisibilityConverter();
        return _converter;
    }

    private static NoElementVisibilityConverter _converter = null;
}

And use it on your column like this:
<DataGridTemplateColumn Header="Left" Width="25*"
                        Visibility={Binding RightLabel.Components, Converter={local:NoElementVisibilityConverter}>

Don't forget to include Converter namespace in your Window.


text:
Q: Where should I store api key in rails3? What is the best practice for storing/retrieving API keys in rails3?
Should I create my own application yaml and access it through there?  If so, how?
Sorry for the noob question...

A: I use the settingslogic plugin for things like this.  Very easy to use.
Add settingslogic to your Gemfile and bundle install:
gem 'settingslogic'

Create a directory for your settings and place the settingslogic yaml in there:
/my_app/config/settings/my_settings.yml

You can include default settings and per environment settings.  The file looks like this:
defaults: &defaults
  api_key: abc123

development:
  <<: *defaults

test:
  <<: *defaults

production:
  <<: *defaults

Add this file: app/models/my_settings.rb, start up your app and you are good to go
class MySettings < Settingslogic
  source "#{Rails.root}/config/settings/my_settings.yml"
  namespace Rails.env
end

Now you can use call these settings from anywhere in the app like so:
MySettings.api_key


text:
Q: MongoDB profiling level automatically reverts to zero I've got a non-sharded MMAPv1 replica set running in the MongoDB Cloud Manager. I want to keep profiling on indefinitely for several databases, but for some reason it returns to zero after maybe 48 hours or so.
Is there something in the MongoDB database server or perhaps the Cloud Manager that sets the profiling level to zero? I don't see anything in my code that would do this, and noone with access to the databases is manually changing the profiling level.
I enabled profiling for each database by executing db.setProfilingLevel(1) from the mongo console. Result:
{
  "was": 0,
  "slowms": 100,
  "ok": 1
}

A: When using the db.setProfilingLevel(1) command, if mongod is restarted (perhaps by MongoDB Cloud Manager if you are using it), it resets profiling level to default (0).
To keep the expected profiling level after reboot, you can use option operationProfiling.mode in your mongod config file.


text:
Q: How to copy project from iphone to ipad using xcode 8? I write a iphone project (Objective C) in XCode 8. I create a new iPad project. I want to copy the iPhone project and paste the iPad project.
what should I do ?

A: If you want to make a new app for iPad (and not a universal app):
1- Make a copy of your project forlder.
2- Open the new copy that will target iPad. Open The xcodeproj file and in Xcode, select your project from the left menu, then select your target. From Deployment Info change Device target from iPhone to iPad.

3- Now, your project targets iPad. Don't forget to edit your storyboards (or XIB files) to fit to iPad's screen size.
4- If this answers what you wanted to do, please don't forget to accept it :)


text:
Q: Illuminate\Database\QueryException errno: 150 "Foreign key constraint is incorrectly I have a migration like this:
  public function up()
    {
        Schema::create('categories', function (Blueprint $table) {
            $table->bigIncrements('id');
            $table->text('name');
            $table->unsignedSmallInteger('category_id');
            $table->unsignedInteger('section_d');
            $table->unsignedBigInteger('order');

            $table->timestamps();

            $table->foreign('category_id')
                ->references('id')->on('categories')
                ->onDelete('restrict');

            $table->foreign('section_id')
                ->references('id')->on('sections')
                ->onDelete('restrict');
        });
    }

There are other migrations that work fine, but everytime "php artisan migrate" is ran it shows this error regarding the specific migration above. Error:
   Illuminate\Database\QueryException  :
   SQLSTATE[HY000]: General error: 1005
   Can't create table `api`.`posts` (errno: 150
   "Foreign key constraint is incorrectly formed")
   (SQL: alter table `categories`
   add constraint `categories_category_id_foreign`
   foreign key (`category_id`)
   references `categories` (`id`) on delete restrict)

Do you know why?


text:
Q: using functions to display numbers in a list I have a list of numbers and I have to use a function to display them in celsius,  they are in fahrenheit now.
nums = [30,34,40,36,36,28,29,32,34,44,36,35,28,33,29,40,36,24,26,30,30,32,34,32,28,36,24,32]
def fahrenToCel(c):
    c = (f - 32) * (5 / 9)
    return c
print fahrenToCel(nums)

this is what I have, can someone please help me

A: If you have a list the_list and you want to apply a function f to each element, creating a new list of the results:
new_list = [f(x) for x in the_list]

A: Your function seems to take as input a single number, yet you're giving it a list of numbers. If you want to generate a list of converted numbers using that function, you can use list comprehension:
cels = [fahrenToCel(fah) for fah in nums]

A: print ','.join([str(fahrenToCel(fahren)) for fahren in nums])

This will not only create a new list, but will also join it as a comma-separated string.
If nums is rather long, you can save some memory and performance by using a generator expression instead of list comprehension. You just have to take off the square brackets:
print ','.join(str(fahrenToCel(fahren)) for fahren in nums)

A: The simplest way would be to use a for loop to iterate over the list and printing each result:
#!/usr/bin/env python

# def farentoCel(x): ...
# ...

if __name__ == '__main__':
    import sys

    for each_num in sys.argv[1:]:
        print farentoCel(int(each_num))

As others have said you can replace this explicit loop with a list comprehension (expression), or even a generator comprehension (in newer versions of Python).
In this case I'm showing a very simple skeleton for you to use for testing simple functions.  The if _ name _ == '_ main _': suite is a Python convention used to separate your function, class, and other definitions from the run-time of your code.  This can be used to structure your code so that it can be re-used in (imported into) other code while also exposing some functionality in a command line utility (wrapper) or providing a default interface (perhaps a GUI).
In the fairly common case where your module doesn't have simply accessible utility (where it's only useful when incorporated into other code) then you can use the '_ main _' suite to contain unit test cases.


text:
Q: Append child on HTML tags I have the follow code where I am trying to add a compiled HTML string inside multiple tags, but the elements are not beeing inserted:
for (var i = 0; i < boxes.length; i++) {
    var ctxmenu = $compile('click here')($scope);
    document.getElementById("box-"+i).append(ctxmenu[0]);
}

If i try to add it without for loop like that:
document.getElementById("box-"+i).append(ctxmenu[0]);

Then it will work.
Any ideias how to do that?

EDIT
The problem was that I was using .append() method instead of .appendChild().

A: You're using javascript, it's .appendChild(NodeElement).

The Node.appendChild() method adds a node to the end of the list of
  children of a specified parent node. If the given child is a reference
  to an existing node in the document, appendChild() moves it from its
  current position to the new position (there is no requirement to
  remove the node from its parent node before appending it to some other
  node).

Change:
document.getElementById("box-"+i).append(ctxmenu[0]);

To:
document.getElementById("box-"+i).appendChild(ctxmenu[0]);

The .append() method belongs to jquery.


text:
Q: do postback programatically from iframe to parent page I have a aspx page, in that page i have an Iframe. In the Iframe i do some stuff in code behind and when it is done I would like to do a postback from the aspx.
In other words, Is it possible to do a postback programatically from the code behind of the iframe to the parent page?
I think a postback can be done using "ClientScript.GetPostBackClientHyperlink(New Control(), String.Empty)" but that will only do a postback for the iframe i think.

A: I have done this in two different ways:
1) Have a hidden button on the parent page.  When you need it to post back you register some javascript that causes a click of that button:
Parent HTML:
<asp:Button ID="Button1" runat="server" Text="" Style="background-color: Transparent;
                                color: inherit; border-style: none;" />

Iframe Code Behind:
ClientScript.RegisterStartupScript(Me.GetType(), "RefreshParent", "<script type='text/javascript'>var btn = window.parent.document.getElementById('Button1');if (btn) btn.click();</script>")

2) From code behind register a client script that calls the post back on the form in the parent page. The JS would be something like:
window.parent.document.forms[0].submit();

A: Assuming that the pages are in the same domain, you can emit Javascript that triggers a postback in the outer page.

A: The article of How to make cross page Postback
Or visit this one http://www.devx.com/dotnet/Article/33835/0/page/2
How to cause a page to postback from a frame at :
http://forums.asp.net/p/1187580/2030635.aspx

A:
Is it possible to do a postback
  programatically from the code behind
  of the iframe to the parent page?

Yes. To post a form automatically from the code behind you need to register a startup javascript, which will submit the form. You can assign the action of the form to point to the aspx page of the parent.

but that will only do a postback for
  the iframe i think.

To make the form submit the parent window instead of the current one, you can add "_target" attribute to the form and set it to "_parent"
If you would want to trigger postback by simulating a button click, you can do as SLaks pointed out.


text:
Q: hiding/showing a table row breaks layout I'm trying to hide and show table rows, the following works but breaks the layout , ie the empty  s lose their width is there a way to prevent this?

$(document).on("click ", "tr.grey", function(e) {
  e.preventDefault();
  $( "tr.sales-details" ).removeClass( "show" );
  $(this).nextUntil(".grey").addClass( "show" );
});
tbody tr.sales-details, tbody tr.sales-details-title{
  display: none;
  &.show{
    display: block;
  }
}

Surgeon name
      Country
      Antiquity
      Amount

      Alex Lloyd
      Spain
      new client
      2690.58 USD

      Seller:
      Percentage:

      Support
      2690.58 USD

A: try using {visibility:hidden} and {visibility:visible} to hide or display the elements - this will haide content but keep its place in the DOM and not cause reflowing / reformatting that disply:none causes.
tbody tr.sales-details, tbody tr.sales-details-title{
  visibility: hidden;
  &.show{
    visibility:visible;
  }
}


text:
Q: How do I remove non-numeric values from specific column in pandas? ['0' '58699' '443' '55420' '53' '1900' '80' '0xb058' '0xacd9' '0xc0a8'
 '0x1432' '0x0000' '123' '67' '5353' '2104' '547' '1' '53290' '4805'
 '2151' '58767' '27643' '58652' '64416' '62529' '55952' '57286' '64466'
 '50497' '0xa29f' '0x2d8e' '0x5b79' '0xb0eb' '0x87b5' '0x8efa' '0xd83a'
 '52142' '52138' '52920' '60162' '54214' '50848' '56986' '50367' '49460'
 '55963' '53327' '52022' '57400' '51755' '52834' '54183' '62724' '54871'
 '59845' '56309' '61878' '58326' '56686']

The column's unique values look like this. When I run:
df[df.DstPort.apply(lambda x: x.isnumeric())].set_index('DstPort')

It takes too long to process because it has 250k rows and I was not able to see the result too. My concern is that they are not numerical all. Like '443', '80' instead of 443, 80 and there are 0xb0eb. How can I get rid of 0xb0eb them and convert this column to int datatype?

A: Those are actually integers, just represented in a different base (base 16, also known as hexadecimal). The int() function takes an optional second argument for the base. We can check if a string consists only of numeric characters, and if so use 10 as the base, 16 otherwise:
df.DstPort.apply(lambda x: int(x, 10 if x.isnumeric() else 16))


text:
Q: Rails: most Quiz attributes passing to params, apart from user_id. Why? For testing/learning purposes, I have a Quiz model with the following attributes (snippet from schema.rb):
create_table "quizzes", force: true do |t|
    t.integer  "user_id"
    t.string   "answer1"
    t.string   "answer2"
    t.string   "answer3"
    t.string   "answer4"
    t.string   "answer5"
    t.string   "answer6"
    t.string   "answer7"
    t.string   "answer8"
    t.datetime "created_at"
    t.datetime "updated_at"
  end

  add_index "quizzes", ["user_id"], name: "index_quizzes_on_user_id"

A Quiz is sent to the 'new' view, like this:
def new
    @quiz = Quiz.new(user_id: current_user.id)
end

When a user completes the quiz, the QuizzesController#create action is triggered:
def create
    @results = Quiz.create(post_params) #from private method
    render :show
end

(Whether this renders the 'show' view or the default 'create' view, it works - while I'm testing and learning, I have both those views as placeholders for now)
And the post_params method looks like this:
def post_params
    params.require(:quiz).permit(:user_id, :answer1, :answer2, :answer3, :answer4, :answer5, :answer6, :answer7, :answer8) #add other attributes here
end

(I have also tried params.require(:quiz).permit! but I get the same result).
The problem is, in the view, which looks like this:

Results

<%= @results.inspect %>

...the @results.inspect line displays all the answer1, answer2 etc, attributes, but displays the user_id attribute as nil - despite the Quiz being set up with a user_id in the QuizzessController#new action. What am I doing wrong, that prevents the user_id passing correctly?

A: If you are always going to set the user_id to the current_user.id, I'd suggest adding that attribute  in your create action.
This way you don't have to worry about user input. Else, a user might abuse this to change the id, so the quiz gets added to another user.
First, remove the user_id from the permitted post_params
def post_params
  params.require(:quiz).permit(:answer1, :answer2, :answer3, :answer4, :answer5, :answer6, :answer7, :answer8)
end

Then simply update your create action to:
def create
  # as mentioned by tagCindy, this is the way to set up the association
  @quiz = current_user.build_quiz(post_params)

  # you should also re-render the new form if there are any errors
  if @quiz.save
    render :show
  else
    render :new
  end
end

A: First off, review ActiveRecord associations.  There should be an association between your   Quiz model and your User model (either many to one, or one to one).  If the association is set up correctly, and the current_user data is saved to the session, there is no need to pass the user_id with the POST.
class QuizzesController < ApplicationController
# grabs the current_user from the session
before_filter :get_current_user

# ...

def create
    # METHOD 1: initialize and persist, check for errors
    @quiz = current_user.create_quiz(quiz_params)
    if @quiz.errors
        render :new
    else
        redirect_to @quiz # or where ever

   # METHOD 2: initialize, check for successful save
   @quiz = current_user.build_quiz(quiz_params)
   if @quiz.save
        render :new
    else
        redirect_to @quiz # or where ever
end

# ...

private

def get_current_user
    @current_user = User.find(session[:user_id])
end

def quiz_params
    params.require(:quiz).permit(:answer1, :answer2, :answer3, :answer4, :answer5, :answer6, :answer7, :answer8)
end

end

If you do not wish to store the user_id in the session, I would set up your routing so that the user_id is passed to the controller in the route.  Passing the user_id as a hidden value on the form should be avoided at all cost as it is not secure and can be easily manipulated and/or spoofed.
On a side note, you should have an Answer model with a many to one relationship to Quiz.

A: Thats because post_params is meant to handle parameters that are given to the controller. i.e. POST/GET
user_id (i assume) isn't in your form therefore not given to the controller via the form.
What I would do is:
def create
  @results = Quiz.create(post_params.merge(user_id: current_user.id) #from private method
  render :show
end

Even better provided you have the relationships setup correctly(singularize quizes if its a 1>1):
def create
  @results = current_user.create_quiz(post_params) #this will fill in the user_id field for you
  render :show
end

In your form, DO NOT do:
= f.hidden_field :user_id, current_user.id

Doing this means that any user can create quizes for any other user.


text:
Q: anybody else experiencing this problem? I'm working in visualForce and in Apex classes and in both experience this problem. It's getting quite annoying. Anybody know how to fix?

A: I have faced this issue many time. This issue happens because of browser. Please make sure that in your browser zoom level is set to 100%. You can use CTRL and '+' or '-' button to set zoom level in chrome browser.


text:
Q: DesignInstance not working in VS2012 I just spent several hours on an issue when using VS2012, WPF 4.5 and design-time data, specifically the DesignInstance attribute.
Goal: I wanted to have design-time data support in my WPF project (MVVM-based), both in VS2012 and Blend, and I could not for the life of me make the MVVMLight approach work consistently.
So I tried to change to "just" using the built-in support for design-time data, using the markup extension provided with Blend.
Problem: Consider the following code:
<Window x:Class="Nova.View.AlertsView"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:local="clr-namespace:Nova.View"
        xmlns:vm="clr-namespace:Nova.ViewModel"
        mc:Ignorable="d"
        DataContext="{Binding Alerts, Source={StaticResource Locator}}"
        d:DataContext="{d:DesignInstance vm:DesignAlertsViewModel, IsDesignTimeCreatable=True}"
... />

Both VS2012 and Blend reports "the name DesignAlertsViewModel does not exist in the namespace clr-namespace:Nova.ViewModel", even though intellisense resolves it just fine, and you have checked a thousand times that the namespace and class name are both correct.

A: Check if the "Platform target" in your build configuration is set to "AnyCPU". My was set to "x64", so the designer was complaining about the missing type.
VS is running in 32 bit so maybe there is an issue with executing code from 64 bit assemblies.
I found the solution when trying to open my UserControl in "Blend for Visual Studio". It displayed an neat exception to me.
P.S.: After using the accepted answer: Use "d:Type=vm:DesignAlertsViewModel" instead of "vm:DesignAlertsViewModel" my control was visible, but no example data was displayed.

A: Workaround: Make sure that the design-time data class is in the same namespace as the View itself. Once I moved my DesignAlertsViewModel to the View namespace, both the VS2012 and Blend designer immediately started working with the design-time data.
Update: This is a workaround for now, until I get to the bottom of the issues. However, in my case, this is the only way to make design-time data work consistently. Of course, if you go down this route you change the class names since - clearly - the DesignAlertsViewModel is no longer a view model. It is now simply a POCO containing design-time data. So perhaps AlertsDesignData would be a better name. I'm not overly happy with the fact my design-time data lives under my View namespace, but it works.
I also encourage you to take a look at Laurent's article from MSDN Magazine, April 2013. I like this approach, since it exercises the MVVM pattern a lot more: The design time data service/provider is injected via IOC, so your view models will get "exercised" even at design time.
Update 2: After spending yet another 4 hours on this, I think the jury is still out on which approach is the better: Should we go with simple POCO data classes or the MVVMLight approach, using IOC for design-time data services? The former is simple and requires less code, the latter is more true to the MVVM approach, and exercises the real view models to some degree and could possibly reveal some bugs along the way.
Also, I did have to restart VS a couple of times during my refactoring to the MVVMLight approach - design-time data simply disappeared and came back after a VS restart. However, right now it seems stable enough, and I cannot pinpoint this any further.

A: I ran into this error myself in VS2013 then found this question.  After searching more, I found an answer that helped me solve it.
instead of
d:DataContext="{d:DesignInstance vm:DesignAlertsViewModel, IsDesignTimeCreatable=True}"

use
d:DataContext="{d:DesignInstance d:Type=vm:DesignAlertsViewModel, IsDesignTimeCreatable=True}"

I was using "...d:DesignInstance Type=vm:..." and that displays the same error described above.  As soon as I add "d:" everything works.
Here is the thread I found that helped.
https://stackoverflow.com/a/21690404/2892400

A: I've found that DesignInstance is not working in my .NET 3.5 and .NET 4.0 projects, whereas it works in >= .NET 4.5 project (the projects are the same, they share the same files by using links).


text:
Q: How to close a screen from a Makefile? I have a test that depend on a specific HTTP server, which requires me to start one with a known setup for the tests.
Since the server cannot be started as a daemon my approach was to just have it start in a screen session, run the test and close the session.
test:
    screen -S test_http_server -d -m start_my_test_http_server
    # run my tests here
    screen -S test_http_server -X kill # works from bash but not makefile :/

Everything works fine except for closing or killing the session (which does work if I run it in bash afterwards).

A: It seems that using the @ prefix (which I did, but was not posted in the original example code) that suppresses the normal 'echo' of the command somehow interferes with closing the screen.
Fails because of @ prefix usage.
test:
    @screen -S test_http_server -d -m start_my_test_http_server
    # run my tests here
    @screen -S test_http_server -X kill

Fixed make file that works as intended.
test:
    screen -S test_http_server -d -m start_my_test_http_server
    # run my tests here
    screen -S test_http_server -X kill


text:
Q: How to get alert Box with sound? I am trying to get alert like pop-up with sound when the balls collide. When I use alert function it gets freeze and it will keep on showing alert. As far as now i tried to get alert like in text. But how to get alert with sound(eg.beep) ?
I have attached the code snippet. Can anyone help to get this.
Thanks in advance

const ctx = document.getElementById("Canvas").getContext("2d");
const containerR = 150;
const size = containerR * 2
ctx.canvas.width = ctx.canvas.height = size;
ctx.globalAlpha = 0.8

const getBall = (x, y, dx, dy, r, color) => ({x, y, dx, dy, r, color});

const balls = [
  getBall(size / 2, size - 30, 1, 1, 8, "Green"),
  getBall(size / 3, size - 50, 1, 1, 8, "Green"),
  getBall(size / 4, size - 60, 1, 1, 8, "Green"),
  getBall(size / 2, size / 5,  1, 1, 8,  "Green"),
];

const drawBall = (ball) => {
  ctx.beginPath();
  ctx.arc(ball.x, ball.y, ball.r, 0, Math.PI * 2, false);
  ctx.fillStyle = ball.collider ? "red" : ball.color;
  ctx.fill();
  ctx.closePath();
}

const updatePos = (ball) => {

  ball.x += ball.dx;
  ball.y += ball.dy;
  const dx = ball.x - containerR;
  const dy = ball.y - containerR;

  if (Math.sqrt(dx * dx + dy * dy) >= containerR - ball.r) {
    const v = Math.sqrt(ball.dx * ball.dx + ball.dy * ball.dy);
    const angleToCollisionPoint = Math.atan2(-dy, dx);
    const oldAngle = Math.atan2(-ball.dy, ball.dx);
    const newAngle = 2 * angleToCollisionPoint - oldAngle;
    ball.dx = -v * Math.cos(newAngle);
    ball.dy = v * Math.sin(newAngle);
  }
}

const collides = (a, b) => (Math.hypot(Math.abs(a.x - b.x), Math.abs(a.y - b.y)) < (a.r + b.r));

function engine() {
  //console.clear(); // Clear console test messages
  mydiv.textContent =" ";
  ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);

  balls.forEach((a, ai) => {
    a.collider = undefined;

    balls.forEach((b, bi) => {
      if (bi === ai) return; // Don't look at self
      if (collides(a, b)) a.collider = b; // Store the colliding B ball
    });

    if (a.collider) { // If ball has a collider:
     mydiv.textContent = ("Alert");
      //console.log(`${a.color[0]} → ← ${a.collider.color[0]}`);
    }

    updatePos(a);
    drawBall(a);
  });

  requestAnimationFrame(engine);
}

engine();

<canvas id="Canvas"></canvas>

A: You can't use normal .alert() without halting the javascript execution so you have to stick with HTML alert/prompt (there is many libraries out there provide neat and customizable UI),  for the beep sound, you can just use based64 data with data URI, this snippet here wont work because the SO snippets are sandbox, here is a working fiddle you can improve.
the beep sound example based on this answer here
Update: I added the custom alert and its based on this example from bluebird implementation, there is custom HTML and CSS, and Javascript PromptDialog(), basically this Javascript object implementation is asynchronous ans doesn't block the execution, please refer to the linked bluebird article for more information since its a guide on how to build it and it explains everything better than me.

function beep() {
    var snd = new Audio("data:audio/wav;base64,//uQRAAAAWMSLwUIYAAsYkXgoQwAEaYLWfkWgAI0wWs/ItAAAGDgYtAgAyN+QWaAAihwMWm4G8QQRDiMcCBcH3Cc+CDv/7xA4Tvh9Rz/y8QADBwMWgQAZG/ILNAARQ4GLTcDeIIIhxGOBAuD7hOfBB3/94gcJ3w+o5/5eIAIAAAVwWgQAVQ2ORaIQwEMAJiDg95G4nQL7mQVWI6GwRcfsZAcsKkJvxgxEjzFUgfHoSQ9Qq7KNwqHwuB13MA4a1q/DmBrHgPcmjiGoh//EwC5nGPEmS4RcfkVKOhJf+WOgoxJclFz3kgn//dBA+ya1GhurNn8zb//9NNutNuhz31f////9vt///z+IdAEAAAK4LQIAKobHItEIYCGAExBwe8jcToF9zIKrEdDYIuP2MgOWFSE34wYiR5iqQPj0JIeoVdlG4VD4XA67mAcNa1fhzA1jwHuTRxDUQ//iYBczjHiTJcIuPyKlHQkv/LHQUYkuSi57yQT//uggfZNajQ3Vmz+Zt//+mm3Wm3Q576v////+32///5/EOgAAADVghQAAAAA//uQZAUAB1WI0PZugAAAAAoQwAAAEk3nRd2qAAAAACiDgAAAAAAABCqEEQRLCgwpBGMlJkIz8jKhGvj4k6jzRnqasNKIeoh5gI7BJaC1A1AoNBjJgbyApVS4IDlZgDU5WUAxEKDNmmALHzZp0Fkz1FMTmGFl1FMEyodIavcCAUHDWrKAIA4aa2oCgILEBupZgHvAhEBcZ6joQBxS76AgccrFlczBvKLC0QI2cBoCFvfTDAo7eoOQInqDPBtvrDEZBNYN5xwNwxQRfw8ZQ5wQVLvO8OYU+mHvFLlDh05Mdg7BT6YrRPpCBznMB2r//xKJjyyOh+cImr2/4doscwD6neZjuZR4AgAABYAAAABy1xcdQtxYBYYZdifkUDgzzXaXn98Z0oi9ILU5mBjFANmRwlVJ3/6jYDAmxaiDG3/6xjQQCCKkRb/6kg/wW+kSJ5//rLobkLSiKmqP/0ikJuDaSaSf/6JiLYLEYnW/+kXg1WRVJL/9EmQ1YZIsv/6Qzwy5qk7/+tEU0nkls3/zIUMPKNX/6yZLf+kFgAfgGyLFAUwY//uQZAUABcd5UiNPVXAAAApAAAAAE0VZQKw9ISAAACgAAAAAVQIygIElVrFkBS+Jhi+EAuu+lKAkYUEIsmEAEoMeDmCETMvfSHTGkF5RWH7kz/ESHWPAq/kcCRhqBtMdokPdM7vil7RG98A2sc7zO6ZvTdM7pmOUAZTnJW+NXxqmd41dqJ6mLTXxrPpnV8avaIf5SvL7pndPvPpndJR9Kuu8fePvuiuhorgWjp7Mf/PRjxcFCPDkW31srioCExivv9lcwKEaHsf/7ow2Fl1T/9RkXgEhYElAoCLFtMArxwivDJJ+bR1HTKJdlEoTELCIqgEwVGSQ+hIm0NbK8WXcTEI0UPoa2NbG4y2K00JEWbZavJXkYaqo9CRHS55FcZTjKEk3NKoCYUnSQ0rWxrZbFKbKIhOKPZe1cJKzZSaQrIyULHDZmV5K4xySsDRKWOruanGtjLJXFEmwaIbDLX0hIPBUQPVFVkQkDoUNfSoDgQGKPekoxeGzA4DUvnn4bxzcZrtJyipKfPNy5w+9lnXwgqsiyHNeSVpemw4bWb9psYeq//uQZBoABQt4yMVxYAIAAAkQoAAAHvYpL5m6AAgAACXDAAAAD59jblTirQe9upFsmZbpMudy7Lz1X1DYsxOOSWpfPqNX2WqktK0DMvuGwlbNj44TleLPQ+Gsfb+GOWOKJoIrWb3cIMeeON6lz2umTqMXV8Mj30yWPpjoSa9ujK8SyeJP5y5mOW1D6hvLepeveEAEDo0mgCRClOEgANv3B9a6fikgUSu/DmAMATrGx7nng5p5iimPNZsfQLYB2sDLIkzRKZOHGAaUyDcpFBSLG9MCQALgAIgQs2YunOszLSAyQYPVC2YdGGeHD2dTdJk1pAHGAWDjnkcLKFymS3RQZTInzySoBwMG0QueC3gMsCEYxUqlrcxK6k1LQQcsmyYeQPdC2YfuGPASCBkcVMQQqpVJshui1tkXQJQV0OXGAZMXSOEEBRirXbVRQW7ugq7IM7rPWSZyDlM3IuNEkxzCOJ0ny2ThNkyRai1b6ev//3dzNGzNb//4uAvHT5sURcZCFcuKLhOFs8mLAAEAt4UWAAIABAAAAAB4qbHo0tIjVkUU//uQZAwABfSFz3ZqQAAAAAngwAAAE1HjMp2qAAAAACZDgAAAD5UkTE1UgZEUExqYynN1qZvqIOREEFmBcJQkwdxiFtw0qEOkGYfRDifBui9MQg4QAHAqWtAWHoCxu1Yf4VfWLPIM2mHDFsbQEVGwyqQoQcwnfHeIkNt9YnkiaS1oizycqJrx4KOQjahZxWbcZgztj2c49nKmkId44S71j0c8eV9yDK6uPRzx5X18eDvjvQ6yKo9ZSS6l//8elePK/Lf//IInrOF/FvDoADYAGBMGb7FtErm5MXMlmPAJQVgWta7Zx2go+8xJ0UiCb8LHHdftWyLJE0QIAIsI+UbXu67dZMjmgDGCGl1H+vpF4NSDckSIkk7Vd+sxEhBQMRU8j/12UIRhzSaUdQ+rQU5kGeFxm+hb1oh6pWWmv3uvmReDl0UnvtapVaIzo1jZbf/pD6ElLqSX+rUmOQNpJFa/r+sa4e/pBlAABoAAAAA3CUgShLdGIxsY7AUABPRrgCABdDuQ5GC7DqPQCgbbJUAoRSUj+NIEig0YfyWUho1VBBBA//uQZB4ABZx5zfMakeAAAAmwAAAAF5F3P0w9GtAAACfAAAAAwLhMDmAYWMgVEG1U0FIGCBgXBXAtfMH10000EEEEEECUBYln03TTTdNBDZopopYvrTTdNa325mImNg3TTPV9q3pmY0xoO6bv3r00y+IDGid/9aaaZTGMuj9mpu9Mpio1dXrr5HERTZSmqU36A3CumzN/9Robv/Xx4v9ijkSRSNLQhAWumap82WRSBUqXStV/YcS+XVLnSS+WLDroqArFkMEsAS+eWmrUzrO0oEmE40RlMZ5+ODIkAyKAGUwZ3mVKmcamcJnMW26MRPgUw6j+LkhyHGVGYjSUUKNpuJUQoOIAyDvEyG8S5yfK6dhZc0Tx1KI/gviKL6qvvFs1+bWtaz58uUNnryq6kt5RzOCkPWlVqVX2a/EEBUdU1KrXLf40GoiiFXK///qpoiDXrOgqDR38JB0bw7SoL+ZB9o1RCkQjQ2CBYZKd/+VJxZRRZlqSkKiws0WFxUyCwsKiMy7hUVFhIaCrNQsKkTIsLivwKKigsj8XYlwt/WKi2N4d//uQRCSAAjURNIHpMZBGYiaQPSYyAAABLAAAAAAAACWAAAAApUF/Mg+0aohSIRobBAsMlO//Kk4soosy1JSFRYWaLC4qZBYWFRGZdwqKiwkNBVmoWFSJkWFxX4FFRQWR+LsS4W/rFRb/////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////VEFHAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAU291bmRib3kuZGUAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAMjAwNGh0dHA6Ly93d3cuc291bmRib3kuZGUAAAAAAAAAACU=");
    snd.play();
}

var noop = function() {
  return this;
};

function UserCanceledError() {
  this.name = 'UserCanceledError';
  this.message = 'User canceled dialog';
}
UserCanceledError.prototype = Object.create(Error.prototype);

function Dialog() {
  this.setCallbacks(noop, noop);
}
Dialog.prototype.setCallbacks = function(okCallback, cancelCallback) {
  this._okCallback     = okCallback;
  return this;
};
Dialog.prototype.waitForUser = function() {
  var _this = this;
  return new Promise(function(resolve, reject) {
    _this.setCallbacks(resolve, reject);
  });
};

Dialog.prototype.show = noop;
Dialog.prototype.hide = noop;

function PromptDialog() {
  Dialog.call(this);
  this.el           = document.getElementById('dialog');
  this.messageEl    = this.el.querySelector('.message');
  this.okButton     = this.el.querySelector('button.ok');
  this.attachDomEvents();
}
PromptDialog.prototype = Object.create(Dialog.prototype);
PromptDialog.prototype.attachDomEvents = function() {
  var _this = this;
  this.okButton.addEventListener('click', function() {
    _this.hide();
    console.log('Ok clicked!!');
  });

};
PromptDialog.prototype.show = function(message) {
  this.messageEl.innerHTML = '' + message;
  this.el.className = '';
  return this;
};
PromptDialog.prototype.hide = function() {
  this.el.className = 'hidden';
  return this;
};

const ctx = document.getElementById("Canvas").getContext("2d");
const containerR = 150;
const size = containerR * 2
ctx.canvas.width = ctx.canvas.height = size;
ctx.globalAlpha = 0.8

var prompt = new PromptDialog();

const getBall = (x, y, dx, dy, r, color) => ({x, y, dx, dy, r, color});

const balls = [
  getBall(size / 2, size - 30, 1, 1, 8, "Green"),
  getBall(size / 3, size - 50, 1, 1, 8, "Green"),
  getBall(size / 4, size - 60, 1, 1, 8, "Green"),
  getBall(size / 2, size / 5,  1, 1, 8,  "Green"),
];

const drawBall = (ball) => {
  ctx.beginPath();
  ctx.arc(ball.x, ball.y, ball.r, 0, Math.PI * 2, false);
  ctx.fillStyle = ball.collider ? "red" : ball.color;
  ctx.fill();
  ctx.closePath();
}

const updatePos = (ball) => {

  ball.x += ball.dx;
  ball.y += ball.dy;
  const dx = ball.x - containerR;
  const dy = ball.y - containerR;

  if (Math.sqrt(dx * dx + dy * dy) >= containerR - ball.r) {
    const v = Math.sqrt(ball.dx * ball.dx + ball.dy * ball.dy);
    const angleToCollisionPoint = Math.atan2(-dy, dx);
    const oldAngle = Math.atan2(-ball.dy, ball.dx);
    const newAngle = 2 * angleToCollisionPoint - oldAngle;
    ball.dx = -v * Math.cos(newAngle);
    ball.dy = v * Math.sin(newAngle);
  }
}

const collides = (a, b) => (Math.hypot(Math.abs(a.x - b.x), Math.abs(a.y - b.y)) < (a.r + b.r));

function engine() {
  //console.clear(); // Clear console test messages
  mydiv.textContent =" ";
  ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);

  balls.forEach((a, ai) => {
    a.collider = undefined;

    balls.forEach((b, bi) => {
      if (bi === ai) return; // Don't look at self
      if (collides(a, b)) a.collider = b; // Store the colliding B ball
    });

    if (a.collider) { // If ball has a collider:
     mydiv.textContent = ("Alert");
     beep();

     prompt.show('collision detected')
      .waitForUser()
      .then(function(name) {
        output.innerHTML = '' + name;
      })
      .catch(function(e) {
        console.log('Unknown error', e);
      })
      .finally(function() {
        prompt.hide();
      });

      //console.log(`${a.color[0]} → ← ${a.collider.color[0]}`);
    }

    updatePos(a);
    drawBall(a);
  });

  requestAnimationFrame(engine);
}

engine();
canvas {
  background: #eee;
  margin: 0 auto;
  border-radius: 50%;
  box-shadow: 0 0 0 4px #000;
}

#dialog {
  width: 200px;
  margin: auto;
  border: thin solid black;
  padding: 10px;
  background: lightgreen;
}
.hidden {
  display: none;
}
<canvas id="Canvas"></canvas>

    <button class="ok">Ok</button>

A: UPDATE: User interaction
you can add an audio tag and play it for sound
note: in newer browser chrome ^50, you need user interaction to audio tag work fine

const startBtn = document.getElementById("start-btn")
const sound = document.getElementById("beeb-player")
const ctx = document.getElementById("Canvas").getContext("2d");
const containerR = 150;
const size = containerR * 2
ctx.canvas.width = ctx.canvas.height = size;
ctx.globalAlpha = 0.8

const getBall = (x, y, dx, dy, r, color) => ({x, y, dx, dy, r, color});

const balls = [
  getBall(size / 2, size - 30, 1, 1, 8, "Green"),
  getBall(size / 3, size - 50, 1, 1, 8, "Green"),
  getBall(size / 4, size - 60, 1, 1, 8, "Green"),
  getBall(size / 2, size / 5,  1, 1, 8,  "Green"),
];

const drawBall = (ball) => {
  ctx.beginPath();
  ctx.arc(ball.x, ball.y, ball.r, 0, Math.PI * 2, false);
  ctx.fillStyle = ball.collider ? "red" : ball.color;
  ctx.fill();
  ctx.closePath();
}

const updatePos = (ball) => {

  ball.x += ball.dx;
  ball.y += ball.dy;
  const dx = ball.x - containerR;
  const dy = ball.y - containerR;

  if (Math.sqrt(dx * dx + dy * dy) >= containerR - ball.r) {
    const v = Math.sqrt(ball.dx * ball.dx + ball.dy * ball.dy);
    const angleToCollisionPoint = Math.atan2(-dy, dx);
    const oldAngle = Math.atan2(-ball.dy, ball.dx);
    const newAngle = 2 * angleToCollisionPoint - oldAngle;
    ball.dx = -v * Math.cos(newAngle);
    ball.dy = v * Math.sin(newAngle);
  }
}

const collides = (a, b) => (Math.hypot(Math.abs(a.x - b.x), Math.abs(a.y - b.y)) < (a.r + b.r));

function engine() {
  //console.clear(); // Clear console test messages
  mydiv.textContent =" ";
  ctx.clearRect(0, 0, ctx.canvas.width, ctx.canvas.height);

  balls.forEach((a, ai) => {
    a.collider = undefined;

    balls.forEach((b, bi) => {
      if (bi === ai) return; // Don't look at self
      if (collides(a, b)) a.collider = b; // Store the colliding B ball
    });

    if (a.collider) { // If ball has a collider:
     mydiv.textContent = ("Alert");
     sound.play()
//console.log(`${a.color[0]} → ← ${a.collider.color[0]}`);
    }

    updatePos(a);
    drawBall(a);
  });

  requestAnimationFrame(engine);
}

startBtn.addEventListener('click', engine, {once:true})

<button id="start-btn">start</button>
<canvas id="Canvas"></canvas>

<audio src="http://soundbible.com/grab.php?id=1815&type=mp3" id="beeb-player"></audio>

you can add an audio tag and play it when the balls collide

function alertWithSound() {
const el = document.getElementById("beeb-player")
el.play()
}
<audio src="http://soundbible.com/grab.php?id=1815&type=mp3" id="beeb-player"></audio>


text:
Q: Using shell to compute averages for students I have a file called: 'winter' witch contains on each line a student name and the average of his grades on his winter finals:
John 4
Brian 8.5

Another file called: 'summer' contains on each line a student name and 5 grades on his summer finals:
John 8 7 9 4 7
Brian 10 9 4 5 8

I want to compute the annual average grade for each student:
John ((8+7+9+4+7)/5 + 4)/2
Brian ((10+9+4+5+8)/5 + 8.5)/2

The output will be sorted by the annual average, so the student with the highest grade comes first.
I want this to be done using shell programming.
I've tried computing the average using awk:
awk '{print $1 " " ($2 + $3 + $4 + $5 + $6)/5}' summer

But I have no idea how to continue, or even how to start.

A: Here is one approach:
$ awk 'FNR==NR{a[$1]=$2;next}{print $1,(a[$1]+($2+$3+$4+$5+$6)/5)/2}' winter summer | sort -rnk2
Brian 7.85
John 5.5

Explanation:
The condition FNR==NR is only true when we are in the first file winter so the block is only executed for that file. The block simply creates an array where the student names are the keys and the grades are the values. The next statement jumps to the next line in file. When we are in the second file the script is much the same as yours but we use the array to get the grade from the first file. The sort is simple -r reverse -n numerical sort on the second field -k2.
It should be noted that this script assumes no two students have the same name.


text:
Q: as3 constant variable generation on compile Is it possible to generate a (constant) variable on compile time, which  from then on will always remain the same during runtime.
For example, is it possible to write a piece of code that generates a version number based on the current date on compile time, but from then on always remains the same, even on different dates, only to change when a new version is compiled.
Thanks in advance,
Citiral.

A: i use an external tool like Apache ANT to do the job and versionize my code:
<!--
Get the current date & time
-->
<tstamp>
<format property="build.time" pattern="dd/MM/yyyy hh:mm aa" locale="en,UK"/>
</tstamp>

Then i put it into a class outside my classpath and exchange it with the equivalent in my classpath (here my Version.as class)
<!--
Copy the template file and replace %BUILDTIME%
-->
<copy file="src/Version.as" tofile="src/as/de/client/project/utils/Version.as" overwrite="true" />
<replace file="src/as/de/client/project/utils/Version.as" token="%BUILDTIME%" value="${build.time}" />
</target>

this is the content of the template Version.as which will replace the Version.as class in your classpath:
package de.client.project.utils
{
public class Version
{
    public static const BUILD_TIME      : String = "%BUILDTIME%";
}
}

then you simply have to trace the constant in your code at startup:
trace("Version: " + Version.BUILD_TIME);

regards.Rob


text:
Q: ¿Como solucióno este error en Python con el método as_matrix? Estoy tratando de implementar un ejemplo que encontre en internet pero me da error el método as_matrix. El código es el guiente:
import findspark
findspark.init()

#%matplotlib inline
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
from pyspark import SparkContext
from IPython.display import display, HTML
from pyspark.sql import SQLContext
from pyspark.ml.feature import PCA
from pyspark.ml.linalg import Vectors
from pyspark.sql import Column as c
from pyspark.sql.functions import array, udf, lit, col as c
import pyspark.sql.functions as f
pd.set_option('max_colwidth',100)
plt.style.use('seaborn-paper')

try:
    sc = SparkContext('local[*]')
except:
    sc = SparkContext.getOrCreate('local[*]')

sqlContext = SQLContext(sc)

#Leyendo los dataframe
whiteWinnePath = 'winequality-White.csv'
redWinnePath = 'winequality-Red.csv'

"""
df_p = pd.read_csv(whiteWinnePath, sep =";")
print("Mostrar el data frame")
display(df_p)
"""
whiteWinneDF = sqlContext.createDataFrame(pd.read_csv(whiteWinnePath, sep = ";")).withColumn('type',lit(0))

redWinneDF = sqlContext.createDataFrame(pd.read_csv(redWinnePath, sep = ";")).withColumn('type',lit(1))

whiteWinneDF.printSchema()

#Dividiendo conjunto de entranamiento y prueba
whiteTrainingDF, whiteTestingDF = whiteWinneDF.randomSplit([0.7,0.3])

redTrainingDF, redTestingDF = redWinneDF.randomSplit([0.7,0.3])

trainingDF = whiteTrainingDF.union(redTrainingDF)

testingDF = whiteTestingDF.union(redTestingDF)

#Preparando el dataframe para PCA
idCol = ['type']

features = [column for column in redWinneDF.columns if column not in idCol]

p = len(features)

meanVector1 = trainingDF.describe().where(c('summary')==lit('mean'))
meanVector2= meanVector1.toPandas()
print("="*50)
print(type(meanVector2))

meanVector= meanVector2.as_matrix()[0][1:p+1]

labeledVectorsDF = trainingDF.select(features+['type']).rdd\
                             .map(lambda x:(Vectors.dense(x[0:p]-Vectors.dense(meanVector)),x[p]))\
                             .toDF(['features','type'])

labeledVectorsDF.limit(5).toPandas()

El error que me da dice: 'DataFrame' object has no attribute 'as_matrix'
Yo imprimí el tipo de dato que es meanVector2 usando print(type(meanVector2)) y dice:
<class 'pandas.core.frame.DataFrame'>
Así que no entiendo que el tipo de dato sea Dataframe de Pandas y me diga el error que no tiene atributo as_matrix


text:
Q: Unset variable specific key from multidimensional array I have different multidimensional arrays with different keys and values:
$array_1 = array('cars' => array('audi' => array('a3' => array('one', 'two', 'three'), 'a5' => array('five', 'six', 'seven')), 'mercedes' => array('type_1' => array('submodel' => array('whatever'))), 'other_cat' => array('different_things')));

then I would like to unset a specific key, for example:
unset($array_1['cars']['audi']['a5']);

Now I like to "split it up", to have the key variable.
$to_unset = ['cars']['audi']['a5'];

How can I unset that specific (variable!) key?
Aäron

A: An easy utility to avoid removing array keys that do not exist by accident:
function removeArrayKey($path, &$array ) {

    $array_temp = &$array;
    $previousItem = null;

    $path_bits = explode( ".", $path );

        foreach( $path_bits as &$path_bit ) {

           if( !isset( $array_temp[ $path_bit ] ) ) {
                  die("Error" . $path_bit);
                   //throw new Exception( "Path does not exist in array" );
            }

            $previousItem = &$array_temp;
            $array_temp = &$array_temp[ $path_bit ];

        }

        if( isset( $previousItem ) ) {

             unset( $previousItem[ $path_bit ] );

        }

        return $array;

}

To use the function, simply use removeArrayKey( "cars.mercedes.cars", $array_1 ); and separate each array index with a .

A: So as i see your problem, you'd like to save your array path into a variable. You can solve this problem on two different ways:
Save every key into a variable
The way i would do it, if my array structure looks always the same (e.g. [cars][type][model]). You can save the key to delete into a variable:
$cars = 'cars';
$type = 'audi';
$model = 'a5';

unset($array_1[$cars][$type][$model]);

This will work excellent in a for(each) loop.
Saving your keys into an array
This method will save your problem, but it is not the best option. You can save all the keys you like to unset into an array. This way can cause many bugs and you should reconsider your array structure, if this way is your solution.
// arrays start at 0
$to_unset = [
    0 => 'cars',
    1 => 'audi',
    2 => 'a5',
];

unset($array_1[$to_unset[0]][$to_unset[1]][$to_unset[2]]);

An other possible option here is to name the keys of the $to_unset array.
// arrays start at 0
$to_unset = [
    'cars' => 'cars',
    'type' => 'audi',
    'model' => 'a5',
];

unset($array_1[$to_unset['cars']][$to_unset['type']][$to_unset['model']]);

A: You can probably go with eval but it's not recommended.
eval('unset($array_1' . $to_unset . ');');


text:
Q: Оператор switch в Java Я только перешел с плюсов на джаву, и у меня возник следующий вопрос: в switch можно "сравнивать" только константы? Нет ли другой возможности использовать НЕконстантные переменные? И если возникла такая ситуация, что нужно, например, сравнивать много перемен, то неужели придется использовать if else if else if else if...?
Спасибо!

A: В этом нет необходимости. Вы всегда можете любое дискретное множество (и не обязательно условий) можете перечислить констастантами и их использовать в качестве условия перехода оператора switch.
Другими словами вы всегда можете определить функцию которая пронумерует вам ваше мнежество из нескольких if else.


text:
Q: PingFederate OpenToken Sample Application I'm trying out the sample applications provided together with the PingFederate .NET Integration Kit. I was able to make it work for the Single Server set-up (my machine served as both the IdP and the SP).
But when I tried setting up two machines like it was specified in this link:
https://documentation.pingidentity.com/display/NETIK/Deploying+the+Sample+Applications

A more realistic scenario is to deploy the applications on a separate IIS server machine

I was able to edit the Adapter Instance and the Default URL but there's this problem of clock skew between servers

Verify that your server clocks are synchronized. If they are not synchronized, you can account for this by adjusting the Not Before Tolerance value in the OpenToken adapter configuration, which is the amount of time (in seconds) to allow for clock skew between servers. The default and recommended value is 0.

I checked the possible values and the max is 3600 seconds.
Question: What if my server has more than an hour of time difference? Is that set-up still possible? (Servers are actually on different time zones.)

A: The OpenToken uses GMT, so timezones are taken out of the picture - as long as your server is set to the proper time, and actual proper timezone for where it is, it should work just fine. For example, you can have serverA in New York City, and serverB in Los Angeles. If serverA is set to Eastern Time, and serverB is set to Pacific Time, then the OpenToken will work - since it converts times to GMT, the times on the token will be the "same".
Hope that makes sense - I need another cup of coffee this morning. :)


text:
Q: how to get parameters from switch or file I've seen in the past before I started scripting that a powershell script that requires a hostname parameter. it could either by typed in like Script.PS1 "hostname"
but you could also run the script in the following method:
gc hostnames.txt | script.ps1

and in this way you could list a number of hostnames in your text file.
how is this achieved.
my parameters looks as follows
Param(
    [Parameter(Mandatory=$True)]
    [ValidateSet("C","K")]
    [ValidateNotNullorEmpty()]
    [String]$Action,

    [Parameter(Mandatory = $True)]
    [ValidateNotNullorEmpty()]
    [String]$Computers

    )

A: As asked you could use syntax something like
gc hostnames.txt | % {  .\script.ps1 -Action A -Computers $_ }

and it would call script.ps1 once for each line in hostnames.txt.
The $_ is a placeholder for the current value of the array being iterated by the ... | % ... syntax.


text:
Q: Android app not listed in Battery Usage I was given a question and I have a hard time finding the correct answer.
Let's say that I have an app called MyApp and when this app is installed it drains the battery life really fast, I know that because when I uninstall the app the battery life is significantly improved.
When the app is installed I can't see it in the Android Build-in Battery Usage Stats in settings app which means that it's not the app that's draining the battery life.
What could be the problem?
I thought that the problem is that maybe the app is activating background services of Android, but was told that when I activate a service from an app, it is registered under the app's name and it should be listed in the battery usage.
I can't seem to find any information describing the problem I was given.
Any ideas guys?


text:
Q: What is the best Xcode version for C++ development Currently I use Eclipse on my Mac to develop with plain C++. However, I've been getting quite a few problems with it, but held back bc of my low disk space. Recently, I've freed a lot of disk space and wish to switch over to Xcode due to multiple advantages. But even after I freed like 30 gigs of space, I can't install the newest version avaliable of Xcode that is even larger than the entire Big Sur OS.
So, what is the best Xcode version for C++ development that preferably isn't that large?
Side question: What is the newest version of Xcode that has new features/a new feature for C++ development?


text:
Q: JavaScript/Greasemonkey: Avoiding FireFox Security Warning when Submitting a Form from a Secure Page I'm writing a Greasemonkey script to connect two company-internal webpages.  One is SSL, and the other is insecure and can only be accessed via a POST request.  If I create a hidden form on the secure page and submit it via an onclick() in an <a>, it works fine, but FF gives a warning:

Although this page is encrypted, the information you have entered is to be sent over an unencrypted connection and could easily be read by a third party.
Are you sure you want to continue sending this information?"

The insecure page can't be accessed via SSL and the other one can't be accessed w/o it, and I can't modify either server =\  Is there any way to avoid this warning by doing some kind of JavaScript/Greasemonkey redirect magic?  Thanks!
EDIT: The warning can't be disabled (for rather good reasons, since it's hard to tell if what you're about to send is secure, otherwise).  I'm mostly wondering if there's a way to POST in JavaScript without looking like you're submitting a form.

A: This may be possible by doing a GM_xmlhttpRequest. e.g.,
GM_xmlhttpRequest({
  method: 'POST',
  url: 'http://your.insecure.site.here',
  onload: function(details) {

      // look in the JavaScript console
      GM_log(details.responseText);

      /* This function will be called when the page (url)
      has been loaded. Do whatever you need to do with the remote page here.*/
  }
});

API/more info here: GM_xmlhttpRequest wiki

A: You could set up a new SSL site as a proxy that just passes data back to the insecure site. Or just have all your users turn off that particular security warning. (Sorry FF team, but that's not a terribly useful message to start with.)

A: That's a browser configuration setting, which can't (or shouldn't) be changable by Javascript.
Unless the script needs to be used by more than one user, Tools -> Options -> Security.  You can click on settings to display which warning messages are displayed.  Note that this currently affects all sites rather then just your internal system.


text:
Q: Can we disassemble (using ILDasm) an NGen-ed assembly? If I NGen an assembly, is it normal that ildasm still disassembles it?
Ok. I wrote a HelloWorld class library and the ensuing dll is named NGenILDasmTest.dll.
--> Targeted for the .Net fw 4.
From Vs 2010 command prompt, I did
gacutil -i NGenILDasmTest.dll

I could see the assembly installed in the GAC. And I ran ildasm so I could view the IL.
So far so good.
Then I run
ngen NGenILDasmTest.dll

(I did not specify any options for ngen). And this assembly successfully got compiled. I located it with a name NGenILDasmTest.ni.dll under the folder
C:\Windows\Assembly\NativeImages_v4.0.30319_32\NGenILDasmTest\81d49dd4c7df22fb3df530402b58ffc9

Now, when I run ildasm like below
ildasm "C:\Windows\Assembly\NativeImages_v4.0.30319_32\NGenILDasmTest\81d49dd4c7df22fb3df530402b58ffc9\NGenILDasmTest.ni.dll"

I could see the contents of the Ngen-ed assembly. Is this normal?.
Technically speaking, Ngen generates native CPU instrcutions for the IL (and apparently places it under C:\windows\Assembly\NAtiveImages_V4.#####_32  - in my case). If that is the case, how am I still able to see the NGen-ed assembly as IL using ILDasm?
Please help me understand that 'little something' that I am missing here.

A: If you look into fast/easy obfuscation, write a mixed mode assembly in C++, which will be a boot loader of your own assembly (it will load legacy .NET FW 4.0 through COM in native code, and use a public interfaces declared from managed part, trough .tlb generated for your managed assembly) held as an encrypted resource (using RSA), and encrypt native C++ code, then sign the both assemblies. That will prevent from ILDASM ing your assembly still allowing you to debug and build project (using build events)

A: An NGEN'ed assembly is the IL plus native code. The IL is not stripped out. There is often confusion that NGen assemblies contain only the native image. The original information is still needed for metadata.
Microsoft doesn't seem to have very specific information on the internals of an NGen assembly. Most information that we know is from reverse engineering.
EDIT:
After installing the .NET Framework 1.1 (yay..) - it appears that .NET 1.1 NGen does strip out the IL. It looks like starting in v2 - the IL is kept. This seems to be why there is contradicting information lying around .The exact reason this change was made doesn't seem to be known.
There is a good article on some of ngen's internals (and how it is an extremely bad idea for obfuscation) here: http://www.woodmann.com/forum/entry.php?68-Rebuilding-native-.NET-exes-into-managed-.NET-exes-by-Exploiting-lefotver-IL...

Now, the interesting thing about Ngen is that it does not eliminate the IL or the metadata, because
  while the IL code is not needed for execution, the metadata is, because all the strings and other
  relevant data that the program needs are contained within the metadata. So, Ngen copies all the
  metadata to the .IL section of the native exe, and copies the IL code as an afterthought


text:
Q: Bridged NIC's but only one active I've "Bridged" the NIC's in my Server 2003 box but when I do a large file transfer, I see that only one is active at a time.
What do I need to do to spread the love across both NIC's?  I'm hoping to increase transfer speeds from my Server to my network.
PS: I have a D-Link DGS-1016D Switch.

A: To do this you need to "trunk" (also called "bonding" or "link aggregation") your two NICs. To do this you need:

*

*NICs that support this (most common are LACP or 802.3ad)

*An OS that supports this

*A switch that supports this

Windows does not support this out of the box, so you will need to use latest manufacturer drivers for your NICs, and follow their instructions for enabling this functionality.
I don't think the DGS-1016D supports link aggregation though, so you might have been struck out on the first hurdle.
The other option is to run different services on the different NICs, so if your issue is with multiple concurrent file transfers, run half over the IP address of NIC1 and half over the IP address of NIC2. This should give you a similar overall result.

A: Disclaimer: This applies to what I see in Windows and may be different for another OS.
When run in load sharing mode it's quite normal to only see one NIC in use. Only when the demand in one direction gets to the point where the second NIC is required will you see traffic flowing through it. OTOH, I quite often see inbound traffic on one NIC and outbound on the other.
Also bear in mind that the total throughput is often limited by other connected devices. e.g. A server with 2 1Gb NICs won't be bothered by a few clients connecting with 100Mb NICs. No point having a suer fast connection on the server if it can't be utilised by the clients.


text:
Q: vsftpd listen on multiple listen_address but not on all I'm looking for a way to configure vsftpd to use multiple listen_address IPs. I'm aware that if I set it to the default, it will listen on all available interface IPs, but that's not what I'm looking for.
Is there a way to configure something like this?
listen_address=192.168.1.3,192.168.1.4,192.168.1.5

Regards

A: I have not idea about vsftpd exactly, but what about listen all interfaces and add iptables rule to prevent access from some of them?
like iptables -A INPUT -i ... -j DROP

A: If the machine is multi homed with 2 or more IP addresses, then you can setup multiple vsftpd services. Make a copy of the vsftpd.conf, adjust the listen_address to the additional IP address. Start another vsftpd daemon using the new config file.


text:
Q: How to send message from a QWidget to QStatusBar? Is there a way to send messages for progression from a QWidget to a QStatusBar in PySide2?. A way to emit message when something happens and another object to receive it and change message accordingly.
I've been trying to solve the problem using QObject.emit() and QObject.connect() to pass the string and display on QStatusBar with no results, both of them are in different classes.
I have only used emit and connect for simple operations like closing child window along with the parent, so if emit and connect is not the right way to handle this please suggest another way to pass messages.
import os
import shutil

from PySide2 import QtWidgets
from PySide2.QtCore import SIGNAL, SLOT

class ChildWidget(QtWidgets.QWidget):
    def __init__(self, parent=None):
        super(ChildWidget, self).__init__(parent)
        self.initUI()

    def initUI(self):
        self.setLayout(QtWidgets.QGridLayout())
        label_A = QtWidgets.QLabel("Path A: ", self)
        self.text_A = QtWidgets.QLineEdit(self)
        label_B = QtWidgets.QLabel("Path B: ", self)
        self.text_B = QtWidgets.QLineEdit(self)
        button_A = QtWidgets.QPushButton("Copy", self)

        button_A.clicked.connect(self.copy_function)

        self.layout().addWidget(label_A, 0, 0)
        self.layout().addWidget(self.text_A, 0, 1)
        self.layout().addWidget(label_B, 1, 0)
        self.layout().addWidget(self.text_B, 1, 1)
        self.layout().addWidget(button_A, 1, 2)

        self.layout().setColumnStretch(1, 1)
        self.layout().setColumnMinimumWidth(2, 72)

    def copy_function(self):
        source = self.text_A.text()
        destination = self.text_B.text()
        self.message = ''; count = 0

        file_list = os.listdir(source)
        for item in file_list:
            count = count + 1
            source_path = source +'/'+ item
            destination_path = destination +'/'+ item
            if os.path.isfile(source_path):
                shutil.copyfile(source_path, destination_path)
            # message
            self.message = 'Transferred {0} out of {1} files...'.format(
                count, len(file_list)
            )

class ParentWidget(QtWidgets.QWidget):
    def __init__(self, parent=None):
        super(ParentWidget, self).__init__(parent)
        self.initUI()

    def initUI(self):
        self.child = ChildWidget()
        self.setLayout(QtWidgets.QGridLayout())
        self.status_bar = QtWidgets.QStatusBar(self)
        self.status_bar.setSizeGripEnabled(False)
        self.h_line = QtWidgets.QFrame(self)
        self.h_line.setFrameShape(self.h_line.HLine)
        self.h_line.setFrameShadow(self.h_line.Sunken)

        # self.status_bar.showMessage(message)

        self.layout().addWidget(self.child, 0, 0)
        self.layout().addWidget(self.h_line, 1, 0)
        self.layout().addWidget(self.status_bar, 2, 0)
        self.layout().setContentsMargins(0, 0, 0, 0)

        self.setWindowTitle("Copy Window")
        self.resize(600, 60)
        self.show()

widget_window = ParentWidget()

A: I found it in one of the PyQt documentation. This works.
import os
import shutil

from PySide2 import QtWidgets
from PySide2.QtCore import Signal, Slot

class ChildWidget(QtWidgets.QWidget):
    status_update = Signal(str)
    def __init__(self, parent=None):
        super(ChildWidget, self).__init__(parent)
        self.initUI()

    def initUI(self):
        self.setLayout(QtWidgets.QGridLayout())
        label_A = QtWidgets.QLabel("Path A: ", self)
        self.text_A = QtWidgets.QLineEdit(self)
        label_B = QtWidgets.QLabel("Path B: ", self)
        self.text_B = QtWidgets.QLineEdit(self)
        button_A = QtWidgets.QPushButton("Copy", self)

        button_A.clicked.connect(self.copy_function)

        self.layout().addWidget(label_A, 0, 0)
        self.layout().addWidget(self.text_A, 0, 1)
        self.layout().addWidget(label_B, 1, 0)
        self.layout().addWidget(self.text_B, 1, 1)
        self.layout().addWidget(button_A, 1, 2)

        self.layout().setColumnStretch(1, 1)
        self.layout().setColumnMinimumWidth(2, 72)

    def copy_function(self):
        source = self.text_A.text()
        destination = self.text_B.text()
        count = 0

        file_list = os.listdir(source)
        for item in file_list:
            count = count + 1
            source_path = source +'/'+ item
            destination_path = destination +'/'+ item
            if os.path.isfile(source_path):
                shutil.copyfile(source_path, destination_path)
            message = 'Transferred {0} out of {1} files...'.format(
                count, len(file_list)
            )
            self.status_update.emit(message)

class ParentWidget(QtWidgets.QWidget):
    def __init__(self, parent=None):
        super(ParentWidget, self).__init__(parent)
        self.initUI()

    def initUI(self):
        self.child = ChildWidget()
        self.setLayout(QtWidgets.QGridLayout())
        self.status_bar = QtWidgets.QStatusBar(self)
        self.status_bar.setSizeGripEnabled(False)
        self.h_line = QtWidgets.QFrame(self)
        self.h_line.setFrameShape(self.h_line.HLine)
        self.h_line.setFrameShadow(self.h_line.Sunken)

        self.child.status_update.connect(self.status_message)

        self.layout().addWidget(self.child, 0, 0)
        self.layout().addWidget(self.h_line, 1, 0)
        self.layout().addWidget(self.status_bar, 2, 0)
        self.layout().setContentsMargins(0, 0, 0, 0)

        self.setWindowTitle("Copy Window")
        self.resize(600, 60)
        self.show()

    @Slot()
    def status_message(self, message):
        self.status_bar.showMessage(message)

widget_window = ParentWidget()