Q: Custom adapter returning wrong row Textview Text I am implementing a custom adapter for listview. In which i have some textview and one checkbox.for checkbox i have implemented setOnCheckedChangeListener.But the problem is when i check a checkbox i am trying to get that row textview text. but it returning last row textview text.
Code
  public class CustomStoreAdapter extends BaseAdapter implements Filterable {

        ItemFilter mFilter;
        int price;
        private int lastPosition = -1;
        ViewHolder mHolder;

        ArrayList<String> favHotel;
        private static SparseBooleanArray positionArray=new SparseBooleanArray();
        SharedPreferences sharedPreferences;
        public static ArrayList<HashMap<String,String>> finalHashList;
        public static ArrayList<HashMap<String,String>> tempName;
        public static ArrayList<Integer> selectedIds = new ArrayList<Integer>();
        Context context;
        String flag;
        String favId;
        ArrayList<String> htlId;
        String [] favArr;

        public CustomStoreAdapter(String flag, Context context, ArrayList<HashMap<String, String>> finalHashList, String favId) {
            System.out.println("custom size>>"+finalHashList.size());
            this.context = context;

          CustomStoreAdapter.finalHashList =finalHashList;
            for (int i=0;i<finalHashList.size();i++) {
                htlId.add(finalHashList.get(i).get("id"));
            }
            tempName=finalHashList;
            selectedIds=new ArrayList<>();
            this.flag=flag;
            this.favId=favId;
            if (!favId.equals(""))
            {
                favId=favId.substring(6,favId.length());
                //Log.e("substring favId",favId);
               favArr=favId.split(",");
            }
            Log.e("flag is>>>",flag);

        }

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

        @Override
        public Object getItem(int position) {
            return finalHashList.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }
        public static void append( ArrayList<HashMap<String, String>> finalHashList1) {

        }

        public static StringBuilder getCheckedItems() {

            StringBuilder mTempArry = new StringBuilder();

            mTempArry.append("htlid=");

            for(int i=0;i<finalHashList.size();i++) {

                if(positionArray.get(i)) {

                   mTempArry.append(finalHashList.get(i).get("id"));
                    mTempArry.append(",");

                }

            }

            return mTempArry;

        }

        @Override
        public View getView(final int position, View convertView, ViewGroup parent) {
            favHotel=new ArrayList<>();
            View v = convertView;
            sharedPreferences = context.getSharedPreferences("hotelDekho", Context.MODE_PRIVATE);

            if(finalHashList.size() > position) {

                LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                TypefaceUtil.overrideFont(context.getApplicationContext(), "SERIF", "fonts/splash-font.ttf");
                if (v == null) {
                    v = inflater.inflate(R.layout.serch_result_page, parent, false);
                    mHolder = new ViewHolder();

                    mHolder.txtId=(TextView)v.findViewById(R.id.txtId);
                     mHolder.txthotelRating = (TextView) v.findViewById(R.id.txtRating);
                    mHolder.txthotelName = (TextView)v.findViewById(R.id.Hotel_name);
                    mHolder.txtFavorite=(CheckBox) v.findViewById(R.id.imgFavorite);
                    mHolder.txthotelLocation = (TextView) v.findViewById(R.id.Hotel_location);
                    mHolder.txthotelPrice = (TextView) v.findViewById(R.id.price);
                    mHolder.txthotelPrice2 = (TextView) v.findViewById(R.id.price2);
                    mHolder.txthotelIconPlace = (TextView)v.findViewById(R.id.locIcon);
                    mHolder.txtLock = (TextView)v.findViewById(R.id.txtLock);
                    mHolder.txthotelIconR1 = (TextView) v.findViewById(R.id.txtR1);
                    mHolder.txthotelIconR2 = (TextView) v.findViewById(R.id.txtR2);
                    mHolder.rhotelRating = (CustomRatingBar) v.findViewById(R.id.ratingBar1);
                    mHolder.lnrPrice=(LinearLayout)v.findViewById(R.id.lnrPrice);
                    mHolder.imgHotel = (ImageView) v.findViewById(R.id.hotel_image);
                    mHolder.lnrRating=(LinearLayout)v.findViewById(R.id.lnrRating);
                    mHolder.lnrSignHotelList=(LinearLayout)v.findViewById(R.id.lnrSignHotelList);
                    mHolder.txthotelIconPlace.setTypeface(FontManager.getTypeface(context, FontManager.FONTAWESOME));

                    mHolder.txthotelIconR1.setTypeface(FontManager.getTypeface(context, FontManager.FONTAWESOME));
                    mHolder. txthotelIconR2.setTypeface(FontManager.getTypeface(context, FontManager.FONTAWESOME));

                    mHolder.txtLock.setTypeface(FontManager.getTypeface(context, FontManager.FONTAWESOME));
                    mHolder.txtFavorite.setTag(position);

                    v.setTag(mHolder);
                }else

                {
                    mHolder = (ViewHolder) v.getTag();
                    mHolder.txtFavorite.setOnCheckedChangeListener(null);
                }

                Animation animation = AnimationUtils.loadAnimation(context, (position > lastPosition) ? R.anim.up_from_bottom : R.anim.down_from_top);
               v.startAnimation(animation);
                lastPosition = position;

                    mHolder.txtId.setText(finalHashList.get(position).get("id"));
                    mHolder.txthotelName.setText(finalHashList.get(position).get("name"));
                    mHolder.txthotelLocation.setText(finalHashList.get(position).get("location"));
                    mHolder.txthotelRating.setText(finalHashList.get(position).get("rating") + "/5");
               // mHolder.txtFavorite.setChecked(positionArray.get(position));

                mHolder.txtFavorite.setChecked(positionArray.get(position));
                for (int i=0;i<favArr.length;i++)
                {
                    if(favArr[i].equals(finalHashList.get(position).get("id")))
                    {
                        mHolder.txtFavorite.setChecked(true);
                    }
                }
                mHolder.txtFavorite.setOnCheckedChangeListener(mCheckedChangeListener);
                if (!flag.equals("favHtl")) {
                    mHolder.lnrPrice.setVisibility(View.VISIBLE);
                    Float price1 = Float.parseFloat(finalHashList.get(position).get("price"));
                    mHolder.txthotelPrice2.setText(String.valueOf(Math.round(price1)));

                    if (SearchHotelResults.flag.equals("offer")) {
                        price = Math.round(price1 + price1);
                    } else
                        price = Math.round(price1 + ((price1 * 20) / 100));
                    mHolder.txthotelPrice.setText(String.valueOf(price));
                    mHolder.txthotelPrice.setPaintFlags(mHolder.txthotelPrice.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
                }
                mHolder.rhotelRating.refreshDrawableState();
                if (!sharedPreferences.getString("email","").equals(""))
                {
                    mHolder.lnrSignHotelList.setVisibility(View.GONE);
                }

                mHolder.rhotelRating.setScore(Float.parseFloat(finalHashList.get(position).get("star")));

                    if (finalHashList.get(position).get("img").startsWith("hoteldekho")) {
                        loadImagePicaso( mHolder.imgHotel, Config.storeImagePath + finalHashList.get(position).get("img"));
                    } else {
                        loadImagePicaso( mHolder.imgHotel, finalHashList.get(position).get("img"));
                    }

                }
            return v;

            }
        CompoundButton.OnCheckedChangeListener mCheckedChangeListener = new CompoundButton.OnCheckedChangeListener() {

            @Override

            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

                // TODO Auto-generated method stub

                Animation zoomOutAnimation = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.bounce);
                buttonView.startAnimation(zoomOutAnimation);
                positionArray.put(htlId.indexOf(mHolder.txtFavorite.getText().toString()), isChecked);
                Log.e("array is>>",getCheckedItems().toString()+">>>>"+ finalHashList.indexOf(mHolder.txtId.getText().toString()));
                SharedPreferences.Editor editor = sharedPreferences.edit();

                editor.putString("favHotelId", getCheckedItems().toString());
                editor.apply();

            }

        };

 private class ViewHolder {
        private TextView txtId;
        private TextView txthotelRating;
        private TextView txthotelName;
        private TextView txthotelLocation;
        private TextView txthotelPrice;
        private TextView txthotelPrice2;
        private TextView txthotelIconPlace;
        private  TextView txtLock;
        private CheckBox txtFavorite;
        LinearLayout lnrPrice;
        private TextView txthotelIconR1;
        private TextView txthotelIconR2;
        private TextView txthotelIconArrow;
        private CustomRatingBar rhotelRating;
        private ImageView imgHotel;
        private Button btnSubmit;
        private LinearLayout lnrRating;
        private LinearLayout lnrSignHotelList;
    }

    }

Please help me to how to get same row textview text on checkbox click

A: Problem:
Currently you're storing your ViewHolder in a class level field, which is being set in getView(), its going to be set to the latest ViewHolder every time ListView is calling getView() and there's absolutely no guarantee in the order of the position the getView() is called for. Its going to get random ViewHolder references, creating problems for you to track position So a class level ViewHolder isn't good solution.
Solution:
You need to keep track of position related to every check box. Tag the position to checkbox and get it in the listener as follow:
mHolder.txtFavorite.setOnCheckedChangeListener(mCheckedChangeListener);
mHolder.txtFavorite.setTag(position+""); //tag position as String object

Now you can get this position in your listener:
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
    //Since we set position in form of String, we need to convert String to int
    int position = Integer.parseInt(buttonView.getTag());
}

A: You save position of mHolder.txtFavorite to tag, so you should just read the right position from tag, not from text
positionArray.put(htlId.indexOf(mHolder.txtFavorite.getTag()), isChecked);


Q: CSS3: show/hide icon in li a I have this code for show/hide icon using css hover:
HTML:

CSS:
.box .todo-list > li> a> .tools {
  display: none;
  float: right;
  color: #f56954;
}
.box .todo-list > li> a:hover .tools {
  display: inline-block;

}

Now This Not Worked and not hide my icon. if i remove > a> from code this worked and hide but when add a> not worked.
how do can i fix this problem?

A: Your CSS selectors are slightly wrong, try:
.box .todo-list > li > .tools > a

And
.box .todo-list > li > .tools > a:hover

The selector parts need to go in the same order as the elements that they select are nested in the HTML.
Check out the W3C Selectors documentation for more details.

A: The > selector means immediate descendent.
In your markup, the immediate descendant of the li is the span.tools.
Therefore, li > a does not select anything.
But, li > .tools > a does select the a element.
An excellent write-up can be found here: Child and Sibling Selectors

A: The > selector above is a child combinator selector. This means it will only select elements that are direct children of a parent. In otherwords, it only looks one level down the markup structure, no deeper.
So
.box .todo-list > li > .tools > a


Q: serve content from cache Node JS Good Night
I am trying of serving content from cache memory, I am learning using a online course, but I have a problem, becouse when i modify a file of the content, the serve continnue using cache memory and I use a conditionel where evaluate if the cache is update or no....
I have used this code in Linux and it serves, but when I do it using windows It does not serve...
 var http = require('http');
 var path = require('path');
 var fs = require('fs');

 var mimeTypes = {
 '.js' : 'text/javascript',
 '.html': 'text/html',
 '.css' : 'text/css'
  };

  var cache = {};
  function cacheYEntrega(f, cb) {
  fs.stat(f, function (err, stats) {
  var ultimoCambio = Date.parse(stats.ctime),
  estaActualizado = (cache[f]) && ultimoCambio  > cache[f].timestamp;
  if (!cache[f] || estaActualizado) {
  fs.readFile(f, function (err, data) {
    console.log('cargando ' + f + ' desde archivo');
    if (!err) {
      cache[f] = {content: data,
                  timestamp: Date.now() //almacenar datos tiempo actual
                 };
    }
    cb(err, data);
  });
  return;
  }
  console.log('cargando ' + f + ' de cache');
  cb(null, cache[f].content);
  }); //final de fs.stat
   }

   http.createServer(function (request, response) {
   var buscar= path.basename(decodeURI(request.url)) || 'index.html',
   f = 'content/' + buscar;
   fs.exists(f, function (exists) { //path.exists para Node 0.6 e inferiores
   if (exists) {

   cacheYEntrega(f, function (err, data) {
    if (err) {response.writeHead(500); response.end(); return; }
    var headers = {'Content-type': mimeTypes[path.extname(f)]};
    response.writeHead(200, headers);
    response.end(data);

     });
     return;

     }
    response.writeHead(404); //no se ha encontrado archivo
    response.end('Pagina no encontrada');

     });

      }).listen(8080);

Thanks

A: After of checking the code and the variables, I discovered I had a problem with the ctime of stats, I do not know why the ctimes does not change when a file content is modified, so I only used mtime instead of ctime and it start serving the content in the right way....
thanks...


Q: Having Docker access External files I am interested in having Docker have access to external files, but I do not wish to include them as a volume.  The files that I need access to will change over time, and this means I would need to re-mount repeatedly, unless I can mount a mere directory, and whatever is in that directory is also mounted.
I am just in need of allowing a software program pushed into a container, to run "over" my local system, where this software program has access to files on my local system.
Advice?  Is there another way besides adding the files needing to be processed as a volume?

A: I solved the same problem with below commands
docker run  --mount type=bind,source="$(pwd)"/data,target=/home/data -it <name_of_container>

Note "-it conainter_name" should be the last flags.

A: It sounds like mounting a host directory in the container is what you're looking for. You won't have to restart the container to pick up changes to the mounted directory. Link to relevant docs.

A: I wonder if the ADD command could help you accomplish your goal. For instance, given the Dockerfile line:
ADD /Users/userX/myappfiles /appfiles

and the command line:
docker run myapp --input /myappfiles

myapp would be able to access /Users/userX/myappfiles on the local filesystem to fetch its inputs.


Q: java jzy3d dependencies issue I've linked latest jogl library to my project, but unfortunately I have next error during compiling the program Exception in thread "main" java.lang.NoSuchMethodError: javax.media.opengl.GLProfile.isAvailable(Ljava/lang/String;)Z
what library should I link to solve this issue?

A: I just solved this issue for myself.
Go here: http://search.maven.org/#search%7Cga%7C2%7Cjogamp
and download gluegen-2.3.2, gluegen-rt-2.3.2, and jogl-all-2.3.2 (or whatever the latest version is). You have to download two things for each, the regular jar AND the source.


Q: How to bind ngFormModel in angular2 using Dart? The following works in a form (the form is displayed)
.html
  <form (ngSubmit) = "onSubmit()"
         #nameForm = "ngForm">
    {{diagnostic}}

Name

        <input
            required
            type = "text"
            [(ngModel)] = "name.first"
            ngControl = "first"
            #first = "ngForm"
            (input)="onInputHandler($event)"
            class = "mdl-textfield__input ng-valid"
            id = "first">
        First
        {{firstErrorMsg}}

        <button id = "startButton"
                class = "mdl-button mdl-js-button mdl-button--raised mdl-button--accent mdl-js-ripple-effect"
        >Submit
        </button>

    <button class = "mdl-button mdl-js-button mdl-button--raised mdl-button--colored">
      Button All
    </button>

  </form>

Trying to follow the example at Forms and Validation in Angular 2.0,
I cannot get the UI to display by changing the first line of the form to
<form (ngSubmit) = "onSubmit()"
        [ngFormModel]="form" #f="form">
    {{diagnostic}}
..

With the change the browser simply does not display anything as if it cannot parse the markup - the error is actually shown in pub-serve or debug mode.
Transform TemplateCompiler on epimss_ng2_reg|lib/components/name_component.ng_meta.json threw error: Template parse errors:
There is no directive with "exportAs" set to "form" ("

  <form (ngSubmit) = "onSubmit()"
        [ng-form-model]="form" [ERROR ->]#f="form">
    {{diagnostic}}

"): NameComponent@12:31
....

Why is this not working?

A: Seems this was changed since when the blog post was created.
NgForm is now exported as ngForm instead of form.
[ngFormModel]="form" #f="ngForm">

It's correct in the GitHub source but not in the blog post.
Full component according to the example in the blog post in Dart
@Component(selector: 'form-element')
@View(template: '''

form-element

<form (ngSubmit)="onSubmit()" [ngFormModel]="form" #f="ngForm">

First Name

        <input type="text" id="firstName" ngControl="firstName">

First Name is required

Street Address

        <input type="text" id="firstName" ngControl="streetAddress">

Street Address is required

Zip Code

        <input type="text" id="zip" ngControl="zip">

Zip code has to be 5 digits long

Address Type

        <select id="type" ngControl="type">
            <option [value]="'home'">Home Address</option>
            <option [value]="'billing'">Billing Address</option>
        </select>

    <button type="submit" [disabled]="!f.form.valid">Save</button>

The form contains the following values

            {{payLoad}}

</form>
''')
class FormElement {
  ControlGroup form;
  String payLoad;
  FormElement(FormBuilder fb) {
    form = fb.group({
      "firstName": ['', Validators.required],
      "streetAddress": ['', Validators.required],
      "zip": [
        '',
        Validators.compose([ZipValidator.validate])
      ],
      "type": ['home']
    });
  }

  void onSubmit() {
    payLoad = JSON.encode(this.form.value);
  }
}


Q: Gmail sending error (C#) I'm trying to send an email via C# but I keep on getting this error:

The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required. Learn more at...

The stack trace can be found here:

System.Net.Mail.SmtpException: The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required. Learn more at
at System.Net.Mail.MailCommand.CheckResponse(SmtpStatusCode statusCode, String response)
at System.Net.Mail.SmtpTransport.SendMail(MailAddress sender, MailAddressCollection recipients, String deliveryNotify, Boolean allowUnicode, SmtpFailedRecipientException& exception)
at System.Net.Mail.SmtpClient.Send(MailMessage message)
at Repetrel.View.EmailForm.btnSend_Click(Object sender, EventArgs e) in c:\2015 Hyrel Projects\Repetrel\src\Repetrel\View\EmailForm.cs:line 238

Here is my code:
            NetworkCredential loginInfo = new NetworkCredential(Properties.Settings.Default.MyEmailAddress, Properties.Settings.Default.MyEmailPassword);
            //System.Net.Mail.SmtpClient smtpClient = new System.Net.Mail.SmtpClient(Properties.Settings.Default.SMTPAddress);
            ////Trace.WriteLine("smtp = " + Properties.Settings.Default.SMTPAddress);
            //smtpClient.Port = 587;
            //smtpClient.EnableSsl = true;
            //smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
            ////smtpClient.UseDefaultCredentials = false;
            //smtpClient.Credentials = loginInfo;

            var smtpClient = new SmtpClient
            {
                Host = "smtp.gmail.com",
                Port = 587,
                EnableSsl = true,
                DeliveryMethod = SmtpDeliveryMethod.Network,
                UseDefaultCredentials = true,
                Credentials = loginInfo,
                Timeout = 20000
            };

            //smtpClient.SendAsync(message, "test");
            smtpClient.Send(message);

            //Output to log
            OutputToLog(message);

            //Close Window
            Close();
        }
        catch (Exception ex)
        {
            Trace.WriteLine(ex.ToString());
            MessageBox.Show("An error occurred.  Please see the trace log for more information.");
        }

I have tried everything mentioned in previous posts(there are many of them), but nothing seems to work.  I have tried with and without default credentials and setting the flag to false/true.  Nothing seems to work.  Might anyone be able to point me in the right direction?
Thanks in advance!

A: Apparently GMAIL was blocking my email address from using less secure devices. You can turn off the blocking at: https://www.google.com/settings/security/lesssecureapps.

A: Perhaps UseDefaultCredentials = false, instead?
Edit: This seems similar to an older StackOverflow question: SmtpClient with Gmail


Q: Does AWS Device Farm support Android Orchestrator? Can I upload Android Orchestrator .apk to the AWS Device Farm as a 3rd apk (together with main app apk and test-suite apk)? Or application state is not persistent in the Device Farm, so that it doesn't require external Orchestrator at all?
Currently we use local runner for Android Espresso tests. Some tests require app state/data to be cleared between tests, so that we use Orchestrator. According to a console, it is uploaded as a separate apk to the device. AWS Device Farm allows uploading only 2 apks: app itself and a test-suite.
So, how could I use Orchestrator in the AWS Device Farm for tests to have cleared app state/data after each test?

A: You could send Orchestrator as an auxiliary apps when using AWS Device Farm.
If you're using the console, this is done during the Specify device state step under Install other apps
If you're using the CLI use auxiliaryApps flag https://docs.aws.amazon.com/cli/latest/reference/devicefarm/schedule-run.html

A: Short answer: Uploading the orchestrator seems to work, but you dont need it to get the tests run in separate processes.
Long answer: As Scott's answer said, you can upload and install the orchestrator to the device. You should upload android test services apk as well (test-services-1.4.0-alpha05.apk for example)
Also the Piotr's comment is correct. If you want to use the orchestrator, you should specify your own start command for tests like this: "adb shell "CLASSPATH=$(pm path androidx.test.services) exec app_process / androidx.test.services.shellexecutor.ShellMain am instrument ...". This can be done by using the custom evironment option from the device farm's start test wizard. More info can be found here: https://developer.android.com/training/testing/junit-runner#using-android-test-orchestrator
If you want to get the tests run separatedly, just use the default environment option, as it seems to isolate the tests by default in the aws farm. There's no need to use the orchestrator. Orchestrator is needed only, if you want to use your own custom test runners, or use custom parameters that needs to be passed to the tests.


Q: php re-sorting an array I have an array of entries that are separated by year and month like below. I need to sort this array so that entries are "grouped" by year and then by category.
Array
(
    [Oct 2011] => Array
        (
            [0] => Array
                (
                    [title] => CAD Drawing Updates
                    [file] => /gm-June2010-driver.pdf
                    [category] => Windows
                )
        )

    [Sep 2011] => Array
        (
            [0] => Array
                (
                    [title] => title
                    [file] => /gm-June2010-driver.pdf
                    [category] => Windows
                )

            [1] => Array
                (
                    [title] => edges
                    [file] => /gm-June2010-driver.pdf
                    [category] =>Walling
                )

            [2] => Array
                (
                    [title] => Specification update
                    [file] => /gm-June2010-driver.pdf
                    [category] => Windows
                )
        )
)

So this is the sort of thing I'm after.
Array
(
    [Oct 2011] => Array
        (
                [Windows] => Array
                        (
                            [0] => Array
                                (
                                    [title] => CAD Drawing Updates
                                    [file] => /gm-June2010-driver.pdf
                                )
                        )
        )

    [Sep 2011] => Array
        (
                [Windows] => Array
                                (
                            [0] => Array
                                (
                                    [title] => title
                                    [file] => /gm-June2010-driver.pdf
                                    [category] => Windows
                                )

                            [1] => Array
                                (
                                    [title] => Specification update
                                    [file] => /gm-June2010-driver.pdf
                                    [category] => Windows
                                )
                                )
                [Walling] => Array
                                (
                            [0] => Array
                                (
                                    [title] => edges
                                    [file] => /gm-June2010-driver.pdf
                                    [category] => Curtain Walling
                                )
                                )
        )
)

I'm not sure if this is a job for the sort functions, any help would be appreciated, thanks.

A: No, that can't be done with the sort function, you need to create a new array by iterating through your original array with nested foreach loops.
$newArr = array();
foreach($arr as $month => items) {
  foreach($items as $data) {
    $newArr[$month][$data["category"]][] = $data;
  }
}

A: You don't want to sort but just to rename keys. PHP Arrays do not support to rename keys directly, so you need to create a new array first that is build with the new keys while maintaining the existing values.
At the end you can replace the original array with the new one:
$rekeyed = array();
foreach($array as $monthYear => &$value)
{
    $r = sscanf($monthYear, '%s %d', $month, $year);
    if ($r != 2) throw new Exception(sprintf('Invalid Key "%s".', $monthYear));
    $categories = array();
    foreach($value as &$item)
    {
        $category =& $item['category'];
        unset($item['category']);
        $categories[$category][] =& $item;
    }
    unset($item);
    $value =& $categories;
    unset($categories);
    $rekeyed[$year][$month] =& $value;
}
unset($value);
$array =& $rekeyed;
unset($rekeyed);
print_r($array);

Output:
Array
(
    [2011] => Array
        (
            [Oct] => Array
                (
                    [Windows] => Array
                        (
                            [0] => Array
                                (
                                    [title] => CAD Drawing Updates
                                    [file] => /gm-June2010-driver.pdf
                                )

                        )

                )

            [Sep] => Array
                (
                    [Windows] => Array
                        (
                            [0] => Array
                                (
                                    [title] => title
                                    [file] => /gm-June2010-driver.pdf
                                )

                        )

                    [Walling] => Array
                        (
                            [0] => Array
                                (
                                    [title] => edges
                                    [file] => /gm-June2010-driver.pdf
                                )

                        )

                )

        )

)

Demo

A: I think the function you should be looking at is uasort.
http://www.php.net/manual/en/function.uasort.php
First do a sort on the main array, the for each element in the array, do a usort on the child array.


Q: Why is Parallelizable attribute not showing in my SpecFlow feature.cs files I'm using NUnitv3 with SpecFlow 2.0, ive added the attribute [assembly: Parallelizable(ParallelScope.Fixtures)] to my assemblyinfo.cs and have regenerated all of the steps.
However what im noticing is this attribute is not being populated into the generated feature files.
A post by Gaspar Nagy here: https://github.com/techtalk/SpecFlow/wiki/Parallel-Execution
suggests that it should be. Could someone she light on how I can get this attribute included?

A: This is an assembly level attribute. You need it only once. This is the "flag" that the NUnit Test Runner uses to determine if the tests supports parallelism.
SpecFlow 2.0 is not adding this attribute automatically to your code, so have to do it manually once.


Q: Select all events from a month in grails I am new to groovy/grails, and I'm trying to to do a criteria search that finds all posts for a month, basically like this:
def getUserMinutesForYear(User user, Date date){

    Date firstDate = new GregorianCalendar(date.year, Calendar.JANUARY, 1, 0, 0, 0).time
    Date lastDate = new GregorianCalendar(date.year, Calendar.DECEMBER, 31, 23, 59, 59).time

    def c = JobRegistration.createCriteria()

    def minutes = c.get {
        and{
            eq("user.id", user.id)
            between("job.happening", firstDate, lastDate)

        }

        projections {
            sum("minutesWorked")
        }
    }

    return minutes
}

The domain classes are
 class Job {

     String title
     String description
     Date   happening

     static hasMany = [registrations:JobRegistration]
 }

class User {
    static hasMany = [authorities: Role, registrations: JobRegistration]
    static belongsTo = Role
    String username
}

class JobRegistration {

    Job job
    User user

    Integer minutesWorked
    static belongsTo = [user:User,job:Job]

    static constraints = {
        user(blank: false)
        job(blank:false)
        minutesWorked(nullable :true)
    }

    String toString(){
        return user.userRealName
    }

}

Now, why do I get this exception?

org.codehaus.groovy.runtime.InvokerInvocationException: org.hibernate.QueryException: could not resolve property: job.happening of: JobRegistration

A: You need to nest the job relationship (you can also just us eq with user):
def minutes = c.get {
    and{
            eq("user", user)
            job{
                between("happening", firstDate, lastDate)
            }

    }

    projections {
            sum("minutesWorked")
    }
}

cheers
Lee


Q: Find and replace String from Object value using foreach C# I want to replace the value of two "string" members from their record in Object with the string I want.
I'm trying to use the .Contains() and replace() function on object
This is the object:
EmailParam param = new EmailParam();

And the EmailParam:
public class EmailParam {
  public string UserName {get; set;}
  public string Code {get; set;}
  public string Param1 {get; set;}
  public string Param2 {get; set;}
}

And this is the example:
string body = "My name is @UserName and my code is @Code";

param.UserName = "Tony";
param.Code = "A01";

What I want for result will be like My name is Tony and my code is A01
It is come from find body @UserName, and then replace from value Username Tony

A: you can use this code
List<EmailParam> param = new List<EmailParam>()
{
    new EmailParam(){Code ="A01",UserName="Tony"},
    new EmailParam(){Code ="B01",UserName="William"},
};
string body = "My name is @UserName and my code is @Code";

var findItem = param.Where(a => a.UserName.Equals("Tony") && a.Code.Equals("A01")).FirstOrDefault();
body = body.Replace("@UserName", findItem.UserName).Replace("@Code", findItem.Code);

A: You can use something similar to following
string body = "My name is {0} and my code is {1}"; //use placeholders instead of @UserName, @Code.
param.UserName = "Tony";
param.Code = "A01";

var convertedBody = String.Format(body, aram.UserName, param.Code);


Q: Call another rest api from my server in Spring-Boot I want to call another web-api from my backend on a specific request of user. For example, I want to call Google FCM send message api to send a message to a specific user on an event.
Does Retrofit have any method to achieve this? If not, how I can do that?

A: Modern Spring 5+ answer using WebClient instead of RestTemplate.
Configure WebClient for a specific web-service or resource as a bean (additional properties can be configured).
@Bean
public WebClient localApiClient() {
    return WebClient.create("http://localhost:8080/api/v3");
}

Inject and use the bean from your service(s).
@Service
public class UserService {

    private static final Duration REQUEST_TIMEOUT = Duration.ofSeconds(3);

    private final WebClient localApiClient;

    @Autowired
    public UserService(WebClient localApiClient) {
        this.localApiClient = localApiClient;
    }

    public User getUser(long id) {
        return localApiClient
                .get()
                .uri("/users/" + id)
                .retrieve()
                .bodyToMono(User.class)
                .block(REQUEST_TIMEOUT);
    }

}

A: Create Bean for Rest Template to auto wiring the Rest Template object.
@SpringBootApplication
public class ChatAppApplication {

    @Bean
    public RestTemplate getRestTemplate(){
        return new RestTemplate();
    }

    public static void main(String[] args) {
        SpringApplication.run(ChatAppApplication.class, args);
    }

}

Consume the GET/POST API by using RestTemplate - exchange() method. Below is for the post api which is defined in the controller.
@RequestMapping(value = "/postdata",method = RequestMethod.POST)
    public String PostData(){

       return "{\n" +
               "   \"value\":\"4\",\n" +
               "   \"name\":\"David\"\n" +
               "}";
    }

    @RequestMapping(value = "/post")
    public String getPostResponse(){
        HttpHeaders headers=new HttpHeaders();
        headers.setAccept(Arrays.asList(MediaType.APPLICATION_JSON));
        HttpEntity<String> entity=new HttpEntity<String>(headers);
        return restTemplate.exchange("http://localhost:8080/postdata",HttpMethod.POST,entity,String.class).getBody();
    }

Refer this tutorial[1]
[1] https://www.tutorialspoint.com/spring_boot/spring_boot_rest_template.htm

A: As has been mentioned in the various answers here, WebClient is now the recommended route.
You can start by configuring a WebClient builder:
@Bean
public WebClient.Builder getWebClientBuilder(){
    return WebClient.builder();
}

Then inject the bean and you can consume an API as follows:
@Autowired
private WebClient.Builder webClientBuilder;

Product product = webClientBuilder.build()
            .get()
            .uri("http://localhost:8080/api/products")
            .retrieve()
            .bodyToMono(Product.class)
            .block();

A:
Does Retrofit have any method to achieve this? If not, how I can do that?

YES
Retrofit is type-safe REST client for Android and Java. Retrofit turns your HTTP API into a Java interface.
For more information refer the following link
https://howtodoinjava.com/retrofit2/retrofit2-beginner-tutorial

A: This website has some nice examples for using spring's RestTemplate.
Here is a code example of how it can work to get a simple object:
private static void getEmployees()
{
    final String uri = "http://localhost:8080/springrestexample/employees.xml";

    RestTemplate restTemplate = new RestTemplate();
    String result = restTemplate.getForObject(uri, String.class);

    System.out.println(result);
}

A: Instead of String you are trying to get custom POJO object details as output  by calling another API/URI, try the this solution. I hope it will be clear and helpful for how to use RestTemplate also,
In Spring Boot, first we need to create Bean for RestTemplate under the @Configuration annotated class. You can even write a separate class and annotate with @Configuration like below.
@Configuration
public class RestTemplateConfig {

    @Bean
    public RestTemplate restTemplate(RestTemplateBuilder builder) {
       return builder.build();
    }
}

Then, you have to define RestTemplate with @Autowired or @Injected under your service/Controller, whereever you are trying to use RestTemplate. Use the below code,
@Autowired
private RestTemplate restTemplate;

Now, will see the part of how to call another api from my application using above created RestTemplate. For this we can use multiple methods like execute(), getForEntity(), getForObject() and etc. Here I am placing the code with example of execute(). I have even tried other two, I faced problem of converting returned LinkedHashMap into expected POJO object. The below, execute() method solved my problem.
ResponseEntity<List<POJO>> responseEntity = restTemplate.exchange(
    URL,
    HttpMethod.GET,
    null,
    new ParameterizedTypeReference<List<POJO>>() {
    });
List<POJO> pojoObjList = responseEntity.getBody();

Happy Coding :)

A: In this case need download whit my API, files hosted in other server.
In my case, don't need use a HTTP client to download the file in a external URL, I combined several answers and methods worked in previous code for files that were in my local server.
My code is:
@GetMapping(value = "/download/file/pdf/", produces = MediaType.APPLICATION_PDF_VALUE)
    public ResponseEntity<Resource> downloadFilePdf() throws IOException {
        String url = "http://www.orimi.com/pdf-test.pdf";

        RestTemplate restTemplate = new RestTemplate();
        byte[] byteContent = restTemplate.getForObject(url, String.class).getBytes(StandardCharsets.ISO_8859_1);
        InputStream resourceInputStream = new ByteArrayInputStream(byteContent);

        return ResponseEntity.ok()
                .header("Content-disposition", "attachment; filename=" + "pdf-with-my-API_pdf-test.pdf")
                .contentType(MediaType.parseMediaType("application/pdf;"))
                .contentLength(byteContent.length)
                .body(new InputStreamResource(resourceInputStream));
    }

and it works with HTTP and HTTPS urls!

A: Since the question explicitly tags spring-boot, it worth noting that recent versions already ship a pre-configured instance of a builder for WebClient, thus you can directly inject it inside your service constructor without the needing to define a custom bean.
@Service
public class ClientService {

    private final WebClient webClient;

    public ClientService(WebClient.Builder webClientBuilder) {
        webClient = webClientBuilder
                        .baseUrl("https://your.api.com")
    }

    //Add all the API call methods you need leveraging webClient instance

}

https://docs.spring.io/spring-boot/docs/2.0.x/reference/html/boot-features-webclient.html

A: Simplest way I have found is to:

*

*Create an annotated interface (or have it generated from somehing like OpenAPI)

*Give that interface to Spring RestTemplate Client
The Spring RestTemplate Client will parse the annotations on the interface and give you a type safe client, a proxy-instance. Any invocation on the methods will be seamlessly translated to rest-calls.
final MyApiInterface myClient = SpringRestTemplateClientBuilder
  .create(MyApiInterface.class)
  .setUrl(this.getMockUrl())
  .setRestTemplate(restTemplate)         // Optional
  .setHeader("header-name", "the value") // Optional
  .setHeaders(HttpHeaders)               // Optional
  .build();

And a rest call is made by inoking methods, like:
final ResponseEntity<MyDTO> response = myClient.getMyDto();


Q: how to take input in python when no of input are not defined this is an c++ code , how can I implement this in python ?
while(scanf("%lld",&n)!=EOF)
    {
        cout<<convert(n)<<endl;
    }

A: This is roughly equivalent:
def convert(input):
     #do something with your input

import sys
for line in sys.stdin:
    convert(int(line))

A: In Python, instead of using scanf and friends, usually you read a line or an entire file into a string, and use string operations to get the results you want.
In your example, you could do something like:
import sys
for line in sys.stdin:
    for word in line.split():
        number = int(word)

        ... = convert(number)

A: it can be done using try except
link below can be used
https://stackoverflow.com/a/38621838/4557946


Q: matplotlib.plot.show continues shows plots even the script finished There isn't duplicated answer because I was always blocked by solution below !!!!!!!
I want to plot a graph and still run following code without closing the graph automatically like Matlab.
I try plt.show(block=False) , it failed and appear in a small moment then close itself.
Code:
import numpy as np
import matplotlib.pyplot as plt

if __name__ == '__main__':
    plt.figure(figsize=(10, 10))
    plt.plot(range(5), lw=2, label='Real')
    plt.title('Prediction')
    plt.legend(loc="best")
    plt.show(block=False)
    print("---Plot graph finish---")

I try plt.draw() or interactive mode , it failed, too. Check the code below.
Code:
import numpy as np
import matplotlib.pyplot as plt

if __name__ == '__main__':
    plt.figure(figsize=(10, 10))
    plt.plot(range(5), lw=2, label='Real')
    plt.title('Prediction')
    plt.legend(loc="best")
    plt.draw()
    plt.show()
    print("---Plot graph finish---")

Above will block until I close it.
Code:
import numpy as np
import matplotlib.pyplot as plt

if __name__ == '__main__':
    plt.ion()
    plt.figure(figsize=(10, 10))
    plt.plot(range(5), lw=2, label='Real')
    plt.title('Prediction')
    plt.legend(loc="best")
    plt.draw()
    plt.show()
    print("---Plot graph finish---")

Above will appear nothing, or it appear and disappear very fast.
My version is below:
user@ya:~/$ sudo pip freeze | grep matplotlib
matplotlib==2.2.3
user@ya:~/$ sudo pip -V
pip 18.1 from /usr/local/lib/python2.7/dist-packages/pip (python 2.7)

Environments:
I only execute script in Ubuntu ex: user@ya: python xxx.py
Distributor ID: Ubuntu
Description:    Ubuntu 16.04.5 LTS
Release:    16.04
Codename:   xenial

Can anyone help me? I just want to do like Matlab which won't close the plotted graph even if the script finishes.

A: The plots will close when the script is finished, even if you use block=False
Similar to the answer here, when running from the terminal you have to call plt.show at the end of the script to keep these plots open after you've finished. I made a similar code to yours which works as intended; the plot simply refreshes at the end of the code. (added a for loop for a 5 second delay just so you can see it's running).
import numpy as np
import matplotlib.pyplot as plt
import time

if __name__ == '__main__':
    plt.figure(figsize=(10, 10))
    plt.plot(range(5), lw=2, label='Real')
    plt.title('Prediction')
    plt.legend(loc="best")
    plt.show(block=False)
    print("---Plot graph finish---")
    for i in range(5):
        print('waiting...{}'.format(i))
        time.sleep(1)
    print('code is done')
    plt.show()


Q: Slide out animation of three elements on top of each other I'm looking for the best way to make the following animation. I've tried some solutions, but none of them seem to tackle my problem as every single solution seems to fail at some point. The animation I need to do is the following:

User swipes his finger up and the tableView & 1 & 2 scroll up (it's like tableView & 1 & 2 are one scrollable element). Then, when 2 becomes invisible upon the scroll, 3 & 1 & tableView become scrollable (again, as if it were one scrollable element). Then, when 3 becomes invisible (as it is scrolled) the tableView is then the only scrollable element.
What I tried:

*

*I initially tried with simple animations like changing height constraints for every 1/2/3 element based on the scroll offset and although it seemed fine to me, it didn't to the reviewer as he wanted more precise scrolling in between hiding elements animations

*I then tried to combine panGesture with scroll. I embedded 1 & 2 and tableView into one scroll View and set panGesture recognizer for it with delegate function shouldRecognizeSimultaneouslyWith returning true while having tableView scrolling disabled. Then, upon intersecting 3 I was disabling the panGesture and tried to enable tableView scrolling, but failed to recognize which panGesture/scrolling works or not, which one to disable, which one to fail or work alone/simultaneously.
How would you dear developers tackle it so that the animations are smooth and as described? Perhaps, you have an awesome idea :)

A: I'm using a simplified version of your idea with a UIScrollView & 3 UILabel instances.
You can easily adapt this to be UITableView & 3 UIView instances.
Idea

*

*UIScrollView & 3 UILabel instances have a common superview. In this case it's UIViewController.view.

*UIScrollView is laid out to be full screen (edge-to-edge) and extends below these 3 UILabel instances.

*UIScrollView has contentInset.top = height_of_three_labels so it's content starts below these other instances.

*Whenever UIScrollView.contentOffset changes, we shift frame.origin.y for these 3 instances to provide the needed effect.

UI Setup
import UIKit

class ViewController: UIViewController {

    let tileHeight: CGFloat = 60
    let view1 = UILabel()
    let view2 = UILabel()
    let view3 = UILabel()

    override func viewDidLoad() {
        super.viewDidLoad()

        let bounds = self.view.bounds

        let scrollView = UIScrollView(frame: bounds)
        scrollView.autoresizingMask = [.flexibleWidth, .flexibleHeight]
        scrollView.delegate = self
        scrollView.alwaysBounceVertical = true
        self.view.addSubview(scrollView)

        view1.frame = CGRect(x: 0, y: 2*tileHeight, width: bounds.width, height: tileHeight)
        configureLabel(view1, text: "1", backgroundColor: .red)

        view2.frame = CGRect(x: 0, y: tileHeight, width: bounds.width, height: tileHeight)
        configureLabel(view2, text: "2", backgroundColor: .blue)

        view3.frame = CGRect(x: 0, y: 0, width: bounds.width, height: tileHeight)
        configureLabel(view3, text: "3", backgroundColor: .green)

        scrollView.contentInset = UIEdgeInsets(top: 3*tileHeight, left: 0, bottom: 0, right: 0)

        // 3 is between 2 and 1, 1 is at the top, order is important here
        self.view.addSubview(view2)
        self.view.addSubview(view3)
        self.view.addSubview(view1)
    }

    private func configureLabel(_ label: UILabel, text: String, backgroundColor: UIColor) {
        label.text = text
        label.textColor = .white
        label.font = .boldSystemFont(ofSize: 34)
        label.textAlignment = .center
        label.backgroundColor = backgroundColor
    }

}

Scroll Management
extension ViewController: UIScrollViewDelegate {
    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        let offset = scrollView.adjustedContentInset.top + scrollView.contentOffset.y
        print(offset)
        if offset > 0 {
            view3.frame.origin.y = (offset > tileHeight) ? (tileHeight - offset) : 0
            view2.frame.origin.y = tileHeight - offset
            view1.frame.origin.y = 2*tileHeight - offset
        }
        else {
            view3.frame.origin.y = 0
            view2.frame.origin.y = tileHeight
            view1.frame.origin.y = 2*tileHeight
        }
    }
}

Output

A: I think you'll be fighting a losing battle trying to toggle scrolling.
Here's another approach...

*

*add the tableView as a subview of a "container" UIView

*add the three "top" views as subviews

*give the tableView a contentInset.top of the height of the three views plus vertical spacing

*constrain the three "top" views so

*

*3 will stick to the top, until it is pushed up by 1

*2 till slide under 3 when 1 pushes it up

*update the top constraint for 1 when the tableView scrolls

You can try it with this example code (no @IBOutlet connections needed):
class ExampleViewController: UIViewController, UIScrollViewDelegate {

    let tableView: UITableView = {
        let v = UITableView()
        v.translatesAutoresizingMaskIntoConstraints = false
        v.separatorInset = .zero
        return v
    }()
    let view1: UILabel = {
        let v = UILabel()
        v.translatesAutoresizingMaskIntoConstraints = false
        v.textAlignment = .center
        v.backgroundColor = .systemRed
        v.text = "1"
        return v
    }()
    let view2: UILabel = {
        let v = UILabel()
        v.translatesAutoresizingMaskIntoConstraints = false
        v.textAlignment = .center
        v.backgroundColor = .systemGreen
        v.text = "2"
        return v
    }()
    let view3: UILabel = {
        let v = UILabel()
        v.translatesAutoresizingMaskIntoConstraints = false
        v.textAlignment = .center
        v.backgroundColor = .systemBlue
        v.text = "3"
        return v
    }()

    // this will hold the tableView and the
    //  three other views
    let containerView: UIView = {
        let v = UIView()
        v.translatesAutoresizingMaskIntoConstraints = false
        // clip to bounds to prevent the "top" views from showing
        //  as they are "pushed up" out of bounds
        v.clipsToBounds = true
        return v
    }()

    // this constraint constant will be changed
    //  in scrollViewDidScroll
    @IBOutlet var view1TopConstraint: NSLayoutConstraint!

    override func viewDidLoad() {
        super.viewDidLoad()

        // add our container view
        view.addSubview(containerView)

        // add our tableView and three "top" views
        containerView.addSubview(tableView)

        containerView.addSubview(view2)
        containerView.addSubview(view3)
        containerView.addSubview(view1)

        for v in [view1, view2, view3] {
            // all three "top" views should be
            //  equal width to tableView
            //  horizontally centered to tableView
            //  40-pts tall
            NSLayoutConstraint.activate([
                v.widthAnchor.constraint(equalTo: tableView.widthAnchor),
                v.centerXAnchor.constraint(equalTo: tableView.centerXAnchor),
                v.heightAnchor.constraint(equalToConstant: 40.0),
            ])
        }

        let g = view.safeAreaLayoutGuide
        NSLayoutConstraint.activate([

            // constrain container view with 20-pts "padding"
            containerView.topAnchor.constraint(equalTo: g.topAnchor, constant: 20.0),
            containerView.leadingAnchor.constraint(equalTo: g.leadingAnchor, constant: 20.0),
            containerView.trailingAnchor.constraint(equalTo: g.trailingAnchor, constant: -20.0),
            containerView.bottomAnchor.constraint(equalTo: g.bottomAnchor, constant: -20.0),

            // constrain all 4 sides of tableView ot container view
            tableView.topAnchor.constraint(equalTo: containerView.topAnchor, constant: 0.0),
            tableView.leadingAnchor.constraint(equalTo: containerView.leadingAnchor, constant: 0.0),
            tableView.trailingAnchor.constraint(equalTo: containerView.trailingAnchor, constant: 0.0),
            tableView.bottomAnchor.constraint(equalTo: containerView.bottomAnchor, constant: 0.0),

        ])

        // view3 should stick to the top of the table,
        //  unless it's being pushed up by view1
        let v3Top = view3.topAnchor.constraint(equalTo: tableView.topAnchor)
        v3Top.priority = .defaultHigh + 1

        // view2 should stick to the bottom of view3,
        //  unless it's being pushed up by view1
        let v2Top = view2.topAnchor.constraint(equalTo: view3.bottomAnchor, constant: 4.0)
        v2Top.priority = .defaultHigh

        // view1 should ALWAYS be 4-pts from bottom of view2
        let v1TopA = view1.topAnchor.constraint(equalTo: view2.bottomAnchor, constant: 4.0)
        v1TopA.priority = .required

        // view1 should ALWAYS be greater-than-or-equal 4-pts from bottom of view3
        let v1TopB = view1.topAnchor.constraint(greaterThanOrEqualTo: view3.bottomAnchor, constant: 4.0)
        v1TopB.priority = .required

        // view1 top should ALWAYS be greater-than-or-equal top of tableView
        let v1TopC = view1.topAnchor.constraint(greaterThanOrEqualTo: tableView.topAnchor)
        v1TopC.priority = .required

        // 88-pts is 40-pts for view3 and view2 plus 4-pts vertical spacing

        // view1 top should NEVER be more-than 88-pts from top of tableView
        let v1TopD = view1.topAnchor.constraint(lessThanOrEqualTo: tableView.topAnchor, constant: 88.0)
        v1TopD.priority = .required

        // view1 top will start at 88-pts from top of tableView
        view1TopConstraint = view1.topAnchor.constraint(equalTo: tableView.topAnchor, constant: 88.0)
        view1TopConstraint.priority = .defaultHigh + 2

        // activate those constraints
        NSLayoutConstraint.activate([
            v3Top,
            v2Top,
            v1TopA,
            v1TopB,
            v1TopC,
            v1TopD,
            view1TopConstraint,
        ])

        tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
        tableView.dataSource = self
        tableView.delegate = self

        // top inset is
        //  three 40-pt tall views
        //  plus 4-pts vertical spacing between each
        //  and 4-pts vertical spacing below view1
        tableView.contentInset.top = 132
        tableView.contentOffset.y = -132
    }

    func scrollViewDidScroll(_ scrollView: UIScrollView) {
        // we're getting called when the tableView scrolls
        // invert the contentOffset y
        let y = -scrollView.contentOffset.y
        // subtract 44-pts (40-pt tall view plus 4-pts vertical spacing)
        view1TopConstraint.constant = y - 44.0
    }

}

extension ExampleViewController: UITableViewDelegate, UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 30
    }
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let c = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
        c.textLabel?.text = "Row \(indexPath.row)"
        return c
    }
}

Here's how it looks to start:

then, after scrolling up just a bit (2 is sliding under 3):

scrolling a bit more (1 is pushing 3 up and out of view):

and then table scrolling while 1 remains at the top:


Q: Building a nested HashMap I want to build a nested hashmap in java like this
   {Customer:
             {
              Area:{}
             }
      Bank:
            {
            City:{}
            }
   }

How can i do this?

A: The easiest way is to use a map as the value of your outer map, like the following:
Map<String, Map<String, String>> nestedMap = new HashMap<> ();
Map<String, String> fooInnerMap = new HashMap<> (), barInnerMap = new HashMap<> ();
nestedMap.put ("foo", fooInnerMap);
nestedMap.put ("bar", barInnerMap);

However, this is not really convenient to use. If you want better answers, please specify what you want and what you tried.
Your data structure, for example, looks like JSON. If you need your Map to save or exchange data, you could use a JSON library.


Q: React Material UI 2 TableRows in one loop error I'm making my first project in React and I have a problem rendering my table correctly.
What I'm trying to achieve is this;

The green brackets are what's inside my loop. The problem is that REACT says I need a wrapper for my TableRow-elements. I would assume my wrapper is my TableBody. The return method of my table looks like this;
return(

                    <TableHead>
                        <TableRow>
                            {this.props.headers.map((el, i) =>
                                <TableCell key={i+3}>{el}</TableCell>
                            )}
                        </TableRow>
                    </TableHead>
                    <TableBody>
                    {this.props.data.map((element, j) =>
                        <TableRow key={j+j+j+j+j}>
                            <TableCell key={element["Nr"]+j}>{element["Nr"]}</TableCell>
                            <TableCell key={element["Description"]+j}>{element["Description"]}</TableCell>
                            <TableCell key={element["Reference"]+j}>{element["Reference"]}</TableCell>
                            <TableCell key={element["Parameters"]+j}><FontAwesomeIcon data-index={j} className="font-awesome-icon info-icon" onMouseLeave={this.hideToolTip} onMouseEnter={this.showToolTip} icon={faInfoCircle} />
                                {toolTip[j]}
                            </TableCell>
                        </TableRow>
                        <TableRow> !!REACT WON'T ACCEPT  THIS SECOND TABLEROW!! </TableRow>
                    )}
                    </TableBody>

        )

The error is the following;
Parsing error: Adjacent JSX elements must be wrapped in an enclosing tag. Did you want a JSX fragment < >...< />?
What I've tried so far is wrap both TableRows of this loop in a parent TableRow, but Table rows cannot directly contains Table rows, of course.
Any help is greatly appreciated!

A: In react some things (almost everything) needs the same start and end tag to be valid, take a return for example, this is valid:
export default observer(() => {
    return (

Hello

    )
})

This will reslut in a error
export default observer(() => {
    return (

Hello

    )
})

So what you can do is to use the <React.Fragment>tag around all code in your loop, or simply use a loop foreach block. This is valid
export default observer(() => {
    return (
     <React.Fragment>

Hello

     </React.Fragment>
    )
})

Your code with fragment
return(

                    <TableHead>
                        <TableRow>
                            {this.props.headers.map((el, i) =>
                                <TableCell key={i+3}>{el}</TableCell>
                            )}
                        </TableRow>
                    </TableHead>
                    <TableBody>
                    {this.props.data.map((element, j) =>
                       <React.Fragment>
                        <TableRow key={j+j+j+j+j}>
                            <TableCell key={element["Nr"]+j}>{element["Nr"]}</TableCell>
                            <TableCell key={element["Description"]+j}>{element["Description"]}</TableCell>
                            <TableCell key={element["Reference"]+j}>{element["Reference"]}</TableCell>
                            <TableCell key={element["Parameters"]+j}><FontAwesomeIcon data-index={j} className="font-awesome-icon info-icon" onMouseLeave={this.hideToolTip} onMouseEnter={this.showToolTip} icon={faInfoCircle} />
                                {toolTip[j]}
                            </TableCell>
                        </TableRow>
                        <TableRow> !!REACT WILL ACCEPT  THIS SECOND TABLEROW!! </TableRow>
                      </React.Fragment>
                    )}
                    </TableBody>

        )


Q: iOS CoreBluetooth CBPeripheral didReceiveReadRequest I have two projects. One acts as central ,the other as a peripheral. Central has connected to peripheral, then central calls method readValueForCharacteristic.
Not immediately, but after about 5-10 seconds, peripheral invokes delegate method - (void)peripheralManager:(CBPeripheralManager *)peripheral didReceiveReadRequest:(CBATTRequest *)request. Why is there a delay? How can I eliminate the delay?
 Any thoughts? I've been trying for almost a week now.
 Appreciate every helps, thanks
central
- (void)sendBtnClick:(id)sender
{
    USCPeerBtn *btn = (USCPeerBtn *)sender;
    CBPeripheral *peripheral = btn.connectedPeripheral;
    if (!peripheral) {
        return;
    }

    [self.charachterMDict enumerateKeysAndObjectsUsingBlock:^(id  _Nonnull key, id  _Nonnull obj, BOOL * _Nonnull stop) {

        if (key == peripheral) {
            [(CBPeripheral *)key readValueForCharacteristic:(CBCharacteristic *)obj]; // read
            *stop = YES;
        }
    }];
}

periperal
// CBPeripheralManagerDelegate
- (void)peripheralManager:(CBPeripheralManager *)peripheral  didReceiveReadRequest:(CBATTRequest *)request
{
    NSLog(@"didReceiveReadRequest");
}

A: Call respondToRequest: in method - (void)peripheralManager:(CBPeripheralManager *)peripheral  didReceiveReadRequest:(CBATTRequest *)request
// CBPeripheralManagerDelegate
- (void)peripheralManager:(CBPeripheralManager *)peripheral     didReceiveReadRequest:(CBATTRequest *)request
{
    [peripheral respondToRequest:request withResult:CBATTErrorSuccess];
    NSLog(@"didReceiveReadRequest");
}

@Paulw11 ,thanks


Q: How can I make a path for a folder on the root? Here is my directory:
/myweb
    /css
        style.css
    /img
        icon.png
    index.php
    .htaccess

I need to call icon.png in style.css. I've tested lots of cases but none of these works:
// style.css

url(../img/icon.png)
url(./img/icon.png)
url(/img/icon.png)
url(img/icon.png)
url(../icon.png)
url(./icon.png)

Does anybody know what's the correct path?

A: Calling url(../img/icon.png) is correct.
Did you try to call the image from somewhere else, in example for background:
body {
    background-image: url(../img/icon.png);
}

Also please check the configuration in your .htaccess.


Q: Extracting text from PDF file using pdfbox I am trying to extract text from PDF file using pdfbox but not as a command line tool but inside my Java app. I am downloading pdf using jsoup.
res = Jsoup
.connect(host+action)
.ignoreContentType(true)
.data(data)
.cookies(cookies)
.method(Method.POST)
.timeout(20*1000)
.execute();

// prepare document
InputStream is = new ByteArrayInputStream(res.bodyAsBytes());
PDDocument pdf = new PDDocument();
pdf.load(is,true);

// extract text
PDFTextStripper stripper = new PDFTextStripper();
String text = stripper.getText(pdf);

// print extracted text
System.out.println(text);

This code prints just empty line. When I do this:
System.out.println(res.body());

it prints the pdf file to output like this:
%PDF-1.4
%����
6 0 obj
<<
/Filter /FlateDecode
/Length 1869
>>
stream
x��X�n��

...
<<
/Size 28
/Info 27 0 R
/Root 26 0 R
>>
startxref
20632
%%EOF

So I am sure that pdf in downloaded correctly - just this PDF stripper doesnt work...
---------------------------------------------- edit
this problem is solved - working code is here http://thottingal.in/blog/2009/06/24/pdfbox-extract-text-from-pdf/

A: (Question answered in the comments. See Question with no answers, but issue solved in the comments (or extended in chat) )
@WeloSefer wrote:

maybe this can help you get started ... I have never worked with jsoup nor pdfbox so I am no help but I sure will try pdfbox since I've been testing itextpdf reader for extracting texts.

The OP wrote:

Thanks, that is what I was looking for - it works now :)
  this problem is solved - working code is here http://thottingal.in/blog/2009/06/24/pdfbox-extract-text-from-pdf/


Q: how to solve the no mono behavior script found error in unity? I have a problem with a game I am programming in unity. This specificaly occured when i added the script given below. the error message says that no monobehaviorscripts in the file, or their names do not match the file name. This script is meant to spawn the eniemies in the game.
I have already tried changing the class name, file name and copy the one into the other. but this does not seem to help.
screenshot unity of error message and code

i just edited my code and it does not seem to be solved.
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class wavesystem : MonoBehaviour
{
    public int enimicount;
    public int[] enimi = { 1 };
    public int wave = 1;
    // Start is called before the first frame update
    void Start()
    {

    }

    // Update is called once per frame
    void Update()
    {
        if (enimicount = 0)
        {
            int threat = 0;
            for (threat < wavesystem.wave)
            {
            int name = Random.Range(0, wavesystem.enimi.Length);
            int enimitreat = wavesystem.enimi[name];
            if (threat + enimitreat <= wave)
                {
                float xpos = Random.Range(0, 2);
                Instantiate("enimie" + name, (xpos, 1));
                wavesystem.enimicount = wavesystem.enimicount + 1;
                threat = threat + enimitreat;
                }

            }
            wavesystem.wave = wavesystem.wave + 1;
        }

    }
}

A: you need the exact same name in the unity editor for the script as well as in the  code editor (I suppose visual studio). the name is Case Sensitive and needs to be correctly spelled in each part. check the name and the location of the file and place them so they are easily found by you.
for example:
Name in unity: WaveSystem_LoL
//Name in C# code:

   public class WaveSystem_LoL : MonoBehavior

if they do not match the error will appear so double and even triple check!

A: Seems like your file name is different than class name. Your file name of cs file should be wavesystem.cs


Q: Laravel 5 shows php file content in browser (doesn't render html) Laravel 5 site doesn't render html, rather it shows php file content in browser. I tried various apache configurations and changes in htaccess but no luck. Not sure where this is going wrong.
Here is the .htaccess file
<IfModule mod_rewrite.c>
<IfModule mod_negotiation.c>
    Options -MultiViews
</IfModule>
DirectoryIndex index.php
RewriteEngine On

# Redirect Trailing Slashes...
#RewriteRule ^(.*)/$ /$1 [L,R=301]

# Handle Front Controller...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ public/$1 [L]
#  RewriteRule ^ index.php [L]

</IfModule>

and here is the apache conf file:
<VirtualHost *:80>
DocumentRoot /var/www/laravelapp/public
ServerName laravelapp.dev
ServerAlias laravelapp.dev
<Directory "/var/www/laravelapp/public">
 AllowOverride all
 Allow from all
</Directory>
</VirtualHost>


Q: AOSP - Android 6 Marshmallow compilation - make: *** [run_soong] Error 126 I've tried to compile Android 6 Marshmallow for my Sony Xperia Z1 Compact.
I've done everything what was in:
How to build AOSP Marshmallow for unlocked Xperia devices (developer.sonymobile.com)
and checking out:
Android - Downloading and Building (source.android.com)
on virtual machine with newest Debian (32-bit), but when I was on

To start the build, type: make –j < insert the cpu thread number of
  your computer >

I've received an error:
root@debian:~/android# make –j 8
============================================
PLATFORM_VERSION_CODENAME=REL
PLATFORM_VERSION=6.0.1
TARGET_PRODUCT=aosp_d5503
TARGET_BUILD_VARIANT=userdebug
TARGET_BUILD_TYPE=release
TARGET_BUILD_APPS=
TARGET_ARCH=arm
TARGET_ARCH_VARIANT=armv7-a-neon
TARGET_CPU_VARIANT=krait
TARGET_2ND_ARCH=
TARGET_2ND_ARCH_VARIANT=
TARGET_2ND_CPU_VARIANT=
HOST_ARCH=x86
HOST_2ND_ARCH=
HOST_OS=linux
HOST_OS_EXTRA=Linux-4.5.0-2-686-pae-i686-with-debian-stretch-sid
HOST_CROSS_OS=windows
HOST_CROSS_ARCH=x86
HOST_CROSS_2ND_ARCH=x86_64
HOST_BUILD_TYPE=release
BUILD_ID=MASTER
OUT_DIR=out
============================================
out/soong/soong: line 43: prebuilts/build-tools/linux-x86/bin/ninja: cannot execute binary file: Exec format error
build/core/soong.mk:87: recipe for target 'run_soong' failed
make: *** [run_soong] Error 126

#### make failed to build some targets (1 seconds) ####

Debug info:
root@debian:~/android# make -nd –j 8
GNU Make 4.1
Built for i586-pc-linux-gnu
Copyright (C) 1988-2014 Free Software Foundation, Inc.
License GPLv3+: GNU GPL version 3 or later <http://gnu.org/licenses/gpl.html>
This is free software: you are free to change and redistribute it.
There is NO WARRANTY, to the extent permitted by law.
Reading makefiles...
Reading makefile 'Makefile'...
(...)
Reading makefile 'build/core/dumpvar.mk' (search path) (no ~ expansion)...
============================================
PLATFORM_VERSION_CODENAME=REL
PLATFORM_VERSION=6.0.1
TARGET_PRODUCT=aosp_d5503
TARGET_BUILD_VARIANT=userdebug
TARGET_BUILD_TYPE=release
TARGET_BUILD_APPS=
TARGET_ARCH=arm
TARGET_ARCH_VARIANT=armv7-a-neon
TARGET_CPU_VARIANT=krait
TARGET_2ND_ARCH=
TARGET_2ND_ARCH_VARIANT=
TARGET_2ND_CPU_VARIANT=
HOST_ARCH=x86
HOST_2ND_ARCH=
HOST_OS=linux
HOST_OS_EXTRA=Linux-4.5.0-2-686-pae-i686-with-debian-stretch-sid
HOST_CROSS_OS=windows
HOST_CROSS_ARCH=x86
HOST_CROSS_2ND_ARCH=x86_64
HOST_BUILD_TYPE=release
BUILD_ID=MASTER
OUT_DIR=out
============================================
Reading makefile 'build/core/ninja.mk' (search path) (no ~ expansion)...
Reading makefile 'build/core/soong.mk' (search path) (no ~ expansion)...
Reading makefile 'vendor/google/build/ninja_config.mk' (search path) (do not care) (no ~ expansion)...
Updating makefiles....
 Considering target file 'vendor/google/build/ninja_config.mk'.
  File 'vendor/google/build/ninja_config.mk' does not exist.
  Looking for an implicit rule for 'vendor/google/build/ninja_config.mk'.
  No implicit rule found for 'vendor/google/build/ninja_config.mk'.
  Finished prerequisites of target file 'vendor/google/build/ninja_config.mk'.
 Must remake target 'vendor/google/build/ninja_config.mk'.
 Failed to remake target file 'vendor/google/build/ninja_config.mk'.
 Considering target file 'build/core/soong.mk'.
  Looking for an implicit rule for 'build/core/soong.mk'.
  No implicit rule found for 'build/core/soong.mk'.
  Finished prerequisites of target file 'build/core/soong.mk'.
 No need to remake target 'build/core/soong.mk'.
 Considering target file 'build/core/ninja.mk'.
  Looking for an implicit rule for 'build/core/ninja.mk'.
  No implicit rule found for 'build/core/ninja.mk'.
  Finished prerequisites of target file 'build/core/ninja.mk'.
 No need to remake target 'build/core/ninja.mk'.
 Considering target file 'build/core/dumpvar.mk'.
  Looking for an implicit rule for 'build/core/dumpvar.mk'.
  No implicit rule found for 'build/core/dumpvar.mk'.
  Finished prerequisites of target file 'build/core/dumpvar.mk'.
 (...)
 No need to remake target 'build/core/main.mk'.
 Considering target file 'Makefile'.
  Looking for an implicit rule for 'Makefile'.
  No implicit rule found for 'Makefile'.
  Finished prerequisites of target file 'Makefile'.
 No need to remake target 'Makefile'.
Updating goal targets....
Considering target file '–j'.
 File '–j' does not exist.
  Considering target file 'ninja_wrapper'.
   File 'ninja_wrapper' does not exist.
    Considering target file 'out/combined-aosp_d5503.ninja'.
     File 'out/combined-aosp_d5503.ninja' does not exist.
      Considering target file 'out/build-aosp_d5503.ninja'.
       File 'out/build-aosp_d5503.ninja' does not exist.
        Considering target file 'prebuilts/build-tools/linux-x86/bin/ckati'.
         Looking for an implicit rule for 'prebuilts/build-tools/linux-x86/bin/ckati'.
         No implicit rule found for 'prebuilts/build-tools/linux-x86/bin/ckati'.
         Finished prerequisites of target file 'prebuilts/build-tools/linux-x86/bin/ckati'.
        No need to remake target 'prebuilts/build-tools/linux-x86/bin/ckati'.
        Considering target file 'prebuilts/build-tools/linux-x86/bin/makeparallel'.
         Looking for an implicit rule for 'prebuilts/build-tools/linux-x86/bin/makeparallel'.
         No implicit rule found for 'prebuilts/build-tools/linux-x86/bin/makeparallel'.
         Finished prerequisites of target file 'prebuilts/build-tools/linux-x86/bin/makeparallel'.
        No need to remake target 'prebuilts/build-tools/linux-x86/bin/makeparallel'.
        Considering target file 'out/Android.mk'.
         Finished prerequisites of target file 'out/Android.mk'.
        No need to remake target 'out/Android.mk'.
        Considering target file 'out/CleanSpec.mk'.
         Finished prerequisites of target file 'out/CleanSpec.mk'.
        No need to remake target 'out/CleanSpec.mk'.
        Considering target file 'run_soong'.
         File 'run_soong' does not exist.
          Considering target file 'out/soong/.soong.bootstrap'.
            Considering target file 'bootstrap.bash'.
             Looking for an implicit rule for 'bootstrap.bash'.
             No implicit rule found for 'bootstrap.bash'.
             Finished prerequisites of target file 'bootstrap.bash'.
            No need to remake target 'bootstrap.bash'.
           Finished prerequisites of target file 'out/soong/.soong.bootstrap'.
           Prerequisite 'bootstrap.bash' is older than target 'out/soong/.soong.bootstrap'.
          No need to remake target 'out/soong/.soong.bootstrap'.
          Considering target file 'out/soong/soong.variables'.
            Considering target file 'FORCE'.
             File 'FORCE' does not exist.
             Finished prerequisites of target file 'FORCE'.
            Must remake target 'FORCE'.
            Successfully remade target file 'FORCE'.
           Finished prerequisites of target file 'out/soong/soong.variables'.
           Prerequisite 'FORCE' of target 'out/soong/soong.variables' does not exist.
          Must remake target 'out/soong/soong.variables'.
mkdir -p out/soong/
(\
echo '{'; \
echo '    "Make_suffix": "-aosp_d5503",'; \
echo ''; \
echo '    "Platform_sdk_version": 23,'; \
echo '    "Unbundled_build": false,'; \
echo '    "Brillo": false,'; \
echo '    "Malloc_not_svelte": true,'; \
echo '    "Allow_missing_dependencies": false,'; \
echo '    "SanitizeHost": [],'; \
echo '    "SanitizeDevice": [],'; \
echo '    "HostStaticBinaries": false,'; \
echo ''; \
echo '    "DeviceName": "amami",'; \
echo '    "DeviceArch": "arm",'; \
echo '    "DeviceArchVariant": "armv7-a-neon",'; \
echo '    "DeviceCpuVariant": "krait",'; \
echo '    "DeviceAbi": ["armeabi-v7a", "armeabi"],'; \
echo '    "DeviceUsesClang": true,'; \
echo ''; \
echo '    "DeviceSecondaryArch": "",'; \
echo '    "DeviceSecondaryArchVariant": "",'; \
echo '    "DeviceSecondaryCpuVariant": "",'; \
echo '    "DeviceSecondaryAbi": ["", ""],'; \
echo ''; \
echo '    "HostArch": "x86",'; \
echo '    "HostSecondaryArch": "",'; \
echo ''; \
echo '    "CrossHost": "windows",'; \
echo '    "CrossHostArch": "x86",'; \
echo '    "CrossHostSecondaryArch": "x86_64",'; \
echo '    "Safestack": false'; \
echo '}') > out/soong/soong.variables.$$; \
if ! cmp -s out/soong/soong.variables.$$ out/soong/soong.variables; then \
  mv out/soong/soong.variables.$$ out/soong/soong.variables; \
else \
  rm out/soong/soong.variables.$$; \
fi
          Successfully remade target file 'out/soong/soong.variables'.
          Considering target file 'out/soong/.soong.in_make'.
           Finished prerequisites of target file 'out/soong/.soong.in_make'.
          No need to remake target 'out/soong/.soong.in_make'.
          Pruning file 'FORCE'.
         Finished prerequisites of target file 'run_soong'.
        Must remake target 'run_soong'.
out/soong/soong out/soong/build.ninja  -w dupbuild=err
        Successfully remade target file 'run_soong'.
        Pruning file 'FORCE'.
       Finished prerequisites of target file 'out/build-aosp_d5503.ninja'.
      Must remake target 'out/build-aosp_d5503.ninja'.
echo Running kati to generate build-aosp_d5503.ninja...
prebuilts/build-tools/linux-x86/bin/ckati --ninja --ninja_dir=out --ninja_suffix=-aosp_d5503 --regen --ignore_dirty=out/% --no_ignore_dirty=out/soong/Android-aosp_d5503.mk --no_ignore_dirty=out/soong/make_vars-aosp_d5503.mk --ignore_optional_include=out/%.P --detect_android_echo --use_find_emulator -f build/core/main.mk  --gen_all_targets BUILDING_WITH_NINJA=true SOONG_ANDROID_MK=out/soong/Android-aosp_d5503.mk SOONG_MAKEVARS_MK=out/soong/make_vars-aosp_d5503.mk
Putting child 0x94b8a18 (out/build-aosp_d5503.ninja) PID 8221 on the chain.
Live child 0x94b8a18 (out/build-aosp_d5503.ninja) PID 8221
/bin/bash: prebuilts/build-tools/linux-x86/bin/ckati: cannot execute binary file: Exec format error
Reaping losing child 0x94b8a18 PID 8221
build/core/ninja.mk:161: recipe for target 'out/build-aosp_d5503.ninja' failed
make: *** [out/build-aosp_d5503.ninja] Error 126
Removing child 0x94b8a18 PID 8221 from chain.

#### make failed to build some targets (1 seconds) ####

What should I do to compile this correctly?

A: This post is not going to be an answer, it didn't really solve the problem. The purpose is to provide more valuable information.
Create two symbolic links in your build top directory. It will get rid of the problem. Run following command in you build top directory.
$ ln -s build/soong/bootstrap.bash
$ ln -s build/soong/Android.bp

But as you go further, you will encounter problems like following
FAILED: out/soong/.bootstrap/bin/minibp -t -m ./build/soong/build.ninja.in -b out/soong -d out/soong/.bootstrap/bootstrap.ninja.in.d -o out/soong/.bootstrap/bootstrap.ninja.in Android.bp
error: Android.bp:81:1: "soong-android" depends on undefined module "blueprint"
error: Android.bp:81:1: "soong-android" depends on undefined module "blueprint-bootstrap"
[2/4] minibp out/soong/.bootstrap/primary.ninja.in
FAILED: out/soong/.bootstrap/bin/minibp --build-primary -t -m ./build/soong/build.ninja.in --timestamp out/soong/.bootstrap/primary.ninja.in.timestamp --timestampdep out/soong/.bootstrap/primary.ninja.in.timestamp.d -b out/soong -d out/soong/.bootstrap/primary.ninja.in.d -o out/soong/.bootstrap/primary.ninja.in Android.bp
error: Android.bp:13:1: "soong_build" depends on undefined module "blueprint"
error: Android.bp:13:1: "soong_build" depends on undefined module "blueprint-bootstrap"
ninja: error: rebuilding 'out/soong/build.ninja': subcommand failed
make: *** [run_soong] Error 1

I have no idea how to solve this either. Maybe the new build system for aosp master branch is not fully prepared.


Q: input type hidden attribute value missing when I inspect with Fiddler For the same request, the attrib value of tag input type=hidden is not displayed on the content (raw text) of the response using Fiddler and VStudio debugger. But when I inspect the code with Chrome it is displayed. Why does this happen?  See these snapshots:
Element inspect from google

Inspector response content from Fiddler4

I'm a beginner in HTTP and HTML.


Q: How to add a Hyperlink to a tab in Excel? I want to add a hyperlink to a Tab in Excel. Actually I want to do it as an Excel Add in?
But now it seems there is not option for it by customizing ribbon directly. I know there is document location with a drop down list. But I want a link to a URL. From what I know hyperlinks can be placed on cells only. Please give me some ideas.

A: What is a hyperlink, really? Its a text "button" that, when clicked, brings you to a website or opens a link of some sort.
So in this case, use a button in a tab on the Excel ribbon that when clicked brings you to a website. Easy:
Private Sub MyRibbonButton_Click(Byval sender as Object, Byval e as EventArgs) Handles MyRibbonButton.Click

System.Diagnostics.Process.Start("my website url")

End Sub

Does it look like a button? Of course, but essentially it's just a hyperlink, right?

A: Use a CustomUI to create buttons for macros:
'To send email
'Callback for customButton onAction
Sub MyWeb(control As IRibbonControl)
Dim oShell As Object
Set oShell = CreateObject("Wscript.Shell")
    oShell.Run ("http://www.plugpro.com.br")
End Sub

'To Open URL
'Callback for customButton onAction
Sub MyWeb(control As IRibbonControl)
Dim oShell As Object
Set oShell = CreateObject("Wscript.Shell")
    oShell.Run ("mailto:oton@podium.pro.br")
End Sub


Q: Jquery cross domain request? I just need a single digit returned, but I can't get it to work I am making a dashcode webapp and all I want is a single digit, a 1 or 0 returned from an external server so if there is an easier way to do this please let me know.  I am using the plug in found at http://james.padolsey.com/javascript/cross-domain-requests-with-jquery/ to try to make a cross domain request, but everything I am trying isn't working.
When I run this code
$.ajax({
  url: "status.html",
  context: document.body,
  success: function(data){
    alert("working" + data);
  }
});

everything works perfectly and an alert with the text "working1" is displayed, but when I run this code
$.ajax({
  url: "http://externalsite.com/status.html",
  context: document.body,
  success: function(data){
    alert("working" + data);
  }
});

nothing happens.  Can anyone help?  This is just what I am trying now, I've also tried a .get request and the returned data was "objectObject"  I also tried a php proxy without any luck.  I'm just asking for a simple solution to return a SINGLE number from an external server.

A: If you can control other server output, put header:
Access-Control-Allow-Origin: *

in http response, and load with ajax without plugins or using YQL
https://developer.mozilla.org/en/HTTP_access_control

A: It looks like the plugin is making a JSONP request via YQL (see line 18 here).
If you load up Firebug or the developer tools in Chrome, do you see the JSONP request being made?


Q: Redirect to a specific page when WooCommerce product search returns "no product found" In Woocommerce I am trying to use the following code snippet to redirect to a specific page of my site instead of showing "no result found" on an empty product search.
Now the shortcode [insert page id="99"] doesn't work, and displays [insert page id="99"] as plain text. If I use shortcode any shortcode like '[recent_products per_page="4"]' it displays products.
remove_action( 'woocommerce_no_products_found', 'wc_no_products_found' );
add_action( 'woocommerce_no_products_found', 'show_products_on_no_products_found', 20 );
function show_products_on_no_products_found() {
    echo '<h4>' . __( 'Are u looking for this?', 'domain' ) . '</h4>';
    echo do_shortcode( '[insert page id="99"]' );
}

But I want is to redirect to a specific WordPress page which post id is 99.
How to redirect user to a specific page when a product search returns "no product found"?

A: Using template_redirect hook, you can redirect user to a specific page when there is "no results found" on a product query search, like:
add_action( 'template_redirect', 'no_products_found_redirect' );
function no_products_found_redirect() {
    global $wp_query;
    if( isset($_GET['s']) && isset($_GET['post_type']) && 'product' === $_GET['post_type']
    && ! empty($wp_query) && $wp_query->post_count == 0 ) {
        wp_redirect( get_permalink( 99 ) );
        exit();
    }
}

Code goes in functions.php file of your active child theme (or active theme). Tested and works.


Q: Turn "fieldname .startsWith. 'fieldValue'" into .Where(p => p.fieldname.StartsWith('fieldValue')) predicate? I attempted to do this below, with mind blanks as it got complicated.
I need to build a predicate to pass to my Product Repository from a client string:
"fieldname .startsWith. 'fieldvalue'"
"fieldname .contains. 'fieldvalue'"
"fieldname .equals. 3"
"fieldname .greaterThan. 3"
"fieldname .lessThan. 3"

The field names could be any existing field in the Entity.  It's there job to match them exactly.  There are only numbers and string, and only the commands listed.
Code so far (wild flailing):
// p => p.L == R
// L is the left side (the field to examine)
// R is the right side (the value to compare to)
// O is the operator (Equal)

var fieldParm    = Expression.Parameter(typeof(Entity), typeof(Entity).Name);

var compareL1 = MemberExpression.Property(fieldParm, "fieldName"); // fieldname
var compareR1 = Expression.Constant("fieldValue");  // what field should equal
var compareO1 = MemberExpression.Equal(compareWhat, compareTo);

// Do it again for each one (probably should make a foreach out of this)
var compareL2 = MemberExpression.Property(fieldParm, "fieldName"); // fieldname
var compareR2 = Expression.Constant("fieldValue");  // what field should equal
var compareO2 = MemberExpression.Equal(compareWhat, compareTo);

// Put them all together
var myExpress = Expression.And(compareO1, compareO2) // And them together

// Create predicate
Expression<Func<Entity, bool>> resultLambda =
    Expression.Lambda<Func<Entity, bool>>( myExpress,
        new ParameterExpression[] { fieldParm });

And resultLambda should contain our predicate to pass to our .Where() clause
How would you do this for a series of AND conditions like above?


Q: Adding an Enter key to the end of scanned data I have Motorola MC32.. and Windows CE 7.
I intend to use Symbol.Barcode2 namespace and looking for the setting to set this data modifying rule.
There is the Datawedge preinstalled but I want to set the rule programmaticaly. I have found nothing in EMDK Help.
Could somebody help me where can I found this opportunity?


Q: Xamarin Bluetooth. Show scan in popup menu and connect I'm programing a bluetooth controller for android. I've been able to switch the Bluetooth on and off, but now I need to scan the nearby devices. These I want to display as a popup menu as soon it finished scanning. Then you should click on the device you want and connect with it.
Note that it should connect also to not paired devices.
And the popup menu should be "big" like covering most of the screen... (not like the button-popup only)
namespace BluetoothController
{
    [Activity(Label = "BluetoothController", MainLauncher = true)]
    public class MainActivity : Activity, View.IOnTouchListener
    {
        BluetoothAdapter BTAdapter;
        Button button_OnOff, button_Forward, button_Fire, button_Backward, button_Left, button_Right;

        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

            // Set our view from the "main" layout resource
            SetContentView(Resource.Layout.Main);

            // Initialize Components
            Initialize();

            // Get local Bluetooth Adapter
            BTAdapter = BluetoothAdapter.DefaultAdapter;
        }

        public void Initialize()
        {
            button_OnOff = (Button)FindViewById(Resource.Id.button_onoff);
            button_Forward = (Button)FindViewById(Resource.Id.button_forward);
            button_Fire = (Button)FindViewById(Resource.Id.button_fire);
            button_Backward = (Button)FindViewById(Resource.Id.button_backward);
            button_Left = (Button)FindViewById(Resource.Id.button_left);
            button_Right = (Button)FindViewById(Resource.Id.button_right);
            button_OnOff.SetOnTouchListener(this);
            button_Forward.SetOnTouchListener(this);
            button_Backward.SetOnTouchListener(this);
            button_Left.SetOnTouchListener(this);
            button_Right.SetOnTouchListener(this);
            button_Fire.SetOnTouchListener(this);
        }

        // Event handler for Buttons
        public bool OnTouch(View v, MotionEvent e)
        {
            // Handle if Buttons is pressed or released
            switch (e.Action)
            {
                case MotionEventActions.Down:
                    // Do if pressed
                    switch (v.Id)
                    {
                        case Resource.Id.button_forward:
                            break;
                        case Resource.Id.button_backward:
                            break;
                        case Resource.Id.button_left:
                            break;
                        case Resource.Id.button_right:
                            break;
                        case Resource.Id.button_fire:
                            break;
                        case Resource.Id.button_onoff:
                            break;
                    }
                    break;
                case MotionEventActions.Up:
                    // Do if released
                    switch (v.Id)
                    {
                        case Resource.Id.button_forward:
                            break;
                        case Resource.Id.button_backward:
                            break;
                        case Resource.Id.button_left:
                            break;
                        case Resource.Id.button_right:
                            break;
                        case Resource.Id.button_fire:
                            break;
                        case Resource.Id.button_onoff:
                            if (BTAdapter != null)
                            {
                                if (!BTAdapter.IsEnabled)
                                {
                                    BTAdapter.Enable();
                                    Toast.MakeText(this, "Bluetooth enabled", ToastLength.Short).Show();
                                    System.Threading.Thread.Sleep(5000);

                                    // Display Devices and connect to the clicked one
                                }
                                else
                                {
                                    BTAdapter.Disable();
                                    Toast.MakeText(this, "Bluetooth disabled", ToastLength.Short).Show();
                                }
                            }
                            else
                            {
                                Toast.MakeText(this, "Bluetooth not supported", ToastLength.Long).Show();
                            }
                            break;
                    }
                    break;
            }
            return true;
        }
    }
}

After I turn on the Bluetooth in the event handler, it should wait a bit and display the selectable devices... this I did with System.Threading.Thread.sleep()
How can I take the discovered BT-devices and show them on the popup menu?
And how can I choose one of them to connect to it?

A: I think this could help you recognising bluetooth devices and managing them.
[BroadcastReceiver]
public class AndroidBluetooth : BroadcastReceiver
{

    private static BluetoothDevice _bluetoothDevice;
    private readonly BluetoothAdapter _bluetoothAdapter;
    public BluetoothSocket _bluetoothSocket;
    public readonly IntentFilter _intentFilter;

     public  AndroidBluetooth()
    {

        _bluetoothAdapter = BluetoothAdapter.DefaultAdapter;
        _intentFilter = new IntentFilter();

        _intentFilter.AddAction(BluetoothDevice.ActionFound);
        _intentFilter.AddAction(BluetoothDevice.ActionNameChanged);
        _intentFilter.AddAction(BluetoothDevice.ActionBondStateChanged);
        _intentFilter.AddAction(BluetoothDevice.ActionPairingRequest);
        _intentFilter.AddAction(BluetoothDevice.ActionAclConnected);
        _intentFilter.AddAction(BluetoothDevice.ActionAclDisconnected);
        _intentFilter.AddAction(BluetoothDevice.ActionAclDisconnectRequested);
        _intentFilter.AddAction(BluetoothAdapter.ActionDiscoveryStarted);
        _intentFilter.AddAction(BluetoothAdapter.ActionDiscoveryFinished);
        _intentFilter.AddAction(BluetoothAdapter.ActionRequestEnable);

        Xamarin.Forms.Forms.Context.RegisterReceiver(this, _intentFilter);
    }

    public override void OnReceive(Context context, Intent intent)
    {
        try
        {
            BluetoothDevice item = null;
            string action = intent.Action;

            switch (action)
            {

                case BluetoothDevice.ActionPairingRequest:

                try
                {
                    //You can set device pin by default to avoid asking.

                    int pin = intent.GetIntExtra(BluetoothDevice.ExtraPairingKey, 1234);
                    _bluetoothDevice.SetPin(ASCIIEncoding.UTF8.GetBytes(pin.ToString()));
                }
                catch (Exception e)
                {

                    System.Diagnostics.Debug.WriteLine(e.ToString());
                }
                    break;

                case BluetoothDevice.ActionBondStateChanged:
                    break;

                case BluetoothDevice.ActionFound:
                    //Bluetooth device found

                    /*/
                    / Here you can make a list for preparing popup
                    /*/
                    break;

                case BluetoothDevice.ActionNameChanged:

                    break;

                case BluetoothAdapter.ActionDiscoveryFinished:
                    //Occurs when scan is finished

                    /*/
                    / Launch desired popup
                    /*/
                    break;

                case BluetoothDevice.ActionAclConnected:
                    //Bluettoth device is connected
                    break;

                case BluetoothDevice.ActionAclDisconnected:
                    //Device is disconnected
                    break;

                case BluetoothDevice.ActionAclDisconnectRequested:
                    break;
        }

        }
        catch (Exception ex)
        {
            Logger.WriteException(ex);
            System.Diagnostics.Debug.WriteLine(ex.ToString());
        }
    }

}


Q: MySQL workbench says bad handshake I tried connecting the database from the server, but MySQL Workbench says that the connection cannot be made and declaring it as Bad Handshake. Can someone help me with this? But if I use the same user id and password and DB connections, it works on the other computer systems. Can someone solve this issue?

A: The authentication has changed from mysql V8, you must use a compatible client and server.
BTW it's a bug : https://bugs.mysql.com/bug.php?id=91828
Here is a workaround without uninstalling the new workbench.
The most probable case is having an old server with a new workbench:

*

*get the server version

From a SQL cli tool:
SHOW VARIABLES LIKE "%version%";

or from a cli connected on the server:
$ mysql -v

It should show a version < 8.0, in my case 5.1.73

*Get the mysqlWorkbench for a version <8.0:
You cannot install the msi if you already have a workbench V8.0, so you have to choose  a portable installation form a zip file here:

https://dev.mysql.com/downloads/workbench/6.1.html
Select the version 6.2.5 (last before v8.0) zip version
Unzip
Close the workbench v.8 (it lock any other workbench launch)
Launch the V6.2.3 version of workbench, it should works.

A: This is probably because of a mismatch in the versions of MySQL servers.
Check the version of the MySQL server you are trying to connect to, and the version you have installed on the computer you are using, they have to be the same.

A: The reason of this warning is version problem. If you have installed mysql server version <= 5.1 and your remote server mysql version is greater than that you will face this problem. I recommend you to install 5.7 or greater in both your local and remote server. This problem will be fixed.

A: Fortunately there is an easy way around this.  Use the old MYSQL ADMINISTRATOR tool as shown below.  In my case I was trying to open a MySQL 5.1 database for a clients WordPress installation with MySQL Workbench 8 and that did not work out :).
ALl credits goes to https://www.urtech.ca/2019/01/solved-bad-handshake-mysql-workbench-failed-to-connect-to-sql/
Follow this link for the details
https://www.urtech.ca/2019/01/solved-bad-handshake-mysql-workbench-failed-to-connect-to-sql/


Q: How to get the package name where error is triggered in Oracle Forms 6i I'm giving support on some oracle forms 6i forms, and I'm getting a Numeric or value error. However, the process is very long and it navigates along many packages in the form. What I could do, is just put messages along the process (only visible to me, of course) to see where exactly it comes out, but this would be really long. So, I was wondering if there is anything I could use like DBMS_UTILITY.format_error_backtrace but on the client side, and get the package name where the error was generated. I currently use:
exception when others then functionThatPrintsMe(sqlerrm);
But this does not give me enough information.

A: DBMS_ERROR_TEXT returns the entire sequence of recursive errors
so you should get all the required information from that
Kindly use
exception when others then functionThatPrintsMe(DBMS_ERROR_TEXT);

for more information about oracle 6i forms you can refer
http://www.oracle.com/technetwork/documentation/6i-forms-084462.html

A: At form level ON-ERROR TRIGGER .Add these lines will solve your problem
--form level error display

message(ERROR_type||'-'||TO_CHAR(message_code)||': '||ERROR_text); message(' ');

--Database level error display

    if DBMS_ERROR_TEXT is not null then
            message(DBMS_ERROR_TEXT );message(' ');
   end if ;


Q: How can I print scroll tab content with whole page?
As shown in an image I want to print the whole page with scroll content of tab. Currently the only visible screen content is being printed

A: You may use CSS media selectors to alter your styling for components when printing:
https://developer.mozilla.org/en-US/docs/Web/CSS/@media
It is perhaps the cleanest solution as it was meant for such situations. Ofc, it may require to address CSS for all the components on the page to make the outcome look as desired.