text:
Q: When including header files, is the path case sensitive? Given this directory tree:
src/MyLibrary/MyHeader.h
src/file.cpp

file.cpp:

#include "mylibrary/myheader.h"
...

Compiling file.cpp works with VS, fails in gcc.

*

*What does the standard say?

*If the path is case sensitive, why is this wise?

*What's the best practice, keep all file/folder names lowercase and thus do the same when including?

Thanks.

A:
What does the standard say?

Case sensitivity in #include directives is controlled by the implementation (compiler/preprocessor). This is explained under 16.2.2 [cpp.include]:

A preprocessing directive of the form
# include < h-char-sequence> new-line
  searches a sequence of implementation-defined places for a header identified uniquely by the specified sequence between the < and > delimiters, and causes the replacement of that directive by the entire contents of the header. How the places are specified or the header identified is implementation-defined.

Similarly, 16.2.3 [cpp.include]:

A preprocessing directive of the form
# include " q-char-sequence" new-line
  causes the replacement of that directive by the entire contents of the source file identified by the specified sequence between the " delimiters. The named source file is searched for in an implementation-defined manner. If this search is not supported, or if the search fails, the directive is reprocessed as if it read
# include < h-char-sequence> new-line
  with the identical contained sequence (including > characters, if any) from the original directive.

A natural choice for an implementation of the language is to use the case sensitivity of the filesystem or OS, but there is no strict requirement to do so (as all other answers suggest).

What's the best practice, keep all file/folder names lowercase and thus do the same when including?

Best practice, as always: Keep things consistent. If you are using mixed-case source/header files in your project, keep using them and replicate the exact casing in your #include directives.

A: The case sensitivity depends on the Operating System. Windows is not case sensitive. Linux is.
EDIT:
Actually, as observed by Martin York's comment, the case sensitivity depends on the file system. By default Windows uses a case insensitive file system, while Linux uses a case sensitive one. For whoever is interested to know which file systems are case sensitive and which aren't, there is a comprehensive list on Wikipedia: Comparison of file name limitations.

A: Another point to remember is the path separator character.  Even though Visual Studio (and other Windows IDEs I'm sure) will accept either '/' or '\', you should always use '/' within an include path for portability.

A: Its not C++ standard, its the Linux way, where all path names are case sensitive.
The best practice is too chose whatever file name you want ( mostly lowercase) and use the same case in the include directive. Also always use relative file paths.


text:
Q: Standard Deviational Ellipsoid, Average Direction of 3D Points I need help to calculate "average direction" from a set of 3D points, located around (0,0,0).
In other words I want the direction vector for biggest axis of the 3d ellipsoid covering the points.
I was able to make it work for 2D points.
Based on this information:
http://resources.esri.com/help/9.3/arcgisengine/java/gp_toolref/spatial_statistics_tools/how_directional_distribution_colon_standard_deviational_ellipse_spatial_statistics_works.htm
Using Standard Deviational Ellipse
My C++ code ended up like this:
void AvgDirU(Vec2 &dir, C Array<Vec2> &points) // // get average direction from array of points, points should be located around center Vec2(0,0)  , direction is not normalized
{
   float x2=0, y2=0, xy=0;
   for(int i=0; i<points.elms(); i++)
   {
    C Vec2 &p=points[i];
      x2+=Sqr(p.x);
      y2+=Sqr(p.y);
      xy+=p.x*p.y;
   }
   float a=x2-y2,
         c=2*xy,
         b=sqrt(sqr(a)+sqr(c));
   dir.x=a+b; // if we would normalize, then dir.x=cos
   dir.y=c  ; // if we would normalize, then dir.y=sin
}

I've tested this and it works great.
'dir' points in the average direction of an array of 2D points.
Note that instead of calculating tangent of the angle as in the link above, I prefer to specify Vec2 direction vector (cos and sin), this is much better because it avoids infinite values and division by zero.
However how to extend this to 3D Ellipsoid?
I need:
void AvgDirU(Vec3 &dir, C Array<Vec3> &points)
{
..
}

Many thanks!

redpajama_set_name: RedPajamaStackExchange


text:
Q: Rails3: Gem Gmap4rails with mongoid doesn't show map I followed the instruction on github to install everything.
(Gmaps4Rails-github)
The problem is that the map is blank, I only see the border of the map from the css.
Model:
class Recipe
  include Mongoid::Document
  include Gmaps4rails::ActsAsGmappable
  acts_as_gmappable

  field :name, :type => String
  field :city, :type => String
  field :country, :type => String
  field :latitude, :type => Float
  field :longitude, :type => Float
  field :gmaps, :type => Boolean

  def gmaps4rails_address
    "#{self.city}, #{self.country}"
  end
end

Controller:
class RecipesController < ApplicationController
  def index
   @location = Recipe.all.to_gmaps4rails
  end
end

View:
= gmaps4rails(@location)

@location has the lat and lng in an array like
[{"lat":13.055363,"lng":47.811886},{"lat":13.055363,"lng":47.811886}]

The required JS and CSS files are getting loaded:
gmaps4rails.base.js, gmaps4rails.googlemaps.js, gmaps4rails.bing.js, gmaps4rails.mapquest.js, gmaps4rails.openlayers.js, gmaps4rails.css
I don't get any errors in the server log or in the JS console. I don't know what I'm doing wrong here.
Any suggestion would be really helpful! Thanks!

A: I can't see any mention of:
<%= yield :scripts %>

in your code here. This is mandatory though!


text:
Q: Transpile async/await function from NodeJS to browser side vis Browserify I have a .js code that is a NodeJS code and is wrote for back-end. But, I want to transpile it to client side. I use Browserify for this purpose. It worked and works until I faced to an error when I browserified the .js file by an async/await function. There is an async/await function in back-end JavaScript that should fetch a file. The async function is:
async function accountHistory(address){
      web3.eth.getBlockNumber().then(function(blockNumber){
           const timeLine=await fetch(<file>);
         });
       }

This causes this error in browserifying:
SyntaxError: Unexpected token (102:57) while parsing E:\Crypto-Wallet-Demo\New-Wallet.js while parsing file: E:\Crypto-Wallet-Demo\New-Wallet.js
    at DestroyableTransform.end [as _flush] (C:\Users\lenovo\AppData\Roaming\npm\node_modules\browserify\node_modules\insert-module-globals\index.js:114:21)
    at DestroyableTransform.prefinish (C:\Users\lenovo\AppData\Roaming\npm\node_modules\browserify\node_modules\readable-stream\lib\_stream_transform.js:138:10)
    at DestroyableTransform.emit (node:events:390:28)
    at prefinish (C:\Users\lenovo\AppData\Roaming\npm\node_modules\browserify\node_modules\readable-stream\lib\_stream_writable.js:619:14)
    at finishMaybe (C:\Users\lenovo\AppData\Roaming\npm\node_modules\browserify\node_modules\readable-stream\lib\_stream_writable.js:627:5)
    at endWritable (C:\Users\lenovo\AppData\Roaming\npm\node_modules\browserify\node_modules\readable-stream\lib\_stream_writable.js:638:3)
    at DestroyableTransform.Writable.end (C:\Users\lenovo\AppData\Roaming\npm\node_modules\browserify\node_modules\readable-stream\lib\_stream_writable.js:594:41)
    at DestroyableTransform.onend (C:\Users\lenovo\AppData\Roaming\npm\node_modules\browserify\node_modules\readable-stream\lib\_stream_readable.js:577:10)
    at Object.onceWrapper (node:events:509:28)
    at DestroyableTransform.emit (node:events:402:35)

Whenever I erase the async and await keywords from the code, browserifying is successfull but fetching is incomplete.
What is the problem? What should I do? How can I browserify an async/await function by Browserify?


text:
Q: How to download in-memory-ZIP-FILE object using Flask send_file With Flask HTTP server running server.py:
import os, io, zipfile, time

from flask import Flask, request, send_file

app = Flask(__name__)

FILEPATH = '/change/it/to/any_file.path'

@app.route('/download', methods=['GET','POST'])
def download():
    fileobj = io.BytesIO()
    with zipfile.ZipFile(fileobj, 'w') as zip_file:
        zip_info = zipfile.ZipInfo(FILEPATH)
        zip_info.date_time = time.localtime(time.time())[:6]
        zip_info.compress_type = zipfile.ZIP_DEFLATED
        with open(FILEPATH, 'rb') as fd:
            zip_file.writestr(zip_info, fd.read())
    fileobj.seek(0)

    return send_file(fileobj.read(), mimetype='zip', as_attachment=True, attachment_filename = '%s.zip' % os.path.basename(FILEPATH))

app.run('0.0.0.0', 80)

the client.py sends a request to download the file:
import requests
response = requests.post('http://127.0.0.1:80/download', timeout = 6000)
print type(response)

The server raises a TypeError:
TypeError: file() argument 1 must be encoded string without NULL bytes, not str
How to fix the problem?

A: One of the possible solutions would use Flask.make_response method:
from flask import Flask, request, send_file, make_response

@app.route('/download', methods=['GET','POST'])
def download():
    fileobj = io.BytesIO()
    with zipfile.ZipFile(fileobj, 'w') as zip_file:
        zip_info = zipfile.ZipInfo(FILEPATH)
        zip_info.date_time = time.localtime(time.time())[:6]
        zip_info.compress_type = zipfile.ZIP_DEFLATED
        with open(FILEPATH, 'rb') as fd:
            zip_file.writestr(zip_info, fd.read())
    fileobj.seek(0)

    response = make_response(fileobj.read())
    response.headers.set('Content-Type', 'zip')
    response.headers.set('Content-Disposition', 'attachment', filename='%s.zip' % os.path.basename(FILEPATH))
    return response


text:
Q: Display JSON Objects as options in dropdown I have a simple HTML page in which I would like to read objects from a JSON file and show them as options in a dropdown using JavaScript. HTML and JSON are as below :
HTML
<html>
  <body>
    <select id="myid">MyList</select>
    <script src="myscript.js"></script>
  </body>
</html>

JSON
[{"Mode":"CARD"},
{"Mode":"CASH"},
{"Mode":"CHEQUE"}];

Any help w.r.t. the JavaScript is much appreciated!

A: Working and Tested code, for reading the external local JSON file (data.json) using javascript, first create your data.json file with below data:
data = '[{"Mode":"CARD"}, {"Mode":"CASH"}, {"Mode":"CHEQUE"}]';

Mention the path of the JSON file in the script tag
<html>
    <script type="text/javascript" src="data.json"></script>
    <script>
        function addOptions(){
            var jsonArray = JSON.parse(data);
            var select = document.getElementById('dd');
            var option;
            for (var i = 0; i < jsonArray.length; i++) {
              option = document.createElement('option');
              option.text = jsonArray[i]["Mode"];
              select.add(option);
            }
        }
    </script>
    <body onload="addOptions();">
        <select id="dd"></select>
    </body>
</html>

A: If you had a server resource that returned the following.
/myjson
[
    {
        "Mode": "CARD"
    },
    {
        "Mode": "CASH"
    },
    {
        "Mode": "CHEQUE"
    }
]

Then create the <option> elements using JavaScript.
$.ajax({
    url:'/myjson',
    type:'GET',
    dataType: 'json',
    success: function( json ) {
        $.each(json, function(i, value) {
            $('#myid').append($('<option>').text(value).attr('value', value.Mode));
        });
    }
});


text:
Q: How to optimize percentage check and cols drop in large pyspark dataframe? I have a sample pandas dataframe like as shown below. But my real data is 40 million rows and 5200 columns
 df = pd.DataFrame({
'subject_id':[1,1,1,1,2,2,2,2,3,3,4,4,4,4,4],
'readings' : ['READ_1','READ_2','READ_1','READ_3',np.nan,'READ_5',np.nan,'READ_8','READ_10','READ_12','READ_11','READ_14','READ_09','READ_08','READ_07'],
 'val' :[5,6,7,np.nan,np.nan,7,np.nan,12,13,56,32,13,45,43,46],
 })

from pyspark.sql.types import *
from pyspark.sql.functions import isnan, when, count, col

mySchema = StructType([ StructField("subject_id", LongType(), True)\
                       ,StructField("readings", StringType(), True)\
                       ,StructField("val", FloatType(), True)])

spark_df = spark.createDataFrame(df,schema=mySchema)

spark_df.select([((count(when(isnan(c)|col(c).isNull(), c))/spark_df.count())*100).alias(c) for c in spark_df.columns]).show()

The above code helps me to get the percentage of nulls/nan in each column. But when I run the same on my real data, the code is been running for a long time but no output yet. How do I optimize this search and drop the columns which has 80% of nulls/nan? Below is my server config

UPDATED SCREENSHOT


text:
Q: Too many arguments fo function call I'm getting started with C++ and using a beginner project template for ATM Banking system. Alot of the functions are set up, but I am adding a function to check for duplicate account number when creating a new account. A user is asked to enter their new account number, which then I am adding a function to check if it exists now. If the account exists I want the function to run again and ask user for an account number again and run through the duplicate check again.
I get this message:

error: too many arguments to function call, expected 0, have 1
      int dup = ac.check_duplicate(acno);

Here's what fires in order:
User chooses to create account:
void write_account()
{

    account ac;
    ofstream outFile;
    ifstream inFile;
    outFile.open("account.dat", ios::binary | ios::app);
    ac.create_account();
    outFile.write(reinterpret_cast<char *>(&ac), sizeof(account));
    outFile.close();
}

Create_account:
void account::create_account()
{
    account ac;
    cout << "\nEnter The account No. :";
    cin >> acno;
    cout << "\nChecking account No...";

    int dup = ac.check_duplicate(acno);
    if (dup == 1)
    {
        cout << "\n\nEnter The Name of The account Holder : ";
        cin.ignore();
        cin.getline(name, 50);
        cout << "\nEnter Type of The account (C/S) : ";
        cin >> type;
        type = toupper(type);
        cout << "\nEnter The Initial amount(>=500 for Saving and >=1000 for current ) : ";
        cin >> deposit;
        cout << "\n\n\nAccount Created..";
    }
    cout << "\nAccount No. is taken. Please choose a different account No.";
    ac.create_account();
}

check_duplicate
    int check_duplicate(int n)
{
    bool found = false;
    int num;
    account ac;
    fstream File;
    File.open("account.dat", ios::binary | ios::in | ios::out);
    if (!File)
    {
        cout << "File could not be open !! Press any Key...";
    }
    while (!File.eof() && found == false)
    {
        File.read(reinterpret_cast<char *>(&ac), sizeof(account));
        if (ac.retacno() == n)
        {
            return 0;
            found = true;
        }
    }
    File.close();
    if (found == false)
        return 1;
}


text:
Q: Lazy Loading not working properly I am showing a list of contacts in a recyclerview. I am showing contact profile images, first I am loading these images from server and then storing these images in an external memory.
Then Loading the images from external storage. I can see the images loaded, but as I scroll I can see some images for a second or two then they get disappear and I can see the default image icon.
public class ContactAdapter extends RecyclerView.Adapter<ContactAdapter.ContactHolder> {

    private List<Contact> contactList;
    File myDir1;
    private Activity mContext;

    private Boolean fileExists;
    private File file;
    private static final int MY_PERMISSIONS_REQUEST_CALL= 20;

    public ContactAdapter(Activity context, List<Contact> contactList) {
        this.contactList = contactList;
        this.mContext = context;
    }

    @Override
    public ContactHolder onCreateViewHolder(ViewGroup viewGroup, int i) {

        View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.item_layout,null);
        ContactHolder mh = new ContactHolder(v);

        return mh;
    }

    @Override
    public void onBindViewHolder(final ContactHolder contactHolder, int i) {

        final Contact contact = contactList.get(i);
        //  Log.e("Imagename",""+"http://xesoftwares.co.in/contactsapi/profile_images/85368a5bbd6cffba8a3aa202a80563a2.jpg");//+feedItem.getThumbnail());

        Target target = new Target() {

            @Override
            public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {

                // your code here ...

                bitmap = Bitmap.createScaledBitmap(bitmap,(int)(bitmap.getWidth()*0.8), (int)(bitmap.getHeight()*0.8), true);

                contactHolder.thumbnail.setImageBitmap(bitmap);

                Log.e("ProfileImage", contact.getmProfileImage());

                SaveImages(bitmap, contact.getmProfileImage());

            }

            @Override
            public void onBitmapFailed(Drawable errorDrawable) {
                contactHolder.thumbnail.setImageDrawable(errorDrawable);
                // do error handling as required
            }

            @Override
            public void onPrepareLoad(Drawable placeHolderDrawable) {
                contactHolder.thumbnail.setImageDrawable(placeHolderDrawable);
            }
        };

        contactHolder.thumbnail.setTag(target);

        String url = ServiceUrl.getBaseUrl() + ServiceUrl.getImageUserUrl() + contact.getmProfileImage();

        Log.e("url",url);

        if(contact.getmProfileImage().equals(""))

        {

            file = new File("");

            fileExists = file.exists();

            contactHolder.thumbnail.setImageDrawable(ContextCompat.getDrawable(mContext, R.drawable.ic_account_circle_black_48dp));
        }
        else {

            file = new File(Environment.getExternalStorageDirectory() + "/ContactProfileImages/" + contact.getmProfileImage());

            fileExists = file.exists();
        }

        if(fileExists)
        {

            Log.e("fileExists",file.getAbsolutePath());

            BitmapFactory.Options bmOptions = new BitmapFactory.Options();
            Bitmap bitmap = BitmapFactory.decodeFile(file.getPath(), bmOptions);

            contactHolder.thumbnail.setImageBitmap(bitmap);

        }

        else {

            Log.e("Picasso",file.getAbsolutePath());

            Picasso.with(mContext).load(url)
                    .error(R.drawable.ic_account_circle_black_24dp)
                    .placeholder(R.drawable.ic_account_circle_black_24dp)
                    .into(target);
        }

        contactHolder.title.setText(contact.getmUserName());
        //feedListRowHolder.genre.setText(Html.fromHtml(feedItem.getGenre()));

    }

    @Override
    public int getItemCount() {
        return (null != contactList ? contactList.size() : 0);
    }

    public void SaveImages(Bitmap bitmap,String profileName)
    {

        try {
            String root = Environment.getExternalStorageDirectory().getPath();
            File myDir = new File(root +"/ContactProfileImages");

            if (!myDir.exists()) {
                myDir.mkdirs();
            }

            // String name = new Date().toString();=
            String name = profileName;
            File myDir1 = new File(myDir, name);
            if(!myDir1.exists()) {
                FileOutputStream out = new FileOutputStream(myDir1);
                bitmap.compress(Bitmap.CompressFormat.PNG,100,out);

                out.flush();
                out.close();
            }

        } catch(Exception e){
            // some action
        }

        //myDir1= imageFilePath1.getprofile();

    }

    public class ContactHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
        protected CircleImageView thumbnail;
        protected TextView title;

        public ContactHolder(View view) {
            super(view);
            this.thumbnail = (CircleImageView) view.findViewById(R.id.thumbnail);
            this.title = (TextView) view.findViewById(R.id.title);
            view.setOnClickListener(this);

        }

        @Override
        public void onClick(View v) {

            final Contact contact = contactList.get(getAdapterPosition());

            final Dialog dialog = new Dialog(mContext);
            dialog.setCanceledOnTouchOutside(true);
            dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
            dialog.setContentView(R.layout.custom);
            final Window window = dialog.getWindow();

            WindowManager.LayoutParams wlp =window.getAttributes();
            wlp.gravity = Gravity.CENTER_HORIZONTAL|Gravity.TOP;
            wlp.y=320;
            window.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
            window.setAttributes(wlp);

            // set the custom dialog components - text, image and button
            TextView txtusername = (TextView) dialog.findViewById(R.id.txtusername);
            TextView txtmobile = (TextView) dialog.findViewById(R.id.txtmobile);
            TextView txtemail = (TextView) dialog.findViewById(R.id.txtemail);

            txtusername.setText(contact.getmUserName());
            txtemail.setText(contact.getmEmailId());
            txtmobile.setText(contact.getmMobileNo());

            SquareImageView image = (SquareImageView) dialog.findViewById(R.id.image);
            ImageView image1 = (ImageView) dialog.findViewById(R.id.image1);
            ImageView image2 = (ImageView) dialog.findViewById(R.id.image2);
            ImageView image3 = (ImageView) dialog.findViewById(R.id.image3);

            if(contact.getmProfileImage().equals(""))

            {
                image.setImageDrawable(ContextCompat.getDrawable(mContext,R.drawable.profile_icon));
            }
            else {
                File file = new File(Environment.getExternalStorageDirectory() + "/ContactProfileImages/" + contact.getmProfileImage());
                BitmapFactory.Options bmOptions = new BitmapFactory.Options();
                Bitmap bitmap = BitmapFactory.decodeFile(file.getPath(), bmOptions);

                image.setImageBitmap(bitmap);
            }

            image1.setImageResource(R.drawable.ic_call_black_24dp);
            image2.setImageResource(R.drawable.ic_textsms_black_24dp);
            image3.setImageResource(R.drawable.ic_email_black_24dp);

            image2.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {

                    Uri sms_uri = Uri.parse("smsto:" + contact.getmMobileNo());
                    Intent sms_intent = new Intent(Intent.ACTION_SENDTO, sms_uri);
                    mContext.startActivity(sms_intent);
                    dialog.dismiss();

                }
            });

            image1.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {

                        Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + contact.getmMobileNo()));
                        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
                        mContext.startActivity(intent);
                        dialog.dismiss();
                }
            });

            image3.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Intent email = new Intent(Intent.ACTION_SEND);
                    email.putExtra(Intent.EXTRA_EMAIL, new String[]{contact.getmEmailId()});
                    email.setType("message/rfc822");
                    mContext.startActivity(Intent.createChooser(email, "Choose an Email client :"));

                }
            });

            Button dialogButton = (Button) dialog.findViewById(R.id.dialogButtonOK);
            // if button is clicked, view all information custom dialog

            dialogButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {

                    ((MainActivity)mContext).finish();

                    Intent intent = new Intent(mContext,DetailViewActivity.class);
                    intent.putExtra("contact",contact);
                    intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TASK);
                    intent.addFlags(Intent.FLAG_ACTIVITY_NO_ANIMATION);
                    mContext.startActivity(intent);

                    dialog.dismiss();

                }
            });
            dialog.show();

        }
    }
 }

EDIT : I searched for the same issue with picasso library, when we load images from server, for this I got the solution from SO as :
   recyclerView.setHasFixedSize(true);
    recyclerView.setItemViewCacheSize(20);
    recyclerView.setDrawingCacheEnabled(true);
    recyclerView.setDrawingCacheQuality(View.DRAWING_CACHE_QUALITY_HIGH);

And this worked when I am loading the images from server, but when I am loading the images from the external storage still the problem exists.
Can anyone help with this please? Thank you..

A:
Then Loading the images from external storage. I can see the images
  loaded, but as I scroll I can see some images for a second or two then
  they get disappear and I can see the default image icon.

This is becuase you are using Target callback in picasso. And callbacks are called little bit late when you are scrolling the list. Just remove the target and use the imageview into Picasso, it should work fine. Also you don't need to cache bitmaps on your own as Picasso does it for you.
public void onBindViewHolder(final ContactHolder contactHolder, int i) {
    final Contact contact = contactList.get(i);
    //  Log.e("Imagename",""+"http://xesoftwares.co.in/contactsapi/profile_images/85368a5bbd6cffba8a3aa202a80563a2.jpg");//+feedItem.getThumbnail());

    String url = ServiceUrl.getBaseUrl() + ServiceUrl.getImageUserUrl() + contact.getmProfileImage();
    Log.e("url",url);

    if(contact.getmProfileImage().equals("")) {
        file = new File("");
        fileExists = file.exists();
        contactHolder.thumbnail.setImageDrawable(ContextCompat.getDrawable(mContext, R.drawable.ic_account_circle_black_48dp));
    } else {
        file = new File(Environment.getExternalStorageDirectory() + "/ContactProfileImages/" + contact.getmProfileImage());
        fileExists = file.exists();
    }

    Log.e("Picasso",file.getAbsolutePath());

    Picasso.with(mContext).load(url)
        .error(R.drawable.ic_account_circle_black_24dp)
        .placeholder(R.drawable.ic_account_circle_black_24dp)
        .into(contactHolder.thumbnail);

    contactHolder.title.setText(contact.getmUserName());
    //feedListRowHolder.genre.setText(Html.fromHtml(feedItem.getGenre()));
}

A: use this code in your Application class to apply setting in whole app.
final int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
// Use 1/8th of the available memory for this memory cache.
final int cacheSize = maxMemory / 8;
Picasso.Builder builder = new Picasso.Builder(getApplicationContext());
builder.memoryCache(new LruCache(cacheSize));
Picasso built = builder.build();
built.setIndicatorsEnabled(true);// it will show indicator where it downloaded from
built.setLoggingEnabled(false);
Picasso.setSingletonInstance(built);

now pass the url to Picasso  to load it to view .If you are dealing with large image you can resize image size also for faster loading.
Picasso
    .with(mContext)
    .load(url)
    .error(R.drawable.on_error)
    .placeholder(R.drawable.place_holder)
    //.resize(custom_width,custom_height)  put custom_height to 0 if you want to maintain aspect ratio
    .into(your_view);

A: I may mistake, but your problem could be caused by that you use Contact that you got from your dataset by layout position, but since you use it asynchroniously in onBitmapLoaded callback, the position could already be changed at that moment. So all you need is to use adapter position as follows:
@Override
public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {

     // your code here ...

    Contact c = contactList.get(contactHolder.getAdapterPosition());

    bitmap = Bitmap.createScaledBitmap(bitmap,(int)(bitmap.getWidth()*0.8), (int)(bitmap.getHeight()*0.8), true);

    contactHolder.thumbnail.setImageBitmap(bitmap);

    Log.e("ProfileImage", c.getmProfileImage());

    SaveImages(bitmap, c.getmProfileImage());
}

I'm not sure that it would be helpful, but let's try, and I hope it will be:)

A: If you wanna simply load the image then why you need to store in the external storage.if you have to store for any other purpose then store it but when you show it in the ImageView then please use any third party api like Picasso or Universal Image Loader it does lazy loading and also it does all type of cache memory management also provies many display fasality.
Hope this will help you

A: Operations like loading images should be performed using AsyncTask on a background thread.

A: *

*Check every images how much MB it is.For Example : If the
image is 1mb or 500kb it will take more time to download images in
background and after downloaded it will store in catche.That means
first time only it will take some time to download the image.

*on the second time, those images from catche.It will show all the
images in the fraction of seconds.

*Use Volley - for faster and Glide - for Memory management.
Glide
    .with(context)
    .load(rowItem.getPosteduserpostimage())
    .asBitmap()
    .diskCacheStrategy(DiskCacheStrategy.SOURCE)
    .fitCenter()
    .placeholder(R.drawable.load_image)
    .error(R.drawable.cancel_image)
    .into(holder.ivPostedImageNew);

*Refer
here
how to load large size bitmap.You need to scale down image.

*Otherwise, When I'm uploading every image, I did crop using
library.It will take care of scale down large bitmap.for eg: 5mb
images will be scale down to 180 kb.

*Check this CropImage
lib
to scale down bigger size images.Even if user not crop image,just
select the entire portion when cropping, it will scale down 5 mb to
180kb.Image Quality also good.
I think without crop also you can use the below code to scale down image.You can see this code in that:
private void startCropImage() {

    Intent intent = new Intent(this, CropImage.class);

    intent.putExtra(CropImage.IMAGE_PATH, mFileTemp.getPath());
    intent.putExtra(CropImage.SCALE, true);
    intent.putExtra(CropImage.ASPECT_X, 0); //3 for aspect ratio
    intent.putExtra(CropImage.ASPECT_Y, 0); //2 for aspect ratio

    startActivityForResult(intent, REQUEST_CODE_CROP_IMAGE);
}

*

*And also don't use nested scroll view inside recyclerview.


text:
Q: Maximising an expression We are to maximise $x^{2}y-y^{2}x$, where $x,y \in [0,1]$. I've tried using AM-GM to find another (easier to maximise) expression, which gave me $xy(x-y) \le \frac{1}{2}(x^{2}+y^{2}) (x-y)$ but that doesn't appear to help.
The next part of the question asks to maximise $x^{2}y+y^{2}z+z^{2}x-x^{2}z-y^{2}x-z^{2}y$, where $x,y,z \in [0,1]$. I would imagine that this is simply triple the maximum for the first expression.
Any help would be appreciated.
NOTE: I shouldn't be using any calculus.

A: By AM-GM
$$x^2y-xy^2=xy(x-y)\le x\cdot \left(\frac {y+(x-y)}2\right)^2=\frac{x^3}4\le \frac14$$
with equality at the first $\le$ iff $y=x-y$ (i.e. $x=2y$) and at the second $\le$ iff $x=1$. Hence
$$x^2y-xy^2\le\frac 14$$
with equality iff $x=1$, $y=\frac 12$.

A: A small technicality here, AM-GM only works in general for positive reals, although in this case using it works because $ab\le\frac{(a+b)^2}{4}\Leftrightarrow\frac{(a-b)^2}{4}\ge 0$ is true for all reals.
As for the second question, it can be approached similarly:
Note that $x^2y+y^2z+z^2x-xy^2-yz^2-zx^2=(x-z)(z-y)(y-x)$. Now two of $x-z, z-y, y-x$ have the same sign, so WLOG let them be $x-z, z-y$. Then we have $|x-z|+|z-y|=|x-y|$. Note that:
$$(x-z)(z-y)(y-x)\le (|x-z||z-y|)|y-x|\le \frac{|x-y|^3}{4}\le \frac{1}{4}$$
Equality holds here when $y=1, x=0, z=\frac{1}{2}$, or the cyclic permutations.


text:
Q: Getting "Android resource linking failed" even though my code has not changed Recently I have been getting this error while running my app:
Execution failed for task ':app:processDebugResources'.
> A failure occurred while executing com.android.build.gradle.internal.tasks.Workers$ActionFacade
   > Android resource linking failed
     C:\Users\Ved\.gradle\caches\transforms-2\files-2.1\17b6ef056be36c409382a0a8037faedc\core-1.7.0\res\values\values.xml:105:5-114:25: AAPT: error: resource android:attr/lStar not found.

And:
Android resource linking failed
C:\Users\Ved\.gradle\caches\transforms-2\files-2.1\17b6ef056be36c409382a0a8037faedc\core-1.7.0\res\values\values.xml:105:5-114:25: AAPT: error: resource android:attr/lStar not found.

When I click on it, it takes me to values.xml line 150:
<declare-styleable name="ColorStateListItem">
        <!-- Base color for this state. -->
        <attr name="android:color"/>
        <!-- Alpha multiplier applied to the base color. -->
        <attr format="float" name="alpha"/>
        <attr name="android:alpha"/>
        <!-- Perceptual luminance applied to the base color. From 0 to 100. -->
        <attr format="float" name="lStar"/>
        <attr name="android:lStar"/>
    </declare-styleable>

I don't even use this styleable yet the error persists. I have read posts talking about the problem being with my compileSDK or with android-core:core-ktx:+
However when i change the SDK to 31 and android-core:core-ktx:1.7.0 it still doesn't work and gives me another error. I have been trying to find the answer but I haven't been able to and hopefully one of you can.
Here are my build gradles:

apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'

android {
    compileSdkVersion 29

    defaultConfig {
        applicationId "com.suad.venttome"
        minSdkVersion 15
        targetSdkVersion 29
        versionCode 6
        versionName "1.5"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: "libs", include: ["*.jar"])
    implementation 'androidx.appcompat:appcompat:1.2.0'
    implementation 'com.google.android.material:material:1.2.1'
    implementation 'com.google.android.material:material:1.2.1'
    implementation 'androidx.constraintlayout:constraintlayout:2.0.4'
    implementation 'androidx.lifecycle:lifecycle-extensions:2.2.0'
    implementation 'androidx.legacy:legacy-support-v4:1.0.0'
    implementation 'androidx.core:core:1.3.2'
    testImplementation 'junit:junit:4.13'
    androidTestImplementation 'androidx.test.ext:junit:1.1.2'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'
    implementation 'com.google.android.material:material:1.3.0-alpha04'
    implementation 'com.jjoe64:graphview:4.2.2'
    implementation 'com.github.PhilJay:MPAndroidChart:v3.1.0'

    //Passcode view
    implementation 'com.hanks:passcodeview:0.1.2'

    //Material.io implementation
    implementation 'com.google.android.material:material:1.2.0-alpha04'

    //Android Jetpack Navigation
    def nav_version = "2.3.2"
    implementation "androidx.navigation:navigation-fragment:$nav_version"
    implementation "androidx.navigation:navigation-ui:$nav_version"
    implementation "androidx.core:core-ktx:+"
    implementation "androidx.lifecycle:lifecycle-viewmodel-ktx:2.2.0"
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
}
repositories {
    maven { url 'https://dl.bintray.com/kotlin/kotlin-eap' }
    mavenCentral()
}

AND:
// Top-level build file where you can add configuration options common to all sub-projects/modules.
buildscript {
    ext.kotlin_version = '1.4.30-M1'
    repositories {
        google()
        jcenter()
        maven { url 'https://dl.bintray.com/kotlin/kotlin-eap' }
    }
    dependencies {
        classpath "com.android.tools.build:gradle:4.0.0"
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"

        // NOTE: Do not place your application dependencies here; they belong
        // in the individual module build.gradle files
    }
}

allprojects {
    repositories {
        google()
        jcenter()
        maven { url 'https://jitpack.io' }
    }
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

If you have a possible solution I would love to her it. Thanks in advance!

A: just change
implementation "androidx.core:core-ktx:+"

to
implementation "androidx.core:core-ktx:1.6.0"

with version 1.7.0 it also does't work for me


text:
Q: Why isn't GROUP_BY returning the desired records? Given a table of:
invitations (id, created_at, type, email)

Given the following query:
SELECT DISTINCT email_address
FROM invitations
WHERE type = 'email'
AND date(created_at) in (curdate() - interval 3 day,
                           curdate() - interval 8 day,
                           curdate() - interval 13 day,
                           curdate() - interval 21 day,
                           curdate() - interval 34 day,
                           curdate() - interval 50 day);

Given my query above, I get several hundred records. What I would like is to get the records grouped by email, meaning a unique email should exist at most once.
I therefore added:
GROUP BY email_address

This results in only 2 records when I run the query... Am I using GROUP BY incorrectly?

A: There's no point doing SELECT DISTINCT email ... GROUP BY email - use either the DISTINCT  or the GROUP BY to achieve the same result
If you got two email addresses out as a result, then the set of records selected only contained two unique email addresses
GROUP BY is used to aggregate data where some combination of columns is the same. Any other columns outside this combination must be contained within an agregation function like AVG, MAX, SUM etc
An example:
SELECT city, ethnicity, MAX(age), AVG(salary)
FROM people
GROUP BY city, ethnicity

It will present a unique set of city/ethnicity pairs, together with the oldest age and the average pay for the group
DISTINCT is essentially less useful than a GROUP BY, as it doesn't let you run aggregation functions on other columns; it jsut returns a unique set of records across all selected columns. I consider it a convenience equivalent:
SELECT DISTINCT city, ethnicity
FROM people

SELECT city, ethnicity
FROM people
GROUP BY city, ethnicity --more to type

A: I'm assuming here that you want the records group-concatenated as such, or similar, based on your inclusion of the created_at field:
SELECT email, GROUP_CONCAT( DISTINCT created_at ORDER BY created_at DESC ) AS list_of_dates FROM invitations GROUP BY email;

to produce something along the lines of:
email              |  list_of_dates
==========================================================
jenny@hotmail.com  |  01/26/2019, 01/23/2019
jonny@gmail.com    |  01/23/2019, 01/18/2019, 01/13/2019
greg@yahoo.com     |  01/13/2019

, or alternatively:
SELECT created_at, GROUP_CONCAT( DISTINCT email ORDER BY created_at DESC SEPARATOR '; ' ) AS list_of_dates FROM invitations GROUP BY created_at;

created_at  |  list_of_emails
====================================
01/26/2019  |  jenny@hotmail.com
01/23/2019  |  jenny@hotmail.com; jonny@gmail.com
01/18/2019  |  jonny@gmail.com
01/13/2019  |  jonny@gmail.com; greg@yahoo.com

In the context of GROUP_CONCAT(), a GROUP BY is optional and is used to further partition the groupings beyond a single-line aggregate.  If no GROUP BY clause is specified, it'll concatenate everything to a single line.

*

*The DISTINCT keyword inside the GROUP_CONCAT() must precede the concatenation field(s) and will give only the unique field values back

*The optional ORDER BY follows the concatenation field(s) and works the same as in SELECT queries

*SEPARATOR is also optional but must follow ORDER BY if also used; this allows you to specify the joining string used in concatenation

Depending on how many records/how long the concatenation might become, you can adjust the max value by setting the session variable:
SET SESSION group_concat_max_len=<max length>

Either way - use GROUP BY on whichever field you want to summarize and include the others inside GROUP_CONCAT, hopefully this helps.


text:
Q: Python 3 removing puctuation from text file I'm a beginning programmer and I've been having some trouble with my assignment. So i'm hoping you will be able to help me with it. My assignment is as follows:
Write a program in Python that displays on the  screen the last 3  words of lines read from a text file entered as standard input. Assume that all lines in the text file contain at least three words. Consider as a word only a string of at least one letter.
This is the input text file:
Elizabeth it is in vain you say
"Love not"—thou sayest it in so sweet a way:
In vain those words from thee or L.E.L.
Zantippe's talents had enforced so well:
Ah! if that language from thy heart arise,
Breath it less gently forth—and veil thine eyes.
Endymion, recollect, when Luna tried
To cure his love—was cured of all beside—
His follie—pride—and passion—for he died.

and this should be the output:
vain you say
sweet a way
l e l
enforced so well
thy heart arise
veil thine eyes
when luna tried
of all beside
for he died

However, it seems I'm required to remove all punctuation as well. And this is what i'm having trouble with. So here's my code:
import sys

def main():

    for item in sys.stdin:
        item = item.split()[-3:]
        string = ' '.join(item)
        print (string)

main()

A: The best way to do this is s.translate(None, string.punctuation)


text:
Q: add more than one example for request body in post request in swagger Post request in swagger ui
Is there a method to add more than one example for request body using swagger annotaitons?
I have added these annotations to create first example
@Data
public class RefCustomerGenderDto extends BaseDto<Integer> implements Serializable {
@ExampleProperty( value = "genderCode")
@ApiModelProperty( example = "1515")
private String genderCode;
@ApiModelProperty( example = "genderdesc")
private String genderDesc;
@ApiModelProperty( example = "1515")
private Long sortOrder;

}


text:
Q: Error in listing tree structure using ng-repeat in angularjs I am trying to list a nested dictionary on html using ng-repeat
Here is the full code
But it seems like I can't access the value of dictionary key by
tree.value

as it either doesn't show up or will only print
'tree.value'

Can someone help me out?

A: You json is wrongly defined, you should always wrap string value inside single quotes ' like value: c111 & value: 'c112' values should be like value: 'c111' & value: 'c112'
Markup
    <ul ng-include="'myTemplate'"
        ng-init="tree =
                   {
            children:
                [
                    {children: [], value: 'c12'},
                    {
                        children:
                            [
                                {children: [], value: 'c112'},
                                {children: [], value: 'c111'}
                            ],
                        value: c11
                    }
                ],
            value: c1
        }
">

More better would be define tree variable inside $scope rather than on html.
Working JSFiddle

A: it seems c1 is object not string.so c1 has properties.for example c1 has text property.
you should write in template {{tree.value.text}}


text:
Q: Reading all products' tags in a FOR loop with a Shopify theme app extension. Can it be done? I am working on a Shopify app that uses a theme app extension to alter how the price is displayed based on the tags associated with that product. The following code achieves this effect on product pages by inserting these lines of liquid in the price . The if statement looks for a match on the product tags and displays either my code when there is a match or the straight price when there is not.
var x = document.querySelectorAll(".product-single__price");
var i;
for (i=0; i < x.length; i++) {
    x[i].innerHTML = `
      {%- if product.tags contains 'mytags' -%}
        {% comment %} mycode {% endcomment %}
      {%- else -%}
        {{ product.price | money | strip_html }}
      {%- endif -%}
    `;
}

However, I cannot get this to work on collection pages. I'm assuming this is because the theme app extension's injection is occurring after the loop that displays the product grid and the product tags are no longer readable. Even if I assign the last product on the collection page with the tag to match, it doesn't display my code.
Is there a work around where I can pull the tags for each product and inject this code to each in the grid/list?

A: You should render all products in a collection into a Javascript data structure, because as you well know, Liquid renders first, creating a giant string of HTML. Inside this HTML Shopify is injecting your Liquid too in your Theme App Extension. So far so good?
Once the Liquid has been totally rendered, that is, the entire collection up to the limits of pagination are in the DOM would any Javascript execute. So it is at this point that you could iterate the DOM for rendered products, and use it. So you could do your querySelector on product prices, and do your logic based on the data you previously saved.
If you expect to be able to change prices on the fly in the Liquid phase, your logic has to be moved from JS to Liquid itself. In other words, when rendering a single product in the collection template, you alter the price then and there, based on logic you have at your disposal, like a tag or metafield.


text:
Q: mysqli_stmt object is not fully initialized I have an SQL statement in PHP as follows:
$sql = "SELECT t_da_edu_questions.ID, t_da_edu_questions.question_part1, t_da_edu_questions.question_part2, t_da_edu_questions.question_part3, t_da_edu_questions.answer, t_da_edu_questions.option2, t_da_edu_questions.option3, t_da_edu_questions.option4, t_da_edu_questions.option5, t_da_edu_questions.Supplerende, t_da_edu_questions.pic_id, t_da_edu_questions.Category_ID, t_da_edu_questions.approved, t_da_edu_questions.NeedAdmin
        FROM t_da_edu_questions
        WHERE (((t_da_edu_questions.Category_ID=?)) AND ((t_da_edu_questions.approved)=1) AND ((t_da_edu_questions.NeedAdmin)=0) AND
        ((t_da_edu_questions.ID) Not In (SELECT t_da_edu_UserAnswers.ID_qst FROM t_da_edu_UserAnswers WHERE ((t_da_edu_UserAnswers.ID_team = ?) AND T_da_edu_UserAnswers.AnsOrBack = 1 ))))
        ORDER BY RAND()
        LIMIT 1";

$stmt = mysqli_stmt_init($conn);
mysqli_stmt_prepare($stmt, $sql);
mysqli_stmt_bind_param($stmt, "ii", $cat, $TeamID); //(Line 36 in error)
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);

I get the error:

Fatal error: Uncaught Error: mysqli_stmt object is not fully initialized in C:\xampp\htdocs\app\content\db.php:36 Stack trace: #0 C:\xampp\htdocs\app\content\db.php(36): mysqli_stmt_bind_param(Object(mysqli_stmt), 'ii', '6', 304) #1

If I remove the subquery in "Not In" it works fine.
I have not been able to find a similar problem.
So, basically, how do i properly add prepared statement to query with sub query?

A: As usual, you forgot to enable mysqli error reporting. Turn it on and you will see what error is coming from MySQL. To enable it just add this line before making a connection.
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

We can't really tell what the real error is until you enable error reporting. However, I can explain what this cryptic error means.
When you instantiate mysqli_stmt object with mysqli_stmt_init(), it is just a plain PHP object without any prepared statement linked to it. You must call mysqli_stmt_prepare() to prepare the statement on the MySQL server. When there is a problem with your SQL, the preparing will fail and the mysqli_stmt object will remain uninitialized. You can't use such an object for anything.


text:
Q: How to write a LINQ query to select from a collection with given set of matching IDs I'm using a self tracking entity model. ProductInstallation is a DTO which contains all the details about the product installation for a company.
The UserRoles entity holds the relationship in-between the Product-System Role-UserID.
As an example:

Product: Inventory
System Role : PurchasingUser
User ID : hasithaH <- (Suppose me)

using the below LINQ query, I can get the distinct UserIDs.
string[] userIDs = productInstallation.UserRoles
                  .Select(u=>u.UserID).Distinct().ToArray();

now I need to get all the User Profiles for the UserIDs I queried in above steps.
productInstallation.SystemUsers = context.SystemUsers.Select(u=> u.UserID ..???

In SQL point of view, this is the query I want:
Select * from SystemUsers where UserID in ('UserA','UserB','UserC')

How should I write a LINQ query to get this done?

A: You write it as follows:
var result = context.SystemUsers.Where(su =>
               productInstallation.UserRoles.Any(ur => su.UserID == ur.UserId));

Or if both sources are not IQuerable from the same db:
string[] userIDs = productInstallation.UserRoles
                  .Select(u=>u.UserID).Distinct().ToArray();

var result = context.SystemUsers.Where(su =>
                   userIDs.Contains(su.UserID));

A: You can try this:
productInstallation.SystemUsers =
context.SystemUsers.FindAll(u=> userIDs.Contains(u.UserID))

A: What you really want to do here is join the two tables.  Using a Join you can do this in one query rather than executing two separate queries:
var systemUsers = from userRole in UserRoles
                  join systemUser in SystemUsers
                  on userRole.UserID equals systemUser.UserID
                  select systemUser;


text:
Q: Is there a way in Java to find out how many CPUs (or cores) are installed? I want to make some tuning for multithreaded program.
If I know how much threads can really work in parallel I can make the program much more effective.
Is there a way in Java to get this info?

A: One note about the availableProcessors() method, it does not distinguish between physical cpus and virtual cpus.  e.g., if you have hyperthreading enabled on your computer the number will be double the number of physical cpus (which is a little frustrating).  unfortunately, there is no way to determine real vs. virtual cpus in pure java.

A: Runtime.getRuntime().availableProcessors();

A: How about (code snippets speak a 1000 words):
 public class Main {

 /**
  * Displays the number of processors available in the Java Virtual Machine
  */
 public void displayAvailableProcessors() {

    Runtime runtime = Runtime.getRuntime();

    int nrOfProcessors = runtime.availableProcessors();

    System.out.println("Number of processors available to the Java Virtual Machine: " + nrOfProcessors);

 }

 public static void main(String[] args) {
    new Main().displayAvailableProcessors();
 }
}

A: You can use
Runtime.getRuntime().availableProcessors()

But its more of a best guess and even mentioned by the API

This value may change during a particular invocation of the virtual
        machine.  Applications that are sensitive to the number of available
        processors should therefore occasionally poll this property and adjust
        their resource usage appropriately.

A: Yes on windows for sure. JNA with kernel32.dll. Use SYSTEM_INFO structure from GetNativeSystemInfo call. There is dwNumberOfProcessors among other things.
I believe this will provide the actual number of processors installed, not the number available.


text:
Q: Javascript code to verify a URL works in IE and Chrome, but not in Firefox I am using the following code to determine whether a file exists on a site. I'm checking for large files, so I don't need to wait for it to download, I just need to know if it exists. When I run the code on IE (11.0.9600.17843) or Chrome (43.0.2357.134), it returns true for the file. When I run it on Firefox (39.0), it returns null for the same file.
    function checkUrl(url) {
        var aborted = false;
        try {

            var request = new XMLHttpRequest();
            var timer = Date.now();
            request.onreadystatechange = function () {
                if ((request.readyState > 1) & (request.status === 200)) {
                    aborted = true;
                    request.abort();
                    return true;
                }
            }
            request.open('GET', url, false);
            request.send();
            if (request.status === 200) {
                return true;
            }
        }
        catch (e) {
            console.log(e.message);
            if (aborted) { return true; }
        }
    }

Any ideas why it's not working on Firefox?

A: Instead of issuing a GET request you can just issue a HEAD request. HEAD requests will only return the headers of the requested resource, not the body, so it's perfect for querying the existence of files.


text:
Q: How to hide addThis plugin on vertical scroll I'm using addThis social plugin on my blog. I believe the plugin is floating at a fixed position as I see in it's css file.
I don't think I can control that file. Correct me, if I'm wrong.

Problem: how do I let it go upwards and hide after scrolling down.

This is not a highly critical problem but I do not want our readers to get annoyed with that sticky thing.

A: You mean to hide the Sharing Sidebar tool when scrolling down the page? If so, unfortunately we don't offer any support for it. The Sharing Sidebar tool was designed to appear at the leftmost or rightmost side of the page. But you're welcome to apply your own CSS/JavaScript to any of our existing elements.  I'll pass your feedback along to our team.
Thanks!

A: The position of .atss Class is fixed you may may uses JQuery to make it to position:absolute
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
     $(".atss").css("position","absolute");
});
</script>

Include This script in your website!! You can feel the diffrence.

A:
!important css

The issue was resolved by using !important css declaration in the site's main css file
Below is the snapshot of the same:
//Keep addThis unsticky
.atss{
      position:absolute !important;
}

Thanks to hemnath and ribin for their opinions.


text:
Q: Porque el if...else se ignora En este codigo no entiendo porque el if que esta adelante se ignora ya que aunque haya un error en la autenticacion, siempre pasa a la pagina principal sin importar si la variable err es true.
entrar()
{
var err=false;

firebase.auth().signInWithEmailAndPassword(this.email, this.password).then(function(result){
  console.log("exito");
  err=false
})
.catch(function(error) {
  console.log("error");
  console.log(error.code);
  console.log(error.message);
  err=true;
});

if (err){
console.log("error");}
else{
this.navCtrl.push(HomePage);}
}

Alguien me explica que estoy haciendo mal.

A: Ya teniendo una funcion then y err escribiendo la lógica de cuando es satisfactorio y cuando da error quedaria lo siguiente :
entrar(){
  var err=false;
  var _this = this; //guardamos la instancia
  firebase.auth().signInWithEmailAndPassword(this.email,
  this.password).then(function(result){
    console.log("exito");
    err=false;
    _this.navCtrl.push(HomePage);
  })
  .catch(function(error) {
    console.log("error");
    console.log(error.code);
    console.log(error.message);
    err=true;
});

Con respecto al guardar la instancia this , generalmente el this es el objeto que llama a la funcion, ya sea un objeto javascript o un objeto del DOM, pero cuando utilizas funciones que llaman funciones anónimas el alcance de this el contexto es el dentro de la funcion por eso te da undefined.
Te aconsejo que busques un tutorial sobre el this en javascript, porque es un poco complicado de explicar (al menos para mi), aprenderlo en la practica será darte de cabezazos contra el teclado.
Algunos enlaces de referencia

Contexto this en un Objeto
Que Son Promesas


text:
Q: java.sql.SQLException:EXECUTE permission denied on object testproc, database mydatabase, owner dbo - Sybase ASE Im using Sybase ASE DB.
I do like this:
  Create procedure testproc
As
Begin
  SELECT @line = 'drop table testtable'
        execute(@line)
end

This works fine if I execute this proc directly. But when I execute a
stmt= connection.prepareCall("{ call testproc }");
    stmt.execute();

Error:
throws
java.sql.SQLException:EXECUTE permission denied on object testproc, database mydatabase, owner dbo

The same is working fine with a Sybase IQ DB. How to execute the same in ASE?


text:
Q: Rename only visible layers in illustrator javascript Super noob question. I found a code that renames my top level layers as "Frame 1, Frame 2, etc..." How can I have the rename apply ONLY to visible layers? Second question is how do I rename only a selected layer (whether it visible or not) to "Frame 1" or whatever I choose and not affect any other layers in the document?
Here is the code.
    var doc = app.activeDocument;

    idLayers(doc); // Rename layers

    function idLayers(doc){
        for(i=0;doc.layers.length>i;i++){
            var currentLayer = doc.layers[i];
            currentLayer.name= 'Frame  '+(i+1);
        }
}

Thank you so much for your help!

A: This can all be easily found in the  illustrator scripting reference.
This script does both things you asked, just comment out the function call you don't want to run and put the layer prefix or name you want for the layer in the function call.
var doc = app.activeDocument;

idLayers("Frame "); // Rename visible layers
renameSelectedLayer("Active"); // Rename active layers

// Hidden layers will be skipped and not counted
function idLayers(prefix){
  var counter = 1;
  for(i=0;doc.layers.length>i;i++){
    var currentLayer = doc.layers[i];

    // if layer is visible...
    if (currentLayer.visible) {
      currentLayer.name= prefix + counter;
      counter++;
    }

  }
}

function renameSelectedLayer(layerName){
  doc.activeLayer.name = layerName
}


text:
Q: NameError occurs after switching from vendored gems to Bundler in Rails 2.3.8 /Users/me/.rvm/gems/ree-1.8.7-2011.03@evokat25/gems/activesupport-2.3.8/lib/active_support/dependencies.rb:105:in `const_missing':NameError: uninitialized constant Rails::Initializer::Paperclip
There is no mention of Rails::Initializer::Paperclip anywhere in my code base. Anybody have a clue as to what it is trying to do?

A: I figured this out. I had some configuration lines in config/initializers/.rb and config/environments/.rb. After I put the "require" lines in each for the appropriate gems, the problem disappeared.


text:
Q: Use czech chars in regular expression I need to use regular expression in my webapp, which allows czech characters (ěščřžýáíéóúůďťňĎŇŤŠČŘŽÝÁÍÉÚŮ). Current I have
[a-zA-Z]*\w{1,20}

but this doesn't allow to input them. Thanks

A: var words = Regex.Matches(inputstr, @"[ěščřžýáíéóúůďťňĎŇŤŠČŘŽÝÁÍÉÚŮĚÓa-zA-Z]{1,20}")
                .Cast<Match>()
                .ToArray();

A: Alternative solution (works only for .NET):
[\p{Ll}\p{Lu}]{1,20}

A: Based on this documentation you can use \p{L} to match any letter.
https://javascript.info/regexp-unicode


text:
Q: Is $\lim\limits_{n \to \infty} f(x_{0} + \frac{1}{n}) = \lim\limits_{h \to 0^{+}} f(x_{0} + h) \triangleq f(x_{0}^{+})$? We know in probability, the cumulative distribution function is right continuous. The proof of this statement used a relation that
$$\lim\limits_{n \to \infty} F_{X}\left(x_{0} + \frac{1}{n}\right) = \lim\limits_{h \to 0^{+}} F_{X}(x_{0} + h) \triangleq F_{X}(x_{0}^{+})$$
However, I do not know why this is true? Or is it true in general or only for CDF's?

A: It is not true in general. For CDFs it is true because
\begin{align}
\lim_{n\to \infty} F_X\left(x+\frac{1}{n}\right)&=\lim_{n\to \infty}\mathrm{Pr}\left(X \le x+\frac{1}{n}\right)\\&=\mathrm{Pr}\left(\bigcap_n (X\le x+\frac{1}{n})\right)\\
& =\mathrm{Pr}\left(X\le x\right)=F_X(x).
\end{align}


text:
Q: Визуализация звука с помощью библиотеки BASS на C# Здравствуйте. Недавно занялся написанием плеера на C#. Хотелось бы сделать визуализацию звука, вроде графических образов WMP. Подскажите, как это можно реализовать?

A: Для получения графического представления звука нужно использовать метод BASS_ChannelGetData с флагом BASS_DATA_FFT... Метод возвращает массив амплитуд для набора диапазонов частот. Из него нужно отбросить первый элемент (0 Гц - это постоянная составляющая), и построить график по относительным значениям амплитуды и частоты.
Пример кода для вывода графика в Windows Forms (на форме нужно поместить элементы Button, Panel и Timer):
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Un4seen.Bass;

namespace BassTest
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        int chan = 0;//номер потока
        Single[] fft=null;//массив данных спектра

        private void button1_Click(object sender, EventArgs e)
        {
            int n=Bass.BASS_GetDevice();//получаем устройство по умолчанию
            if (Bass.BASS_Init(n, 44100, 0, IntPtr.Zero) == false)
            {
                MessageBox.Show("BASS_Init failed");
                return;
            }

            chan = Bass.BASS_StreamCreateFile(@"C:\MP3\file.mp3",
                0, 0, BASSFlag.BASS_SAMPLE_FLOAT | BASSFlag.BASS_SAMPLE_LOOP);//создаем поток в режиме FLOAT

            if (chan == 0)
            {
                MessageBox.Show("BASS_StreamCreateFile failed");
                return;
            }

            bool f;
            f = Bass.BASS_ChannelPlay(chan, false);//воспроизводим поток
            if (f == false)
            {
                MessageBox.Show("BASS_ChannelPlay failed");
                return;
            }

        }

        private void timer1_Tick(object sender, EventArgs e)//запускаем каждые 500 мс
        {
            if (chan == 0) return;
            if (Bass.BASS_ChannelIsActive(chan) != BASSActive.BASS_ACTIVE_PLAYING) return;

            fft = new Single[2048];//выделяем массив для данных
            Bass.BASS_ChannelGetData(chan, fft, (int)BASSData.BASS_DATA_FFT4096);//получаем спектр потока
            fft[0] = 0.0f;//избавляемся от постоянной составляющей

            panel1.Refresh();//перерисовка графика
        }

        private void panel1_Paint(object sender, PaintEventArgs e)//построение графика
        {
            if (fft == null) return;

            PointF p1,p2;
            float max_y = 0;//максимальное значение амплитуды
            float min_y=Single.MaxValue;//минимальное значение амплитуды
            float max_x = fft.Length - 1;//максимальная частота, для которой амплитуда ненулевая

            int i = 0;
            max_x = 0;
            foreach(float f in fft)//находим максимальные и минимальные значения
            {
                if (f > max_y) max_y = f;
                if (f < min_y) min_y = f;

                if (f > 0.001f) max_x = (float)i;
                i++;
            }

            /*меняем направление оси Y, чтобы она смотрела вверх*/
            e.Graphics.ScaleTransform(1.0f,-1.0f);
            e.Graphics.TranslateTransform(0.0f, -1.0f * panel1.Height);

            System.Drawing.Drawing2D.GraphicsPath path = new System.Drawing.Drawing2D.GraphicsPath();

            float y;
            p1 = new PointF(0.0f, 0.0f);//начальная точка

            for (float x = 1; x <= max_x; x++)
            {
                y = fft[(int)x];

                /*вычисляем координату следующей точки по относительной амплитуде*/
                p2 = new PointF((x / max_x) * panel1.Width, panel1.Height * (y - min_y) / (max_y - min_y));

                path.AddLine(p1, p2);//добавляем линию в график
                p1 = p2;
            }
            e.Graphics.DrawPath(Pens.Black, path);

        }
    }
}

Выглядит так (не настолько красиво, как в WMP, но уже что-то):


text:
Q: Trying to fix email validation for school project Hey so uh I have a project due in a few days which requires us to make a contact page where someone can enter a name, email address, subject and message. We need to create javascript to make sure all fields are filled in and that the email is valid.
I have written the HTML for the form, as well as the javascript but I have 2 problems:

*

*No error message displays when no message is entered in the memo field

*The email field will not accept a valid email
I have tried to change the ID tag for the email but it automatically allows me to submit straight away without entering any data, I'm quite stuck.
Yes, they are both in two separate documents.
Note: I have not included all the code for the contact page, just the relevant form.
Thank you so much
Here are the images of my code:
HTML for contact page:

Javascript for Contact page:

function checkForm(){
  var isValid = true;
  var name = document.forms['contact']['name'].value;
  var email = document.forms['contact']['emailaddress'].value;
  var emailpattern = /\S+@\S+\.\S+/;
  var subject = document.forms["contact"]["subject"].value;
  var textarea = document.forms["contact"]["memo"].value;
  console.log(name, email, subject, textarea);

if(name == ""){
  document.getElementById('namemessage').innerHTML = "PLEASE enter a name";
  isValid = false;
} else {
  document.getElementById('namemessage').style.display = "none";
}

if(!emailpattern.test(emailaddress)){
  document.getElementById('emailmessage').innerHTML = "PLEASE enter a valid email";
  isValid = false;
}
else {
  document.getElementById('emailmessage').style.display = "none";
}

if(subject == ""){
  document.getElementById('subjectmessage').innerHTML = "PLEASE enter a subject";
  isValid = false;
} else {
  document.getElementById('subjectmessage').style.display = "none";
}

if(memo == ""){
  document.getElementById('memomessage').innerHTML = "PLEASE enter your request";
  isValid = false;
} else {
  document.getElementById('memomessage').style.display = "none";
}
  return isValid;
}
<form action="thankyou.html" name="contact" onsubmit="return checkForm()">
  Name:
  <input type="text" id="name">

  Email Address:
  <input type="text" id="emailaddress">

  Subject:
  <input type="text" id="subject">

  Message:

<textarea id="memo" placeholder = "please type your message here.">
</textarea>

  <input type="submit" value="Submit">

</form>

A:
No error message displays when no message is entered in the memo field

Because you have:
var textarea = document.forms["contact"]["memo"].value;
...
if (memo == "") {

Change textarea to memo.

The email field will not accept a valid email

Because you have:
var email = document.forms['contact']['emailaddress'].value;
...
if (!emailpattern.test(emailaddress)) {

Change emailaddress to email.
Fix those issues and it "works".


text:
Q: OnClientClick event doesn't register javascript alert from code-behind Alright, I have an embarrassingly simple question that hopefully has an embarrassingly simple answer. I am trying to get an asp:ImageButton to display an alert message that contains variables from my codebehind. Here's the overly simplified version of the code:
public string AlertMe
{
    get
    {
        return "alert('hi');";
    }
}

Now when I try and access it this way:
<asp:ImageButton ID="btn" runat="server" ImageUrl="/Images/img.ico" OnClientClick='<%=AlertMe%>'/>

I see a postback, but no alert message, as if it can't access my property at all. Meanwhile, these 2 lines:
<%=AlertMe%>

<a onclick="<%=AlertMe%>">click this

both work fine and dandy. (The first displays the code for the javascript alert, and the second fires the alert with no issues.)
So my big question is: why does the OnClientClick event for an asp control fail to register the alert? Is there an obvious flaw I'm missing, or do I really need to register the entire event from code-behind?

A: You can't use the <%= ... %> syntax to set attributes of a Server Control.  To set dynamic attributes on Server Controls, you have to set it in code.
this.btn.OnClientClick = this.AlertMe;

This is because <%= ... %> is a shortcut for Response.Write().  So, it isn't called until after the aspx has been parsed, evaluated, and rendering has begun.  By then it's too late.
As an alternative to setting the value in the code behind, you could use this quasi-declarative technique:
<asp:ImageButton ID="btn" runat="server" ImageUrl="/Images/img.ico" />
<%
btn.OnClientClick = <%=AlertMe%>;
%>

There are other ways to get around it.  This answer to a similar question discusses several approaches you can take.  I can't find any "official" reference (eg, msdn) that mentions this specifically, but I didn't look that hard.  Here are a couple of blog posts that discuss the issue as well:

*

*Blog post by Jim Black: Server tags cannot contain <% ... %> constructs

*Blog post at weblogs.asp.net: Use ExpressionBuilder To Avoid "Server tags cannot contain <% … %> constructs"
Or google it with bing for more fun reading.

A: For anyone else encountering this issue, I ran across this blog from way back when:
http://weblogs.asp.net/infinitiesloop/archive/2006/08/09/The-CodeExpressionBuilder.aspx
I found the sections about Expression Builders and ViewState concerns to be particularly informative.

A: I think its a quoting problem.  Try
OnClientClick="<%=AlertMe%>"


text:
Q: (How to) When hovering over a logo, transforms up and text appears underneath? On my website, I want to be able to hover my mouse over a logo, the logo will slide (or transform) up, and text will appear underneath. Once you move the mouse away, the logo will slide back down and the text disappears.
I am very new to CSS and HTML and have been self teaching myself.
Please help me out!

A: This should get you started:

/* The wrapper class that will contain the logo and the text */
.logo_wrapper {
  height: 40px;
  overflow: hidden;
}

/* The logo will be the same height as the wrapper and transition for 300ms */
.logo_wrapper img {
  height: 40px;
  width: auto;
  transition: transform 300ms;
}

/* The text should also transition for 300ms */
.logo_wrapper .logo_text {
  transition: transform 300ms;
}

/* When hovering over the wrapper, the logo and text will "translate" up 40px */
.logo_wrapper:hover img, .logo_wrapper:hover .logo_text {
  transform: translateY(-40px);
}

Stack Overflow

A: Here's a demo that took a couple minutes to whip up. The animations are accomplished using CSS transition. Let me know if you have any questions.

.logo {
  width: 180px;
  margin: 0 auto;
  position: relative;
}

.logo__image {
  width: 100%;
  transition: transform .5s;
}

.logo__text {
  color: darkorange;
  font-size: .9em;
  font-weight: bold;
  font-family: sans-serif;
  text-align: center;
  text-transform: uppercase;
  opacity: 0;
  transition: opacity .5s;
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
}

.logo:hover .logo__image {
  transform: translateY(-20px);
}

.logo:hover .logo__text {
  opacity: 1;
}

  Home of the Whopper


text:
Q: Sum rows in Excel with same text value I am trying to sum the rows in Excel that have the same text value in 2 different columns.  I saw the post here Group by Sum in Excel about summing rows with the same text value in one column.  Here is my table:
A     B     C
Item Region quantity_sold
A     South    1
A     South    4
A     North    7
B     South    5
B     South    9
D     South    3
C     South    6
C     South    4
C     North    8

I think I need to use Sumifs instead of Sumif.  I would like the result to be:
Item Region quantity_sold
A     South
A     South     5
A     North     7
B     South
B     South    14
D     South     3
C     South
C     South    10
C     North     8

I tried =IF(A2=A1,"",SUMIFS(A:A,A2,B:B,B2,C:C)) but I got: #VALUE!

A: Try this formula:
=IF(OR(B2<>B3,A2<>A3),SUMIFS($C$2:$C$10,$A$2:$A$10,A2,$B$2:$B$10,B2),"")

On caveat, the columns must be sorted.  This will not work if the columns are not sorted.

A: An alternative I find works well is to add a column which contains both columns you wish to group as a single value.  For example set up col D with this:
=A1&"_"&B1
result is A_South etc

You can then use normal SUMIF, using this column as criteria.
Main benefits are separation of formulae, and you can extend easily to further grouping variables.

A: You can do it using an UDF:
=SumQuatitySold(2;A2;B2;C:C)

Where:

*

*The First entry is the start row, in this case is 2

*The second one is your item (select the cell)

*The third one is the region (select the cell)

*Last one select the column of the quantity_sold

You just need to enter this code in a module:
Function SumQuatitySold(StartRow As Long, Item As Range, region As Range, Quantity_Sold As Range) As Long

Dim ws As Worksheet
Dim i As Long, j As Long

Set ws = ThisWorkbook.ActiveSheet

With ws
    i = Item.Row
    j = StartRow
    Do
            If .Cells(i, Item.Column) = .Cells(j, Item.Column) And .Cells(i, region.Column) = .Cells(j, region.Column) And i <> j Then
                    If quantitysold = 0 Then
                        quantitysold = .Cells(j, Quantity_Sold.Column)
                    Else
                        quantitysold = quantitysold + .Cells(j, Quantity_Sold.Column)
                    End If
            End If
    j = j + 1
    Loop Until IsEmpty(.Cells(j, Quantity_Sold.Column))

 End With

SumQuatitySold = quantitysold + ws.Cells(Item.Row, Quantity_Sold.Column)

End Function


text:
Q: Unable to start elastic search as it cannot find JAVA_HOME I am using docker compose to spin two elastic search services. so I am having a file named elasticsearch.yml . I execute the file using the command (docker-compose -f src/main/docker/elasticsearch.yml up). However when i run, the second service  elasticsearch2 I am getting an error .
Building elasticsearch2
Step 1/5 : FROM docker.elastic.co/elasticsearch/elasticsearch:6.6.1
 ---> c6ffcb0ee97e
Step 2/5 : ADD elasticsearch/scripts/initializeElasticSearch.sh /usr/local/bin/initializeElasticSearch
 ---> 8bd9e8821c4e
Step 3/5 : RUN chmod 755 /usr/local/bin/initializeElasticSearch
 ---> Running in 71184d2e0af6
Removing intermediate container 71184d2e0af6
 ---> bc015460473c
Step 4/5 : ADD elasticsearch/initial-data/cars.json  /tmp/cars.json
 ---> b7140ea04924
Step 5/5 : ENTRYPOINT ["initializeElasticSearch"]
 ---> Running in f29015d87c1d
Removing intermediate container f29015d87c1d
 ---> 5faf42e80d33
Successfully built 5faf42e80d33
Successfully tagged docker_elasticsearch2:latest
WARNING: Image for service elasticsearch2 was built because it did not already exist. To rebuild this image you must use `docker-compose build` or `docker-compose up --build`.
Starting elasticsearch  ... done
Creating elasticsearch2 ... done
Attaching to elasticsearch, elasticsearch2
elasticsearch2    | /opt/jdk-11.0.1
elasticsearch2    | which: no java in (/usr/local/bin:/bin:/usr/bin:/usr/local/sbin:/usr/sbin:/usr/share/elasticsearch/.local/bin:/usr/share/elasticsearch/bin)
elasticsearch2    | could not find java; set JAVA_HOME or ensure java is in PATH
elasticsearch     | OpenJDK 64-Bit Server VM warning: Option UseConcMarkSweepGC was deprecated in version 9.0 and will likely be removed in a future release.
elasticsearch2    |
elasticsearch2    |   % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
elasticsearch2    |                                  Dload  Upload   Total   Spent    Left  Speed
  0     0    0     0    0     0      0      0 --:--:-- --:--:-- --:--:--     0curl: (7) Failed connect to 0.0.0.0:9200; Connection refused

elasticsearch.yml
version: '2.0'
services:
  elasticsearch:
    image: docker.elastic.co/elasticsearch/elasticsearch:6.6.1
    container_name: elasticsearch
    environment:
      - cluster.name=docker-cluster
      - bootstrap.memory_lock=true
      - "ES_JAVA_OPTS=-Xms512m -Xmx512m"
    ulimits:
      memlock:
        soft: -1
        hard: -1
    volumes:
      - esdata1:/usr/share/elasticsearch/data
    ports:
      - 9200:9200
    networks:
      - esnet
  elasticsearch2:
    build:
        context: .
        dockerfile: elasticsearch/elasticsearch-Migration.Dockerfile
    container_name: elasticsearch2
    environment:
      - cluster.name=docker-cluster
      - bootstrap.memory_lock=true
      - "ES_JAVA_OPTS=-Xms512m -Xmx512m"
      - "discovery.zen.ping.unicast.hosts=elasticsearch"
      - network.host=0.0.0.0
    ulimits:
      memlock:
        soft: -1
        hard: -1
    volumes:
      - esdata2:/usr/share/elasticsearch/data
    networks:
      - esnet

volumes:
  esdata1:
    driver: local
  esdata2:
    driver: local

networks:
  esnet:

the second elastic search container is build using a context and path with a docker file (elasticsearch-Migration.Dockerfile). so this my docker file
FROM docker.elastic.co/elasticsearch/elasticsearch:6.6.1

# script to orchestrate the automatic index creation.

ADD elasticsearch/scripts/initializeElasticSearch.sh /usr/local/bin/initializeElasticSearch
RUN chmod 755 /usr/local/bin/initializeElasticSearch

#
ADD elasticsearch/initial-data/cars.json  /tmp/cars.json

ENTRYPOINT ["initializeElasticSearch"]

my initializeElasticSearch.sh  is as follows.
#!/usr/bin/env bash
export JAVA_HOME=/opt/jdk-11.0.1

echo $JAVA_HOME

su - elasticsearch -c 'bash /usr/share/elasticsearch/bin/elasticsearch'

sleep 5
echo
curl -XPOST http://0.0.0.0:9200/cars/car/_bulk --data-binary  @/tmp/cars.json
sleep 5

any idea how can i solve the issue of not find the java
thank you

A: You do export JAVA_HOME=/opt/jdk-11.0.1 in initializeElasticSearch.sh, but finally when you execute elasticsearch you use su - which means you are nolonger run elasticsearch in the shell which you export JAVA_HOME.
To fix it, you need to add the JAVA_HOME to the shell which really execute elasticsearch like next:
su - elasticsearch -c 'bash -c "export JAVA_HOME=/opt/jdk-11.0.1; /usr/share/elasticsearch/bin/elasticsearch"'


text:
Q: Unable to get UDID from iPhone Xs Max | iOS | Apple | iPhone I need to get the UDID of my iPhone Xs Max to test my App.
Apparently, That does not work on the iPhone Xs Max

A: You are getting an error because iOS 12 requires device management profiles to be installed over a valid HTTPS connection.  That site's certificate is not trusted.

A: Better to use direct System Report or XCode to find UDIDs:

Answers: https://stackoverflow.com/a/52473809/342794
  or https://stackoverflow.com/a/52997294/342794

Details on using udid.io (Specific to this question)
It seems you are using udid.io (http://get.udid.io -- No "https" !!??) to get UDID without any app installation or connecting to USB. security concern, this would fail with iOS 12.
Note: Even for older iOS devices, As it installs a certificate on the mobile device. Not really a recommended way. Could be a shortcut in case you don't have an alternative. Say if you have a large pool of QA devices and don't have physical access to the devices (device farms accessible over the network) and don't care about installing a certificate from the untrusted source. Even in that case, look for an alternative to use a script to find UDID for all connected devices (https://stackoverflow.com/a/52997294/342794).
On supported iOS:
a. Asks to install a certificate that gets deleted automatically.
b. Shows UDID on the browser with an option to email
Screenshots:

A: *

*Open Xcode

*Go to Window

*Select Devices & Simulators

*Select your iPhone

*Copy the value for Identifier
See the answer here - https://stackoverflow.com/a/53041428/1722622


text:
Q: Even Digit Series (2,4,6,8,20,....) I have a series of numbers whose Nth term is a number whose all of the digits are even. The series is of course divergent , but i am interested in finding a formula to find the Nth term of this series.The beginning terms of the series is as follows:-
2,4,6,8,20,22,24,26,28,40,....
We can see that each of the numbers in the above series consists of digits that are all even numbers.
Can anyone please help me in finding the Nth term of this series.

A: These are all numbers that only contain even digits.
For a general formula look at this link https://oeis.org/A014263


text:
Q: Call a function for a filtered dataframe in pyspark I am having data such as ,
data
ID          filter
1             A
2             A
3             A
4             A
5             B
6             B
7             B
8             B

I want to apply a function for the dataframe,
def add(x):
    y = x+1
    return(y)

from pyspark.sql.functions import *
from pyspark.sql.functions import udf

ol_val = udf(add, StringType())

data = data.withColumn("sum",ol_val(data.ID))

this gives an output,
data
ID          filter        sum
1             A            2
2             A            3
3             A            4
4             A            5
5             B            6
6             B            7
7             B            8
8             B            9

I want to apply this function only when filter = A and for the remaining part I want it be NULL. The output I want here is,
data
ID          filter        sum
1             A            2
2             A            3
3             A            4
4             A            5
5             B            NULL
6             B            NULL
7             B            NULL
8             B            NULL

Here the value is NULL because it didnt satisfy the condition filter= A. I want the function to be applied only when filter = A.
Can anybody help me in changing the code inorder to get this output in pyspark?

A: What you need is to use when and otherwise. By the way you don't have to create that UDF.
df = sc.parallelize([
    (1, "a"),
    (1, "b"),
    (3, "c")
  ]).toDF(["id", "filter"])

df.select("*", when(col("filter") == lit("a"), col("id") + 1).otherwise(None).alias("result")).show()

If you really need to call that function, you can simply replace col("id") + 1 by     yourUDF(col("id"))


text:
Q: Linux as 3rd boot OS I would like to install another linux kali beside my linux mint and win10.
My question is, do I need make 3 partition again for installation, /root /home and swap od I don't need swap because I already have it from the Mint.
And what about the boot loader (GRUB2 whatever) since I already installed it once.
Can I skip that installation or what?
I want to hear your opinions and try to find best option.

A: *

*No, you don't need to have three partitions.  You didn't even need them for the Mint install - they're a choice, not a requirement.  You could have 1 big / partition, or multiple small partitions, or anything in between.  As long as /bin, /lib, /etc, and /sbin are on the rootfs, it will be fine.

IIRC, systemd chokes if /usr isn't on the rootfs too. because LP knows best and "nobody needs to do that any more"...so if you're running systemd or are likely to get force-migrated to systemd in future, don't do that.

*yes, you can share the swap partition with Mint unless you are using it for suspend-to-disk aka hibernate.

*you won't need to install grub into the MBR again, but you will need to update your grub configuration to generate a menu that includes your new kali installation.  The easiest way to do that is to let the kali installer install grub again.  Otherwise, make sure you have the grub packages AND the os-prober package installed and run update-grub


text:
Q: how to convert firebase time stamp to date angular typescipt
    public Patients: Observable<any>;
    constructor(private db: AngularFirestore) {
        this.Patients = this.db.collection('Patients').valueChanges();

// get data from firebase :
     ngOnInit(): void {
    this.Patients.subscribe((response) => {
      this.prepareData(response);
      this.console.log(response);
    });
  }

// in this section use for add data to apexcharts
      prepareData(patients) {

     patients.forEach((patient) => {

      });
      }

A: I guess the firebase Timestamp is in ISO 8601 and thats not fully supported by the JavaScript Date method.
To convert it for further use you could try something like:

const firebaseDate = "20190412T131518.000Z";
const convertedDate = new Date(firebaseDate.replace(/(....)(..)(.....)(..)(.*)/, '$1-$2-$3:$4:$5'));
console.log(convertedDate);

EDIT
just saw your comment reply you can simply pass the seconds to the date method

const firebaseObj = { seconds: 1612890000, nanoseconds: 0 }
const convertedDate = new Date(firebaseObj.seconds)

console.log(convertedDate)

A: The firebase timestamp offers a toDate method that basically returns a Date object.
You can create some utility types and guards that might come in handy when dealing with Firestore records.
export interface FireTimeStamp extends Date {
    toDate: () => Date;
}

export type TimeStamp = Date | FireTimeStamp;

export const isFireStamp = (value: FireTimeStamp | Date | unknown): value is FireTimeStamp =>
    (value as FireTimeStamp)?.toDate && (value as FireTimeStamp)?.toDate() !== undefined;

export const isTimeStamp = (value: TimeStamp | unknown): value is TimeStamp =>
    isFireStamp(value) || value instanceof Date;

And here is a utility function for getting the date when you're not sure if it's a Date object or firebase time stamp object.
export const toDate = (date: TimeStamp): Date => isFireStamp(date) ? date.toDate() : date;

You can also have a custom pipe to convert the date if you need to display it.

@Pipe({
    name: 'toDate'
})
export class ToDatePipe implements PipeTransform {
    transform(date: TimeStamp): Date {
        return toDate(date);
    }
}


text:
Q: What is the period of $\cos(x)=1-\frac{x^2}{2!}+\frac{x^4}{4!}-\frac{x^6}{6!}\cdots$? In calculus, $\cos x$ is defined as $1-\frac{x^2}{2!}+\frac{x^4}{4!}-\frac{x^6}{6!}\cdots$. With this definition, how can we find the period of $\cos x$

A: Define $\sin(x) = x - x^3/3! + ...$. Note that $d/dx \sin(x) = \cos(x)$ and $d/dx \cos(x) = -\sin(x)$.
Taylor expand $f(x) = \cos(x + \alpha)$ about $x = 0$ to get $\cos(\alpha + x) = f(x) = \cos(\alpha) - \sin(\alpha) - \cos(\alpha) x^2/2 + \sin(\alpha) x^3 / 3! + ... = \cos(\alpha) (1 - x^2 / 2! + ...) - \sin(\alpha) (x - x^3 / 3! + ...) = \cos(\alpha) \cos(x) - \sin(\alpha) \sin(x)$. That is, for all $x, \alpha$, $\cos(x + \alpha) = \cos(x) \cos(\alpha) - \sin(x) \sin(\alpha)$.
Furthermore, note that $\cos^2(x) + \sin^2(x)$ has a derivative of 0 and thus is constant; therefore, $\cos^2(x) + \sin^2(x) = \cos^2(0) + \sin^2(0) = 1$ for all $x$.
We now seek some $\eta > 0$ such that $\cos(\eta) = 0$. We know such an $\eta$ exists since if one didn't, we would have $d^2/dx^2 \cos(x) = -\cos(x)$ always negative for $x > 0$ and therefore $\cos(x)$ would have a negative, decreasing derivative for all $x > 0$ and yet still remain positive, which  is clearly impossible. Take the least such $\eta$; then clearly we must have $\cos'(\eta) = -\sin(\eta) \leq 0$; then $\sin(\eta) = 1$. Define $\tau = 4 \eta$. We have $\cos(\tau / 2) = \cos(\eta + \eta) = \cos^2(\eta) - \sin^2(\eta) = -1$ and therefore $\sin(\tau / 2) = 0$. Then $\cos(\tau) = \cos(\tau/2 + \tau/2) = \cos^2(\tau / 2) - \sin^2(\tau / 2) = 1$, and therefore $\sin(\tau) = 0$. Then for all $x$, we have $\cos(x + \tau) = \cos(x) \cos(\tau) - \sin(x) \sin(\tau) = \cos(x)$.  A bit more analysis shows that no $\tau'$ such that $0 < \tau' < \tau$ satisfies $\cos(0 + \tau') = \cos(\tau') = 1$; then $\tau$ is the period of the cosine function.


text:
Q: Automatic dependency injecting using Scrutor I have many services in my project, and trying to use Scrutor for automatic DI instead registering each service manually on startup.cs
BarService.cs
public class BarService : IBar
    {
        public Bar Get(int id)
        {
            var bar = new Bar
            {
                bar_date = DateTime.UtcNow,
                bar_name = "bar"
            };
            return bar;
        }

        public List<Bar> GetMany()
        {
            List<Bar> list = new List<Bar>
            {
                new Bar
                {
                    bar_date = DateTime.UtcNow,
                    bar_name = "bar 1"
                },

                new Bar
                {
                    bar_date = DateTime.UtcNow,
                    bar_name = "bar 2"
                }
            };

            return list;
        }
    }

IBar.cs
public interface IBar
    {
        Bar Get(int id);
        List<Bar> GetMany();
    }

Bar.cs
public class Bar
    {
        public string bar_name { get; set; }
        public DateTime bar_date { get; set; }
    }

BarController.cs
[Route("api/[controller]")]
    [ApiController]
    public class BarController : ControllerBase
    {
        public IBar _service { get; set; }

        public BarController(IBar service)
        {
            _service = service;
        }

        [HttpGet("{id:int}")]
        public IActionResult Get(int id)
        {
            var result = _service.Get(id);
            if (result != null)
            {
                return Ok(result);
            }
            return NotFound("No data found");
        }

        [HttpGet]
        public IActionResult GetMany()
        {
            var result = _service.GetMany();
            if (result != null)
            {
                return Ok(result);
            }
            return NotFound("No data found");
        }

    }

Adding services.AddScoped<IBar, BarService>(); to Startup.cs works fine, but not with Scrutor to auto map.
     services.Scan(scan =>
                    scan.FromCallingAssembly()
                        .AddClasses()
                        .AsMatchingInterface());

I get error

A: @Vikash Rathee, you could try AsImplementedInterfaces(). It registers each matching concrete type as all of its implemented interfaces.
         services.Scan(scan =>
                        scan.FromCallingAssembly()
                            .AddClasses()
                            .AsImplementedInterfaces());

The result is shown below.

A: You are currently using AsMatchingInterface(), which

Registers services which match a standard naming convention

Which would apply to a match like below.
public class BarService : IBarService

In your example
public class BarService : IBar

Does not follow that convention so does not provide your expected behavior
So either refactor your interfaces to follow Scrutor's expected naming convention between abstraction and implementation,
Or use AsImplementedInterfaces(), which

Registers an implementation as all implemented interfaces

Note however that this will register those interfaces as singleton by default unless a lifetime is provided.
I would suggest registering them as scoped.


text:
Q: Discovering the 'audit-log-path' for a kubernetes cluster kube-apiserver I am reviewing my rke installation:
https://docs.rke2.io/security/cis_self_assessment123#1219
The instruction works, makes sense, but shouldn't I be able to check this by running a kubectl describe po -n kube-system kube-apiserver-{my-ip}. I did a describe po on the resource, expecting to see the audit-log-path, but it was not there. How can I discover this setting if it isn't in the pod description. Is ps the best way? The only way?

A: Audit backends stores audit logs to an external persistent storage. There are two backends available for  kube-apiserver:
Log backend, stores logs to a director in the filesystem.
Webhook backend, which pushes logs to an external storage using HTTP API.
Since you are trying to store data locally we will be using the log backend. As mentioned in the doc provided by you --audit-log-path is used for setting up the path for your audit log files and if haven't provided any path it will go to the standard output /var/log/kubernetes/audit/audit.log and persistent volumes should be used for storing these logs, so you can get the path details by using below command
Kubectl get pv (In most cases audit will be the keyword so you can find the path using this)
References:

*

*https://kubernetes.io/docs/tasks/debug/debug-cluster/audit/

*https://www.ibm.com/docs/en/mvi/1.1.1?topic=environment-checking-kubernetes-storage-status


text:
Q: Validation library for Node.js Is there a good validation framework for node.js that validates a variable for:

*

*if its a type of String, Date, Number etc

*max and min length

*email, phone

*etc...

A: I recently discovered node-validator by chriso.
Example
var check = require('validator').check,
    sanitize = require('validator').sanitize

//Validate
check('test@email.com').len(6, 64).isEmail();       //Methods are chainable
check('abc').isInt();                               //Throws 'Invalid integer'
check('abc', 'Please enter a number').isInt();      //Throws 'Please enter a number'
check('abcdefghijklmnopzrtsuvqxyz').is(/^[a-z]+$/);

//Sanitize / Filter
var int = sanitize('0123').toInt();                  //123
var bool = sanitize('true').toBoolean();             //true
var str = sanitize(' \s\t\r hello \n').trim();      //'hello'
var str = sanitize('aaaaaaaaab').ltrim('a');        //'b'
var str = sanitize(large_input_str).xss();
var str = sanitize('<a>').entityDecode();     //'<a>'

A: I gather that this is the sort of thing that the schema module is meant to do.  Note that it is labeled as being "in development" (tagged as v0.1a).  I haven't tried it myself, but it looks pretty good from the examples shown in the README.

A: Not on a variable level, but on a function argument level:
http://github.com/torvalamo/argtype.js
Date currently needs to pass as type 'object'. It is definately something that I have forgotten, and will put on the todo-list. ;)
Specific max and min length is not supported, and will probably not be implemented (but who knows). Email, phone and all that can be checked by regex. See the example on the github page, which includes a (simple) regex example.

A: I wanted ruby on rails and cakephp style validations. I knew it was something I would use over and over so I made this quick npm module: https://npmjs.org/package/iz
It reads semantically like well like jasmine, and can be used client or server side. This means it comes with support for commonjs and amd along with validation rules passed in via JSON.
It is pretty well unit tested, it has no production dependencies, and the scope is locked down to just validation. We seem to have a small community going now. Ideas, feedback and pull requests are all welcome.
Current library functions:
iz.alphaNumeric(*);               // Is number or string(contains only numbers or strings)
iz.between(number, start, end);   // Number is start or greater but less than or equal to end, all params numeric
iz.blank(*);                      // Empty string, undefined or null
iz.boolean(*);                    // true, false, 0, 1
iz.cc(*);                         // Luhn checksum approved value
iz.date(*);                       // Is a data obj or is a string that is easily converted to a date
iz.decimal(*);                    // Contains 1 decimal point and potentially can have a - at the beginning
iz.email(*);                      // Seems like a valid email address
iz.extension(ob1, ob2);           // If obj2's methods are all found in obj1
iz.fileExtension(arr, value);     // Checks if the extension of value is in arr. An obj can be provide, but must have indexOf defined.
iz.fileExtensionAudio(value);     // Check against mp3, ogg, wav, aac
iz.fileExtensionImage(value);     // Check against png, jpg, jpeg, gif, bmp, svg, gif
iz.inArray(arr, value);           // If * is in the array
iz.int(*, bool (optional));       // Is an int. If the 2nd variable is true (false by default) a decimal is allowed
iz.ip(str);                       // str resembles an IPV4 or IPV6 address
iz.minLen(val, min);              // val (str or arr) is greater than min
iz.maxLen(val, max);              // val (str or arr) is shorter than max
iz.multiple(num, mult);           // Number is multiple of another number
iz.number(*);                     // Is either an int or decimal
iz.ofType(obj, typeName);         // If it is a named object, and the name matches the string
iz.phone(str, canHaveExtension?); // Is an american phone number. Any punctuations are allowed.
iz.postal(*);                     // Is a postal code or zip code
iz.ssn(*);                        // Is a social security number

A:
Node-validator is a library of string validation, filtering and sanitization methods.

So if you want to have better support for Numbers and Arrays, you may try Chai.js. Here's some examples:
var expect = require('chai').expect;
try {
    expect([1, 2, 3]).to.have.length.below(4);
    expect(5).to.be.within(3,6);
    expect('test').to.have.length(4);
} catch (e) {
    // should not occur
}

A: I recommend valida there is lack of documentation however it is pretty simple to understand looking at the examples.
Valida features are:

*

*Sanitization

*Synchronous and asynchronous validation

*Groups

*Extensible

A: I'm finishing writing a library on Javascript validations (both node and browser), I'll be writing the docs on the next few days, but the code is almost ready: https://github.com/wilkerlucio/composed-validations
Please let me know if you have any questions/suggestions on it :)


text:
Q: Embedding artwork with FFmpeg during FLAC to ALAC conversion How does one embed artwork during FLAC → ALAC conversion?
ffmpeg -i track.flac -acodec alac track.m4a

transfers metadata but not artwork.

A: I think FFmpeg can't do that – M4A files store metadata in a strange way compared to FLAC, or MP3, or OGG. You can, however, use AtomicParsley as detailed in this answer to a very similar question. In summary:
ffmpeg -i input.flac -vn -c:a alac output.m4a cover.jpg
AtomicParsley output.m4a --artwork cover.jpg --overWrite


text:
Q: Разбить логическую цепочку or на отдельные строки (Ansible) Добрый вечер.
Как разбить очень длинную цепочку из or на строки для удобства чтения?
- degub:
    msg: "Сообщить если одно из условий выполнено"
  when: long_variable_name != none or long_variable_name in check_list or long_variable_name in check_list_2

A: Т.к. плейбуки написаны на YAML, можно использовать все его свойства. В т.ч. и переносы строк:
- debug:
    msg: "Сообщить если одно из условий выполнено"
  when: >
        long_variable_name != none
        or long_variable_name in check_list
        or long_variable_name in check_list_2