text:
Q: Select elements by attribute I have a collection of checkboxes with generated ids and some of them have an extra attribute. Is it possible to use JQuery to check if an element has a specific attribute?
For example, can I verify if the following element has the attribute "myattr"? The value of the attribute can vary.
<input type="checkbox" id="A" myattr="val_attr">A</input>

For example how can I get a collection of all checkboxes that have this attribute without checking one by one? Is this possible?

A: In JavaScript,...
null == undefined

...returns true*. It's the difference between == and ===. Also, the name undefined can be defined (it's not a keyword like null is) so you're better off checking some other way. The most reliable way is probably to compare the return value of the typeof operator.
typeof o == "undefined"

Nevertheless, comparing to null should work in this case.
* Assuming undefined is in fact undefined.

A: $("input[attr]").length might be a better option.

A: A couple ideas were tossed around using "typeof", jQuery ".is" and ".filter" so I thought I would post up a quick perf compare of them. The typeof appears to be the best choice for this. While the others will work, there appears to be a clear performance difference when invoking the jq library for this effort.

A: if ($('#A').attr('myattr')) {
    // attribute exists
} else {
    // attribute does not exist
}

EDIT:
The above will fall into the else-branch when myattr exists but is an empty string or "0". If that's a problem you should explicitly test on undefined:
if ($('#A').attr('myattr') !== undefined) {
    // attribute exists
} else {
    // attribute does not exist
}

A: if (!$("#element").attr('my_attr')){
  //return false
  //attribute doesn't exists
}

A: as in this post, using .is and the attribute selector [], you can easily add a function (or prototype):
function hasAttr($sel,attr) {
    return $sel.is('['+attr+']');
}

A: Do you mean can you select them? If so, then yes:
$(":checkbox[myattr]")

A: I know it's been a long time since the question was asked, but I found the check to be clearer like this :
if ($("#A").is('[myattr]')) {
    // attribute exists
} else {
    // attribute does not exist
}

(As found on this site here)
Documentation about is can be found here

A: This will work:
$('#A')[0].hasAttribute('myattr');

A: $("input#A").attr("myattr") == null

A: In addition to selecting all elements with an attribute $('[someAttribute]') or $('input[someAttribute]') you can also use a function for doing boolean checks on an object such as in a click handler:
if(! this.hasAttribute('myattr') ) { ...

A: To get collection of all checkbox elements based on multiple attributes, e.g. in this case id and myattr:
var checkboxCollection = $(":checkbox[id][myattr]");

If you need to assign event handler to each checkbox in collection:
$(":checkbox[id][myattr]").change(function() {
    if(this.checked) {
        var valueOfAttribute = $(this).attr('myattr');
        // code here
    }
    else{
        // code here
    }
});

A: simply:
$("input[name*='value']")

more info: official docs

A: I have created npm package with intended behaviour as described above in question.
Link to [npm] and [github]
Usage is very simple. For example:

something

$("#test").hasAttr("class")

returns true.
Works with camelcase too.

A: To select elements having a certain attribute, see the answers above.
To determine if a given jQuery element has a specific attribute I'm using a small plugin that returns true if the first element in  ajQuery collection has this attribute:
/** hasAttr
 ** helper plugin returning boolean if the first element of the collection has a certain attribute
 **/
$.fn.hasAttr = function(attr) {
   return 0 < this.length
       && 'undefined' !== typeof attr
       && undefined !== attr
       && this[0].hasAttribute(attr)
}

A: We can easy to access the value attribute value if the attribute present in the given HTML element.
var offORonlinePath="../img/";   //We can easy to change the path anytime
var extension=".webp"; //we can later change any value like png,jpg,...

$("img[data-src]").each(function(){
  var imgName=$(this).data("src");

  $(this).attr("src",offORonlinePath+imgName+extension);

})

A: JQuery will return the attribute as a string.  Therefore you can check the length of that string to determine if is set:
if ($("input#A").attr("myattr").length == 0)
 return null;
else
 return $("input#A").attr("myattr");


text:
Q: Where multi column adds up over 16 I'm trying to pull all records that have the engineer and has an overall score of 16 or higher.
value_money, quality_service, friendliness, response_time are all fields in the same table.
I'm trying to add all these and perform a WHERE.
This is what I've got so far
SELECT *,
value_money+quality_service+friendliness+response_time AS overall
FROM feedback
WHERE engineer LIKE '%Chris Gauden%'
AND
overall < 16
ORDER BY date DESC
LIMIT 0, 15

And this is the error i'm getting.
#1054 - Unknown column 'overall' in 'where clause'

A: You cannot use alias in there WHERE clause.
You have to use full value_money+quality_service+friendliness+response_time combination.

A: Alias cannot be used in WHERE. Do either
SELECT *,
value_money+quality_service+friendliness+response_time AS overall
FROM feedback
WHERE engineer LIKE '%Chris Gauden%'
AND
value_money+quality_service+friendliness+response_time < 16
ORDER BY date DESC
LIMIT 0, 15

or
SELECT * FROM
(
SELECT *,
value_money+quality_service+friendliness+response_time AS overall
FROM feedback
WHERE engineer LIKE '%Chris Gauden%'

)a WHERE overall < 16
ORDER BY date DESC
LIMIT 0,15

A: The simplest solution is to move the condition to the having clause:
SELECT *, value_money+quality_service+friendliness+response_time AS overall
FROM feedback
WHERE engineer LIKE '%Chris Gauden%'
HAVING overall < 16
ORDER BY date DESC
LIMIT 0, 15;

This is a MySQL extension and will not work in other databases.

A: Not sure what database your using but try something like this:
SELECT *,
value_money+quality_service+friendliness+response_time AS overall
FROM feedback
WHERE engineer LIKE '%Chris Gauden%'
AND
SUM(value_money+quality_service+friendliness+response_time) < 16
ORDER BY date DESC
LIMIT 0, 15

A: You since overall isn't a column in that table, you can't reference it in the where clause.
You could do something like this instead:
SELECT * FROM
(
    SELECT *,
           value_money+quality_service+friendliness+response_time AS overall
    FROM feedback
    WHERE engineer LIKE '%Chris Gauden%'
) AS ComputedTable
WHERE
    overall < 16
ORDER BY date DESC
LIMIT 0, 15

A: It's possible your server doesn't support that. If that's the case, I can think of two options. Subquery:
SELECT * FROM (
SELECT *, value_money+quality_service+friendliness+response_time AS overall
FROM feedback
WHERE engineer LIKE '%Chris Gauden%') AS t
WHERE overall < 16
ORDER BY date DESC
LIMIT 0, 15

Or repeating the equation:
SELECT *,
value_money+quality_service+friendliness+response_time AS overall
FROM feedback
WHERE engineer LIKE '%Chris Gauden%'
AND
value_money+quality_service+friendliness+response_time < 16
ORDER BY date DESC
LIMIT 0, 15

redpajama_set_name: RedPajamaStackExchange


text:
Q: $L^{\infty}$ and semi-norm i'm starting of course of functional analysis and i'm struggling to understand how to manipulate the following

Show that $\lVert f\rVert_{\infty}=\text{Inf} \left\{  M>0,|f(x)| \leq M
  \ \mu \ a.e \text{ over } X\right\} $ is a semi-norm over $\mathcal{L}^{\infty}(X,\mathcal{A}, \mu).$

I have no idea how to manipulate this definition.
If you could help me i would greatly appreciate it thanks !

A: This works fairly directly using the definition.
If $\lambda\in\mathbb C$ is nonzero,
\begin{align}
\|f\|_\infty&=\inf\{M>0:\ |\lambda f|<M\ \text{a.e.}\}\\[0.3cm]
&=\inf\{M>0:\ | f|<M/|\lambda|\ \text{a.e.}\}\\[0.3cm]
&=\inf\{|\lambda|M>0:\ | f|<M\ \text{a.e.}\}\\[0.3cm]
&=|\lambda|\,\|f\|_\infty.
\end{align}
And if $|f|<M$, $|g|<N$ a.e., then $$|f+g|≤|f|+|g|<M+N$$ a.e. Thus $$\|f+g\|_\infty\leq M+N.$$ As this can be done for any such $M$,
$$\|f+g\|_\infty\leq \|f\|_\infty+N.$$ And this works for any $N$ as above so
$$\|f+g\|_\infty\leq \|f\|_\infty+\|g\|_\infty.$$


text:
Q: Cannot display Google Maps I am trying to create my first Google Maps in Android using an emulator in Eclipse with no success. All I get for the map is a gray tiled screen that I can zoom but there is no map there. Below is my AndroidManifest file:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.herb2"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="16"
        android:targetSdkVersion="17" />

    <uses-feature
        android:glEsVersion="0x00020000"
        android:required="true" />

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="com.example.mapdemo.permission.MAPS_RECEIVE" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <uses-library android:name="com.google.android.maps" />

        <activity
            android:name="com.example.herb2.Herb2Activity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

    <meta-data
        android:name="com.google.android.maps.v2.API_KEY"
        android:value="my key is not shown here" />

</manifest>

Below is my layout file:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin" >

    <TextView
        android:id="@+id/latitude_view"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Latitude: " />

    <TextView
        android:id="@+id/longitude_view"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Longitude: " />

    <com.google.android.maps.MapView
        android:id="@+id/mapvw"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:apiKey="my key is not shown here"
        android:clickable="true"
        android:enabled="true" />

</LinearLayout>

Finally below is my java source:
public class Herb2Activity extends MapActivity {

    private TextView latitudeView;
    private TextView longitudeView;
    private LocationManager locationManager;
    private MapController mapController;
    private MapView mapView;
    private GeoPoint point;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_herb2);
        latitudeView = (TextView) findViewById(R.id.latitude_view);
        longitudeView = (TextView) findViewById(R.id.longitude_view);
        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        mapView = (MapView) findViewById(R.id.mapvw);
        mapView.setBuiltInZoomControls(true);
        mapView.setSatellite(true);
        mapController = mapView.getController();
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
                3600, 1000, new LocationListener() {

                    public void onProviderDisabled(String provider) {
                    }

                    public void onProviderEnabled(String provider) {
                    }

                    public void onStatusChanged(String provider, int status,
                            Bundle extras) {
                    }

                    public void onLocationChanged(Location loc) {
                        if (loc != null) {
                            int lt = (int) (loc.getLatitude());
                            int lg = (int) (loc.getLongitude());
                            latitudeView.setText("Latitude is: "
                                    + String.valueOf(lt));
                            longitudeView.setText("Longitude is: "
                                    + String.valueOf(lg));
                            int latit = (int) (loc.getLatitude() * 1E6);
                            int longit = (int) (loc.getLongitude() * 1E6);
                            point = new GeoPoint(latit, longit);
                            mapController.animateTo(point);
                            mapController.setZoom(15);
                        }
                    }
                });
    }

    @Override
    protected boolean isRouteDisplayed() {
        return true;
    }

    @Override
    protected boolean isLocationDisplayed() {
        return false;
    }
}

I am suspecting it may have something to do with my API key which I generated from Google.  I provided the SHA1 certificate fingerprints to generate my key. I added at the end of the key my package name which is com.example.herb2 as shown above. I also made sure I was using a Google API device as my emulator. I assume the MD5 fingerprint is used for production. I will appreciate any help on why my map shows nothing but gray.

A: Have you looked at Google map signed api key errors in Android?
It most probably is that you're using a signed key instead of a debug key.


text:
Q: Concatenate two ideas I have two doubts in the following sentence:
Plastic has the lowest production cost but the best efficiency against other materials.

*

*The first one is if it's correctly written because I want to say that plastic has lowest production cost and the best efficiency at the same time. So if there's a better way to write it, please tell me.

*The second one is if I should use "and" instead of "but" and why.

Any other suggestions are welcome. Thanks.

A: I think that you should use and, because low production cost and best efficiency are similar ideas (not contrasting). But you should probably say compared with instead of against.


text:
Q: How do I duplicate jackal model tag in Halo PC campaign without exception errors?(Not Custom Edition) I'm trying to replace the single green jackal shield in the campaign with yellow and blue shields like it was in the original xbox version. And the way I tried to do that was by duplicating the characters\jackal\jackal model tag.
What I did was open and expand the map in question in eschaton 0.8.1, and open (not expand), a second map to extract the tag from. So I extract the jackal model tag from the opened map, then import it into the expanded map with "do not import duplicates" unchecked.
I then rebuilt the map with the duplicate tag, which is assigned a plus sign to differentiate it from the original, including its dependencies.
Then I reopened the map in eschaton and clicked on the jackal major biped tag and swapped its model to the duplicated one. I then opened up halo map tools v3.5 and injected a blue shield texture to the original bitmap, and a yellow texture to the duplicate with the plus sign.
Next I tested it out by playing the campaign, which works perfectly with one glaring problem, it crashes during the cutscenes and gives me an exception error. Every level I do this to crashes during the cutscenes. I even expanded the base map that I took the tag from and renamed the tag and its dependencies so there wouldn't be duplicates, but the game still crashes during cutscenes.
Is my method just flawed? Is there another way to do this? Or is this not possible in vanilla Halo PC without exceptions?
Again this is Halo PC, not Custom Edition, and I'm trying to have two colors of jackal shield, yellow and blue, like in the xbox version of Halo CE.
Update: it seems I answered my own problem; I used an earlier version of eschaton(0.7.2) to rebuild the map, and it didn't crash!
If you want to successfully open and expand/rebuild campaign maps, use eschaton 0.7.2 or maybe 0.8.


text:
Q: Can multiple calls be made to the same db context? Copy a record to a second table before removing it using multiple steps in an action I am trying to copy a record to a second table prior to removing the record, but my code only removes the record and does not actually copy to the second db(testPortal_scClientRemoved) table.
   public async Task<IActionResult> DeleteFinal(int id)
    {
        var scClient = await _context.testPortal_ClientInfo
            .Where(x => x.ClientID == (int)HttpContext.Session.GetInt32("ssClooID"))
            .FirstOrDefaultAsync(m => m.ID == id);

        // --- Add Info to History table ---
        scClientRemoved scHistory = new scClientRemoved();

        scHistory.ClientID = scClient.ClientID;
        scHistory.LastName = scClient.LastName;
        scHistory.FirstName = scClient.FirstName;
        scHistory.PaidDate = scClient.PaidDate;
        scHistory.Modelname = scClient.Modelname;
        scHistory.Makename = scClient.Makename;
        scHistory.Year = scClient.Year;
        scHistory.scClientID = scClient.ID;
        scHistory.Custno = scClient.Custno;
        scHistory.DeleteDateTime = DateTime.Now;
        scHistory.DeleteEmployee = HttpContext.Session.GetString("ssADName");
        scHistory.CreatedDateTime = DateTime.Now;

        _context.testPortal_scClientRemoved.Add(scHistory);
        _context.SaveChanges();

        // --- Delete record from ClientInfo table ---

        var deleteCustomer = await _context.testPortal_ClientInfo
            .Where(x => x.ClientID == (int)HttpContext.Session.GetInt32("ssClooID"))
            .FirstOrDefaultAsync(m => m.ID == id);

        _context.testPortal_ClientInfo.Remove(deleteCustomer);
        _context.SaveChanges();

        return RedirectToAction(nameof(Index));
    }


text:
Q: godbolt fails to link when including windows.h on MSVC? Now Im fully aware this may not be the correct site to post this question, but Im a bit lost where else to post it.
Using the godbolt.org compiler explorer, has shown to be great little tool for many things (including on this site).
However, it seems linking on windows platform isn't very well 'supported' when including windows headers (or am I missing something). Compilation works just fine, but linking seems to fail. (and there seem to be no option in the library list)
#define WIN32_LEAN_AND_MEAN
#include <windows.h>

int main (void)
{
     return 0;
}

Yields the link error:
LINK : fatal error LNK1104: cannot open file 'LIBCMT.lib'

Anyone know what's the reason for this ? (or if theres hack/workaround ?)
It compiles fine, but the little './a.out' is disabled on the compiler pane (as isn't the case for gcc). Also the executor (the pane to the right) works seemingly fine - just not when including and thus linking with any windows headers.
What is a 'shareable' way to get code executed with windows headers linked, if there is one ? (eg. for use on this site)

A: This is a known issue with the software (#1502).
Summary:

Execution is not supported on any MSVC compiler currently.
  The wine compilers run on our infrastructure, but are not able to produce a binary.
  The non-wine compilers run on microsoft's infrastructure and we have no control over them.
I believe it is a bug that these compilers even show up in the dropdown on the execution only pane.

Any further engagement about this issue should take place on that bug tracker.


text:
Q: How to add conditions from a variable on Powershell? I would like to add an input variable that would allow me to add as many conditions as I want.
Ex : A variable for add -and ($_ -notmatch '67'
$file = "\Input\27532.csv"
$outFile = "\Output\27532.csv"

$content= Get-Content $file | Where-Object { ($_ -notmatch '24') -and ($_ -notmatch '67')  } | Set-Content $outfile

A: Use a single -notmatch operation with regex alternation (|), which allows you to pass an open-ended number of substrings:
$valuesToExclude = '24', '67', '42'

$content= Get-Content $file |
  Where-Object { $_ -notmatch ($valuesToExclude -join '|') } |
   Set-Content $outfile

Note: The above assumes that $valuesToExclude contains only values that contain no regex metacharacters (e.g., .); if there's a chance of that, and you want these characters to be interpreted literally, call [regex]::Escape() on the values:
($valuesToExclude.ForEach({ [regex]::Escape($_) }) -join '|')


text:
Q: Error android.view.InflateException: Binary XML file line #21: Binary XML file line #21: Error inflating class fragment Error inflating class fragment

I am trying to add fragment in activity at runtime dynamically.
After running the app crashes.
File names are
There is a main activity(MainActivity.java), its xml(activity_main.xml)

A fragment (MainFragment.java), its xml (fragment_main.xml)

Following is Code for app.
fragment_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/fragment_main"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <Button
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_alignParentTop="true"
        android:layout_marginLeft="119dp"
        android:layout_marginStart="119dp"
        android:layout_marginTop="63dp"
        android:text="Button" />
</RelativeLayout>

MainFragment.java
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class MainFragment extends Fragment {
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_main, container, false);
        return view;
    }
}

activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.example.vikashyadav.myquiz.MainActivity">

    <fragment
        android:id="@+id/fragment_holder"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_alignParentRight="true"
        android:layout_alignParentEnd="true"
         />

</RelativeLayout>

MainActivity.java
package com.example.vikashyadav.myquiz;

import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        FragmentTransaction ft=getSupportFragmentManager().beginTransaction();
        ft.add(R.id.fragment_holder,new MainFragment());
        ft.commit();
    }

}

i am not able to find why this crashes.

A: Remove fragment layout by other like FrameLayout..
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.example.vikashyadav.myquiz.MainActivity">

<FrameLayout
    android:id="@+id/fragment_holder"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_alignParentRight="true"
    android:layout_alignParentEnd="true"
     />

A: import android.os.Bundle;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        addFragment(R.id.fragment_holder,new MainFragment(), "MainFragment");
    }

    protected void addFragment(@IdRes int containerViewId, @NonNull Fragment fragment,@NonNull String fragmentTag) {
        getSupportFragmentManager()
                .beginTransaction()
                .add(containerViewId, fragment, fragmentTag)
                .disallowAddToBackStack()
                .commit();
    }

}


text:
Q: Understanding of rate() function of PromQL I went through the PromQL docs and found rate little bit confusing. Then I tried one query from Prometheus query dashboard and found below given results
Time Count increase  rate(count[1m])
15s  4381  0          0
30s  4381  0          0
45s  4381  0          0
1m   4381  0          0

15s  4381  0          0
30s  4402  21         0.700023
45s  4402  0          0.700023
2m   4423  21         0.7

15s  4423  0          0.7
30s  4440  17         0.56666666
45s  4440  0          0.56666666
3m   4456  16         0.53333333

Last column value I am getting from dashboard but I am not able to understand how is this calculated.
Resolution - 15s
scrape_interval: 30s

A: The "increase" function calculates how much some counter has grown and the "rate" function calculates the amount per second the measure grows.
Analyzing your data I think you used [30s] for the "increase" and [1m] for the "rate" (the correct used values are important to the result).
Basically, for example, in time 2m we have:
increase[30s] = count at 2m - count at 1.5m = 4423 - 4402 = 21
rate[1m]      = (count at 2m - count at 1m) / 60 = (4423 - 4381) / 60 = 0.7

Prometheus documentation: increase and rate.

A: I found this:
rate = Count_{now} - Count_{now-30s} / 30s

Time Count increase  rate(count[1m])

15s  4381  0          0
30s  4381  0          0
45s  4381  0          0
1m   4381  0          0

15s  4381  0          0
30s  4402  21         = [4402-4381]/30s = 0.7
45s  4402  0          = [4402-4381]/30s = 0.7
2m   4423  21         = [4423-4402]/30s = 0.700023

15s  4423  0          = [4423-4402]/30s = 0.7
30s  4440  17         = [4440-4423]/30s = 0.56666666
45s  4440  0          = [4440-4423]/30s = 0.56666666
3m   4456  16         = [4456-4440]/30s = 0.53333333

A: Prometheus calculates rate(count[d]) at timestamp t in the following way:

*

*It obtains raw samples per each time series with count name on the time range (t-d ... t]. Note that t-d timestamp isn't included in the range, while t timestamp is included in the range. For example, when calculating rate(count[1m]) at a timestamp t=2m the following raw samples are selected: 4423 @ 2m, 4402 @ 1m45s, 4402 @ 1m30s, 4381 @ 1m15s. Note that the 4381 @ 1m sample isn't included in calculations.

*Then it calculates the difference between the last and the first sample on the selected time range per each time series with the name count. Prometheus can detect and remove time series resets to zero on the selected time range, but let's skip this for now for the sake of clarity. In the case above it calculates 4423 @ 2m - 4381 @ 1m15s = 42.

*Then it divides results from step 2 by the duration d in seconds per each time series with name count. In the case above it calculates 42 / 1m = 42 / 60s = 0.7.

The actual result for rate(count[1m]) @ 2m - 0.700023 - differs from the calculated result - 0.7 - because of extrapolation, which can be applied to results calculated at step 2 if timestamps for the first and/or the last raw sample are located too far from the selected time range bounds. See more details about the extrapolation in this issue.
Note also that Prometheus misses possible counter increase on the time range [1m ... 1m15s] when calculating both rate() and increase(). See more details about this issue here and here.


text:
Q: Which distribution family should I choose for my GLMM? I'am modelling the effect of individuals' chronotype on their respective school performance.
So, my dataframe consist of the subjective and school declared performance (dependent variable) of middle school students (random variable), and their chronotype (independent variable).
The students' subjective performance was measured on a scale from 1 to 5, while the school declared performance was on a scale from 0 to 10. Thus, I Z-standardized these performance values.
#Loading data
data <- read.table("clipboard", header=T)
#Scale function: Z-Score Standardization
data.st <- as.data.frame(scale(data$performance, center = FALSE))
data$performance.st <- data.st$V1
hist(data$performance.st, prob=TRUE, ylim=c(0,1),
     main = "Histogram", col= "lightblue")

shapiro.test(data$performance.st)
#W = 0.96497, p-value = 6.798e-07

Then I modelled my data considering a poisson family:
# Poisson distribution
glmer.poisson <- glmer(performance ~ chronotype + (1|random),
               family = poisson(link = log),
                     data =  data)

Generalized linear mixed model fit by maximum likelihood (Laplace Approximation) ['glmerMod']
 Family: poisson  ( log )
Formula: performance ~ chronotype + (1 | random)
   Data: data
     AIC      BIC   logLik deviance df.resid
     Inf      Inf     -Inf      Inf      310
Random effects:
 Groups Name        Std.Dev.
 random (Intercept) 1
Number of obs: 315, groups:  random, 55
Fixed Effects:
 (Intercept)  chronotypemm  chronotypemv  chronotypeve
    -0.03279      -0.02495      -0.12318       0.01500
optimizer (Nelder_Mead) convergence code: 0 (OK) ; 29610 optimizer warnings; 1 lme4 warnings

plot(simulateResiduals(glmer.poisson))

However, the GLMM clearly did not fit.
And now I have some questions regarding my data and GLMMs.
First: I don't really know which family to use to model my data. Although I have non-integer values, I think poisson is the right family to use (although lognormal distribution provided nice results). Though, what about the warnings returned in the lm4 package saying that my values are non-integer? and the optimizer warnings? should I change my optimizer? if so, how?
Second: A fellow of mine suggested for me to use gamma or negative binomial instead of poisson. Though, after I see the histogram i thought a lognormal distribution would be a nice try. So I modelled accordingly:
#Gamma distribution
gamma <- glmer(performance ~ chronotype + (1|random),
               family = Gamma(link="inverse"),
               data =  data)
qqnorm(resid(gamma), pch=16)
qqline(resid(gamma))
plot(gamma)

# Negative binomal distribution
glmer.nb <- glmer.nb(performance ~ chronotype + (1|random),
               data =  data, family=MASS::negative.binomial(theta=1.75))

plot(simulateResiduals(glmer.nb))
# The simulated residuals of the glmer.nb were very similar to the poisson model
plot(glmer.nb)
qqnorm(resid(glmer.nb), pch=16)
qqline(resid(glmer.nb))

# lognormal distribution
lognormal <- glmer(formula = log(performance) ~ chronotype + (1|random),
               data = data, family=gaussian(link = identity))
plot(simulateResiduals(lognormal))
plot(lognormal)

qqnorm(resid(lognormal), pch=16)
qqline(resid(lognormal))

The lognormal seems to be a good distribution for my data, but I am not sure.
Finally: Suppose that I'am building a GLMM considering a poisson family. Should I standardize my dependent variable even though poisson use a log link function? I think the correct answer is yes since my data have different scales.

A: Plots are good.
We often learn a lot from visualizing the raw data. It's more effective than fitting an inappropriate model and then wondering whether the residual QQ plot looks normal "enough".
So I made a few plots of your data. The plots suggest a substantial revision of your analysis; choosing a different distribution family won't be sufficient to make sense of your data.
First, we look at histograms of performance scores by subject (mat, pt, science) and type (school-declared, subjective).

The transformation
data$performance = scale(data$performance, center = FALSE)

assumes subjective scores and school-declared scores have the same variance. The histograms, which are aligned on the x-axis, show the assumption doesn't hold. So the transformation is misapplied.
Once you standardize the scores, you ignore the fact that you are working with different measures of performance. By plotting subjective against school-declared scores, we see that the two measures are correlated only for math. There is little agreement between students' perception and teachers' evaluation of performance in pt and science.

And finally, let's look at (school-declared) performance as a function of choronotype. There seems to be something going on though it will be difficult to estimate the effect of chronotype with high precision as 39 out of 55 students have the in chronotype; the other three types are rare. A lot of the difference is in the spread (variability) rather than the mean, except for pt where mv seems to be associated with lower performance.

Here is the R code to reproduce the figures; I use ggplot2.
library("readxl")
library("tidyverse")

data <-
  read_xlsx(
    "data.xlsx",
    col_types = c("text", "text", "text", "numeric")
  ) %>%
  separate(
    subjects,
    c("type", "subject")
  ) %>%
  mutate(
    type = recode(type, "subj" = "subjective")
  )

data %>%
  ggplot(
    aes(performance)
  ) +
  geom_histogram(
    breaks = 0:10
  ) +
  facet_grid(
    type ~ subject
  )

ggsave("chronotypes1.png", width = 12, height = 8, dpi = 600)

data %>%
  pivot_wider(
    names_from = type,
    values_from = performance
  ) %>%
  ggplot(
    aes(subjective, school)
  ) +
  geom_smooth(
    method = "lm", formula = y ~ x, se = FALSE
  ) +
  geom_jitter(
    width = 0.1,
    height = 0,
    shape = 1,
    size = 2,
    stroke = 1
  ) +
  facet_grid(
    ~subject
  )

ggsave("chronotypes2.png", width = 12, height = 4, dpi = 600)

data %>%
  pivot_wider(
    names_from = type,
    values_from = performance
  ) %>%
  ggplot(
    aes(chronotype, school)
  ) +
  geom_jitter(
    aes(color = chronotype),
    width = 0.1,
    height = 0,
    shape = 1,
    size = 2,
    stroke = 1
  ) +
  facet_grid(
    ~subject
  ) +
  theme(legend.position = "none")

ggsave("chronotypes3.png", width = 12, height = 4, dpi = 600)


text:
Q: Defining variable using value of another variable in Python? I am trying to get Python to define two integer variables, numberone and numbertwo, with the first being between 1 and 100 and the second being less than the first.
I have tried this code:
    numberone=random.randint(0,100)
    numbertwo=random.randint(0,numberone)

but the second number is occasionally larger than the first.
Am I missing something completely obvious? :s

A: I believe you are confusing "greater than" and "not less than" - is not possible for the numbertwo > numberone but it might very well be that numbertwo == numberone, which also means that numbertwo < numberone is false.

random.randint(a, b) is a bit confusing in that unlike range(a, b) which includes numbers up to b - 1 only, randint might produce b. To get the "including a but excluding  b behaviour, use random.randrange:
numberone = random.randint(0, 100)   # 0 .. 100
numbertwo = random.randrange(0, numberone)   # 0 .. numberone - 1


text:
Q: How to use "in respective of" and how does it compare to "in terms of"? How to use the expression "in respective of" and how does it compare to "in terms of"?
What is their appropriate usage?

A: Do not use it. There is no such term.
The nearest correct term is

With respect to
With respect to Section 13 of the contract, my client would like to suggest a change.

To compare:

In terms of
In terms of enforceability, the contract is weak.


text:
Q: Unit testing for asyncio coroutines I'd like to use nosetests to test the coroutines in a class. My first thought was to call each coroutine with asyncio.run(). Unfortunately, I started to receive runtime exceptions after the first test. This is a minimal example to show the problem:
import asyncio

class MyClass:

    def __init__(self):
        self.event = asyncio.Event()

    async def hello(self):
        print("Hello from MyClass")

class TestMyClass:

    def setup(self):
        self.my_class = MyClass()

    def test1(self):
        asyncio.run(self.my_class.hello())

    def test2(self):
        asyncio.run(self.my_class.hello())

When this script is run with nosetests, a RuntimeError: There is no current event loop in thread 'MainThread'. is raised for test2. The offending line is the creation of an Event in MyClass. I don't fully understand the issue. The documentation for asyncio.run() states that the function "should be used as a main entry point for asyncio programs, and should ideally only be called once." To me, this sounds as if it's possible to call asyncio.run() multiple times in a program, even though it's not recommended.
Anyway, as the error points to a non-existing event loop, I decided to manage the event loop manually, and came up with the following workaround:
import asyncio

class MyClass:

    def __init__(self):
        self.event = asyncio.Event()

    async def hello(self):
        print("Hello from MyClass")

class TestMyClass:

    def __init__(self):
        try:
            self.loop = asyncio.get_event_loop()
        except RuntimeError:
            self.loop = asyncio.new_event_loop()

    def setup(self):
        asyncio.set_event_loop(self.loop)
        self.my_class = MyClass()

    def test1(self):
        asyncio.run(self.my_class.hello())

    def test2(self):
        asyncio.run(self.my_class.hello())

The try...except in the initialization is required when multiple test scripts are run sequentially. I'm using Python 3.7.6.
My workaround doesn't look very clean to me, and I'm wondering if there's a better approach.

A: A potential cleaner workaround, since I'm using asyncio low-level APIs anyway, could be this:
import asyncio

class MyClass:

    def __init__(self):
        self.event = asyncio.Event()

    async def hello(self):
        print("Hello from MyClass")

class TestMyClass:

    def __init__(self):
        self.loop = asyncio.get_event_loop()

    def setup(self):
        self.my_class = MyClass()

    def test1(self):
        self.loop.run_until_complete(self.my_class.hello())

    def test2(self):
        self.loop.run_until_complete(self.my_class.hello())

Is there any possible issues with this approach?


text:
Q: How to manipulate the view based on the itemsource count in xamarin if you are having any control example stacklayout or list,
<StackLayout Padding="0,0,0,15" x:Name="GoalsStack" BindableLayout.ItemTemplateSelector="{StaticResource Goaltemplateselector}" BindableLayout.ItemsSource="{Binding FinalGoalList}">
</StackLayout>

Now you want to hide show this stacklayout based on the itemsource count without using any convertor.

A: you can use the following code easily to perform any action using triggers
<StackLayout Padding="0,0,0,15" x:Name="GoalsStack" BindableLayout.ItemTemplateSelector="{StaticResource Goaltemplateselector}" BindableLayout.ItemsSource="{Binding FinalGoalList}">
<StackLayout.Triggers>
<DataTrigger TargetType="StackLayout" Binding="{Binding Path=FinalGoalList.Count}" Value="0">
<Setter Property="HeightRequest" Value="20"/>
 </DataTrigger>
 </StackLayout.Triggers>
 </StackLayout>


text:
Q: jquery validate - ignoring blank fields when submitting I have a form that allows a user to resend a username to the e-mail address listed.  It also has two input fields for new e-mail and new e-mail confirmation.  The idea is that if the address listed is bad, a new e-mail address can be entered and confirmed.  When the form is submitted, the e-mail is sent to the new address.  If both new address fields are left blank, then the e-mail goes to the address listed.  I have jquery.validate checking to make sure that email confirm === email, but if they're submitted blank I get my validated CSS showing because the blank email confirmation field matches the blank email field.
I have an onblur() "ignoreifblank" rule that covers tabbing through fields, but I need a real ignore if blank that covers the form submit as well.
$(document).ready(function () {
function preload(arrayOfImages) {
    $(arrayOfImages).each(function () {
        $('<img/>')[0].src = this;
    });
}
preload(['https://url.to.images/tick-green.png']);

$('.ignoreifblank').blur(function () {
    if ($(this).val() === "") {
        $(this).parent().removeClass("success error");
        $(this).next('label').css('display', 'none');
        $(this).next('label').remove();
        $('#result').html('');
    }
});
$("#jqvForm").validate({
    ignore: ".ignore",
    onkeyup: false,
    onfocusout: function (element) {
        if ($(element).hasClass('optional')) {
            return false;
        } else {
            $(element).valid();
        }
    },
    highlight: function (label) {
        $(label).closest('.form-element').addClass('error')
            .closest('.form-element').removeClass('success');
        $('#result').html('');
    },
    success: function (label) {
        label.text('OK!').addClass('valid')
            .closest('.form-element').addClass('success');
    },
    rules: {
        new_email: {
            required: false,
            email: true,
            maxlength: 50
        },
        new_email_v: {
            equalTo: "#new_email"
        },
    },
    messages: {
        new_email: {
            email: "E-mail address does not appear to be valid.",
            maxlength: "Maximum length is 50 characters."
        },
        new_email_v: {
            equalTo: "E-mail addresses do not match."
        },
    }
});

The validation css and green tick only appear for a second when the form is submitted, but I'm thinking there's got to be a better way than that.  If I use the class="ignore" then it's just completed ignored.
Here be the fiddle - http://jsfiddle.net/stevelogan/W3gWn/


text:
Q: How to Add Jface Support to project in Eclipse? I am new to Eclipse environment.
I have Eclipse Indigo.
Using I've downloaded the following via Install new Software:
Eclipse Plug-in Development Environment and
Eclipse RCP Plug-in Developer Resources
I created a new Java project, in java build path libraries tab I clicked on Add Library selected plugin dependencies but the list is empty.

A: You have two options to use JFace. You can either create a plug-in project (instead of Java project), and then you can use plug-in dependencies in the manifest.mf editor.
However, I believe, you want to use JFace in a standalone Java application. In this case you have to obtain the corresponding jar files manually, and add them to the project, but not as plug-in dependencies, but as normal jar dependencies. For details about this latter method check the JFace wiki page: http://wiki.eclipse.org/JFace#Create_the_Eclipse_SWT.2FJFace_Project


text:
Q: how to insert multiple column/ row values from textarea into mysql Edited Question:
Thank You for your answers. Sorry for that i am not really looking as per your answers. I want multiple insertion from textarea box while form submission.
i have this result. i want to insert multiple data (both column and rows)  into mysql table using (textarea box) (on form submission)

when we copy above data to textarea box its look like below

following source link already done with single column values.. But i want to insert two column values same time in mysql.
https://www.webslesson.info/2019/06/how-to-insert-multiple-data-into-mysql-in-php-using-textarea-field.html
Any one help me for code
i found two discussion page here below same like my question
How to insert multiple row from textarea to multiple column?
How to insert multiple value and Multiple rows from textarea to MySQL using PHP?
---- but from above no answer posted properly...
For eg:
I want to insert following two columns (state,distance(miles) in mysql using textarea box.

A: *

*Firstly, you have to use <form></form> tags around the table.

*Then to get values of each columns in a row, you can use some <input> tags inside the <td> tags. The reason why doing this is because <td> tags don't have a name attribute and thus cannot use php $_GET or $_POST variables

*Once you have the name attribute, use $_POST or $_GET to capture and transfer to database

You can check this link. This will give you some insight
Link here


text:
Q: Measuring end user latency or performance on the client side? Are there tools to measure end to end performance that the end user is facing ? Like bandwidth, latency, page load times in a way that it is non obtrusive ?

A: There are few tools available

*

*Boomerang by Yahoo

*Episodes by Google


text:
Q: WebRTC Events in Firefox I have a working WebRTC connection in Chrome. It uses 1 data channel as part of a chat application.
I want to also support Firefox thus I need to change some not supported events:
For the RTCPeerConnection as well as for the DataChannel.
The changes to the data channel worked as expected:
    //chrome implenetation
    dc.onopen = this.conncectionStats.bind(this);
    dc.onmessage = onMessage;
    // chrome and firefox
    dc.addEventListener('open', (event) => {
        this.conncectionStats.bind(this)
    });
    dc.addEventListener('message', (event) => {
        onMessage(event)
    });

However, the problem arises when changing the PeerConnection:
    // chrome implenetation
    pc.onconnectionstatechange  = this.onConnectionStateChange.bind(this);
    // chrome and firefox
    pc.addEventListener('onconnectionstatechange', (event) => {
        console.log("onconnectionstatechange fired")
        this.onConnectionStateChange.bind(this);
    })

The event is never occuring. Any ideas why this is the case?
The event should be correct, but on the other hand, the documentation is missing on MDN Web Docs.

A: You should use WebRTC adapter so that unsupported events will be shimmed for you:
https://github.com/webrtc/adapter
I am using it on my webpages, and onconnectionstatechange fires fine in Firefox:
...
pc.onconnectionstatechange = onConnStateChange;
...

function onConnStateChange(event) {
        if (pc.connectionState === "failed") {
            Terminate();
            alert("Connection failed; playback stopped");
        }
    }


text:
Q: How to create non blocking popup How to create non blocking Popup
                         LayoutInflater inflater = (LayoutInflater)
                         PollRatings.this
                         .getContext().getSystemService(
                         Context.LAYOUT_INFLATER_SERVICE);
                         View layout = inflater
                         .inflate(R.layout.toast, null);
                         PopupWindow pw = new PopupWindow(layout, 300,
                         470,
                         true);
                         pw.setFocusable(true);
                         pw.setOutsideTouchable(true);
                         pw.setTouchable(true);
                         pw.showAtLocation(layout, Gravity.CENTER, 0, 0);

but when I shows popup, other widgets on screen are blicked ( I cannot click on anything ) HOw to solve this ?

A: Perhaps you could use Toast? http://developer.android.com/reference/android/widget/Toast.html

A: Then try to cancel the dialog from the code by starting a timer and doing dialog.cancel() in the run() procedure of the timer.


text:
Q: Wicket not running on Google App Engine (GAE) My application is configured to use
GAE version 1.9.30
Wicket version 7.1.0
While accessing the wicket app, this error is thrown:
java.lang.NoSuchMethodError: javax.servlet.http.HttpServletRequest.isAsyncStarted()Z
    at org.apache.wicket.protocol.http.servlet.ServletWebResponse.flush(ServletWebResponse.java:317)
    at org.apache.wicket.protocol.http.HeaderBufferingWebResponse.flush(HeaderBufferingWebResponse.java:99)
    at org.apache.wicket.protocol.http.WicketFilter.processRequestCycle(WicketFilter.java:263)
    at org.apache.wicket.protocol.http.WicketFilter.processRequest(WicketFilter.java:203)
    at org.apache.wicket.protocol.http.WicketFilter.doFilter(WicketFilter.java:284)
    at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
    at com.google.appengine.api.socket.dev.DevSocketFilter.doFilter(DevSocketFilter.java:74)
    at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
    at com.google.appengine.tools.development.ResponseRewriterFilter.doFilter(ResponseRewriterFilter.java:128)
    at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
    at com.google.appengine.tools.development.HeaderVerificationFilter.doFilter(HeaderVerificationFilter.java:34)
    at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
    at com.google.appengine.api.blobstore.dev.ServeBlobFilter.doFilter(ServeBlobFilter.java:63)
    at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
    at com.google.apphosting.utils.servlet.TransactionCleanupFilter.doFilter(TransactionCleanupFilter.java:43)
    at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
    at com.google.appengine.tools.development.StaticFileFilter.doFilter(StaticFileFilter.java:125)
    at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
    at com.google.appengine.tools.development.DevAppServerModulesFilter.doDirectRequest(DevAppServerModulesFilter.java:366)
    at com.google.appengine.tools.development.DevAppServerModulesFilter.doDirectModuleRequest(DevAppServerModulesFilter.java:349)
    at com.google.appengine.tools.development.DevAppServerModulesFilter.doFilter(DevAppServerModulesFilter.java:116)
    at org.mortbay.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1157)
    at org.mortbay.jetty.servlet.ServletHandler.handle(ServletHandler.java:388)
    at org.mortbay.jetty.security.SecurityHandler.handle(SecurityHandler.java:216)
    at org.mortbay.jetty.servlet.SessionHandler.handle(SessionHandler.java:182)
    at org.mortbay.jetty.handler.ContextHandler.handle(ContextHandler.java:765)
    at org.mortbay.jetty.webapp.WebAppContext.handle(WebAppContext.java:418)
    at com.google.appengine.tools.development.DevAppEngineWebAppContext.handle(DevAppEngineWebAppContext.java:98)
    at org.mortbay.jetty.handler.HandlerWrapper.handle(HandlerWrapper.java:152)
    at com.google.appengine.tools.development.JettyContainerService$ApiProxyHandler.handle(JettyContainerService.java:512)
    at org.mortbay.jetty.handler.HandlerWrapper.handle(HandlerWrapper.java:152)
    at org.mortbay.jetty.Server.handle(Server.java:326)
    at org.mortbay.jetty.HttpConnection.handleRequest(HttpConnection.java:542)
    at org.mortbay.jetty.HttpConnection$RequestHandler.headerComplete(HttpConnection.java:923)
    at org.mortbay.jetty.HttpParser.parseNext(HttpParser.java:547)
    at org.mortbay.jetty.HttpParser.parseAvailable(HttpParser.java:212)
    at org.mortbay.jetty.HttpConnection.handle(HttpConnection.java:404)
    at org.mortbay.io.nio.SelectChannelEndPoint.run(SelectChannelEndPoint.java:409)
    at org.mortbay.thread.QueuedThreadPool$PoolThread.run(QueuedThreadPool.java:582)

Anyway to run Wicket with GAE?

A: It seems this version of GAE uses Jetty 6.x/7.x with Servlet API 2.5.
Wicket 7 requires Servlet 3.0+.
Consult with GAE documentation to see whether it is possible to use newer Jetty. In case it is not possible you will have to downgrade Wicket to 6.x.

A: I have a Wicket application running on GAE. I'm using Wicket 6.20.0 (and also wicketstuff-gae-initializer)
You can check my POM for all the versions.
Just a note, there is a bug opened for Servlet API 3.x. Since April 2010...


text:
Q: Create MongoDB server in Node.js and use it with Mongoose Is there any way to create and initiate a MongoDB server and a DB inside Node.JS and use Mongoose with that MongoDB server? I want to rent a VPS and use it with Node.JS, but I don't know how to run a Node.JS and MongoDB server at the same time in a VPS. I only have used MongoDB and Node.JS in my mac.
PD: Sorry for my English.

A: Maybe you're confusing between mongoDB database and Node.js application.
You don't run a mongoDB IN Node.js, they are two different things and processes.
First of all you must have a mongoDB instance running on the machine.
Here's only one example to run it as a service on a Linux server.
Node.js is a server side environment that among other things can CONNECT to a mongoDB instance to store o retrieve data. You have to install it as well on your server.
Mongoose is a Node.js module that "mediates" the connection from a Node.js application to MongoDB and give you a set of utility to interact with your mongo database.


text:
Q: How can I set a specific decimal value for the output of pbinom()? I have a single line of code below and the output displayed as below too. But how do I actually set the output to be 4 decimal places?

2*(1-pbinom(175, 240, 0.5))

output: 2.853273e-13

A: You can set options(digits = ...)
> options(digits = 5)

> 2 * (1 - pbinom(175, 240, 0.5))
[1] 2.8533e-13


text:
Q: Tomcat8 crash under load - ArrayIndexOutOfBoundsException, StandardWrapperValve My Tomcat8 (CentOS) webserver is expiring a high load today, > 100,000 requests per hour.
At one point the server crashed/hung. I rebooted the server, and it seem fine and has not crashed again so far.
The only thing I can find as to why it crashed is this error logged to the lochost-20016-10-10.log file at the same time as the crash.
I'm not certain if it is the cause, or just an affect, but I have not seen the error previously.
If anyone has seen this error and knows the cause, please share your information.
10-Oct-2016 12:25:27.370 SEVERE [http-nio-80-exec-86] org.apache.catalina.core.StandardWrapperValve.invoke Servlet.service() for servlet [default] in context with path [] threw exception
 java.lang.ArrayIndexOutOfBoundsException
        at org.apache.tomcat.util.buf.ByteChunk.append(ByteChunk.java:322)
        at org.apache.catalina.connector.OutputBuffer.writeBytes(OutputBuffer.java:418)
        at org.apache.catalina.connector.OutputBuffer.write(OutputBuffer.java:406)
        at org.apache.catalina.connector.CoyoteOutputStream.write(CoyoteOutputStream.java:97)
        at org.apache.catalina.servlets.DefaultServlet.copyRange(DefaultServlet.java:2210)
        at org.apache.catalina.servlets.DefaultServlet.copy(DefaultServlet.java:2044)
        at org.apache.catalina.servlets.DefaultServlet.serveResource(DefaultServlet.java:1008)
        at org.apache.catalina.servlets.DefaultServlet.doGet(DefaultServlet.java:398)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:622)
        at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:292)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
        at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
        at org.apache.catalina.filters.CorsFilter.handleNonCORS(CorsFilter.java:436)
        at org.apache.catalina.filters.CorsFilter.doFilter(CorsFilter.java:177)
        at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240)
        at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
        at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:212)
        at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
        at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
        at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:141)
        at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
        at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:616)
        at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
        at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:522)
        at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1095)
        at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:672)
        at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1502)
        at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1458)
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
        at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
        at java.lang.Thread.run(Thread.java:745)


text:
Q: ~t returning blank instead of time I'm trying to get the name and time of the oldest file in a folder (By modification date).
I can get the name without any problem using this code
for /f "delims=" %%x in ('dir /b /o-d /a-d %currentfolder% ^| grep -v / ') do (SET FILEINFO=%%x )

From my understanding swapping the %%x for %%~tx should return the modified time instead of the filename. But I get a blank instead.
for /f "delims=" %%x in ('dir /b /o-d /a-d %currentfolder% ^| grep -v / ') do (SET FILEINFO=%%~tx )

The following code returns the time of a file in the folder but not the oldest one.
for %%a in (%currentfolder%\*) do (set LAST_TIME=%%~ta)

I tried to combine the first and last code to get the time of the oldest file but it also returns a blank.
    for %%b in (%currentfolder%\%FILEINFO%) do (set MAXDATE=%%~tb)

What is the error here ? How can I solve this ?
Thank you very much for the help

A: You are almost there:
@echo off
set "currentfolder=D:\some directory\"
pushd "%directory%"
for /f "delims=" %%i in ('dir /b /a-d /od') do (
    set "file=%%i"
    set "moddate=%%~ti"
    goto :done
)
popd
:done
echo %file% %moddate%

So we sort by date (oldest first) then set the first filename as %file% and it's date to %moddate% then we exit the loop so it does not do the same for the other files in the folder.

A: The problem is caused by the fact that your current working directory referred to by for /F is not the same as the directory you are searching files in by dir.
This can be fixed like this (omitting grep as I do not understand its purpose here):
rem // Temporarily change to the directory containing the files of interest:
pushd "%currentfolder%"
rem /* The current working directory is now the target directory;
rem    thus both `dir` and `for /F` work in the same directory: */
for /F "delims=" %%x in ('dir /B /A:-D /O:-D') do (set "FILEINFO=%%~tx")
rem // Restore the former working directory:
popd
rem // Just output the gathered information:
echo/%FILEINFO%

Alternatively, the pushd command line could be replaced by cd /D "%currentfolder%" when popd is removed, given that you do not need the original working directory to be restored.

To understand what was going on in your original code, let us assume:

*

*the current working directory is C:\TEST;

*the content of variable currentfolder is D:\DATA;

*the directory C:\TEST contains nothing but the batch file;

*the directory D:\DATA contains a file called some.txt;

The command line dir /b /o-d /a-d %currentfolder% returns only pure file names (due to its option /B), so based on the predefined sample data, the output would be:

some.txt

Now this text is captured by the for /F loop. Now the last modification date/time is queried by %%~tx, which of course requires access to the file system. Remember that the current working directory is C:\TEST, so the for /F loop tries to gather the information from the following file:

C:\TEST\some.txt

Since such a file does not exist, the output is blank.
To prove that, simply place a new file some.txt into the directory C:\TEST, then you would receive the last modification date/time of that file.


text:
Q: openCV - white color filter I'd like to generate some kind of color filter method that is able to filter a specific color - in my case the WHITE color.
This is what I've got so far but tbh I'm sure if this is the right way.
(c++ myfile.mm)
static Mat whiteFilter(cv::Mat img) {
    cv::Mat temp;
    cv::cvtColor(img, temp, CV_RGB2HSV);
    cv::Scalar  lower(0, 0, 0),
                higher(180, 255, 255);
    cv::inRange( temp, lower, higher, img);
    return img;
}

... because of these results:

How to edit the function & the values to achieve a way better WHITE-color extraction?


text:
Q: mac os x authorization plugin through bluetooth Is it possible create authorization plugin for login screen with BLE support? (not lock screen)
Can BLE start in the preLogin mode ?
for example add BLE to this example
https://github.com/skycocker/NameAndPassword
Thanks


text:
Q: How to show user profile data in codeigniter with session? I am new in CI and I have make login system but I am trying to show user profile data in username and email are show on user profile view page. I am to much try but I cant solve this issue. Here is my code.
Can one tell me about how to show user profile data in profile view page? I have too much trying but no solution is available for showing a user profile data in codeigniter.
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class UserLogin extends CI_Controller
{

    public function __construct()
    {
        parent::__construct();
        $this->load->library('session');
        $this->load->helper(array('form', 'url'));
        $this->load->model('login_model');
    }

    public function index()
    {
        $this->load->helper(array('form', 'url'));
        $this->load->library('form_validation');
        $this->load->view('UserLoginPage');
    }

    public function userLoginProcess()
    {
      // $this->form_validation->set_error_delimiters('
', '
');
      // echo "login reached";
      $this->form_validation->set_rules('username', 'Username', 'required|alpha|trim');
      $this->form_validation->set_rules('password', 'Password','required');
      $this->form_validation->set_error_delimiters("
","
");
      $this->session->set_flashdata("
","
");

        if ($this->form_validation->run() ){
            //username aur password araha hay
              $username = $this->input->post('username');
                    $password = $this->input->post('password');

              $this->load->model('login_model');

              //$loginObj session ko check variable haa..!
              $loginObj = $this->login_model->login_valid($username,$password);
              if($loginObj){
                   // print_r($loginObj->password);
                   $this->session->set_userdata('userSessionObj', $loginObj);
                   //print_r($loginObj);
                           $this->load->view('userDashboard');
                }
                else{
               // echo "";
              // $this->session->set_flashdata('error', 'Invalid Username and Password');
              $this->load->view('UserLoginPage');
              // echo "";
              $this->session->set_flashdata('error','
 you entered invalid username and password');
                }   // end of else

        }  // end of public function
        else
            {

                $this->load->view('userLoginPage');

            } // end of else

      }  //end of function
    //logout function Start
    public function logout()
    {
      $this->session->sess_destroy();
      $this->session->unset_userdata('username','password');
       return redirect("userLogin");
    }
        //logout function End
    public function register()
    {

       $this->load->view('registered');

    } //end of register function
    public function preRegister()
    {
      $this->form_validation->set_rules('username', 'Username', 'required|alpha|trim|min_length[5]|max_length[12]|is_unique[user.username]');
      $this->form_validation->set_rules('email', 'email','required|valid_email|is_unique[user.email]');
      $this->form_validation->set_rules('password', 'Password','required');
      $this->form_validation->set_rules('confirmpassword', 'ConfirmPassword','required|matches[password]');

      $this->form_validation->set_error_delimiters("
","
");

      if($this->form_validation->run())
      {
        $store = array(
        'username' => $this->input->post('username'),
        'email' => $this->input->post('email'),
        'dateOfbirth' => $this->input->post('dateOfbirth'),
        'password' => $this->input->post('password'),
        'confirmpassword'=> $this->input->post('confirmpassword'),
        'gender' => $this->input->post('gender')
        );

          $this->login_model->insert_mod($store);
          redirect('UserLogin/index');

      } // end of if form_validation
      else
      {
          $this->load->view('registered');

      } // end of else

  }  //end of preRegister function

  public function employess()   // employes of add ka page view kr rha haaaa
    {
            $this->load->view('userDashboard');
    }                          // employes of add ka page view kr rha haaaa

  public function proEmployess()
  {

    // $this->load->view('addEmployess');
    // $this->load->view('addEmployess');
    $employessData = array(
    // 'id' => $this->input->post('id'),
    'name' => $this->input->post('name'),
    'address' => $this->input->post('address'),
    'department' => $this->input->post('department')
    );

      $this->login_model->employess_add($employessData);
      redirect('UserLogin/employess');
  }

  public function myProfile(){

    // $myProfile = $this->session->userdata();
    $this->load->view('headerDashboard.php');
    $myProfiledata ['profiles'] = $this->login_model->profileVeiw();
    $this->load->view('myProfileView', $myProfiledata);
    $this->load->view('footerDashboard.php');
  }

  //  public function myProfile(){
  //
  //     $this->load->view('headerDashboard');
  //     //$myProfiledata ['datas'] = $this->login_model->veiw_Employess();
  //     //$employessRecord['datas'] = $this->login_model->veiw_Employess();
  //     $this->load->view('myProfileView');
  //     $this->load->view('footerDashboard');
  //
  // }
}
<?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Login_model extends CI_Model{

    public function login_valid($username ,$password)
    {
        $q = $this->db->where(['username'=>$username, 'password'=>$password])
                        ->get('user');

        if( $q->num_rows() )
        {
            //return pori row ho rhe ha jo database sa arhe haaa
             return $q->row();
            // return $q->row()->id;
            // return TRUE;
        }
else
        {
            return FALSE;
        }

    }

    public function insert_mod($store)
    {
        $this->db->insert('user', $store);
    }
    public function employess_add($employessData)
    {
        $this->db->insert('employessRecord',$employessData);
    }
    public function view_employess(){

        $query = $this->db->get('employessrecord');
        return $query;
    }public function profileVeiw(){

              $queries = $this->db->get('user');
             //$queries = $this->session->userdata();
            // print_r($queries);
            return $queries;

        }
}

Profile Details

            <?php foreach($profiles->result() as $profile):?>

              Username:
              <?php echo $profile->username;?>

              Email:
              <?php echo $profile->email;?>

              Passowrd:
              <?php echo $profile->password;?>

              Gender:
              <?php echo $profile->gender;?>

          <?php endforeach; ?>

A: There is opening tag php tag

so you received the data from form and inserted it in database $this->login_model->insert_mod($store) .
when you call myProfile function you get data in $myProfiledata ['profiles'] = $this->login_model->profileVeiw(); here and passed it to view. if this is correct then first try to print $myProfiledata before passing to the view if everything ok there then try to print  $profiles on the "myProfileView" view.
$this->session->userdata('userSessionObj');
 here you can check the session data


text:
Q: How to Encrypt and Decrypt Data in SQL Server 2008 r2 from C#? Hi I am able to do Encryption and Decryption for a specified string and Saving in to the database. But i want to search that Data.But it is not possible to search data for an Encrypted column. There is any Way to that. In front i am using AES, the below method is used for encryption.
  private string Encrypt(string Text)
    {
        string EncryptionKey = "abcdef@123";
        byte[] clearBytes = Encoding.Unicode.GetBytes(Text);
        using (Aes encryptor = Aes.Create())
        {
            Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
            encryptor.Key = pdb.GetBytes(32);
            encryptor.IV = pdb.GetBytes(16);
            using (MemoryStream ms = new MemoryStream())
            {
                using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateEncryptor(), CryptoStreamMode.Write))
                {
                    cs.Write(clearBytes, 0, clearBytes.Length);
                    cs.Close();
                }
                Text = Convert.ToBase64String(ms.ToArray());
            }
        }
        return Text;
    }

the below method is used for Decryption
     private string Decrypt(string Text)
    {
        string EncryptionKey = "abcdef@123";
        byte[] cipherBytes = Convert.FromBase64String(Text);
        using (Aes encryptor = Aes.Create())
        {
            Rfc2898DeriveBytes pdb = new Rfc2898DeriveBytes(EncryptionKey, new byte[] { 0x49, 0x76, 0x61, 0x6e, 0x20, 0x4d, 0x65, 0x64, 0x76, 0x65, 0x64, 0x65, 0x76 });
            encryptor.Key = pdb.GetBytes(32);
            encryptor.IV = pdb.GetBytes(16);
            using (MemoryStream ms = new MemoryStream())
            {
                using (CryptoStream cs = new CryptoStream(ms, encryptor.CreateDecryptor(), CryptoStreamMode.Write))
                {
                    cs.Write(cipherBytes, 0, cipherBytes.Length);
                    cs.Close();
                }
                Text = Encoding.Unicode.GetString(ms.ToArray());
            }
        }
        return Text;
    }

can anybody help me based on this..,

A: I don't believe that there is - that's part of the point of encryption in a round-about way.
If the string has certain characteristics which are searched on, such as a name embedded in it for example, you could calculate the SOUNDEX value of the name and store that in a separate column. You could then do a search based on the soundex value of the name, which would cut down on the number of rows returned each of which you then decrypt and do your search on. That was at least you won't have to pull down the whole table.
Of course, doing that may be a security loophole....
Cheers -

A: I think, you need to create SQL CLR Database Project  and created one function with
Decryption logic and call in SQL Query. you will able to search encrypted data.


text:
Q: React/Redux frontend communicating with Node.js API Auth I have a react/redux app that I want to communicate with a Node.js app (probably Express) through its API. The Node.js app has a CloudantDB and contains sensitive info. Each user can only access his/her part of the DB.
How would you recommend I secure the API endpoints and establish a user Auth? I was thinking to use Passport.js on the Node.js app and have it interact with a Jason Web Token Auth on the react side.
Thanks!

A: There are several ways.
Token, Cookies, JWT
JWT is the most simplest way, (I think) and the most feature rich..
But its up to you..

A: You may want to check out https://github.com/cloudant-labs/envoy which is an express based app that you can extend to use Passport.js
Most importantly it limits the scope of what a user can pull from the DB and store in browser.


text:
Q: Migrate Data from Azure cosmos US region to European Region using data factory I want to migrate records which has country column as one of the EU countries from US region cosmos DB to cosmos DB of West Europe.
I have multiple collections and I want to dynamically iterate through these collection, run queries "where country in ('abc')" and migrate/copy data to sink(cosmos of EU region).
How can I design a pipeline using azure data factory ?
I tried following this
https://learn.microsoft.com/en-us/azure/data-factory/tutorial-bulk-copy-portal.
I am not able to find a dynamic content for all tables from cosmos as source.
Thanks,
Rihuk

A: *

*A Cosmos DB should be created in European Region and need to make that as a sink in copy activity in Azure Data Factory.

*Below are the steps to create Cosmos DB for which you need to create 2 linked services one in US region that should be source database and other should be sink database in European Region.

*

*Below image will help you in configuring service details, testing connection and creating new linked service.

*

*Here is the Microsoft Document regarding Copy and Transform data in Azure Cosmos DB.

*Also, you can Refer Azure CosmosDB container link if you are using Open API.


text:
Q: How to get a list of pages if site having two pages-with same name? for example
http://www.sitename.com/section1/pagename.aspx
http://www.sitename.com/section2/pagename.aspx
I need quick report only for pages which has same name. like "pagename.html" in example.

A: crawl your site, reverse the found URLs and sort?

A: If this is a Sitecore site as I'm led to believe, could you not just go into the Content Editor and search for the name you're looking for? Anything with the item name of "pagename", for example, will have a URL ending with "pagename.aspx" in your standard Sitecore install. Just make sure you're looking at the actual item name and not the display name, as they can be quite different at times depending on how you've got the URL's set up.

A: I would write a quick utility program to just traverse the content tree programmatically, saving the names to a dictionary... when you hit an item that is already in the dictionary, you've got a name collision.

A: One thing you might consider is writing a filter (I think that is what it is called) for this
http://trac.sitecore.net/AdvancedSystemReporter
That would allow you to have a nice interface in Sitecore for viewing duplicate item names.

A: How big is your database, and how is your LINQ to Objects? Theoretically you could write a LINQ query against Database.Items that looks for items with the same name that descend from the same site branch of your content tree. This could be very memory intensive if your master DB is large, but would not be difficult to code.
Edit -- if you can loop over all your site items, you could do something like this (untested):
        var items = siteItem.Axes.GetDescendants();
        var dupes = from item in items
                    join item2 in items on item.Name equals item2.Name
                    where item.ID != item2.ID
                    select item;


text:
Q: Java jdb remote debugging command line tool anyone have any experience using this?
if so, is it worth while?

A: I just used jdb for the first time yesterday and am really pleased with the results.  You see, I program in Eclipse on my laptop, then deploy to a VM to make sure the whole shebang still works.  Very occasionaly, I'll have to work on something that gets executed standalone, as a commandline.  These things sometimes need debugging.
This has always been a problem, because I don't want to go to the trouble of installing Eclipse on the VM (it's slow enough already!), yet I don't know of an easy way to get it to connect to my commandline-running class before it finishes running.
jdb to the rescue!  It works a treat - small and functional, almost to the point where it is bare... this forces you to apply your mind more than you apply the tool (like I said here).
Make sure to print out the reference (solaris, windows, java 1.5 - I think they're all about the same, really) and have your source code open and browsable on your second screen.  I hope you have a second screen, or you'll be alt-tabbing a lot.

A: Assume your program is started by the following command:
java -Xdebug -Xrunjdwp:transport=dt_socket,server=y,address=<port> <class>

You can attach to this process by jdb:
jdb -attach <port>

In some cases you need to use the following command  .
 jdb -sourcepath \.src -connect com.sun.jdi.SocketAttach:hostname=localhost,port= <port>

A: JDB is incredibly difficult to use. Placing System.outs or using an IDE debugger will produce better results. And for the more interesting features (e.g. tracking threads, heap size, etc.), you can get the information graphically with the JConsole tool.


text:
Q: Sorting assets based on name or id I'm trying to add a sorting select function to my app where a user can decide to sort assets based on name or id. In my render I added the select html. With the sortedAssets I am trying to act on the chosen decision. Can someone please help me with debugging the code as it is not working?

Error console:
/src/App.js
  Line 51:20:  'sortbyid' is not defined    no-undef
  Line 60:27:  'sortbyname' is not defined  no-undef
  Line 77:83:  'value' is not defined       no-undef

Relevant part of App.js
    sortedAssets(value){
      if(value === sortbyid){
        let sortbyassetid = this.state.assetsarr.sort((a,b) => {
        return a.id > b.id ? 1 : -1
      })
      this.setState({
        ...this.state,
        clickedassets:sortbyassetid
      })
      } else if(value === sortbyname){
        let sortbyassetname = this.state.assetsarr.sort((a,b) => {
        return a.name > b.name ? 1 : -1
      })
        this.setState({
          ...this.state,
          clickedassets:sortbyassetname
      })
      }
    }

  render(){
  return (

            Sort assets by:
            <select name="sorting" id="sorting" onSelect={() => this.sortedAssets(value)}>
              <option value="sortbyname">NAME</option>
              <option value="sortbyid">ID</option>
            </select>

A: There are a couple of things wrong with your code, I put comments in your code where I changed it:

//Put magic strings in constants
const SORT_BY_ID = 'SORT_BY_ID';
const SORT_BY_NAME = 'SORT_BY_NAME';
class App extends React.Component {
  state = {
    assetsarr: [
      { id: 2, name: 'A' },
      { id: 1, name: 'B' },
    ],
    clickedassets: [
      { id: 2, name: 'A' },
      { id: 1, name: 'B' },
    ],
  };
  sortedAssets(value) {
    //not using magic strings but constants
    if (value === SORT_BY_ID) {
      //sort mutates the array so will sort copy of assetsarr
      let sortbyassetid = [...this.state.assetsarr].sort(
        (a, b) => {
          //id is a number so can use a.id-b.id
          return a.id - b.id;
        }
      );
      this.setState({
        ...this.state,
        clickedassets: sortbyassetid,
      });
    } else if (value === SORT_BY_NAME) {
      //still not mutating state
      let sortbyassetname = [...this.state.assetsarr].sort(
        (a, b) => {
          //name is string, use localeCompare
          return a.name.localeCompare(b.name);
        }
      );
      this.setState({
        ...this.state,
        clickedassets: sortbyassetname,
      });
    }
  }
  render() {
    return (

        {/* no reason to use id make select a child of label */}

          Sort assets by:
          <select
            name="sorting"
            onChange={(e) =>
              //passing e.target.value
              this.sortedAssets(e.target.value)
            }
          >
            <option value={SORT_BY_NAME}>NAME</option>
            <option value={SORT_BY_ID}>ID</option>
          </select>

          {JSON.stringify(this.state.clickedassets)}

    );
  }
}
ReactDOM.render(<App />, document.getElementById('root'));


text:
Q: How to convert CIL to a LINQ Expression Tree
*

*Has any work been done on the direct conversion of CIL to LINQ expression trees?  This would include class libraries, blogs, books, academic papers, etc.

*What are the known mismatches between CIL and LINQ Expression API?  I have seen a project that significantly extended the Expression API to support an almost complete mapping between C# and LINQ Expressions.  What work arounds would be suggested to accommodate any of these mismatches?

*Is there something fundamentally wrong about converting directly from CIL to LINQ Expressions?  If so, why?


text:
Q: Calling existing Stored procedure using Entity Framework 6 with C# I need to know how to call the existing stored procedure in the Entity framework 6 Code First using c#.
Below is the procedure that I am using:
CREATE PROCEDURE proc_getEmployees
    @departmentname varchar(50),
    @sortCol varchar(30),
    @sortdir varchar(25),
    @searchString varchar(50)
AS
BEGIN
    SET NOCOUNT ON;
    declare @strSQl varchar(1000);
    declare @strSQlwhere varchar(500);
    declare @strSelectEndPart varchar(100);

    set @strSQl = ';WITH employeetable as
                (
                    select ROW_NUMBER() OVER (ORDER BY '+@sortCol+' '+@sortdir+' ) AS RowNumber,COUNT(*) over() as TotalRecords, ID,FirstName,LastName,Designation,DepartmentName,Contact,EmailAddress,Location from Employees ';
    set @strSQlwhere = 'where DepartmentName = '''+@departmentname+'''';
    set @strSQlwhere = @strSQlwhere+ ' and (Id like ''%' + @searchString + '%'' Or FirstName like ''%' + @searchString + '%'' Or LastName like ''%' + @searchString + '%'' Or Designation like ''%' + @searchString + '%'' Or DepartmentName like ''%' + @searchString + '%'' Or Contact like ''%' + @searchString + '%'' Or EmailAddress like ''%' + @searchString + '%'' Or Location like ''%' + @searchString + '%'')';
    set @strSelectEndPart =') select * from employeetable';

    set @strSQl = @strSQl +@strSQlwhere+@strSelectEndPart;
    execute (@strSQl);
END
GO

Table I am querying is Employees having the structure as:
Column          Type    Length
ID              int       4
FirstName       varchar   50
LastName        varchar   50
Designation     varchar   50
DepartmentName  varchar   50
Contact         varchar   50
EmailAddress    varchar   50
Location        varchar   50

DBContext Class is as below:
public class DevelopmentTestDatabaseContext :DbContext
{
    public DevelopmentTestDatabaseContext() : base("name =DevelopmentTestDatabaseContext")
    {

    }
    public virtual DbSet<Employee> EmployeeData { get; set; }

}

Method for calling the stored procedure as below:
public void GetEmployeeDataUsingProcedure()
{
    object[] parameters = new SqlParameter[4];
    List<EmployeeResultSet> lstEmployees = new List<EmployeeResultSet>();
    try
    {
        using (var db = new DevelopmentTestDatabaseContext())
        {
            SqlParameter param = new SqlParameter("@departmentname", "IT");
            parameters[0] = param;
            param = new SqlParameter("@sortCol", "ID");
            parameters[1] = param;
            param = new SqlParameter("@sortdir", "asc");
            parameters[2] = param;
            param = new SqlParameter("@searchString", "ope");
            parameters[3] = param;

            var results = db.Database.SqlQuery<EmployeeResultSet>("proc_getEmployees @departmentname, @sortCol, @sortdir, @searchString", parameters);
            db.Database.Log = query => System.Diagnostics.Debug.Write(query);
            lstEmployees = results.ToList();
        }
    }
    catch (Exception ex)
    {

    }
}

Defined the class for the stored procedure resultset as below:
public class EmployeeResultSet
{
    public int rowNumber { get; set; }
    public int totalRecords { get; set; }
    public int ID { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public string Designation { get; set; }
    public string DepartmentName { get; set; }
    public string Contact { get; set; }
    public string EmailAddress { get; set; }
    public string Location { get; set; }
}

Please, let me know if anything else needs to be done before calling the stored procedure. I am new to EF6 and running into issues. What is missing in the code? Do I need to make some changes in any of the class?

A: One thing I can tell an issue with is in your method where you call the procedure. You are setting all elements of the array equal to param but you are constantly changing param. All of your elements will be equal to the final state of param. Try this instead:
public void GetEmployeeDataUsingProcedure()
{
    object[] parameters = new SqlParameter[4];
    List<EmployeeResultSet> lstEmployees = new List<EmployeeResultSet>();
    try
    {
        using (var db = new DevelopmentTestDatabaseContext())
        {
            parameters[0] = new SqlParameter("@departmentname", "IT");
            parameters[1] = new SqlParameter("@sortCol", "ID");
            parameters[2] = new SqlParameter("@sortdir", "asc");
            parameters[3] = new SqlParameter("@searchString", "ope");

            var results = db.Database.SqlQuery<EmployeeResultSet>("proc_getEmployees @departmentname, @sortCol, @sortdir, @searchString", parameters);
            db.Database.Log = query => System.Diagnostics.Debug.Write(query);
            lstEmployees = results.ToList();
        }
    }
    catch (Exception ex)
    {
        //log it or something
    }
}

There may be other issues but without looking too much into it I'd need more information about specific errors or behavior you are experiencing.
You may also try typing out the full name of your database:
"MyDatabase.MySchema.proc_getEmployees @departmentname, @sortCol, @sortdir, @searchString"

EDIT Per your comments:
A quick ducking and I found this. Essentially it states that if you cast your numbers as int in your query you should be fine. So instead of:
select * from employeetable

Try:
select CAST(RowNumber as int) as RowNumber,
    CAST(TotalRecords as int) as TotalRecords,
    CAST(ID as int) as ID,
    FirstName,
    LastName,
    Designation,
    DepartmentName,
    Contact,
    EmailAddress,
    Location
from employeetable

A: Something of an aside, but it is not really necessary for you to use dynamic SQL.  Particularly when having search criteria being strings it is safer to stick to a parameterised query.  In your case you can do something like:
;WITH employeetable as
(
    select
    CASE WHEN @sortDir = 'asc' THEN
    ROW_NUMBER() OVER (ORDER BY
    CASE WHEN @sortCol = 'ID' THEN ID END,
    CASE WHEN @sortCol = 'FirstName' THEN FirstName END,
    CASE WHEN @sortCol = 'LastName' THEN LastName END,
    CASE WHEN @sortCol = 'Designation' THEN Designation END,
    CASE WHEN @sortCol = 'DepartmentName' THEN DepartmentName END,
    CASE WHEN @sortCol = 'Contact' THEN Contact END,
    CASE WHEN @sortCol = 'EmailAddress' THEN EmailAddress END,
    CASE WHEN @sortCol = 'Location' THEN Location END
    ASC) ELSE ROW_NUMBER() OVER (ORDER BY
    CASE WHEN @sortCol = 'ID' THEN ID END,
    CASE WHEN @sortCol = 'FirstName' THEN FirstName END,
    CASE WHEN @sortCol = 'LastName' THEN LastName END,
    CASE WHEN @sortCol = 'Designation' THEN Designation END,
    CASE WHEN @sortCol = 'DepartmentName' THEN DepartmentName END,
    CASE WHEN @sortCol = 'Contact' THEN Contact END,
    CASE WHEN @sortCol = 'EmailAddress' THEN EmailAddress END,
    CASE WHEN @sortCol = 'Location' THEN Location END
    DESC) END AS RowNumber,
    COUNT(*) over() as TotalRecords, ID,FirstName,LastName,Designation,
    DepartmentName,Contact,EmailAddress,Location from Employees
    where DepartmentName = @departmentname and
    (Id like '%' + @searchString + '%' Or FirstName like '%'
    + @searchString + '%' Or LastName like '%' + @searchString + '%'
    Or Designation like '%' + @searchString + '%' Or
    DepartmentName like '%' + @searchString + '%' Or
    Contact like '%' + @searchString + '%' Or
    EmailAddress like '%' + @searchString + '%' Or
    Location like '%' + @searchString + '%')
)
select * from employeetable


text:
Q: Loading Module on an Air/Android application I'm building an Air for Android App and I'm having problems loading a flex module. Does anyone know if loading modules is possible???
I built a simple app with just a ModuleLoader in it, which loads a mx:module. The module has only a simple mx:Label with a "Hello World" text.
I build a .air with this. Then I build a .apk with the followin adt command.

adt -package -target apk-emulator -storetype pkcs12 -keystore certificate.p12 hello.apk hello.air

The application works just fine when running it on the PC, but when I do it on the apk-emulator it just goes blank and throws error #2032.

A: I've just solved it. You can't generate the apk using the air file, at least not the way I did it.
I've just generated the apk using the following:

adt -package -target apk -storetype pkcs12 -keystore certificate.p12 AndroidApp.apk AndroidApp-app.xml AndroidApp.swf module.swf

AndroidApp.swf was my main application and module.swf was my module. It worked like a charm :D
Bye!
Gabriel.-


text:
Q: Can't access my array My programme is to create a Train Route Finder using Java, first off as a command line programme then convert into a GUI. That's the least of my worries for now. I am currently stuck on one functionality of my system and that is to display the list of stops between two stations that the user previously input.
Now, I have been able to prompt the user to choose their stops (lines 3,149 - 3,171 in my code):
if(deptChoice == 1 && arrChoice == 2){

    List<String> stopList1_2 = new ArrayList<String>();
    Scanner stopPick = new Scanner(System.in);
    stopPick.useDelimiter(System.getProperty("line.separator"));

    do {
        System.out.println("\nCurrent list of stops between Leicester to Loughborough is:\n\n" + stopList1_2);
        System.out.println("\nWould you like to add a new stop? (Please enter 'Yes' or 'No')\n");

        if (stopPick.next().startsWith("Yes")) {
            System.out.println("\nPlease type in the stop you wish to add to the route:\n");
            stopList1_2.add(stopPick.next());
        }

        else {
            break;
        }

    } while (true);

    String[] stopArr1_2 = stopList1_2.toArray(new String[0]);
    System.out.println("\nCurrent stops between Leicester to Loughborough is:\n\n" + Arrays.toString(stopArr1_2));

}

and the stops they type in are added to an array. When they are satisfied with the amount stops between the stations there are then the loop ends and it displays the array of stops between Station X and Station Y.
However, here comes the problem:
I want to then gain access to this previously created array with all the exact stops further up my code. In this "if" statement, if it is satisfied, then I want the array (stopArr1_2) to be displayed (in lines 3,019 - 3,021):
if(deptChoice == 1 && arrChoice == 2){
    System.out.println(""); //this should be where I call the array back to display itself
}

as those stops would correspond with the users choice of deptChoice == 1 (Station 1 = Leicester) to arrChoice == 2 (Station 2 = Loughborough).
I hope this is clear:
I basically want the array of stops inputted by the user to reappear when they choose Train Routes.
Here his my full code I made in Notepad++ I thought it would be better for you lot to see all of my code rather than small segments and it is commented.
Furthermore, to comprehend my problem run my programme. To understand my problem do this:
1) Compile Train.java (javac Train.java)
2) Run programme (java Train)
3) Pick Admin Menu (Number 5)
4) Pick Input Menu (Number 1)
5) Pick any two stations
6) Enter a couple of stops until you're happy
7) When it shows the final stops array for those two stations the programme seems to end so hopefully that is not an issue
8) Run programme again (java Train)
9) Pick Train Routes (Number 3)
10) Pick the SAME stations in the same order as you did before so it would find the array you just made
11) Now nothing will come up because, well, that's my problem. I don't know how to regain that array I just made for it.
Download link to my Train.java file (and Train.txt file if needed):
https://www.dropbox.com/s/7dy0pp9vyykwhrk/TrainJava.rar
Any suggestions?

A: Whats the location of your second block of code ? ( The code where you said you need access to the List<String> stopList1_2 ) ?
1 If its in the same class but in a different method , then
Move this declaration
List<String> stopList1_2 = new ArrayList<String>(); ( currently in your first block of code ) to a class field.
BUT
2 If its in the same class and also in the same method as your first block of code, then
Move this declaration
List<String> stopList1_2 = new ArrayList<String>(); ( currently within the if statement of code ) to outside the if condition .
but treat this as a quick recipe for you problem at hand. More importantly - please read the variable scoping rule and access specifiers in java.


text:
Q: Usage of the phrasal verb "look at" when there's actually nothing to see in this particular example I wonder whether the usage of the phrasal verb "look at" is possible and OK when there's actually nothing to see(by eyes) in this case.

Now let's move on and look at the structure of skeletal muscle.

A: The answer is: yes, you can use look at without implying the use of your eyes.
According to Cambridge Dictionary, these meanings do not imply that use

[THINK] to think about a subject carefully so that you can make a decision about it
[HAVE OPINION]
  to consider something in a particular way

Notice that I've omitted the word "see" because it also may imply in some contexts that you don't need your eyes to see something.
Some examples from the same dictionary:

[UNDERSTAND] to understand, know, or realize
[MEET] to meet or visit someone, or to visit a place
   to have a romantic relationship with someone

With that said, I think that your example implies the use of the eyes generally.
You have to read that article of the wikipedia to know more about the skeletal muscle. That article or a book or a schema or whatever is being pointed by the teacher giving the lesson.