text:
Q: Linking External JS Files I am working on an assignment which requires that I link an external JS file into an HTML file. Here's the JS (file name 'whileLoop.js'):
function evenCount () {

var loopCount = 2;

while (loopCount <= 101) {

    document.write(loopCount + " is an even number.
);
    loopCount = (loopCount + 2);

    }

}

And here's the HTML:
<!DOCTYPE html>

<title>JS Assignment</title>

If I copy the raw JS code (without the function call) into the HTML file inside the  tags, then the HTML outputs correctly. When I attempt to link to the JS file inside the HTML file, the HTML outputs a blank page.
The expected output is a page that lists every even number between 2 and 101.

A: The document.write line has a syntax error at
 - notice the quotation mark being on the left of > rather than on the right?

As for JS being directly within HTML as opposed to an external file you can include any JS within HTML by wrapping it in  while when including an external JS file you need to use . In your specific case if you want to use the external file, make sure that whileLoop.js is in the same directory as your index.html and then include it as per the snippet below:
Here is your code working with the script being within HTML and another file included in the  part of your HTML. Please note that the script included in  had no effect and I added that line just to show you the two ways of having JS work within your code.

<title>JS Assignment</title>

A: you could change the markup and html to the following. I hope it works for you too:
JS: while.js
function evenCount() {
    console.log(loopCount);
    var loopCount = 2;
    while (loopCount <= 101) {
        document.write(loopCount + " is an even number.
");
        loopCount = (loopCount + 2);
    }
}

evenCount();

HTML:
<!DOCTYPE html>

    <title>JS Assignment</title>

Basically you had unclosed tags and it was an incompletely rendered DOM you were writing into. This created an unbalanced tree error. Also, you JS was not being called (earlier). It has to be called if you wrap your code within a function.
(PS: please note the JS filename change)


text:
Q: How can I passing value into the JavaScript function in asp:LinkButton OnClientClick? Does anyone know how can I passing value into the javascript function in asp:LinkButton OnClientClick?
Example:
If I have the following code:
  <asp:ListView ID="lvTeams" runat="server" DataSourceID="dsTeams" DataKeyNames="ReferenceValue"
    OnItemCommand="lvTeams_ItemCommand">
    <LayoutTemplate>

        <asp:PlaceHolder ID="itemPlaceholder" runat="server" />

    </LayoutTemplate>
    <ItemTemplate>

        <asp:LinkButton runat="server" OnClientClick="return multipleTeamsAllowedValidation()" CausesValidation="true" CommandName="" CssClass="orange"
          Text='<%# Eval("TeamName")%>' />

    </ItemTemplate>
  </asp:ListView>

How can I pass the value <%# Eval("ReferenceValue")%> into the JavaScript function multipleTeamsAllowedValidation()in the asp:LinkButton OnClientClick event??

A: You can try
onclick= 'multipleTeamsAllowedValidation(<%# Eval("SHOW_Name") %>);'

or
You can try out this.Value or this.InnerText to pass the value to html function
<asp:LinkButton runat="server" OnClientClick="return
multipleTeamsAllowedValidation(this.InnerText)" CausesValidation="true" CommandName=""
CssClass="orange" Text='<%# Eval("TeamName")%>' />

or
you can pass object itself by passing this
OnClientClick="return multipleTeamsAllowedValidation(this)"

than you can able to access the text of it easily and than do the perform operation.
in function do  document.getElementById(this.Id).innerText or this.innerText

A: IMHO, its a lot better to write a small helper.
Markup.
OnClientClick='<%# SetClientClick(Eval("ReferenceValue")) %>'>

Code-behind
protected string SetClientClick(object objName)
{
    return String.Format("javascript:return multipleTeamsAllowedValidation('{0}');", objName.ToString());
}

A: There is a another easy way,
 <asp:LinkButton ID="lnkRecord" Text="Click" runat="server" OnClientClick='<%# Eval("TeamName","javascript:return multipleTeamsAllowedValidation({0});") %>'></asp:LinkButton>

You can also hit the link below-
https://snavin.wordpress.com/2011/02/02/pass-eval-value-in-javascript-function-from-gridview/
I hope this would've you.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Display data in a list view from a mysql db I have an Android app that shows me a map, my location and several bus station markers. I want to be able to display the schedule of selected buses from the selected marker "station" in a list view.

Any idea on how to do that? I also need a PHP script for that if you could help me.
Below is my MapActivity:
import android.content.pm.PackageManager;
import android.location.Location;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.widget.Toast;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.CameraPosition;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

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

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

public class MapsActivity extends FragmentActivity implements OnMapReadyCallback, GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener {

    String JSON_STRING;
    HttpURLConnection urlConnection = null;
    private GoogleMap mMap;
    GoogleApiClient mGoogleApiClient;
    LatLng mLatLng;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps);
        // Obtain the SupportMapFragment and get notified when the map is ready to be used.
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);
        new MarkerTask().execute();

    }

    @Override
    public void onMapReady(GoogleMap googleMap) {
        mMap = googleMap;
        mMap.getUiSettings().isCompassEnabled();
        mMap.getUiSettings().setZoomControlsEnabled(true);
        mMap.getUiSettings().setScrollGesturesEnabled(true);
        mMap.getUiSettings().setMapToolbarEnabled(false);

        if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
                && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)
        {
            return;
        }
        mMap.setMyLocationEnabled(true);

        buildGoogleApiClient();

        mGoogleApiClient.connect();

    }

    protected synchronized void buildGoogleApiClient() {
       // Toast.makeText(this, "buildGoogleApiClient", Toast.LENGTH_SHORT).show();
        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build();
    }

    @Override
    public void onConnected(@Nullable Bundle bundle) {
        Toast.makeText(this, "onConnected", Toast.LENGTH_SHORT).show();
        if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            // TODO: Consider calling
            //    ActivityCompat#requestPermissions
            // here to request the missing permissions, and then overriding
            //   public void onRequestPermissionsResult(int requestCode, String[] permissions,
            //                                          int[] grantResults)
            // to handle the case where the user grants the permission. See the documentation
            // for ActivityCompat#requestPermissions for more details.
            return;
        }
        Location mLastLocation = LocationServices.FusedLocationApi.getLastLocation(
                mGoogleApiClient);
        if (mLastLocation != null) {

            mLatLng = new LatLng(mLastLocation.getLatitude(), mLastLocation.getLongitude());
            CameraPosition cameraPosition = new CameraPosition.Builder()
                    .target(mLatLng)
                    .zoom(18)
                    .tilt(75)
                    .bearing(20)
                    .build();
            mMap.animateCamera(CameraUpdateFactory
                    .newCameraPosition(cameraPosition));

        }

    }

    @Override
    public void onConnectionSuspended(int i) {
        Toast.makeText(this,"onConnectionSuspended",Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
        Toast.makeText(this,"onConnectionFailed",Toast.LENGTH_SHORT).show();

    }

    class MarkerTask extends AsyncTask<Void, Void, String> {

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
        }

        @Override
        protected String doInBackground(Void... voids) {
            try {
                URL url = new URL("http://some address.php");
                urlConnection = (HttpURLConnection) url.openConnection();
                InputStream inputStream = urlConnection.getInputStream();
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
                StringBuilder stringBuilder = new StringBuilder();
                while ((JSON_STRING = bufferedReader.readLine()) != null) {

                    stringBuilder.append(JSON_STRING + "\n");
                }

                bufferedReader.close();
                inputStream.close();
                urlConnection.disconnect();
                return stringBuilder.toString().trim();

            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

            return null;

        }
            // Executed after the complete execution of doInBackground() method
            @Override
            protected void onPostExecute (String result){

                JSONObject jsonObj = null;
                JSONArray jsonArray = null;
                try {
                    jsonArray = new JSONArray(result);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                for (int i = 0; i < jsonArray.length(); i++) {
                    try {
                        jsonObj = jsonArray.getJSONObject(i);
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    LatLng latLng = null;
                    try {
                        latLng = new LatLng(jsonObj.getJSONArray("latlng").getDouble(0),
                                jsonObj.getJSONArray("latlng").getDouble(1));
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                    // Create a marker for each station in the JSON data.
                    try {
                        mMap.addMarker(new MarkerOptions()
                                .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_BLUE))
                                .title(jsonObj.getString("name"))
                                .position(latLng));
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
}

I want to mention that I have a MySQL database with three tables:

*

*Station

*

*station_id

*name

*lat

*lng

*Bus

*

*bus_id

*bus_no

*Schedule

*

*bus_id

*station_id

*hour

Thank you for your help!

A: I think your question is not as specific it should be. Maybe this tutorial will help you with the map.
http://www.tutorialspoint.com/android/android_google_maps.htm
Regarding the way to show the schedules, maybe you can use a custom marker popup in the map such as the MarkerOptions and display them in the title, snippet and also add an icon :
Marker TP = googleMap.addMarker(new MarkerOptions().
         position(customPos)
         .title("Sydney")
         .snippet("Population: 4,627,300")
        .icon(BitmapDescriptorFactory.fromResource(R.drawable.arrow))));

See the reference here:
https://developers.google.com/android/reference/com/google/android/gms/maps/model/MarkerOptions#public-method-summary


text:
Q: UI won't load until click I've recently launched my Xamarin app on iOS for the first time. The app works perfectly on Android. However, on iOS the UI won't load fully until I touch the screen. This is related to binding and ui elements which are being created dynamically. For example, this button:
<local:MainMenuButton Command="{Binding NavigateCommand}" CommandParameter="{Type local:page2}" CornerRadiusExtended="{Binding LeftCornersRounded}" Grid.Row="0" Grid.Column="0" HeightRequest="{Binding Width, Source={x:Reference ModelButton}}"/>

won't change it's height to ModelButton's height. Also, ImageButtons are completely invisible (the image is not being loaded). Everything starts working after I click the screen. Does someone know what's going on?
[EDIT]: This applies even to controls I don't reference in code to. For example:
<ImageButton Style="{StaticResource UiButton}" Grid.Row="0" Grid.Column="0" Command="{Binding SetLanguageCommand}" CommandParameter="EN" Source="{helpers:ImageResourceExtension imagesource.png}"/>

// Extension code

[ContentProperty("Source")]
public class ImageResourceExtension : IMarkupExtension
{
    public string Source { get; set; }

    public object ProvideValue(IServiceProvider serviceProvider)
    {
        if (Source == null)
            return null;

        var imageSource = ImageSource.FromResource(Source);

        return imageSource;
    }
}

The ImageButton won't load it's source until click. If I remove binding and directly enter the source, everything works fine.
I used debugger to check whether the extension code executes at page launch or after click, and it turned out that it runs at launch. For some reason though, the image is still being displayed after click.

A: I've received a reply from Microsoft Support. They found the root of the issue. It was a NuGet package called Forms9Patch which caused the problem (https://baskren.github.io/Forms9Patch/). It's unclear how it could affect the rendering, but removing the package from the project resolved the issue. I'll contact the package owner with this.


text:
Q: Is L'Hopital a good idea in this case?
Find $a$ and $b$ so that function $f$ is continuous.
\begin{eqnarray*}
f(x)=\left\{\begin{array}{lcc}
 \frac{\sin(3x)(e^{ax}-1)}{2x^3} &:&x<0 \\
ax^2+3x+b &:& 0\le x <1\\
\frac{\tan^2(x-1)}{(x-1)^2} &:&x\ge1
\end{array}
\right.
\end{eqnarray*}

Well, I've been thinking on this and no way except L'Hôpital's rule has come to my mind, and this way takes a while to solve. Is there any better way?

A: Hints:
Knowing
$$\lim_{x\to0}\frac{\sin x}{x}=\lim_{x\to0}\cos x\frac{\tan x}{x}=1,$$
$$\lim_{x\to0}\frac{e^x-1}x=1,$$
L'Hospital is unnecessary.

A: Hints:
$$
\lim_{x\to0^-}\frac{\sin(3x)}{x}\frac{e^{ax}-1}{x}
$$
is finite. But you still have another $x$ at the denominator, so the limit is infinite unless…
$$
\lim_{x\to1^+}\frac{\tan(x-1)}{x-1}=
\lim_{t\to0^+}\frac{\tan t}{t}=…
$$


text:
Q: Click event on DIV triggered while pointer event is captured by another element in Firefox I have the following fiddle: https://jsfiddle.net/PieterJanVR/b39u4cgr/3/
class SliderAppComponent extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      buttonToggle: false
    }

    this.clicked = (e) => {
      this.setState({
        ...this.state,
        buttonToggle: !this.state.buttonToggle
      });
    };

    this.isPointerDown = false;
    this.onPointerDown = (e) => {
        const currentTarget = e.currentTarget;
        currentTarget.setPointerCapture(e.pointerId);
        this.isPointerDown = true;
    };

    this.onPointerMove = (e) => {
    if (!this.isPointerDown) return;
        const currentTarget = e.currentTarget;
        currentTarget.style.transform = `translate(${e.clientX - 70}px)`;
    };

    this.onPointerUp = (e) => {
        const currentTarget = e.currentTarget;
        this.isPointerDown = false;
        currentTarget.releasePointerCapture(e.pointerId);
    };
  }

  render() {
    return (
      <React.Fragment>

             SLIDE ME

        <button
          style={{backgroundColor: this.state.buttonToggle ? "#00feb0" : "#00b0fe"}}
          onClick={this.clicked}>
        A button with a click event!
        </button>

        A div with a click event!

      </React.Fragment>
    )
  }
}

It displays a 'slide me' div, which slides when dragged and 2 click elements: a button, and a div.
In Chrome, when you click the "slide me", drag the mouse over the 2 click elements and release: nothing happens ✔.
When you do the same in Firefox, the clickable button doesn't get clicked, but the clickable div does ❌!
Is this a bug in Firefox?

Explanation of the example:
The "slide me" div captures the Pointer events on pointer down, and releases the capture again when the pointer goes up. The two clickable elements just have a plain 'onClick' listener which makes the background change color.
Some literature:
The only reference I could find is this github issue of W3C pointer events: https://github.com/w3c/pointerevents/issues/75. Saying

We talked about this issue and we all agreed to stick to sending click to the first common ancestor of pointerdown and pointerup targets

In my example that should ONLY trigger a click on the app element. Which is does in Chrome, but in Firefox it triggers the click on the ancestor AND the clickable div.


text:
Q: Graph theory: Best scalable solution when working with many vertexes I've got a graph were each vertex represents a city.  (identified by lat, lng properties) In between the vertexes (cities) are weighted edges, these represent predefined routes in between the cities.  In between some vertexes we have multiple edges (eg. shortest and fastest route).
I already defined 10K+ vertexes and potentially more will be added in the future.
Vertexes and edges won't change often once they're defined.
Users need to be able to calculate the shortest route in between any 2 of the vertexes.
I'm now considering which "shortest path algorithm" would work best for me.
2 possible solutions came to mind:

*

*Floyd's algorithm where I would store the resulting tables.  Pro:
Fast response times. CON: Takes a lot of memory when loaded in
memory, don't even know if this would be reasonable as a cost.

*A* algorithm where I would create a subset of relevant vertexes before I start the algorithm.  Example: user chooses vertex A & F.  I check how far A & F are apart based on Lat, Lng properties.  I add this distance on all sides of both A & F vertexes and identify all vertexes in this area. I do the algorithm with this subset of vertexes.

I'm looking for some advice on what would be the best solution.  My preference goes to 1).  If somebody did this before and could give some insight on the required infrastructure this would certainly help me.


text:
Q: Colors less saturated in Snow Leopard Finder, Preview & Safari than in Chrome -- why? If I look at the picture here in Safari, Preview or the finder, the shades of blue are significantly different than if I look at the picture in Google Chrome (they are less saturated than in Chrome).

Since I am a photographer and need to prepare pictures for publication online, I need to know what a jpeg should really look like, in order to color-correct it.
I have an excellent Eizo monitor that is correctly calibrated.
If I open the same image in Photoshop CS3, I get the Chrome colors if I use Monitor RGB under view >> proof setup, and I get the Safari colors if I use Macintosh RGB.
Can anyone explain the difference between these two settings, and the difference between Safari and Chrome? Which colors are correct?
Photos that I prepared under Windows (during the past five years) now seem washed out in the Apple Finder and Preview, even though I had correctly prepared them.
Is there a setting on the Macintosh for color calibration, besides the monitor calibration control panel?

A: You're seeing issues with color management, which not all browser support properly. See, for example, here.
Your test image has the same colors in Chrome and Safari on my Mac though.

A: I'll answer myself, but I'm still open to new information if anyone wants to chime in.
The answer is simply that Apple software (and Photoshop) uses any color profile included with JPG images whereas Chrome and probably most other consumer software packages does not.
My camera was saving pictures with a color profile that caused the images to appear washed out when viewed in the expected color space.
The answer as to which is correct is that the Safari / Macintosh RGB colors are correct -- they reflect a correct handling of the image file and its accompanying color profile.
The results in Chrome are wrong -- the browser can't handle color profiles correctly.


text:
Q: How to convert Mysql query to Hive I have this table:
CREATE TABLE ip_logs (
  `ip_address` VARCHAR(11),
  `start_date` VARCHAR(11),
  `end_date` VARCHAR(11),
  `loc_id` INTEGER
);

INSERT INTO ip_logs
  (`ip_address`,`start_date`,`end_date`, `loc_id`)
VALUES
 ('120.0.53.21','2020-01-03','2020-01-09', '5'),
 ('198.5.273.2','2020-01-10','2020-01-14', '4'),
 ('198.5.273.2','2020-01-10','2020-01-14', '4'),
 ('198.5.273.2','2020-01-10','2020-01-14', '4'),
 ('100.36.33.1','2020-02-01','2020-02-02', '4'),
 ('100.36.33.1','2020-02-01','2020-02-02', '4'),
 ('100.36.33.1','2020-02-01','2020-02-02', '4'),
 ('198.0.47.33','2020-02-22','2020-02-24', '2'),
 ('122.8.0.11', '2020-02-25','2020-02-30','4'),
 ('198.0.47.33','2020-03-10','2020-03-17', '2'),
 ('198.0.47.33','2020-03-10','2020-03-17', '2'),
 ('122.8.0.11', '2020-03-18','2020-03-23','4'),
 ('198.5.273.2','2020-03-04','2020-03-09', '3'),
 ('106.25.12.2','2020-03-24','2020-03-30', '1');

I use this query to select the most frequent ip address:
select  (
select ip_address
from ip_logs t2
where t2.loc_id = t1.loc_id
group by ip_address
order by count(*) desc
limit 1)

from ip_logs t1
group by loc_id

This works in mysql8.0. This however does not work in Hive as well. I get this error:
cannot recognize input near 'select' 'ip_address' 'from' in expression specification
Expected output is:
loc_id | ip_address
5        120.0.53.21
4        198.5.273.2
2        198.0.47.33
3        198.5.273.2
1        106.25.12.2

A: You can try using row_number() window function
select * from
(
select ip_address,loc_id,count(*) as frequency
row_number() over(partition by loc_id order by count(*) desc) as rn
from ip_logs group by ip_address,loc_id
)A where rn=1


text:
Q: Passing Scope Through $(document).ready Can someone explain to me why this doesn't work and show me how to make it work? I've tried creating a namespace and IIFEs functions but I cannot seem to get it.
$(document).ready(function() {
  alert (hi);
});

$(document).ready(function() {
  var hi = "hello"
});

Thank You!

A: When you do this:
$(document).ready(function() {
  var hi = "hello"
});

You are creating a variable named hi that is local to that callback function.  It is simply not accessible outside that function.  This is a feature of the language.
You can declare the variable at a higher scope like this:
var hi;
$(document).ready(function() {
  hi = "hello"
});

And, then the value of that variable will be available outside the scope, but you will not necessarily know when it gets the proper value because you won't know when the $(document).ready() callback is called unless you put your code inside that callback.

It really makes little sense to try to share a variable between two calls to $(document).ready().  It would make much more sense to just put the code inside the same $(document).ready() callback:
$(document).ready(function() {
  var hi = "hello"
  alert (hi);
});

Not Really Recommended
If you were going to try to share a variable between two calls to $(document).ready() (something I don't really recommend because it makes your code somewhat fragile), it can be done.  Callbacks to $(document).ready() will be called in the order they are attached so you will have to order things appropriately:
var hi;
$(document).ready(function() {
  hi = "hello"
});

$(document).ready(function() {
  alert (hi);
});

This will make sure that the first $(document).ready() callback that sets the value of hi will be called first before the second one where you try to use the value.


text:
Q: NodeJS/Javascript function returning undefined I'm writing a basic web app in Node, Express and MySQL. Its just a basic site, where a user can create an account, view other peoples accounts, and post infomation on their profile, and I'm creating it to learn Node and javascript.
So, I'm up to creating the userlist, and I've created a nice function that returns all the users in the database. Here is the code:
function getAllUsers() {
    var query = " \
    SELECT \
      id, username, email, password \
    FROM \
      users \
    ";
    connection.query(query, function(err, rows) {
        if (err) throw err;
        return rows;
    });
}

Now, I'm using this function here:
router.get('/list', function(req, res) {
    var users;
    users = getAllUsers();
    res.render('user/list', {'title': 'Users', 'users': users});
});

But users is undefined. Why is this?
I'm pretty sure the MySQL connection is working properly, but here is how I connect it, just in case it comes in handy:
var connection = mysql.createConnection({
    host: 'localhost',
    user: 'root',
    password: 'password',
    database: 'firstnodeapp'
});

connection.connect();

Thanks
--- EDIT ---
I thought I should also mention, rows is defined in the getAllUsers() function, but once I return it it is no longer defined.

A: Callbacks to the rescue (the most simple answer)
Your query is executing asynchronous, that means, when the function ends the query is still executing and your "users" variable ends being undefined.
Just do this:
function getAllUsers(callback) {
    var query = " \
    SELECT \
      id, username, email, password \
    FROM \
      users \
    ";
    connection.query(query, callback);
}

router.get('/list', function(req, res) {
    getAllUsers(function(err, rows) {
          // Or better yet, respond with the correct html code
          if (err) throw err;

          res.render('user/list', {'title': 'Users', 'users': rows});
    });
});

It should work pretty well. Study about Callbacks/Promises/Observables

A: Didn't you forget to return?
function getAllUsers() {
  ...

  var query_result = connection.query(query, function(err, rows) {
    if (err) throw err;
    return rows;
  });

  return query_result;
}


text:
Q: Template function that can take lambda or function pointer and deduce arguments for passing to another template I maintain an open-source lockless threading library designed for high speed parallel loop unrolling which is used in a couple commercial video games. It has incredibly low-overhead, around 8 clocks for creating a message and around 500 (per thread, including latency) for the entire dispatch and remote execute overhead. I say this first to explain why I don't simply use use std::function and bind.
The library packages a function call and the arguments to the function call in a message (of type Functor<>). Then calls it remotely with copies of the arguments.
I have recently rewritten the library to package remote calls using STL style template meta programming rather than the dated C style macros it originally used. Amazingly this only increased the overhead by two ticks but I cannot figure out how to create a packaging function that takes both lambdas and function pointers.
Desired Usage:
CreateFunctor([](int a, int b){doSomething(a, b)}, 1, 2);

or
CreateFunctor(&doSomething, 1, 2);

Currently I have to divide these cases into two separate functions, (CreateFunctor and CreateFunctorLambda). If I could combine them I would be able to merge my packaging and dispatching stages into one neat function call and simplify the API.
The problem is that the code for deducing the arguments of a lambda cannot seem to share a template override with the code for deducing the arguments of a function. I've tried using enable_if and it still executes the ::* portion of the lambda version and causes compiler errors with function pointers.
Relevant Snippet:
template <typename... Arguments>
inline Functor<Arguments...> CreateFunctor(void(*func)(Arguments...))
{
    return Functor<Arguments...>(func);
};

template <typename... Arguments>
inline Functor<Arguments...> CreateFunctor(void(*func)(Arguments...), Arguments ... arg)
{
    Functor<Arguments...> ret(func);
    ret.Set(arg...);
    return ret;
};

// template to grab function type that lambda can be cast to
// from http://stackoverflow.com/questions/7943525/is-it-possible-to-figure-out-the-parameter-type-and-return-type-of-a-lambda
template <class T>
struct deduce_lambda_arguments
    : public deduce_lambda_arguments<typename std::enable_if<std::is_class<T>::value, decltype(&T::operator())>::type>
{};

template <class ClassType, typename... Args>
struct deduce_lambda_arguments<void(ClassType::*)(Args...) const>
    // we specialize for pointers to member function
{
    typedef void(*pointer_cast_type)(Args...);
    typedef Functor<Args...> functor_type;
};

template <typename F, typename... Args>
inline auto CreateFunctorLambda(F f, Args... arg) -> typename deduce_lambda_arguments<F>::functor_type
{
    deduce_lambda_arguments<F>::functor_type ret((deduce_lambda_arguments<F>::pointer_cast_type) f);
    ret.Set(arg...);
    return ret;
};

template <typename F>
inline auto CreateFunctorLambda(F f) -> typename deduce_lambda_arguments<F>::functor_type
{
    return deduce_lambda_arguments<F>::functor_type((deduce_lambda_arguments<F>::pointer_cast_type) f);
};

A: The trick is to ensure that you never evaluate &T::operator() for things-that-you-want-to-support-but-are-not-lambdas. One way to do this is adding an extra template parameter and specializing on that:
template <class T, bool = std::is_class<T>::value>
struct compute_functor_type
    : public compute_functor_type<decltype(&T::operator())>
{};

template <class ClassType, typename... Args>
struct compute_functor_type<void(ClassType::*)(Args...) const, false>
{
    typedef void(*pointer_cast_type)(Args...);
    typedef Functor<Args...> functor_type;
};

template <class ClassType, typename... Args>
struct compute_functor_type<void(ClassType::*)(Args...), false>
{
    typedef void(*pointer_cast_type)(Args...);
    typedef Functor<Args...> functor_type;
};

template <typename... Args>
struct compute_functor_type<void(*)(Args...), false>
{
    typedef void(*pointer_cast_type)(Args...);
    typedef Functor<Args...> functor_type;
};

template <typename F, typename... Args>
inline auto CreateFunctor(F f, Args... arg)
         -> typename compute_functor_type<F>::functor_type
{
    typename compute_functor_type<F>::functor_type ret((typename compute_functor_type<F>::pointer_cast_type) f);
    ret.Set(arg...);
    return ret;
};

template <typename F>
inline auto CreateFunctor(F f) -> typename compute_functor_type<F>::functor_type
{
    return typename compute_functor_type<F>::functor_type((typename compute_functor_type<F>::pointer_cast_type) f);
};

Saving the (way shorter) original approach here for people who don't have to use MSVC:
Since you only care about captureless non-generic lambdas and convert them to function pointers anyway, this is easy.
Create a matching Functor type from a function pointer:
template<class... Args>
Functor<Args...> make_functor(void (*f)(Args...)) { return {f}; }

And force conversion to function pointer via the unary + operator:
template <class F>
inline auto CreateFunctor(F f) -> decltype(make_functor(+f))
{
    return make_functor(+f);
}

template <class F, typename... Arguments>
inline auto CreateFunctor(F f, Arguments ... arg) -> decltype(make_functor(+f))
{
    auto ret = make_functor(+f);
    ret.Set(arg...);
    return ret;
}


text:
Q: Calculus of Variation of Parameters. I come across these 2 problems in my self very first study to calculus of variation of parameters and I faced two problems. I solved the fist one, I hope my solution is right, but I do not know how to attack the second one which is somehow similar to the problem in the following link;
Why $\frac{d}{dx}f_\xi=f_u$ and $f(b,\bar u(b), \bar u'(b))=0$.
Problem one
For the functional
$$J[u] = \int_0^1 (2 x u(x) - (u'(x))^2 + 3 u'(x) (u(x)^2))\,dx,$$
find all the $C^1 ([0,1])$ stationary curves (i.e solutions of Euler-Lagrange equation) satisfying the boundary conditions $u(0)=0, u(1)=\frac{1}{3}.$
My solution
Let $F(u)= 2 x u - (u')^2 + 3 u' u^2.$ Finding the followings
$$\frac{\partial F}{\partial u} = 2 x + 6u u'.$$
$$\frac{\partial F}{\partial u'} = -2 u' + 3 u^2$$
Now we plug the above two equations into Euler-Lagrange equation
\begin{align*}
    \frac{\partial F}{\partial u} - \frac{d}{dx} \left( \frac{\partial F}{\partial u'} \right)&=0,\\
    2x + 6 u u' + 2u''-6uu'&=0.
\end{align*}
Thus we have
$$u''(x) =-x \Rightarrow u'(x) = -\frac{1}{2}x^2 + c_1 \Rightarrow u(x) = -\frac{1}{6} x^3 + c_1 x + c_2.$$
From $u(0)=0$ we have $c_2 =0$ and from $u(1)= \frac{1}{ 3}$ we have
$$\frac{1}{3} = u(1) = - \frac{1}{6} + c_1 \Rightarrow c_1 =\frac{1}{3}.$$
Then the curve is;
$$u(x) = \frac{x}{3}-\frac{x^3}{6}.$$
Problem two
For $f \in C^2 ([a,b] \times \mathbb{R} \times \mathbb{R})$ we consider the minimization problem
$$\inf_{u \in X}J[u],\,\, J[u] = \int_a^b f(x,u(x),u'(x)) dx,\,\,\, X=\{ u \in C^1([a,b]); u(a)=\alpha \}.$$
Assume that a minimizer $\overline{u} \in C^2([a,b]) \cap X$ attaining the infimum of the problem exists, find the condition that the minimizer $\overline{u}$ fulfills at the right endpoint $x=b$ of the interval $[a,b]$ (i.e. find the relation satisfied by $\overline{u}(b)$, $\overline{u}'(b)$).

A: The answer to problem 2 is that one must impose either

*

*Essential/Dirichlet BC: $~~u(b)~=~\beta,$
or

*Natural BC: $~~\left.\frac{\partial f}{\partial u^{\prime}}\right|_{x=b}~=~0,$
cf. e.g. my Math.SE answer here and links therein.


text:
Q: same code but different results using gin + go-template Basic information

*

*Go version: go1.4.2 darwin/amd64

*Operating System: Mac OS X 10.10.5

I'm working on a small Web project written based on go and gin. Here is my golang code. After running go run test.go we have a web server, which is listening on 8089.
Golang test.go
package main

import "github.com/gin-gonic/gin"
import "net/http"

func main() {
    router := gin.Default()
    router.LoadHTMLGlob("templates/*")
    router.GET("/index", func(c *gin.Context) {
        c.HTML(http.StatusOK, "index.html", gin.H{
            "scheme": "http",
            "domain": "meican.loc",
        })
    })
    router.Run(":8089") // listen and serve on 0.0.0.0:8089
}

The html code generated in back-end should contain a template used by front-end javascript engine (Let's say Angular.js).
So the template code is in script tag, just like this:
Part of templates/index.html

When {{.domain}} is used at the second time, I got different result. I refreshed the browser and checked out the source code. Then I got this:
Browser source code result

The second div has 2 extra double quotes.
Why this happens? And how to resolve this problem?

A: This is a bug in Go, and has been slated to be fixed in 1.7 as of March 2016 (Also partially addressed in 1.6)


text:
Q: Java generics: the type parameter T is hiding the type T Why java compiler is giving me "the type parameter T is hiding the type T" in the "translate" method ?
public static interface Translator<T, E> {
  E call(T t);
}

public static <T, E> List<E> translate(List<T> l, Translator<T, E> t) {
  ..
}

If i remove the type parameter T
public static <E> List<E> translate(List<T> l, Translator<T, E> t)

the warning disappeared but now i cannot do
List<Long> l = new ArrayList<>();
List<String> r = translate(l, new Translator<Long, String>() { .. })

cause it give me this error
The method translate(List<T>, GFn.Translator<T,E>)
in the type GList is not applicable for the arguments
(List<Long>, new GFn.Translator<Long,String>(){})

A: I'm using the following code and don't get any warning messages:
public class Main {

public static interface Translator<T, E> {
    E call(T t);
}

public static <T, E> List<E> translate(List<T> l, Translator<T, E> t) {
    List<E> result = new ArrayList<E>();
    for (T item: l) {
        result.add(t.call(item));
    }
    return result;
}

public static class TranslatorImpl implements Translator<Long, String> {

    @Override
    public String call(Long aLong) {
        return String.valueOf(aLong);
    }
}

public static void main(String[] args) throws IOException {
    List<Long> items = new ArrayList<Long>();
    items.add(10L);
    items.add(20L);
    items.add(30L);
    System.out.println(translate(items, new TranslatorImpl()));
}

}

A: I used JDK 1.7 and the following code just works:
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

interface Translator<T, E>
{
    E call(T t);

}

class LongToStringTranslator implements Translator<Long, String>
{

    @Override
    public String call(Long t)
    {
        return t.toString();
    }

}

public class Main
{
    public static <T, E> List<E> translate(List<T> l, Translator<T, E> t)
    {
        List<E> e = new ArrayList<>();
        for (T item : l) {
            e.add(t.call(item));
        }
        return e;
    }

    public static void main(String[] args)
    {
        List<Long> l = Arrays.asList(1L, 2L);
        List<String> s = translate(l, new LongToStringTranslator());
        System.out.println(s);
    }
}

A: Sorry but was a mistake of mine, the problem was in a function after that one that was wrong:
public static void walk(Iterable<T> list, Walker<T> walker)

This mas missing the T type parameter, if i correct it
public static <T> void walk(Iterable<T> list, Walker<T> walker)

All the warnings disappears in all other methods in my class.
Thanks and sorry to all.


text:
Q: Проблема с подключением PDO Добрый день! Перехожу на PDO, столкнулся со странной ситуацией, есть скрипт следующего вида:
include 'db.php';
function addGroup($group_name){

$stmt=$pdo->prepare('INSERT INTO group_back SET name_group=? ');
$stmt=$pdo->execute(array($group_name));

}

При обращении к функции addGroup сыпится ошибка:
Undefined variable:pdo

Вот содержимое db.php
$host = '*****';
$db   = '*****';
$user = '*****';
$pass = '*****';
$charset = 'utf8';

$dsn = "mysql:host=$host;dbname=$db;charset=$charset";
$opt = [
    PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
    PDO::ATTR_EMULATE_PREPARES   => false,
];
$pdo = new PDO($dsn, $user, $pass, $opt);

сам скрипт db.php отрабатывает( проверил банальным запросом к таблице и выводом результата запроса ).
Я так понимаю по какой-то причине php не получает переменную при инициализаци
скрипта db.php...

A: Нужно передать переменную $pdo как аргумент функции или сделать её глобальной с помощью global.
function addGroup($pdo, $group_name){
    $stmt=$pdo->prepare('INSERT INTO group_back SET name_group=? ');
    $stmt=$pdo->execute(array($group_name));
}

Вызывать функцию так:
addGroup($pdo, $group_name);

Область видимости переменной


text:
Q: How can I unit test a class which requires a web service call? I'm trying to test a class which calls some Hadoop web services. The code is pretty much of the form:
method() {
    ...use Jersey client to create WebResource...
    ...make request...
    ...do something with response...
}

e.g. there is a create directory method, a create folder method etc.
Given that the code is dealing with an external web service that I don't have control over, how can I unit test this? I could try and mock the web service client/responses but that breaks the guideline I've seen a lot recently: "Don't mock objects you don't own". I could set up a dummy web service implementation - would that still constitute a "unit test" or would it then be an integration test? Is it just not possible to unit test at this low a level - how would a TDD practitioner go about this?

A: I disagree with "don't mock objects that you don't own" when your are unit testing.
Mocks purpose of existence is the fact that there will be modules, libraries, classes we will not own.
My suggestion for your scenario is mock the web service call.
Setup the mock in such a way that it returns data back to your module.
Make sure you cover all scenario eg when the data returned back is null, when the data returned back is valid etc.
And for the code that you own, your responsibility as a developer is to ensure that the code you are authoring performs as expected in all scenarios.

A: In my opinion you should mock the webservice calls if this is a unit test, as opposed to an integration test.
Your unit test should not test whether the external webservice is working, or whether your integration with it is correct. Without getting too dogmatic about TDD, note that a side effect of turning your unit test into an integration test is that it's likely to run slower, and you want fast unit tests.
Also, if the webservice is temporarily down or working incorrectly, should this cause your unit test to fail? It doesn't seem right. Your unit test should fail for only one reason: if there is a bug in the code in that "unit".
The only portion of code that is relevant here is ...do something with response.... Mock the rest.

A: I would use something like EasyMock for this test. Mocking frameworks are an ideal way to remove outside dependencies on a class and gives you total control over the result of outside dependencies during tests. To extend your example a little:
class WebClass {

private WebServiceInterface webserviceInterface;

    void method(){
        R result = webServiceInterface.performWebServiceCall();
        ... do something with result
    }

    public void setWebServiceInterface(WebServiceInterface webServiceInterface){
        this.webServiceInterface = webServiceInterface;
    }
}

interface WebServiceInterface {

   R performWebServiceCall();

}

class WebClassTest {

private WebServiceInterface mock;
private R sampleResult = new R();

    @Before
    public void before(){
        mock = EasyMock.createMock(WebServiceInterface.class);
    }

    @Test
    public void test() {
        WebClass classUnderTest = new WebClass();
        EasyMock.expect(mock.performWebServiceCall()).andReturn(sampleResult);
        classUnderTest.setWebServiceInterface(mock);
        classUnderTest.method();
        EasyMock.verify(mock);
    }
}

The first thing you'll need to do is extract the logic in your class where you use Jersey to get a WebResource and call the web service into a separate class. Creating an Interface for this class will allow you to create a mock to which you can then dictate behaviour.
Once this interface is created, you can create a mock using EasyMock, which will return a specified object accoring to your test case. The example above is a simplification of how to structure a basic mocked test and how your interface will work.
For more information on mocking frameworks, please see this question. Also, this example assumes the use of Java but mocking frameworks are available in all languages and although they be implemented differently, they will work in generally the same way

A: Mocks are acceptable in this case, but you don't need it. Instead of unit testing method(), instead unit test just the portion that handles the response.
Extract a function that takes ResponseData (of whatever kind is appropriate) and then performs the action.
Instead of mocking, now you just construct a ResponseData object and pass it in.
You can leave the calling of the service to full integration tests - that will cover method() in total

A: What I've done, and it works:

*

*Have all code call webservices through proxy.

*The proxy calls a class that statically knows if we are using proxy or not and redirects accordingly. Mocks are just HashMaps that for each request returns a given reply.

*Run the tests several times in this order:

3.1 First all webservices are tested. From each machine, even developer's machines. These are the real webservices, but running in development envioronment. This means webservices can never be down or reply erroneous values, because otherwise every developer complains that he can't compile.
3.2 Then all unit tests internal to the application are run. This means that all webservices are mocked and tested runnning the same tests as 3.1 (anbde they should pass too, otherwise out mocks are wrong), and being invoked by the real application as if they were really being used. If the mocks are wrong, you can run the test in 3.1 and record those (request, reply) values in a HashMap.
3.3 Then the same tests as 3.2 are run, but this time against the real webservices running in the development environment.
After all these has been completed, for the real production environment you just need to provide the real address for each webservice. Hopefully this doesn't require too much change in the configuration.


text:
Q: what kind of locks are applied by Azure Synapse when loading data using COPY INTO what kind of locks are applied by Azure Synapse when loading data using COPY INTO, if we are running extract from synapse dw (say from table A) and simultaneously loading new data into a some other (say table B). Will it cause any locks, will we face slowness or any locks while extracting data from table A

A: There's a shared update lock on the table during write, and your select is blocked for the duration of the COPY INTO.


text:
Q: ssh behavior for root and non-root user When I ssh as root to a remote machine, the command output looks like this:
root@Machine:/current/path#:

However, if it's a non-root user, all I see is:
$

How can I get the same behavior as for the root user? Why is it different?

A: The "command output" that you referred to is called "the prompt". At the end of the prompt usually there is a character (in bash usually # or $) to indicate the end of the prompt and the start of user input. It is different so that you know if you are the root user or not. Generally when you see a # at the end of you prompt you know that you are root and should be careful with your commands.
Controlling the prompt depends on the shell that you use. For bash you use the environment variable PS1 to do so. For example if you run:
export PS1='\u@\h \w \$ '

Your next prompt will change to something like:
phunehehe@workstation ~/Desktop $

Refer to the PROMPTING section in man bash for the format of the PS1 variable. A point of interest to your question:
\$     if the effective UID is 0, a #, otherwise a $

To change the prompt permanently, put the export line in /etc/profile (system-wise), or ~/.profile (user-wise), or something equivalent.


text:
Q: .NET Core WebApi Hosting Issue in IIS Express I'm trying to host .Net Core2 default WebApi project on my Local IIS Server in Windows 10.
I just published the default project to a local folder without making any change on it and hosted it on IIS.
But it gives me this error when I try to access the URI

My web.config file as follow:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
   <system.webServer>
      <handlers>
        <add name="aspNetCore" path="*" verb="*" modules="AspNetCoreModule" resourceType="Unspecified" />
      </handlers>
      <aspNetCore processPath="dotnet" arguments=".\ToHost2.dll" stdoutLogEnabled="false" stdoutLogFile=".\logs\stdout" />
   </system.webServer>
</configuration>
<!--ProjectGuid: 3be731b8-79e8-4828-a016-54606c34c081-->

Please help me to track where I have made mistake.
Thanks in advance

A: You need to install the .NET Core Windows Server Hosting bundle

A: Convert the Web api project folder as application in IIS tool.
right click on api project folder and convert as application i think it will be work for you


text:
Q: NullPointer exception while setting Bitmap in ImageView I wanted to load an image into an imageview of the app from my mobile storage. Just to be sure, I kept the image in both internal and external storage. But while compiling, I am getting a null pointer exception. I also placed the same image in drawable folder and tried to set the imageview from there. But faced the same issue. Can anyone help me here!. I am adding the code snippets that I tried.
Method-1:
File imageFile = new File(Environment.getExternalStorageDirectory(),"golden_eagle.jpg");
if(imageFile.exists()) {
    Log.v(LOGTAG, "Image file exists");
    BitmapFactory.Options options = new BitmapFactory.Options();
    options.inPreferredConfig = Bitmap.Config.ARGB_8888;
    Bitmap outputImageBitmap = BitmapFactory.decodeFile(imageFile.getAbsolutePath(), options);
    ImageView imageView = (ImageView)findViewById(R.id.sample_image);
    imageView.setImageBitmap(outputImageBitmap);
}

Method-2:
Bitmap bitimage;
bitimage = BitmapFactory.decodeResource(getResources(), R.drawable.golden_eagle);
if(bitimage == null)
Log.v(LOGTAG,"bitimage is empty");
else
Log.v(LOGTAG,"bitimage is not empty");
ImageView imageView = (ImageView)findViewById(R.id.sample_image);
imageView.setImageBitmap(bitimage);

Method-3:
ImageView imageView = (ImageView)findViewById(R.id.sample_image);
int resid = getResources().getIdentifier("golden_eagle","drawable",getPackageName());
imageView.setImageResource(resid);
//imageView.setImageResource(R.drawable.golden_eagle);

Method 4:
//Some class extending AppCompatActivity
asyncTask.execute();

//some asyncTask

onpostExecute(){
    //Method:1
    //Method:2
    //Method:3
}

All the above methods ended with same compilation error
12-24 20:16:42.520 1349-1349/? E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.home.BequestProto, PID: 1349
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.home.BequestProto/com.example.home.BequestProto.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ImageView.setImageResource(int)' on a null object reference
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2585)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2667)
    at android.app.ActivityThread.-wrap11(ActivityThread.java)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1494)
    at android.os.Handler.dispatchMessage(Handler.java:111)
    at android.os.Looper.loop(Looper.java:207)
    at android.app.ActivityThread.main(ActivityThread.java:5776)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:679)
    Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ImageView.setImageResource(int)' on a null object reference
    at com.example.home.BequestProto.MainActivity.onCreate(MainActivity.java:75)
    at android.app.Activity.performCreate(Activity.java:6582)
    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1113)
    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2532)
    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2667)
    at android.app.ActivityThread.-wrap11(ActivityThread.java)
    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1494)
    at android.os.Handler.dispatchMessage(Handler.java:111)
    at android.os.Looper.loop(Looper.java:207)
    at android.app.ActivityThread.main(ActivityThread.java:5776)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:679)

The Error is occurring at at the line where I am setting image to imageview.
I know that It is a null pointer exception because some where I forgot to initialize the required object. I want to know which one.

A: "Method 4:" Shows that you are executing with async task. I guess the layout changed and it tryed to set the image after.
    ImageView imageView = (ImageView)findViewById(R.id.sample_image);
    if (imageView != null)
            imageView.setImageBitmap(outputImageBitmap);

This will set the image only if View is present

A: Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ImageView.setImageResource(int)' on a null object reference

This would appear to be from "Method-3", where you are calling setImageResource().
This error means that this line is where your problem lies:
ImageView imageView = (ImageView)findViewById(R.id.sample_image);

imageView is null in all four cases, because findViewById() cannot find this widget.

A: Double check if you have ImageView with id sample_image. It's not found in your layout


text:
Q: Can horses act as witnesses? I recently murdered a guard outside Riften because he mentioned my furry ears. As a Khajit assassin, I only have a certain amount of tolerance to racist riff raff.
I slit his throat,  drank his mead, then proceded to do the T-bag.
I was especially careful to make sure no one saw me, but alas, a bounty appeared on my head. I looked around and saw nothing but a horse standing there, all innocent like. I proceded to make dog food out of it, but at this point it was too late and the bounty remained.
Now this begs the question, did the horse act as a witness and somehow manage to alert Riften about my acts of justice, or did someone else see me?

A: This has happened to me on more than a couple of occasions.
For this answer I decided to test this. I rode up to Riften, hopped off my horse, crouched down saved and shot a guard. And I got a bounty. So I loaded, shot my horse and then shot the guard and did not get a bounty.


text:
Q: Will the following function achieve my goal of ignoring stale responses? I have a search function that is debounced. It is called each time a keyup event is fired on a text area.
The idea that results are fetched as the user types in the text area.
{
  search: _.debounce(search, 200),
}

But, there is no guarantee AFAICT that the search calls to the backend will return in the order they were sent (network latency, server vagaries), meaning that the results could (although unlikely) correspond to an earlier search term.
So I want to cancel (or at least ignore the response to) any in-flight requests when a search is performed.
I have two questions:

*

*Is this a real problem that needs solving? (I have not seen it solved before), and

*Will the following code help me achieve this?

function ignoreStale(fn) {
    var latest = 0;
    return function() {
        var id = ++latest; // increments latest too
        return fn.apply(this, arguments)
          .then(function(result) {
              if (id !== latest) {
                  throw new Error('Stale callback.');
              }
              return result;
          });
    }
}

var callCount = 0;

var o = {
    foo: ignoreStale(foo),
};

function foo(val) {
    callCount--;
    return new Promise(function(resolve, reject) {
       setTimeout(resolve.bind(null, val), (5000 + callCount*200));
    });
}

function go (val) {
  o.foo(val).then(doSomething).catch(error);
}

go('1'); // returns third
go('12'); // returns second
go('123'); // returns first

function error(err) {
    document.write(err, '
');
}

function doSomething(val) {
    document.write('Doing something:', val, '
');
}

Presumably cancellable promises would help, but I am using vanilla JS.


text:
Q: Combine variant flags in tailwindcss e.g. even:bg-color-black even:dark:bg-color-white I've made a table in zebra style using tailwindcss. But now that I need to add dark mode support it's not applying the dark mode color and keeps the light mode color altough all other colors do change as expected.
I've made a even:bg-color which works and a even:dark:bg-color which doesnt.

    {{name}}

This results in a view like here where the (bright variant is correct):

A: dark: should go first

The dark variant can be combined with both responsive variants and state variants (like hover and focus):
The responsive variant needs to come first, then dark, then the state variant for this to work.

DEMO - toggle dark class at the top


text:
Q: Input string is not correct format when trying to sum gridview column value I know this is a common question but couldn't find any satisfactory ans.here's my gridview column value sum code and the type of value i am trying to sum is decimal.i want to sum total amount value and show it in textbox below gridview column value the 4th column i want to sum and it's type is decimal

public void TypeTotalAmount()
{
    decimal sum = 0;
    for (int i = 0; i < typeWiseGridView.Rows.Count; i++)
    {
        sum += decimal.Parse(typeWiseGridView.Rows[i].Cells[1].Text);
    }
    totalTextBox.Text = sum.ToString();
}

A: use the Value.Tostring() property
 decimal sum = 0;
            for (int i = 0; i < dataGridView1.Rows.Count; i++)

            {
                sum += decimal.Parse(dataGridView1.Rows[i].Cells[0].Value.ToString());

            }

A: May I suggest you use the RowDataBound event instead of looping the cell contents. The problem with this approach is that the cell content is always a string. So if you were to format it like currency, you won't be able to convert it back to a decimal since the cell contents now also contains a currency symbol.
Say you use this for binding the GridView
<asp:BoundField DataField="totalFee" HeaderText="Total Fee" DataFormatString="{0:C2}" />

The cell now contains a string in this format € 179,23. So if you would loop it now you'll always get the input string is.... error
By using the OnRowDataBound event you add the values of the source data, not the (formatted) data bound to the GridView.
decimal sum = 0;
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        DataRowView row = e.Row.DataItem as DataRowView;
        sum += Convert.ToDecimal(row["totalFee"]);

        TextBox1.Text = string.Format("{0:C2}", sum);
    }
}


text:
Q: Sum of values from facts I am trying to add different values together, let's say I have this:
%person(Name, Points).
person(piotr, 3).
person(daniel, 4).
person(marlena, 4).
person(grzegorz, 1).
person(ania, 2).
person(robert, 4).
person(gabrysia, 5).
person(julia, 6).
person(agata, 7).
person(bartek, 4).

I also have a list of names :
[daniel, marlena, grzegorz]
And the problem is I'm trying to add these people(from list) points together and I don't know how.
I used many ways but none worked.
Anyone got any ideas on how to solve this?

A: There are multiple ways to do this but one of the most straight forward is to think of two cases:
% what is the sum when you have an empty list
sum_vals([],0).

% what is the sum when you know one value and the sum of the rest
sum_vals([N|Names],Sum) :-
    person(N,Val),
    sum_vals(Names,Sum1),
    Sum is Sum1 + Val.

A: You can make use of the aggregate library:
:- use_module(library(aggregate)).

sum_persons(Ns, R) :-
    aggregate(sum(P), N, (member(N, Ns), person(N, P)), R).


text:
Q: Not able to uninstall managed package I am trying to uninstall a CPQ related managed package and I am facing issues during the uninstall. There were about 100 errors, and I have addressed most of them by deleting the impacted components. The last error message that I am getting is below.
Component Type      Name             Problem
Custom Field        ProposalId       Component is in use by another component in your organization. Proposal_Page

I have removed the field ProposalId from page layout that is associated with the lightning page Proposal_Page. However, I am still getting the same error.
Any ideas on what could be wrong?

A: I found the issue. The field ProposalId was on two different objects in the managed pakcage. I removed the related list of both objects from the classic and lightning pages and then the uninstall worked.


text:
Q: Charging supercapacitors with reversed polarity I bought six supercapacitors and connected them in series to get a total voltage of 16.2 VDC.
The product's Mouser No is: 723-BCAP0450P270S18, Mfr. No is: BCAP0450 P270 S18, the datasheet can be found on this link:
The problem is that I applied reversed voltage to charge the supercapacitor bank. The supercapacitors were charged (starting with 10A charging current) until reaching their optimal voltage (2.7 VDC each) and the day after, I discharged them using resistors. This happened three to four times. They do not seem to have suffered any damage and no problem occurred during this procedure, so I would like to ask:

*

*Might the supercapacitors have been internally damaged and they are dangerous to use?

*If not, should I keep charging them using reversed polarity or should I apply the correct polarity to charge them again.

A: Electrolytic capacitor polarization is initially set at the factory by applying voltage to form the insulating oxide layer.
That is why caps have a polarity and these standard supercaps are no different. Reversing the polarity will damage the original insulating layer first and then start to form a new insulating layer with the applied polarity. It is not something that should be allowed to happen, so consider the capacitors damaged, or at least degraded, and they could be unstable and dangerous too.
Here is also what manufacturer says about reversing the polarity:
https://maxwell.com/wp-content/uploads/2021/08/Notes_on_Using_Ultracapacitor_Cells.pdf

A: Additionally to the note found in the document linked in Justme's answer:

All ultracapacitors have a positive and negative polarity. Please check the
polarity indicated on the label before use and do not reverse the polarity when electrically connecting the ultracapacitor cells

There is also this one in their document about modules:

Applying reverse voltage on ultracapacitor module(s) may result in
malfunctioning, rapid performance degradation, and/or catastrophic failure of
the module. The polarity of the module terminals must be checked in
advance for the correct connection of the power lines.

A: I wonder if these are non-polarized since both electrodes in this part number are carbon.  If you see no ill-effects, that may confirm this but the double-layer-effect may be more advantageous in one polarity.
Looking now at the specs, I see they are non-polarized and Vr reverse voltage defines the voltage limit .  (
(Although the R in \$V_R\$ is defined by Maxwell as Rated not Reverse)
VR
Rated Voltage
–
–
2.7
V
VSURGE
Surge Voltage
Note 1  1. Surge Voltage
Absolute maximum voltage, non-repetitive. The duration must not exceed 1 second.
–
–
2.85
Additional Information
Polarity / Reverse voltage
Unlike many batteries the anode and cathode of an ultracapacitor are
comprised of the same material. If the positive and negative terminal and
casing are also comprised of similar materials, then theoretically the
ultracapacitor has no true polarity.

A: Putting electrolytic capacitors with reverse polarity will almost certainly with prolonged use cause  them to explode and the fluids of the electrolyte will come out which is dangerous.


text:
Q: Proving True or False, Set Question Is the following statement true or false?
Provide a proof or counter example.
"For any function $f: X \rightarrow Y$, and any subset $A$ of $X$, we have $$f(A \cap (X\backslash A)) = f(A) \cap f(X\backslash A)$$
I think this is false because how can some element be in a set and also not be in its set. But I'm not sure

A: False:
$A \cap A^{c} = \emptyset$ so $f(A \cap A^{c}) = \emptyset$ but take $f\colon [-1,1] \to \mathbb{R}, f(x) = |x|$ then $f((-1,0)) \cap f([0,1)) = (0,1) \cap [0,1) = (0,1)$


text:
Q: Removing blank Excel Pivot Table entries I have a pivot table based on PowerPivot with multiple levels in the Rows section. Quite a few of the elements are blank. Is there a way to suppress the blank rows?
My Pivot Table looks like this at the moment.
Product1
    Release 1
        Iteration 1
            (blank)
        Iteration 2
            (blank)
    Release 2
        (blank)
            (blank)
Product2
    (blank)
Product3
    Release 1
        Iteration 1
            Sprint 1
            (blank)
        (blank)
(blank)

This is what I want it to look like
Product1
    Release 1
        Iteration 1
        Iteration 2
    Release 2
Product2
Product3
    Release 1
        Iteration 1
            Sprint 1

That's just an example. I've tried to set filters for each level not to display blanks but if I filter each level to hide blank fields the pivot table doesn't have any items in it. It seems that Excel ends up filtering each level out that has ANY blank values.
Not sure if I made sense or provided enough information for troubleshooting. I'm pretty much brain dead at the moment so I apologize.
Please let me know if it doesn't make sense or if I can provide any additional information to clarify what I'm trying to do and encountering.
Thanks.
EDIT: Changed the code block to be more clear and added an "after" code block to show what I want to get to. I guess the issue is that the "depth" of the rows for the entire pivot table has to be equal. For example if I have 3 indents for the first item, the others must also show 3 levels of indent worth of data. If I hide blanks and that results in 1 indent worth of data for the first item, it will hide non-blanks for other items as well if they appear after 1 indent. Still not sure if that makes any sense :) I need some sleep.

A: I think you should be able to check Show items with no data on rows and/or Show items with no data on columns in Display under PivotTable Options.

A: I ended up using a Flattened PivotTable instead from the PowerPivot "Manage" screen instead. That seemed to do what I needed.

A: I needed to solve exactly the same problem, but wanted the the rows to be hidden automatically when the pivottable filtering was changed or the data was refreshed, so I wrote a function called from a 'Worksheet_PivotTableUpdate' event on the sheet holding the pivottable, although you could drive it off a button if you prefer I suppose.  This initially did the job by scanning down each row in the pivottable, hiding it if it was visible and didn't need to be (as the row's first cell was '(blank)'), or showing it if it was hidden and shouldn't be, otherwise just leaving it hidden or visible as it was.
However, I found the function ran very slowly, so here's my next attempt, which initially un-hides all the rows in the pivottable, then goes and finds all the blank cells in the first column, adding them to a range object, then it hides the entire row for every cell in that range.  This version works about ten times as fast :-)
Pass in the name of the sheet where the pivottable reside, the name of the pivottable and an optional string to look for in the rows that need to be hidden; this defaults to '(blank)' if not supplied by the calling function.
Apologies in advance if I fall foul of anybody's variable or function naming conventions (I'm only a hacker ;-))
Sub FixBlankPivotRowsV2(ByVal SheetName As String, ByVal PivotName As String, Optional HideDefn as String = "(blank)")
Dim CurrPivot As PivotTable
Dim CurrRow As Range
Dim BlankRange As Range        'NB This is where we'll build the range of things to hide, which will initially be Nothing, as we never initialise it.
Dim oldStatusBar As Boolean

'Show a nice message in the status bar
oldStatusBar = Application.DisplayStatusBar
Application.DisplayStatusBar = True
Application.StatusBar = "Hiding blank entries in " & SheetName & ", back in a sec..."
Application.ScreenUpdating = False

'Get the pivottable to work with
Set CurrPivot = ActiveWorkbook.Sheets(SheetName).PivotTables(PivotName)

'Unhide all of the pivot rows first
CurrPivot.RowRange.Rows.EntireRow.Hidden = False

'Loop around each row in the pivottable
For Each CurrRow In CurrPivot.RowRange.Rows
    If CurrRow.Offset(0, 0).value = HideDefn Then
        If BlankRange Is Nothing Then
            'This is the first blank row we've found, so just set the range up to be the first cell of that range
            Set BlankRange = CurrRow.Offset(0, 0)
        Else
            'Add the newly found blank row to the range using a Union
            Set BlankRange = Union(BlankRange, CurrRow.Offset(0, 0))
        End If
    End If
Next

'Only hide things if there's anything to hide!
If BlankRange Is Nothing Then
    Debug.Print "Nothing to hide!"
Else
    BlankRange.EntireRow.Hidden = True
End If

'Set the status bar back the way it was
Application.ScreenUpdating = True
Application.StatusBar = False
Application.DisplayStatusBar = oldStatusBar
End Sub

I looked for a way to select all of the 'blanks' cells in the first column using one of the Go To Special type functions, but couldn't find anything that would fit the bill, so please let me know if you know how to do such a thing as it will speed this up even more.
I hope this helps somebody out there!

A: Try to select the a cell in the pivot table "blank" press delete button and press spacebar.

A: No idea why or how this works, but I sleclected one of the cells in the PivotTable that contained (blank), then hot spacebar.  I then hit the return key, and all the (blank) cells in the same column went blank.  Repeated this for the other columns in the table.


text:
Q: Common proto3 fields with oneof or aggregation I have to produce a proto class for an object which will have around 12 variations. All 12 variations share four fields which are the same, and then have specific fields. In most cases there will be many more non specific fields than there are common fields.
I was wondering what would be the most performant way to achieve this.
First option: defining the common fields in a common proto class and then declaring a field of this type in all the specific types:
message CommonFields {
    // common_field1
    // ... common_fieldN
}

message SpecificType1 {
    CommonFields common = 1;
    // specific fields...
}

Or would it be better to define one top level proto which contains the fields, and then having a oneof field, which can refer to another type containing the specific fields:
message BaseType {
    // common_field_1
    // ... common_field_N
    oneof specific_fields {
        SpecificTypeFields1 type1_fields = N;
        SpecificTypeFields2 type1_fields = N+1;
    }
}

message SpecificTypeFields1 {
    // specific fields...
}

message SpecificTypeFields2 {
    // specific fields...
}

I'm particularly interested in performance and also convention. Or if there are any more typical ways, such as just repeating the common fields.. Bearing in mind though my protos will only have 4 common fields, and typically 3-8 specific ones.

A: Depending on the protobuf library, there is usually some performance penalty for encoding submessages. For most libraries, such as the Google's own protobuf libraries, the difference is very small. With either of your options, you end up encoding 1 submessage per message, further reducing the impact.
I have seen both formats commonly used. If the decoder side already knows the message type (from e.g. rpc method name), aggregation is usually easier to implement as it doesn't require separately checking the oneof type.
However, if the message type is not known, oneof method is better as it allows easy detection of the type.


text:
Q: Scala: An extension method was tried, but could not be fully constructed (same extension name on multiple classes) In Scala, I'm trying to define an extension method on two different classes. I want the extension method to have the same name, for both classes.
Note that the classes aren't related by inheritance.
As an example, say I have two case classes A and B, each with one String property, and I want to define a lower method on both classes, which will return the lowercase of their property:
import SomeObject.AExt.lower
import SomeObject.BExt.lower

object SomeObject {

  case class A(foo: String)

  case class B(bar: String)

  object AExt {
    extension (x: A) def lower = x.foo.toLowerCase
  }

  object BExt {
    extension (x: B) def lower = x.bar.toLowerCase
  }

  def hello(): Unit = {
    def a = A("foo")

    def b = B("bar")

    println(a.lower)
    println(b.lower)
  }
}

The compilation fails with this error:
An extension method was tried, but could not be fully constructed:

    SomeObject.BExt.lower(a)    failed with

        Found:    SomeObject.A
        Required: SomeObject.B

Looks like the compiler is confused, and is trying to apply the lower extension defined on class B, to my instance of A.

A: One workaround is to put the extension methods inside the same object:
import SomeObject.ABExt.lower
object SomeObject {

  case class A(foo: String)

  case class B(bar: String)

  object ABExt {
    extension (x: A) def lower = x.foo.toLowerCase
    extension (x: B) def lower = x.bar.toLowerCase
  }

  def hello(): Unit = {
    def a = A("foo")

    def b = B("bar")

    println(a.lower)
    println(b.lower)
  }
}


text:
Q: Angular Material Datepicker - select monday by default when other days of the week is chosen I am new to Angularjs. I wonder is there any filtering mechanism for the Angular Material Date Picker(md-datepicker), So that I can choose only Monday when other days of the week is choosen, provided all the days are enabled. For example, when i clicked on 14-04-2016(Thursday), (11-04-2016)monday of that week should be automatically selected.
Let me know if any other details needed. Any help much appreciated. Thanks in advance.

A: You can write a filter for your datepicker:
 <md-datepicker ng-model="myDate" md-date-filter="onlyMondays"></md-datepicker>

 $scope.onlyMondays = function(date) {
    var day = date.getDay();
    return day === 1;
 }

Or if you want to let all days selectable you could change the date to monday in the background with:
<md-datepicker ng-model="selectedDate"></md-datepicker>

you could set the date to the last monday afterwards:
var daysToSubstract = $scope.selectedDate.getDay() - 1;
$scope.myDate.setDate($scope.selectedDate.getDate() - daysToSubstract);


text:
Q: javascript, for function, var seems to behave strangely For the following code I get UNDEFINED, Entering Loop, UNDEFINED, 0, 0, 1, 1, 2. I understand why I only get a single 2 (I think), but I'm having trouble understanding why I get two 0?

'use strict';
console.log(message);

console.log('Entering Loop');
for (var i = 0; i < 3; i++) {
  console.log(message);
  var message = 'number: ' + i;
  console.log(message);
}

A: You are logging before and after you set the variable. var does not restrict the variable to the block so the old value sticks around. On your first loop iteration you are getting
undefined
number: 0

On the second you are getting
number: 0
number: 1

And on the final iteration you are getting
number: 1
number: 2

When a loop executes: The first part (var i = 0;) is ran before looping starts. The second part (i < 3) is ran before each iteration to determine whether to continue or not, and the third part (i++) is ran after each iteration. If the second part is truthy the loop doesn't restart. Here is your loop unrolled.

'use strict';
var message;
console.log(message); // "undefined"

console.log('Entering Loop');
var i = 0;

// loop if i < 3, i === 0
console.log(message); // "undefined"
message = 'number: ' + i;
console.log(message); // "number: 0"
i++; // i === 1

// loop if i < 3, i === 1
console.log(message); // "number: 0"
message = 'number: ' + i;
console.log(message); // "number: 1"
i++; // i === 2

// loop if i < 3, i === 2
console.log(message); // "number: 1"
message = 'number: ' + i;
console.log(message); // "number: 2"
i++; // i === 3

// loop if i < 3, i === 3

A: Entering the loop your number is undefined.
Within the loop it's set to "Number = 0".
Entering the loop again number is still set to "Number = 0" and beeing overwritten with "Number = 1".
Entering the loop again number is still set to "Number = 1" and beeing overwritten with "Number = 2".
Entering the loop again i == 3 thus it ends.
You could have easily done this with a pen and some paper.


text:
Q: Where are the Life Gems in Stage 1-3 (The Dead Bog) In Castlevania: Lords of Shadow, the Dead Bog is a branching stage that has 4 Life Gems hidden in it.  I've found 3 of them, I haven't found the fourth one.  I've played through this stage at least 3 times.
Where are each of the life gems located in the Dead Bog, so I can figure out which one I missed?

A: So the 4 gems are:

*

*Knight's corpse at the beginning

*Left Path: First bog path leads to the Knight

*After Second Gem: Proceed right till dry ground then run TOWARDS the camera (this is usually the one people miss)

*After Boss: its under the stairs.

Hope that helps.


text:
Q: Dividing by zero results negative infinity I was reading about limits and stumbled upon this site and saw the author doing something funny:
$$ \lim_{x\rightarrow 0} \frac{x^3-7x}{x^3} $$
It is quite clear that you can apply l'Hospital at this point but the author does something else:
$$ \lim_{x\rightarrow 0} \frac{x\left(x^2-7\right)}{x\left(x^2\right)} $$
$$ \lim_{x\rightarrow 0} \frac{x^2-7x}{x^3}  = \quad'' \quad \frac{-7}{0} \quad'' = -\infty $$
I looked up indeterminate forms and could not find anything like this. What is going on here ?
With l'Hospital I dont get much farther either.

A: L'Hospital's rule is unnecessary here, as simple algebra gets rid of the indeterminate form. Just cancel an $x$ from the top and bottom as the author does:
$$
\lim_{x\rightarrow 0} \frac{x^3 - 7x}{x^3} = \lim_{x\rightarrow 0} \frac{x^2 - 7}{x^2}.
$$
Now, when the author writes "$-7/0^+$", he's saying that the limit of the numerator is -7, and the limit of the denominator is 0, but is positive on both sides. Whenever you have a finite limit for the numerator and a 0 limit for the denominator, the limit will either be nonexistent (if the signs don't match on opposite sides) or $\pm \infty$ (if they do). In this case the denominator is positive on both sides, so, since the numerator is negative, the limit will be $-\infty$. It is this sense in which $-7/0^+ = -\infty$. Similarly, in this sense $-7/0^- = \infty$, while $-7/0$ remains undefined.


text:
Q: How can I write a function to return all the binary numbers with N digits, and in sorted order? Each binary number should be represented as a tuple. When the function is called, the result should be a tuple containing 2^N binary numbers.
Ex. Binary(2)----> ((0,0), (0,1), (1,0), (1,1))
I am trying to use a while loop to do this.
Just some advice on where I could begin would be very helpful.

A: You can use itertools.product, to get what you want
print [item for item in itertools.product([0, 1], repeat = 4)]

Output
[(0, 0, 0, 0), (0, 0, 0, 1), (0, 0, 1, 0), (0, 0, 1, 1), (0, 1, 0, 0),
 (0, 1, 0, 1), (0, 1, 1, 0), (0, 1, 1, 1), (1, 0, 0, 0), (1, 0, 0, 1),
 (1, 0, 1, 0), (1, 0, 1, 1), (1, 1, 0, 0), (1, 1, 0, 1), (1, 1, 1, 0),
 (1, 1, 1, 1)]

Change the repeat to the desired value.
Edit:
Performance comparison with list and comprehension.
print timeit.timeit("[item for item in itertools.product([0, 1], repeat = 4)]", number = 1000000)
print timeit.timeit("list(itertools.product([0, 1], repeat = 4))", number = 1000000)

List comprehension is slightly faster than list.

A: You'll probably need two loops -- an outer one to loop thru the values, and an inner one to process the binary digits for each value.
You can either loop thru the values as integers & convert them to binary -- or you can carry a "current value" in binary around the loop, copying & incrementing it.

A: try this:
def binary(n):
    num_digits = len(bin(n).replace('0b',''))

    all_bin_numbers=()

    for i in range(n):
        bin_num=()
        for digit in str(bin(i)).replace('0b','').rjust(num_digits, '0'):
            bin_num += (int(digit),)
        all_bin_numbers += (bin_num,)

    return all_bin_numbers

print binary(2)

e: holy cow, that itertools answer.
e2: so it appears I didn't fully read the question, I was thinking you wanted all the binary numbers up to and including your specified n.

A: from numpy import binary_repr
[map(int, binary_repr(i, N)) for i in range(2**N)]


text:
Q: Why included images in a thymeleaf layout takes a long time to being displayed? I am working on a java app, works fine and all, but at the frontend, I am using thymeleaf (first time I use it, moving on from primefaces).
What Ive noticed is that the page loads (working locally) pretty fast, as expected, since the information is not reelevant and no DB is being used by now.
What surprises me is that the images load probably 2 seconds later, I have no idea why, they are stored locally on the app assets folder.
I am incluiding them this way:
<img th:src="@{/assets/images/myimage.png}" />

Is there anyway to make it faster? (Of course, I will later set more memory to my JVM, but this sort of stuff shouldnt take that long...)
Any caching or faster ways?
I am using spring 4 mvc
Thanks.

A: There are so many variable to this i am not going to list all of them but a few:

*

*Distance between Client and Server

*Efficiency of your application

*Size of images

*Browser and all extensions/plugins attached to it

*Power of server

*Power of client machine

*Delivery method

*Potential javascripts that manage loading of images

*Malware

As mentioned there is a lot more that I haven't listed and it really is a process of elimination.
Some things we have on our application that avoids the delay in images include

*

*server memory increase from 512 to 1024

*Changing location of server to a more local source

*changing the location from where the application is sourcing the images (faster raid disks)

*delaying full page display until everything is preloaded on client machine (look into Flash of Unstyled Content Fixes)

*Performance improvements on web application itself

What you need to do is explore each option and start improving on it and eventually you will get the results you need.
Fyi if you want to avoid loading images from server have them hosted on a CDN for speed of transfer.


text:
Q: rollapply fails to cover/roll the whole data set I'm trying to run a function I created using rollapply, on a dataset that has 5706 data points. The function (basically calculates Rescaled Range), uses all the observations in the window (in this case 500 observations) and calculates an output of one single value. So with width = 500 and by = 500, I expect to be left with 11 values (since 5706 is divisible by 500 11 times) after all the NA values were omitted.
But for some reason, rollapply stops calculating the function for the 10th window and only leaves me with only 10 values and ignores the last 706 observations, which doesn't make sense to me.
I tested it with a different function (just made a simple function that calculates the mean) and I still get this problem. I also changed the width and by sizes and whenever they are big they cause the same problem (e.g. if I set width=2853 and by=2853, I only get 1 calculated value and I expect 2.
My code:
test2 <- na.omit(rollapply(returns,
                           width = 500,
                           FUN = RS,
                           fill = NA,
                           partial = TRUE,
                           align = 'right',
                           by = 500))

I know I could just create separate subsets, but I plan to run this later on in a for loop where it calculates this function with several different window sizes.
Does anyone have a solution?
but I don't want it to ignore the last window or 500 observations in this example.
Thanks!


text:
Q: BASH: Redirect time with read command I need to time how much it takes to the user to write a specific sentence in input, in a script.
I've tried with this:
TIMEFORMAT=%R
{ time read -n53 -t45 -e userstring } 2> time.txt

But when I write the sentence in the stdin the terminal doesn't show it; If I cat the time.txt file, it appears like this:
Ma la volpe col suo balzo ha raggiunto il quieto fido

real    0m7.537s
user    0m0.002s
sys   0m0.003s

EDIT: the problem seems to be the -e options; it doesn't show the stdin while the user is typing the sentences and it redirects it to time.txt file


text:
Q: SQL SERVER - Tricky Select Statement Trying to rack my brain for a while, lots of Googling, but to no avail. I have a data set that has the following fields I need to query: DEPT,NUM,TERM,ITLE. I have the following possible rows.
DEPT--NUM---TERM------TITLE
OSS - 1550 - 200830 - COURSE NAME (CI)
OSS - 1550 - 200930 - COURSE NAME (CI)
OSS - 1550 - 201230 - COURSE NAME
ENG - 1600 - 200930 - OTHER COURSE (CI)
OSS - 1600 - 200830 - ANOTHER COURSE (CI)
USS - 2500 - 201240 - COURSE (CI)
PSY - 1600 - 200830 - COURSE TITLE

What I need to do is query a table with data such as this and then pull the DEPT/NUM (OSS 1550) where the title matches a query ONLY IF it's the latest title.
So if I do a search for (CI) I want 3 results using the set above (ENG 1600, OSS 1600, ISS 2500), because 201230 is the latest entry for OSS 1550 I don't want that one, but I do want the others. Right now I cannot for the life of me figure out how to write a query that will do that.
Any help would be appreciated. Let me know if I am not clear enough.
EDIT
I am only getting a single record, here is what I am using based on what you have said
    SELECT data.*
    FROM (
        SELECT SCBCRSE_SUBJ_CODE || ' ' || SCBCRSE_CRSE_NUMB AS crs_combo,
        SCBCRSE_TITLE as title,
        row_number() over (ORDER BY SCBCRSE_EFF_TERM DESC, SCBCRSE_CRSE_NUMB DESC) as term
        FROM        SCBCRSE
        WHERE       (SCBCRSE_TITLE LIKE '%' || :srch || '%')
    ) data
    WHERE data.term = 1
My formatting is now working... no idea why I have four spaces.
EDIT AGAIN
I guess I didn't provide enough sample data... see edited table above. I need the three records with unique DEPT/NUM and the CI in the title, but not the one with older titles and CI. Make sense.
Sorry for not being clear.
ANSWER... here is the winner.
SELECT data.*
FROM (
    SELECT SCBCRSE_SUBJ_CODE || ' ' || SCBCRSE_CRSE_NUMB AS crs_combo,
    SCBCRSE_TITLE as title,
    row_number() over (partition by SCBCRSE_SUBJ_CODE,SCBCRSE_CRSE_NUMB ORDER BY SCBCRSE_EFF_TERM DESC) as seqnum
    FROM SCBCRSE
) data
WHERE seqnum = 1 AND title LIKE '%' || :srch || '%'

Thanks for your help everyone. I wasted hours on this and you answered it in minuets.

A: You can do what you want with ranking functions.  But, as I read the question, it is not as clear as I originally thought.  The following gets the latest course that matches the title:
select t.*
from (select d.*,
             row_number() over (order by term desc, num desc) as seqnum
      from data d
      where title like '%(CI)%'
     ) t
where seqnum = 1

This assumes you are using version 2005 or greater.
If you are trying to find out all the "last" classes that match, then you can try:
select t.*
from (select d.*,
             row_number() over (partition by num order by term desc) as seqnum
      from data d
     ) t
where seqnum = 1 and title like '%(CI)%'

This returns any case where the last class (based on num, order by term) matches the "(CI)".  This is the other interpretation I had for your question.

A: It sounds like you only want to search the books from the MAX(TERM), in which case this would work
IF OBJECT_ID('TEMPDB..#Books') IS NOT NULL
    DROP TABLE #Books
CREATE TABLE #Books
(
    DEPT VARCHAR(5),
    NUM VARCHAR(10),
    TERM VARCHAR(10),
    TITLE VARCHAR(50)
)

INSERT INTO #BOOKS (DEPT, NUM, TERM, TITLE) VALUES('OSS','1550','200830','COURSE NAME (CI)')
INSERT INTO #BOOKS (DEPT, NUM, TERM, TITLE) VALUES('OSS','1550','200930','COURSE NAME (CI)')
INSERT INTO #BOOKS (DEPT, NUM, TERM, TITLE) VALUES('OSS','1550','201230','COURSE NAME')
INSERT INTO #BOOKS (DEPT, NUM, TERM, TITLE) VALUES('ENG','1600','200930','OTHER COURSE (CI)')

SELECT b.*
FROM #Books b
JOIN (
    --Find the latest TERM
    SELECT
        DEPT, NUM, MAX(TERM) as TERM
    FROM #Books
    GROUP BY DEPT, NUM
    ) t
    ON b.DEPT = t.DEPT
    AND b.NUM = t.NUM
    AND b.TERM = t.TERM
WHERE TITLE LIKE ('%(CI)%')

A: Here is a SQLFiddle example:
;with a as
(
  select * from
  (
    select t.*,
    row_number() over (partition by DEPT,NUM order by TERM DESC) row from t
  ) b
  where row=1

)
select * from a where TITLE like '%(CI)%';


text:
Q: Confused about how to use exchanger in java As with basically every exchanger task, I have a producer filling up an empty buffer2, a consumer clearing a full buffer1 and when each thread is done, they should exchange their respective buffers.
I am really unsure about where and how to apply the exchange. I defined readyconsumer and readyproducer as booleans, so that a third thread can check whether it's time to exchange the buffers once both are true. This should solve the problem I had doing it with two threads, where the program was stuck with both threads at wait() (which it unfortunately still is).
This is what the code looks like at the moment. Can anyone help me in which class I have to exchange and at what point in the code? Thank you very much in advance!
    class Buffer {
        static boolean readyconsumer, readyproducer = false;

        volatile int count; // number of put actions
        static int max = 10;

        Buffer() {
        count = 0;
        }

        public synchronized void put() {
            if (count == max) {
                readyproducer = true;
                System.out.println("          wait ");
                try {
                    wait();
                } catch (InterruptedException e) {
                }
            }
            count++;
            System.out.println("put " + count);
            notifyAll();
        }

        public synchronized void get() {
            if (count == 0) {
                readyconsumer = true;
                System.out.println("          wait");
                try {
                    wait();
                } catch (InterruptedException e) {
                }
            }
            count--;
            System.out.println("get " + count);
            notifyAll();
        }
    }

class CheckandSwitch extends ProdCon {
    public void run() {

        while (true) {

            if (Buffer.readyconsumer && Buffer.readyproducer) {
                try {
                    ProdCon.buffer2 = exchanger.exchange(ProdCon.buffer1);
                    ProdCon.buffer1 = exchanger.exchange(ProdCon.buffer2);
                } catch (InterruptedException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                    }
                Buffer.readyconsumer = false;
                Buffer.readyproducer = false;
                buffer1.count = 0;
                buffer2.count = 10;
                notifyAll();
            }

        }
    }

}

class Consumer extends ProdCon {
    static Buffer buffer;

    Consumer(Buffer b) {
        super();
        buffer = b;
        b.count = 10;
    }

    public void run() {
        while (true) {
            consume();
            buffer.get();
        }
    }

    private void consume() {
        System.out.println("consume");
        try {
            Thread.sleep(200);
        } catch (InterruptedException e) {
        }
    }
}

class Producer extends ProdCon {
    static Buffer buffer;

    Producer(Buffer b) {
        super();
        buffer = b;
        b.count = 0;
    }

    public void run() {
        while (true) {
            produce();
            buffer.put();
        }
    }

    private void produce() {
        System.out.println("produce ");
        try {
            Thread.sleep(50);
        } catch (InterruptedException e) {
        }
    }
}

import java.util.concurrent.*;

public class ProdCon extends Thread {
    static Exchanger<Buffer> exchanger = new Exchanger<Buffer>();
    static Buffer buffer1, buffer2 = null;

    public static void main(String[] args) {

        buffer1 = new Buffer();
        buffer2 = new Buffer();
        new Consumer(buffer1).start();
        new Producer(buffer2).start();
        new CheckandSwitch().start();

    }
}

A: You could use an Exchanger.
Here's the code from the javadoc tweaked into a working example.
class DataBuffer<T> {

    T data = null;

    public boolean isFull() {
        return data != null;
    }

    public boolean isEmpty() {
        return data == null;
    }

    public T get() {
        T d = data;
        data = null;
        return d;
    }

    public void put(T data) {
        this.data = data;
    }
}

class FillAndEmpty {

    Exchanger<DataBuffer<Integer>> exchanger = new Exchanger<>();
    DataBuffer<Integer> initialEmptyBuffer = new DataBuffer<>();
    DataBuffer<Integer> initialFullBuffer = new DataBuffer<>();
    int countDown = 10;

    class FillingLoop implements Runnable {

        @Override
        public void run() {
            DataBuffer currentBuffer = initialEmptyBuffer;
            try {
                while (currentBuffer != null && countDown > 0) {
                    addToBuffer(currentBuffer);
                    if (currentBuffer.isFull()) {
                        currentBuffer = exchanger.exchange(currentBuffer);
                    }
                }
            } catch (InterruptedException ex) {
            }
        }

        private void addToBuffer(DataBuffer<Integer> currentBuffer) {
            currentBuffer.put(countDown--);
        }
    }

    class EmptyingLoop implements Runnable {

        @Override
        public void run() {
            DataBuffer<Integer> currentBuffer = initialFullBuffer;
            try {
                while (currentBuffer != null) {
                    takeFromBuffer(currentBuffer);
                    if (currentBuffer.isEmpty()) {
                        currentBuffer = exchanger.exchange(currentBuffer);
                    }
                }
            } catch (InterruptedException ex) {
            }
        }

        private void takeFromBuffer(DataBuffer<Integer> currentBuffer) {
            System.out.println(currentBuffer.get());
        }
    }

    void start() {
        new Thread(new FillingLoop()).start();
        new Thread(new EmptyingLoop()).start();
    }
}

public void test() {
    System.out.println("Hello");
    new FillAndEmpty().start();
}