Q: ViewPager fragmentstatepageadapter getItem isn't passing correct position I have created a viewpager layout, a class that extends FragmentActivity and a fragment. What I want is that each fragment get's passed in what position it is within the viewpager. So first viewpager is created getting the argument 0, second getting 1 etc. Then if I scroll one way or another these numbers remain a true count.
The problem is the first time a fragment is created, it seems to be created twice so the position passed is 0 then 1. However I can't scroll back but I know for sure the class is being called twice. Now as I scroll forward the position increases incrementally by one. However if I scroll back it drops immediately to three on just one page back, then continues to drop past the 1 to 0 so now I can finally see my layout for 0.
I have this:
private class ScreenSlidePagerAdapter extends FragmentStatePagerAdapter {

    public ScreenSlidePagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int position) {
        PracticeFragment fragment = new PracticeFragment();
        getAll.putInt("position", position);
        fragment.setArguments(getAll);
        return fragment;
    }

    @Override
    public int getCount() {
        return numberofQ;
    }
}

It first of all runs getItem twice before even going to my fragment class so that the position is 0 then 1. Then when it gets to my fragment class it makes a layout fine, I scroll through a few (3 or 4) new pages and it adds one to the position each time then when I scroll back it says it is zero or two then the numbers continue to be just as sporadic. Finally suddenly when I scroll back to the beginning the position is again 0 so my fragment for position 0 is suddenly displayed.
I don't understand what's happening, so I'm wondering what the mistake is?
public class PracticeFragment extends Fragment {
TextView question, explain;
private ScrollView sv;
private boolean starActionBar;
private final static int version = Consts.SDKversion;

ArrayList<RadioButton> rbArray;
ArrayList<LinearLayout> lArray;
ArrayList<ImageView> ivArray;

int iRow;

SQLite info;
private String correctAnswer;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    info = new SQLite(getActivity());
    starActionBar = PreferenceManager.getDefaultSharedPreferences(
            getActivity()).getBoolean("star", true);
    setHasOptionsMenu(true);

}

@Override
public void onViewStateRestored(Bundle savedInstanceState) {
    super.onViewStateRestored(savedInstanceState);
    for (RadioButton r : rbArray) {
        if (r.isChecked()) {
            r.performClick();
        }
    }
}

@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    inflater.inflate(R.menu.activity_pm_fragment, menu);
    super.onCreateOptionsMenu(menu, inflater);
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {

    ViewGroup rootView = (ViewGroup) inflater.inflate(
            R.layout.activity_main, container, false);

    lArray = new ArrayList<LinearLayout>();
    rbArray = new ArrayList<RadioButton>();
    ivArray = new ArrayList<ImageView>();

    lArray.add((LinearLayout) rootView.findViewById(R.id.PM_LinLay0));
    lArray.add((LinearLayout) rootView.findViewById(R.id.PM_LinLay1));
    lArray.add((LinearLayout) rootView.findViewById(R.id.PM_LinLay2));
    lArray.add((LinearLayout) rootView.findViewById(R.id.PM_LinLay3));
    lArray.add((LinearLayout) rootView.findViewById(R.id.PM_LinLay4));

    for (LinearLayout l : lArray) {
        l.setOnTouchListener(PracticeFragment.this);
        l.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                if (((ViewGroup) v).getChildAt(0).isEnabled()) {
                    ((ViewGroup) v).getChildAt(0).performClick();
                }
            }
        });
    }

    rbArray.add((RadioButton) rootView.findViewById(R.id.radio0));
    rbArray.add((RadioButton) rootView.findViewById(R.id.radio1));
    rbArray.add((RadioButton) rootView.findViewById(R.id.radio2));
    rbArray.add((RadioButton) rootView.findViewById(R.id.radio3));
    rbArray.add((RadioButton) rootView.findViewById(R.id.radio4));

    ivArray.add((ImageView) rootView.findViewById(R.id.ivradio0));
    ivArray.add((ImageView) rootView.findViewById(R.id.ivradio1));
    ivArray.add((ImageView) rootView.findViewById(R.id.ivradio2));
    ivArray.add((ImageView) rootView.findViewById(R.id.ivradio3));
    ivArray.add((ImageView) rootView.findViewById(R.id.ivradio4));

    rootView.findViewById(R.id.bNext).setVisibility(View.GONE);
    rootView.findViewById(R.id.bPrevious).setVisibility(View.GONE);
    sv = (ScrollView) rootView.findViewById(R.id.svMain);

    info.open();
    iRow = Integer.valueOf(info.getEverything(getArguments(), getArguments().getInt("position"), "next"));
    Cursor c = info.getCursor(iRow);
    ((TextView) rootView.findViewById(R.id.tvQuestion))
            .setText((getArguments().getInt("position") + 1) + ") " + c.getString(2));

    explain = (TextView) rootView.findViewById(R.id.tvExplain);
    explain.setText(c.getString(9));
    explain.setVisibility(View.GONE);
    correctAnswer = c.getString(8);

    String[] aArray = { c.getString(3), c.getString(4), c.getString(5),
            c.getString(6), c.getString(7) };

    c.close();
    info.close();

    int o = 0;
    int pos = 0;
    for (String s : aArray) {
        LinearLayout l = lArray.get(pos);
        if (s.contentEquals("BLANK")) {
            l.setVisibility(View.GONE);
        } else {
            l.setVisibility(View.VISIBLE);
            rbArray.get(pos).setText(s);
            rbArray.get(pos).setOnClickListener(null);
            if (o % 2 == 0) {
                l.setBackgroundColor(Consts.colorAlt);
            }
            o++;
        }
        pos++;
    }

    return rootView;
}

}

However if I comment out everything but the viewgroup and return rootview - still the same problem.

A: initialize the getAll every time as a new object in getItem()
make your fragment class  static
and create one method in PracticeFragment
 static PracticeFragment newInstance(int num) {
        PracticeFragment f = new PracticeFragment();

        // Supply num input as an argument.
        Bundle args = new Bundle();
        args.putInt("num", num);
        f.setArguments(args);

        return f;
    }

and change  in adapter
     @Override
public Fragment getItem(int position) {
        return PracticeFragment.newInstance(position);
       }

A: Subclassing it fixed the problem!


Q: Most viewed product I am trying to find most viewed product as per user ID. If two products have been viewed for the same number of times then the most recent viewed product is to be selected.
I have the following coding:
#tabulating most viewed product by an user in the last 15 days
df_most_viewed_product= new_df.groupby('UserID')['ProductID'].apply(lambda x: x.value_counts().index[0]).reset_index()

Its finding the most viewed product for all the USER IDs except for those, where the USER has viewed two products for the same number of time.In such a scenario I need to get the output as the most recently viewed product.
        ProductID   UserID  Activity    OS      date        time
392281  Pr102405    U100040 PAGELOAD    Windows 2018-05-21  04:18:05.465000
764999  Pr102405    U100040 CLICK   Windows 2018-05-23  15:52:02.061000
1501633 Pr105055    U100040 PAGELOAD    Windows 2018-05-23  15:52:39.035000
1603959 Pr100283    U100040 PAGELOAD    Windows 2018-05-25  15:27:37.062000
2212636 Pr100513    U100040 PAGELOAD    Windows 2018-05-27  02:18:47.676000
3093767 Pr100513    U100040 PAGELOAD    Windows 2018-05-26  20:47:49.788000

The answer should be Pr100513 as it has been been viewed recently.

A: Systematically build it up as you describe

*

*get hits and last hit per UserID and ProductID

*select rows from this aggregated data frame that match max hits and max last_hit
import io
import pandas as pd
df = pd.read_csv(io.StringIO(''' ProductID UserID Activity OS date time
392281 Pr102405 U100040 PAGELOAD Windows 2018-05-21 04:18:05.465000
764999 Pr102405 U100040 CLICK Windows 2018-05-23 15:52:02.061000
1501633 Pr105055 U100040 PAGELOAD Windows 2018-05-23 15:52:39.035000
1603959 Pr100283 U100040 PAGELOAD Windows 2018-05-25 15:27:37.062000
2212636 Pr100513 U100040 PAGELOAD Windows 2018-05-27 02:18:47.676000
3093767 Pr100513 U100040 PAGELOAD Windows 2018-05-26 20:47:49.788000 '''), sep="\s", engine="python")

df["date"] = pd.to_datetime(df["date"] + " " + df["time"])

# count hits per user and product after sorting so last_hit works
dfh = df.sort_values(["UserID","date"]).groupby(["UserID","ProductID"]).agg(hits=("OS","size"),last_hit=("date","last"))
# select the row with max hits and last hit
dfh.loc[dfh["hits"].eq(dfh["hits"].max()) & dfh["last_hit"].eq(dfh["last_hit"].max())]

output
                   hits                last_hit
UserID  ProductID
U100040 Pr100513      2 2018-05-27 02:18:47.676


Q: Files won't run as programs After reading an answer on how to make a file run a command in the terminal when ran, I tried to do it myself.
I made a new document, entered the following and saved.
#! /bin/bash

echo "this is a test"

I then went to Right-Click > Properties > Permissions and checked "Allow executing file as program."
However, when I double-click the document, it simply opens in my text editor (which I believe is gedit). In the right-click menu I see no options for running the file in the terminal.
I've tried doing this with other files as well. For instance, I installed WINE and tried to install a Window's program. WINE said to simply run the installer, but nothing would happen when I tried. I marked it to run as a program and still it wouldn't work. I could only install it by Right-Click > OpenWith and selecting WINE.
Strangely enough, I copied my Keepass-2.28 Portable folder from my Windows partition to my Ubuntu partition and tried running the executable. Keepass fired right up, even though I hadn't marked that file to run as a program. I have Keepass 2.25 from the repository installed on my system if that makes a difference.
I've been running Ubuntu 14.04 in a dual-boot setup for several weeks. The only thing I can fathom I did that would mess this up is I used Synaptic Package Manager to remove a package from KDE Desktop Environment in an attempt to uninstall an alternate desktop environment I installed via the terminal. I don't remember what the package was, but the only package in that category right now is appmenu-qt5. As far as I can tell, removing that package has affected nothing, and I'm pretty sure I had issues with running files as programs since I got my Ubuntu.
EDIT: I have checked, and I don't think this question is a duplicate of this question. My Ubuntu is on a ext4 partition, and it's from there I'm trying to run programs. I also haven't dealt with trying to change permissions via the terminal or anything like that, I'm just trying to make the program run when I check the option in the properties menu. Please correct me if I'm wrong or missing anything.

A: Help in Right-Click > Properties > Permissions explains this behavior:

If the file is a program, such as a script, you must select Allow
  executing file as program to run it. Even with this option selected,
  the file manager may still open the file in an application or ask you
  what to do. See Executable text files for more information.

The default action when double-clicking a script is to open it in the editor. To change this option:

*

*Click Files in the Launcher, select Edit > Preferences and then the Behavior tab:

*Select the default action when opening an executable text file:

*

*Run executable text files when they are opened

*View executable text files when they are opened

*Ask each time

"Ask each time" is probably the right setting here, as you certainly don't want to accidentally execute a script when you just want to open a text file, especially since executable and non-executable text files share the same icon.

A: Edit: This solution will work for single files, but if you're looking after changing this behavior system-wide (i.e. for every executable text file), check out the other answers.

You'll need to create a .desktop file in order to run the script straight from Nautilus:

*

*Create a .desktop file on the desired location: gedit /<path_to_dektop_file>/test.desktop

*Paste the code below

*Save

*Exit

*Make the file executable: chmod u+x /<path_to_dektop_file>/test.desktop
Code:
[Desktop Entry]
Type=Application
Name=Test
Exec=/<path_to_shell_script>/test.sh

Then just double-click the .desktop file created.

A: I suspect that you need to change the settings for the file manager so that it will either run the bash script directly, or ask you if you wish to run the script or display the code.
I don't know if the current version of Ubuntu's file manager works the same way, but a couple of years back, the fix was as follows:
"Open the Nautilus file manager and click on the gear wheel (Location Options) in the top-right corner of the window. Navigate to Preferences – File Preferences – Behaviour – Executable Text Files. A set of radio buttons allows the default option to be set. My preference is for “Ask each time”. Then, when I double click on a script file, I am given the option of either running the script or displaying (editing) its contents."
(See: https://linuxnorth.wordpress.com/2013/11/02/running-bash-scripts-in-ubuntu/)


Q: Recurrent and transient state definitions What is the definition of a recurrent and transient state respectively?
I ask this because while reading Markov Chains by J.R. Norris, he says a state $i$ is recurrent if
$P(X_{n}=i, \mbox{ for infinitely many n }| X_{0} = i)=1$,
and a state $i$ is transient if
$P(X_{n}=i,\mbox{ for infinitely many n} | X_{0}=i) = 0$.
I'm more familiar with the definition which states that if $P(X_{n}=i \mbox{ for some } n\geq 1)=1$, then the state $i$ is said to be recurrent, else if this probability is strictly less than 1, then the state $i$ is said to be transient.
Is there a way to prove these definitions are equivalent?
I think my problem stems from not understanding the probability statement:
$P(X_{n}=i \mbox{ for infinitely many n} | X_{0}=i)=1$.
What is this statement actually saying?
Any help will be much appreciated. Thanks.

A: These two definitions are equivalent. If the event that $X_n = t$ occurs infinite times almost surely, it occurs at least once almost sure. If it occurs once almost sure, it will occur infinite times. That's because of the property of Markov chain.


Q: Take and save screenshot with html javascript I'm trying to take a screenshot and save it in a specific folder in my local computer with an onclick in a button, using HTML and JavaScript (or JQuery).

A: There's no way to save DOM elements as an image (unless you just use Firefox or something), but you can convert the DOM elements into canvas and save the image from there.
See http://html2canvas.hertzen.com/
Then use canvas.toDataURL() to save the image.


Q: gcloud app deploy fails with only [ERROR] I've been running python 2.7 apps on GCP for about 5 years and deploying using the App Engine Launcher.
Now that AEL is deprecated I'm trying to deploy via gcloud and get "ERROR: (gcloud.app.deploy)"

*

*I can use gcloud to run the project locally so I have confidence that the project is setup correctly and in the right directory locally.

*I ran gcloud auth login to give myself permission to upload to the project.
But when I try to redeploy my app I get an error:
DEBUG: Running gcloud.app.deploy with Namespace(__calliope_internal_deepest_parser=ArgumentParser(prog='gcloud.app.deploy', usage=None, description='Deploy the local code and/or configuration of your app to App Engine.', version=None, formatter_class=<class 'argparse.HelpFormatter'>, conflict_handler='error', add_help=False), account=None, authority_selector=None, authorization_token_file=None, bucket=None, calliope_command=<googlecloudsdk.calliope.backend.Command object at 0x037D1F90>, command_path=['gcloud', 'app', 'deploy'], configuration=None, credential_file_override=None, deployables=[], docker_build=None, document=None, flatten=None, format=None, h=None, help=None, http_timeout=None, ignore_bad_certs=False, image_url=None, log_http=None, project='MY_PROJECT', promote=None, quiet=None, server=None, skip_image_url_validation=False, skip_staging=False, stop_previous_version=None, trace_email=None, trace_log=None, trace_token=None, user_output_enabled=None, verbosity='debug', version=None).
DEBUG: API endpoint: [https://appengine.googleapis.com/], API version: [v1beta5]
You are creating an app for project [MY_PROJECT].
WARNING: Creating an app for a project is irreversible.

DEBUG: (gcloud.app.deploy)
Traceback (most recent call last):
  File "C:\Program Files (x86)\Google\Cloud SDK\google-cloud-sdk\lib\googlecloudsdk\calliope\cli.py", line 740, in Execute
    resources = args.calliope_command.Run(cli=self, args=args)
  File "C:\Program Files (x86)\Google\Cloud SDK\google-cloud-sdk\lib\googlecloudsdk\calliope\backend.py", line 1684, in Run
    resources = command_instance.Run(args)
  File "C:\Program Files (x86)\Google\Cloud SDK\google-cloud-sdk\lib\surface\app\deploy.py", line 53, in Run
    return deploy_util.RunDeploy(args)
  File "C:\Program Files (x86)\Google\Cloud SDK\google-cloud-sdk\lib\googlecloudsdk\command_lib\app\deploy_util.py", line 374, in RunDeploy
    app = _PossiblyCreateApp(api_client, project)
  File "C:\Program Files (x86)\Google\Cloud SDK\google-cloud-sdk\lib\googlecloudsdk\command_lib\app\deploy_util.py", line 507, in _PossiblyCreateApp
    create_util.CreateAppInteractively(api_client, project)
  File "C:\Program Files (x86)\Google\Cloud SDK\google-cloud-sdk\lib\googlecloudsdk\command_lib\app\create_util.py", line 109, in CreateAppInteractively
    all_regions = sorted(set(api_client.ListRegions()))
  File "C:\Program Files (x86)\Google\Cloud SDK\google-cloud-sdk\lib\googlecloudsdk\api_lib\app\appengine_api_client.py", line 415, in ListRegions
    self.client.apps_locations.List, request)
  File "C:\Program Files (x86)\Google\Cloud SDK\google-cloud-sdk\lib\googlecloudsdk\api_lib\app\api\requests.py", line 67, in MakeRequest
    raise err() if err else exc
NotFoundError
ERROR: (gcloud.app.deploy)

It doesn't give me much to go on. Wondering if it is a problem with app.yaml or some other basic issue.
gcloud info
Google Cloud SDK [138.0.0]

Platform: [Windows, x86_64]
Python Version: [2.7.10 (default, May 23 2015, 09:40:32) [MSC v.1500 32 bit (Intel)]]
Python Location: [C:\Program Files (x86)\Google\Cloud SDK\google-cloud-sdk\platform\bundledpython\python.exe]
Site Packages: [Disabled]

Installation Root: [C:\Program Files (x86)\Google\Cloud SDK\google-cloud-sdk]
Installed Components:
  bundled-python: [2.7.10]
  app-engine-python: [1.9.49]
  bq-win: [2.0.24]
  core: [2016.12.09]
  core-win: [2016.11.07]
  gcloud: []
  windows-ssh-tools: [2016.05.13]
  app-engine-python-extras: [1.9.49]
  gsutil: [4.22]
  bq: [2.0.24]
  powershell: [1.0.0.1]
  gsutil-win: [4.20]
System PATH: [C:\Program Files (x86)\Google\Cloud SDK\google-cloud-sdk\bin\..\bin\sdk;C:\Users\Jay-swtchbk\Miniconda2\condabin;C:\Program Files (x86)\Common Files\Oracle\Java\javapath;C:\ProgramData\Oracle\Java\javapath;C:\Program Files (x86)\Intel\iCLS Client\;C:\Program Files\Intel\iCLS Client\;C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPowerShell\v1.0\;C:\Program Files (x86)\Intel\Intel(R) Management Engine Components\DAL;C:\Program Files\Intel\Intel(R) Management Engine Components\DAL;C:\Program Files (x86)\Intel\Intel(R) Management Engine Components\IPT;C:\Program Files\Intel\Intel(R) Management Engine Components\IPT;C:\Program Files (x86)\Google\Cloud SDK\google-cloud-sdk\bin;C:\WINDOWS\System32\OpenSSH\;C:\Users\Jay-swtchbk\AppData\Roaming\Dashlane\4.6.5.21982\bin\Firefox_Extension\{442718d9-475e-452a-b3e1-fb1ee16b8e9f}\components;C:\Users\Jay-swtchbk\AppData\Local\Microsoft\WindowsApps;C:\Users\Jay-swtchbk\AppData\Local\Google\Cloud SDK\google-cloud-sdk\bin;C:\Program Files (x86)\Google\google_appengine\]
Cloud SDK on PATH: [True]
Kubectl on PATH: [False]

WARNING: There are old versions of the Google Cloud Platform tools on your system PATH.
  C:\Users\Jay-swtchbk\AppData\Local\Google\Cloud SDK\google-cloud-sdk\bin\gcloud.cmd
  C:\Users\Jay-swtchbk\AppData\Local\Google\Cloud SDK\google-cloud-sdk\bin\dev_appserver.py
  C:\Program Files (x86)\Google\google_appengine\dev_appserver.py
  C:\Users\Jay-swtchbk\AppData\Local\Google\Cloud SDK\google-cloud-sdk\bin\gsutil.cmd
  C:\Users\Jay-swtchbk\AppData\Local\Google\Cloud SDK\google-cloud-sdk\bin\git-credential-gcloud.cmd
  C:\Users\Jay-swtchbk\AppData\Local\Google\Cloud SDK\google-cloud-sdk\bin\bq.cmd
  C:\Users\Jay-swtchbk\AppData\Local\Google\Cloud SDK\google-cloud-sdk\bin\gcloud-ps.ps1
  C:\Users\Jay-swtchbk\AppData\Local\Google\Cloud SDK\google-cloud-sdk\bin\gsutil-ps.ps1
  C:\Users\Jay-swtchbk\AppData\Local\Google\Cloud SDK\google-cloud-sdk\bin\bq-ps.ps1
  C:\Program Files (x86)\Google\google_appengine\endpointscfg.py
  C:\Users\Jay-swtchbk\AppData\Local\Google\Cloud SDK\google-cloud-sdk\bin\endpointscfg.py

Installation Properties: [C:\Program Files (x86)\Google\Cloud SDK\google-cloud-sdk\properties]
User Config Directory: [C:\Users\Jay-swtchbk\AppData\Roaming\gcloud]
Active Configuration Name: [tvpub1]
Active Configuration Path: [C:\Users\Jay-swtchbk\AppData\Roaming\gcloud\configurations\config_tvpub1]

Account: [*******@gmail.com]
Project: [MY_PROJECT]

Current Properties:
  [core]
    project: [MY_PROJECT]
    account: [******@gmail.com]
    disable_usage_reporting: [False]

app.yaml contents:
runtime: python27
api_version: 1
threadsafe: false

libraries:
- name: jinja2
  version: latest

- name: webapp2
  version: latest

- name: lxml
  version: latest

- name: numpy
  version: "1.6.1"

builtins:
- remote_api: on

inbound_services:
- mail

handlers:
- url: /assets
  static_dir: assets

- url: /static
  static_dir: static

- url: /admin/.*
  script: MY_PROJECT.app
  login: admin

- url: /favicon\.ico
  static_files: assets/img/favicon.ico
  upload: assets/img/favicon\.ico

- url: /.*
  script: MY_PROJECT.app```

A: Solved, for those who having similar issues:
I Was using:

*

*gcloud app deploy --project=MY_PROJECT

But it works if you specify the version flag (which is optional according to Google's documentation)

*

*gcloud app deploy --project=MY_PROJECT --version=1


Q: My Flutter App is Not Working on Android 11 But Working fine in emulator as well as android 8 || (OS Error: Operation not permitted, errno = 1) Here is My Code
import 'package:flutter/material.dart';
import 'package:screenshot/screenshot.dart';
import 'package:sweld/globals.dart';
import 'package:geolocator/geolocator.dart';

class WeldSetup extends StatelessWidget {
  WeldSetup({Key? key}) : super(key: key);
  final pageNum = 211;

  @override
  Widget build(BuildContext context) {
    final _ssc = ScreenshotController();
    return Scaffold(
      appBar: AppBar(
        title: Text("Weld Setup"),
        centerTitle: true,
        actions: [
          IconButton(
            onPressed: () {
              Navigator.pop(context);
            },
            icon: Icon(Icons.railway_alert_rounded),
          ),
        ],
      ),
      body: Screenshot(controller: _ssc, child: WsLocation()),
      persistentFooterButtons: [
        ElevatedButton(
            onPressed: () async {
              Globals.ss211 = await _ssc.captureAndSave(Globals.appDir,
                  fileName: "ss211.png",
                  pixelRatio: MediaQuery.of(context).devicePixelRatio,
                  delay: Duration(milliseconds: 100));

              Navigator.pushNamed(context, "/212");
            },
            child: Text("Next"))
      ],
      extendBody: true,
    );
  }
}

class WsLocation extends StatefulWidget {
  const WsLocation({Key? key}) : super(key: key);

  @override
  _WsLocationState createState() => _WsLocationState();
}

class _WsLocationState extends State<WsLocation> {
  late Position curPos;
  var longitute = Globals.longitude;
  var latitude = Globals.latitude;
  TimeOfDay sTime = TimeOfDay(hour: 00, minute: 00);
  TimeOfDay eTime = TimeOfDay(hour: 00, minute: 00);

  Widget selectTime(time) {
    if (time == TimeOfDay(hour: 00, minute: 00)) {
      return Text("Select Time");
    } else {
      if (time == sTime) {
        return Text("${Globals.stime}");
      } else {
        return Text("${Globals.etime}");
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return SingleChildScrollView(
      child: Container(
        margin: EdgeInsets.all(15),
        color: Colors.white,
        child: Column(
          children: [
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Text(
                  "LOCATION",
                  textScaleFactor: 2,
                  style: TextStyle(
                    fontWeight: FontWeight.bold,
                  ),
                )
              ],
            ),
            Divider(
              thickness: 2,
              height: 50,
            ),
            Container(
              child: Form(
                child: Column(
                  mainAxisSize: MainAxisSize.min,
                  children: [
                    Row(
                      mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                      children: [
                        Flexible(
                          child: TextFormField(
                            initialValue: Globals.longitude,
                            decoration: InputDecoration(
                              labelText: "Longitude",
                              border: OutlineInputBorder(
                                borderRadius: BorderRadius.circular(5),
                                borderSide: BorderSide(
                                  color: Colors.black,
                                  style: BorderStyle.solid,
                                  width: 1.5,
                                ),
                              ),
                            ),
                            onChanged: (val) {
                              setState(() {
                                Globals.longitude = val;
                              });
                            },
                          ),
                        ),
                        Divider(
                          indent: 5,
                        ),
                        Flexible(
                          child: TextFormField(
                            initialValue: Globals.latitude,
                            decoration: InputDecoration(
                              labelText: "Latitude",
                              border: OutlineInputBorder(
                                borderRadius: BorderRadius.circular(5),
                                borderSide: BorderSide(
                                  color: Colors.black,
                                  style: BorderStyle.solid,
                                  width: 1.5,
                                ),
                              ),
                            ),
                            onChanged: (val) {
                              setState(() {
                                Globals.latitude = val;
                              });
                            },
                          ),
                        ),
                      ],
                    ),
                    Divider(
                      thickness: 0,
                      height: 10,
                    ),
                    TextFormField(
                      initialValue: Globals.section,
                      decoration: InputDecoration(
                        labelText: "Section",
                        border: OutlineInputBorder(
                          borderRadius: BorderRadius.circular(5),
                          borderSide: BorderSide(
                            color: Colors.black,
                            style: BorderStyle.solid,
                            width: 1.5,
                          ),
                        ),
                      ),
                      onChanged: (val) {
                        setState(() {
                          Globals.section = val;
                        });
                      },
                    ),
                    Divider(
                      thickness: 0,
                      height: 10,
                    ),
                    TextFormField(
                      initialValue: Globals.division,
                      decoration: InputDecoration(
                        labelText: "Division",
                        border: OutlineInputBorder(
                          borderRadius: BorderRadius.circular(5),
                          borderSide: BorderSide(
                            color: Colors.black,
                            style: BorderStyle.solid,
                            width: 1.5,
                          ),
                        ),
                      ),
                      onChanged: (val) {
                        Globals.division = val;
                      },
                    ),
                    Divider(
                      thickness: 0,
                      height: 10,
                    ),
                    TextFormField(
                      initialValue: Globals.distance,
                      decoration: InputDecoration(
                        labelText: "Distance",
                        hintText: "In kilometers(km)",
                        border: OutlineInputBorder(
                          borderRadius: BorderRadius.circular(5),
                          borderSide: BorderSide(
                            color: Colors.black,
                            style: BorderStyle.solid,
                            width: 1.5,
                          ),
                        ),
                      ),
                      onChanged: (val) {
                        Globals.distance = val;
                      },
                    ),
                    Divider(
                      thickness: 0,
                      height: 10,
                    ),
                    DropdownButtonFormField<String>(
                      decoration: InputDecoration(
                        border: OutlineInputBorder(
                          borderRadius: BorderRadius.circular(5),
                          borderSide: BorderSide(
                            color: Colors.black,
                            style: BorderStyle.solid,
                            width: 1.5,
                          ),
                        ),
                      ),
                      hint: Text("Line"),
                      isExpanded: true,
                      items: <String>['Single', 'Up-Line', 'Down-Line']
                          .map((String value) {
                        return DropdownMenuItem<String>(
                          value: value,
                          child: Text(value),
                        );
                      }).toList(),
                      onChanged: (val) {
                        Globals.line = val;
                      },
                    ),
                    Divider(
                      thickness: 0,
                      height: 10,
                    ),
                    Container(
                      child: Row(
                        mainAxisAlignment: MainAxisAlignment.spaceBetween,
                        children: [
                          Flexible(
                            child: Row(
                              children: [
                                Divider(
                                  indent: 15,
                                  endIndent: 5,
                                ),
                                Text("Start Time "),
                                TextButton(
                                  onPressed: () {
                                    showTimePicker(
                                            context: context,
                                            initialTime: sTime)
                                        .then((value) {
                                      if (value != null) {
                                        setState(() {
                                          sTime = value;
                                          Globals.stime = value.format(context);
                                        });
                                      }
                                    });
                                  },
                                  child: Globals.stime == null
                                      ? selectTime(sTime)
                                      : Text(" ${Globals.stime} "),
                                ),
                              ],
                            ),
                          ),
                          // Divider(
                          //   thickness: 0,
                          //   indent: 5,
                          // ),
                          Flexible(
                            child: Row(
                              children: [
                                Divider(
                                  indent: 10,
                                ),
                                Text("End Time "),
                                TextButton(
                                  onPressed: () {
                                    showTimePicker(
                                            context: context,
                                            initialTime: eTime)
                                        .then((value) {
                                      if (value != null) {
                                        setState(() {
                                          eTime = value;
                                          Globals.etime = value.format(context);
                                        });
                                      }
                                    });
                                  },
                                  child: Globals.etime == null
                                      ? selectTime(eTime)
                                      : Text(" ${Globals.etime} "),
                                ),
                              ],
                            ),
                          ),
                        ],
                      ),
                    ),
                  ],
                ),
              ),
            ),
            Divider(
              height: 50,
            ),
          ],
        ),
      ),
    );
  }
}

Here user is able to Input in Text fields, But when He presses Next He is not able to goto next Page. Moreover When I run it in emulator then it is working Totally Fine !.
And Yes its important to take screenshot of everypage therefore, I cannot Exclude it.
And sometime it returns Null, It Might be a problem But I dont know How to deal with it or What should I do Next.
Any Suggestions Please
Here is My Build Gradle File
def localProperties = new Properties()
def localPropertiesFile = rootProject.file('local.properties')
if (localPropertiesFile.exists()) {
    localPropertiesFile.withReader('UTF-8') { reader ->
        localProperties.load(reader)
    }
}

def flutterRoot = localProperties.getProperty('flutter.sdk')
if (flutterRoot == null) {
    throw new GradleException("Flutter SDK not found. Define location with flutter.sdk in the local.properties file.")
}

def flutterVersionCode = localProperties.getProperty('flutter.versionCode')
if (flutterVersionCode == null) {
    flutterVersionCode = '1'
}

def flutterVersionName = localProperties.getProperty('flutter.versionName')
if (flutterVersionName == null) {
    flutterVersionName = '1.0'
}

apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle"

android {
    compileSdkVersion 30

    sourceSets {
        main.java.srcDirs += 'src/main/kotlin'
    }

    defaultConfig {
        // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
        applicationId "com.example.sweld"
        minSdkVersion 16
        targetSdkVersion 30
        versionCode flutterVersionCode.toInteger()
        versionName flutterVersionName
    }

    buildTypes {
        release {
            // TODO: Add your own signing config for the release build.
            // Signing with the debug keys for now, so `flutter run --release` works.
            signingConfig signingConfigs.debug
        }
    }
}

flutter {
    source '../..'
}

dependencies {
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
}

UpDate

I just Recieved the error, It is
[ERROR:flutter/lib/ui/ui_dart_state.cc(199)] Unhandled Exception: FileSystemException: Creation failed, path = 'storage/emulated/0/sweld' (OS Error: Operation not permitted, errno = 1)
E/flutter ( 7337): #0      _Directory.create.<anonymous closure> (dart:io/directory_impl.dart:117:11)
E/flutter ( 7337): #1      _rootRunUnary (dart:async/zone.dart:1362:47)
E/flutter ( 7337): #2      _CustomZone.runUnary (dart:async/zone.dart:1265:19)
E/flutter ( 7337): <asynchronous suspension>

So Please Tell me what SHow I DO ??

A: try to change  minSdkVersion 16 to  minSdkVersion 21

A: I solved this issue My getting Some additional Permissions.
MANAGE_EXTERNAL_STORAGE and INTERNET Permission

in Android Manifest File


Q: regex get text from next line I'm looking for a way to find text on the next line of a certain string using regex.

Say I have the following text:
Note:
Just some text on this line

Some more text here.

I just want to get the text 'Just some text on this line'.
I don't know exactly what the other text will be, so I can't search between 'Note:' and 'Some more text here'.
All I know is that the text I want is on the next line from 'Note:'.
How could I do this?
Cheers,
CJ

A: I'd go line by line down your string, and when a regex matches, then take the next line
string str;
// if you're not reading from a file, String.Split('\n'), can help you
using (StreamReader sr = new StreamReader("doc.txt"))
{
    while ((str = sr.ReadLine()) != null)
    {
        if (str.Trim() == "Note:") // you may also use a regex here if applicable
        {
            str = sr.ReadLine();
            break;
        }
    }
}

Console.WriteLine(str);

A: This can be done with a multiline regex, but are you sure you want to? It sounds more like a case for line-by-line processing.
The Regex would be something like:
new Regex(@"Note:$^(?<capture>.*)$", RegexOptions.MultiLine);

although you might need to make that first $ a \r?$ or a \s*$ because $ only matches \n not the \r in \r\n.
Your "Just some text on this line" would be in the group named capture. You might also need to strip a trailing \r from this because of the treatment of $.

A: You can do this
(?<=Note:(\r?\n)).*?(?=(\r?\n)|$)
---------------- --- ------------
      |           |        |->lookahead for \r\n or end of string
      |           |->Gotcha
      |->lookbehind for note followed by \r\n. \r is optional in some cases

So,it would be like this
string nextLine=Regex.Match(input,regex,RegexOptions.Singline | RegexOptions.IgnoreCase ).Value;


Q: Max application memory Limit in iPad? I have created iPad application which downloads images using web service. But my application crashes somewhere during manipulating with high quality images. So my question is - what is max memory limit for application running on iPad? When does the application hit LowMemoryWarning on iPad?

A: There is no per-application limit so to say. The amount of memory available to an application depends on the amount of free memory, which again depends on the amount of memory used by applications running in the background. These apps include permanently running system apps like SpringBoard, sometimes running system apps like Safari, iPod, etc and (when iOS 4 will come for iPad) user-apps that still run in background.
Nevertheless, I'd say an app should never use more than 50% of all available ram. On iPad this currently means 128 MB and should be quite a lot. Did you do a leak check on your app?


Q: Packages to verify the re-rendering in es5 components other than "WhyDidYouRender" Right now I'm using the WhyDidYourender package to verify the component re-rendering but there are few components in my repo that uses es2015. WhyDidYouRender is not working in es2015 components. Seeing below error:
TypeError: Class constructor MyComponent cannot be invoked without 'new'

So need a way to verify the re-rendering for es5 components. Also, tried Chrome highlights to verify the re-rendering, please don't recommend that.
Any help is appreciated, Thanks!
WhyDidYouRender repo link: https://github.com/welldone-software/why-did-you-render

A: Support the ES6 or not is rely on your Browser. It's more like you trying to use the class but there is no instance to access.
Transpiled to es5 class is available in PR#8656, the whole react class elements are supported to extend with this library. If you transpile your classes by ES5 or ES6, use below code:
// traspiled to es5
const whyDidYouRender = require('@welldone-software/why-did-you-render);
// traspiled to es6
const whyDidYouRender = require('@welldone-software/why-did-you-render/dist/no-classes-transpile/umd/whyDidYouRender.min.js');


Q: Security - Method returns internal array - Sonar security warning - even when I am returning a clone The below return statement gives me a Sonar security warning even when I am not returning the original array but a clone of it.
What is the "correct" way to do this?
public String[] getList() {
        return list!=null? list.clone():null;
}

A: Edited my previous answer for some obvious errors :)
List.clone() doesn't work because it returns a shallow copy of the list. So basically it just returns the reference to the original list. We don't want that here. What we want is a brand new array that doesn't have the same reference to be returned.
For that the best idea will always be to create a new array and run a for loop like this:
String[] newArr = new String[list.length];
int i = 0;
for (String s : list) {
    newArr[i++] = s
}

If you wanna know why this is the issue, refer to this answer :)


Q: Elasticsearch aggregation using Java api Hi I am trying to do query on elastic search by following the sql query and I want to implement same logic using Java API
select dttime, avg(cpu) from table cpustats where server="X" and dttime="Y" group by dttime,cpu

Now I have the following Java code but it does not return expected output
SearchResponse response = client.prepareSearch("cpuindex")
      .setTypes("cputype")
      .setQuery(QueryBuilders.matchAllQuery())
      .addAggregation(AggregationBuilders.terms("cpu_agg")
           .field("cpu").size(100))
      .execute().actionGet();

Please guide I am new to Elastic search. Thanks in advance.

A: since elastic search 2.3, FilterBuilders class has been removed from JavaAPI. you can use
QueryBuilder qb = QueryBuilders.boolQuery()
        .must(QueryBuilders.matchQuery("_all", "JPMORGAN"))
        .must(QueryBuilders.matchQuery(field, value)) ;

instead, and set it to
.setQuery(qb).

A: I think this will help.
SearchResponse response=
                client.prepareSearch("your_index_name_here").setQuery(QueryBuilders.filteredQuery(QueryBuilders.matchAllQuery(),
                FilterBuilders.andFilter(
                        FilterBuilders.termFilter("server","x"),
                        FilterBuilders.termFilter("dt_time","x")
                ))).addAggregation(
                AggregationBuilders.terms("dt_timeaggs").field("dt_time").size(100).subAggregation(
                        AggregationBuilders.terms("cpu_aggs").field("cpu").size(100)
                )
        ).setSize(0).get();

please verify.


Q: QML rotating a Gauge needle - pivot correctly I am trying to rotate a Gauge needle, but instead of pivoting at the base of the needle which have a circle with cross.. needle is pivots around the tip of the needle.. please see the attached image.. tip of the image is fixed/pivots but base is rotating.. please suggest how to correct this ?
main.qml :--
import QtQuick 2.6
import QtQuick.Window 2.2
import QtQuick.Controls 2.5

Window
{
    visible: true
    x :0
    y :0
    width: 800
    height: 480
    color: "grey"

    Rectangle
    {
        id: cluster
        Speed_Needle{
          id: cluster_pointer_base
          x : 214+16
          y : 222
        }
     }

    Slider
    {
        id  : slide_1
        width: parent.width
        from: 0
        to: 360
        value: 0
        enabled: true
        onValueChanged:
        {
            cluster_pointer_base.value=slide_1.value
        }
    }

}

Speed_Needle.qml :--
import QtQuick 2.0

Item {

    property int value: 0
    width: 186
    height: 36

    Image
    {
        id: root
        source: "files/pointer_needle2.png"
        x : 0
        y : 0
        transform: Rotation  {
            id: needleRotation
            angle : value

            Behavior on angle  {

                SmoothedAnimation { velocity: 50 }
            }
        }

    }

}

A: You have to set the origin of the Rotation:
Speed_Needle.qml :--
import QtQuick 2.0

Item {

    property int value: 0
    width: 186
    height: 36

    Image
    {
        id: root
        source: "files/REE Demo images/pointer_needle2.png"
        x : 0
        y : 0
        transform: Rotation  {
            id: needleRotation
            angle : value
            origin.x: root.width / 2    // here!
            origin.y: root.height / 2

            Behavior on angle  {

                SmoothedAnimation { velocity: 50 }
            }
        }
    }
}


Q: Response from Postman shows 200, But Android returns 403 I was trying to develop an android app using Volley, The api I used to communicate is working fine when I checked with POSTMAN and retrieves 200 .
But when I use the same API in my App its returns me 403 "Forbidden"
<p〉You don't have permission to access /API/checkPassOtp on this server.〈/p〉
Please find the screenshot.

I have tried multiple solution for this issue, But nothing worked for me.
Can anyone please help me.
Attaching volley code and error response
JSONObject jsonBody = new JSONObject();
try {
    jsonBody.put("otp", otp);
    Log.e("jsonBody", jsonBody.toString());
} catch (JSONException e) {
    e.printStackTrace();
}

JsonObjectRequest jsonObjReq = new JsonObjectRequest(Request.Method.POST, URL, jsonBody, new Response.Listener<JSONObject>() {
    @Override
    public void onResponse(JSONObject response) {
        // handle response data
        VolleyHelper.progressDialog.dismiss();
        Log.e("onResponse", response.toString());

    }
}, new Response.ErrorListener() {

    @Override
    public void onErrorResponse(VolleyError error) {
        VolleyHelper.progressDialog.dismiss();
        Toast.makeText(getApplicationContext(),error.toString(),Toast.LENGTH_SHORT).show();
        Log.e("onErrorResponse", error.toString());

    }

}) {
    @Override
    public Map<String, String> getHeaders() throws AuthFailureError {
        Map<String, String> params = new HashMap<String, String>();
        params.put("Content-Type", "application/json");
        return params;
    }
};

jsonObjReq.setRetryPolicy(new DefaultRetryPolicy(DefaultRetryPolicy.DEFAULT_TIMEOUT_MS * 2, DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
Application.getInstance().addToRequestQueue(jsonObjReq, "app");
volleyHelper.showProgressDialogWithTitle(MainActivity.this);

A: Try to use

"Accept", "application/json"

in your params (use both).
I have to use x-api-key when connecting with my company's webserver, but I'm not sure if you'll need it.

A: --> Use https instead of http in android , Postman seems fine with the http, but OkHttp needed https.
I was stuck for a day for this error 403 forbidden in android , but giving 200 success in Postman .


Q: Cocoa: loading a bundle in which some classes inherit from a custom framework SHORT VERSION:
How can I load classes during runtime from a bundle, when those classes inherit from superclasses not defined in the bundle, but from another framework which was loaded prior?  When loading my framework, classes contained therein work fine.  When loading the plugin afterwards, any classes which inherit from NSObject work fine but classes inheriting from the framework are not being loaded.
LONG VERSION:
Cocoa allows you to control the Dock icon explicitly via the "Dock Tile Plugin" mechanism.  In a nutshell, when your app is added to the Dock, the OS looks inside the app's bundle plugins directory for a bundle called "MyDockTilePlugin.docktileplugin".  It then loads this plugin's principal class which must conform to the NSDockTilePlugIn protocol.
I have built such a bundle according to Apple's guide.  Now I want to reuse this code by making the component classes superclasses in my custom framework.  Subclasses specific to a given project can load the framework.
Surprisingly, this is not very straightforward.
Here is the process in psuedocode:

*

*The docktileplugin is loaded by the Dock.

*In its +initialize class method, the class loads the custom framework, which is set to "optional" in build settings.

*The class then loads its own plugin which contains classes inheriting from framework classes.

*Something like NSLog(@"%@", NSStringFromClass(NSClassFromString(classInheritingFromFramework))); will always display (null)

How does inheritance work across plugin bundles?  THANKS...
If this isn't enough information, please ask for more.  I'm trying to be concise and thorough.
MORE CODE:
+ (void)initialize {
[[NSNotificationCenter defaultCenter] addObserverForName:NSBundleDidLoadNotification object:nil queue:nil usingBlock:^(NSNotification *note) {
    NSLog(@"bundle loaded %@", note);
}];

//Plugin bundle
NSBundle *selfBundle = [NSBundle bundleForClass:[self class]];

//Load Custom Framework
NSString *frameworkName = @"Custom.framwork";
NSString *frameworkPath = [[selfBundle bundlePath] stringByAppendingPathComponent:[@"Contents/Frameworks" stringByAppendingPathComponent:frameworkName]];
NSLog(@"Framework %@ at %@", ([[NSFileManager defaultManager] fileExistsAtPath:frameworkPath]? @"EXISTS" : @"DOES NOT EXISTS"), frameworkPath);
if( [[NSBundle bundleWithPath:frameworkPath] load] ) {
    NSLog(@"Framework loaded...");
    NSLog(@"Framework provided classes such as DockTilePlugin (%@) and UndoManager (%@)", NSStringFromClass(NSClassFromString(@"DockTilePlugin")), NSStringFromClass(NSClassFromString(@"UndoManager")));
} else {
    NSLog(@"Error, framework failed to load.");
    exit(1);
}

//Load Dock Tile Plugin
NSString *pluginName = [[selfBundle infoDictionary] objectForKey:@"DockTilePluginCoreBundle"];
NSString *pluginPath = [[selfBundle builtInPlugInsPath] stringByAppendingPathComponent:[pluginName stringByAppendingPathExtension:@"bundle"]];
NSLog(@"Plugin %@ at %@", ([[NSFileManager defaultManager] fileExistsAtPath:pluginPath]? @"EXISTS" : @"DOES NOT EXISTS"), pluginPath);
if( [[NSBundle bundleWithPath:pluginPath] load] ) {
    NSLog(@"Plugin loaded...");
    NSLog(@"Plugin provided classes such as DockTilePlugin (%@) and DockTileView (%@)", NSStringFromClass(NSClassFromString(@"DockTilePlugin")), NSStringFromClass(NSClassFromString(@"DockTileView")));
} else {
    NSLog(@"Error, Plugin failed to load.");
    exit(1);
}
}

What output I see in the Console.app is that the first two "classes such as" show up (class names appear), but in the second two I get "Plugin Provided classes such as DockTilePlugin (null) and DockTileView (null)".
Also, the notifications are received for both bundles.  In the framework, I see in the "NSLoadedClasses" key that all framework classes are loaded and available.  In the Plugin bundle, this list is empty (although there should be several classes from the bundle, but they all inherit from the framework).
If I add a third class to the plugin, which inherits from Cocoa, that class appears fine.  Something about bundle-loading a class which inherits from another bundle-loaded class is tricky.  That is the heart of it I think.

A: Mike from http://mikeash.com - an amazing resource - provided me with the tip that solved this problem.  The cause of the problem eludes me, but it was fixed by doing two things:

*

*In the Framework's project, setting its build location to @rpath as described in this article: http://mikeash.com/pyblog/friday-qa-2009-11-06-linking-and-install-names.html

*In the plugins loading the framework, weak reference during build, don't copy the framework during build, and then set the -rpath build setting to the location of the framework in the containing app.  This ensures all items are using the same copy of the framework.


Q: VSCode pylint not displaying relative import failures I am running a Django application in VSCode, using pylint, and the relative imports errors are not displaying. They were before I installed a newer version of VSCode.
I have tried changing user settings and also workspace settings, but still can't get the errors to show.
User Settings
{
    "window.zoomLevel": 1,
    "explorer.confirmDelete": false,
    "workbench.startupEditor": "newUntitledFile",
    "window.menuBarVisibility": "default",
    "explorer.confirmDragAndDrop": false,
    "workbench.colorTheme": "Visual Studio Dark",
    "update.enableWindowsBackgroundUpdates": false,
    "update.channel": "none",
    "php.validate.run": "onSave",
}

Workspace settings
{
    "python.linting.enabled": true,
    "python.linting.pep8Enabled": false,
    "python.linting.pylintArgs": ["--load-plugins", "pylint_django"],
    "python.linting.pylintEnabled": true,
    "python.pythonPath": "/home/justin/anaconda3/bin/python",
    "python.linting.pylintPath": "/home/justin/anaconda3/bin/pylint"
}

At the top of one of my functions, a couple of different relative imports. Which one is right or wrong, VSCode should show me. Both imports are in the same project directory in Django, therefore import should be a single '.' I believe.
from .performance import get_perf_dates, get_perf_data
from ..models import DistributionList, Legend


Q: How can I make texmaker autocomplete commands that it doesn't already autocomplete? When I write
\begin{

in texmaker, I want it to suggest flalign} as a possible choice for autocompletion. At the moment, texmaker doesn't complete \begin{flalign} automatically; as a result, it also doesn't autocomplete \end{flalign}.
I've noticed that texmaker fails to autocomplete other commands too... Is there a way to enable autocompletion for those commands in texmaker?

A: In the menu, select User > Customize Completion. Then add \begin{flalign} to the list of commands. You can also specify arguments using @, e.g \foobar{@}.


Q: ListViewItem ItemSelectionChangedEvent Fires 4 times [e.Selected fires twice] leads to Win32 Exception Unhandled I am using a button and a listview to display a list of options to the user. Selection is made with a mouse click, the listview removes its self from the .Controls array + un-registers eventlistener and loads a new listview else where on the screen.
My problem is both listviews trigger e.selected twice:
' private void _lvKids_ItemSelectionChanged(object sender, ListViewItemSelectionChangedEventArgs e)
    {
        if (e.IsSelected)//fires twice per click
        {
            HideKidsList();//--REMOVE CURRENT LISTVIEW
            ValidateUser();//CREATE NEW LISTVIEW
        }`

If the button is clicked a second time to restart the process, it causes a win32 Exception. After much research, this exception is the often the cause of a memory leak. So I'm thinking memory leak?
When I first started, listboxes were used which worked perfectly. I'd love to able to use them, but my form has a graphic for a background and listbox doesn't. Listview does.
I don't have anyone to turn to so any thing you can offer would be appreciated.
Thanks;
Sam

A: An update if anyone else has the same issue. Selecting the listview item called for it to be removed from Controls array. Removing the listview also cause the selected item to be deselected, thus 4 calls to the handler.


Q: Start EC2 for specific time XX hours and then terminate A customer requested an  EC2 instance for XX hours.
I created an on-demand EC2 instance and I sent the credentials to the user. He used it for a short lived calculation.
How can I terminate that EC2 instance exactly after XX hours?
Thank you in advance.

A: The simplest way to terminate an instance after a given time period is:

*

*Provide a User Data script when launching the Amazon EC2 instance

*The script should wait the given period then issue a shutdown command, such as:

sleep 3600; shutdown now -h

Also, when launching the instance, set Shutdown Behavior = Terminate. This means that when the instance is stopped from within the instance, it will actually be terminated.
Alternatively, you could code a Stopinator that would trigger at times and determine which instances to stop/terminate. For some examples see: Simple Lambda Stopinator: Start/Stop EC2 instances on schedule or duration

A: Thanks, John(@john-rotenstein).
I tested all your suggestions.
I used the following User Data script for
Windows instances:
<script>
shutdown -s -t 3600
</script>
<persist>true</persist>

Linux instances:
...
#cloud-config
cloud_final_modules:
- [scripts-user, always]

--//
Content-Type: text/x-shellscript; charset="us-ascii"
MIME-Version: 1.0
Content-Transfer-Encoding: 7bit
Content-Disposition: attachment; filename="userdata.txt"

#!/bin/bash
sleep 3600
shutdown now -h

In addition, Stopinator Type 2 is working perfectly well for me, but only with Stop-After tag


Q: Disable all triggers in a database How do I disable all triggers in a database from another database  which are currently enabled .And then enable it back only the ones I disabled .

A: For DML triggers you can use below cursor.
If you need to disable DDL triggers as well, you will need to create similar cursor base on sys.triggers view. (as in sys.objects we have only DML cursors)
declare @sql nvarchar(150)

declare trigger_cursor CURSOR FOR
select  'DISABLE TRIGGER ' + SCHEMA_NAME(schema_id)+'.'+name
       +' ON '+SCHEMA_NAME(schema_id)+'.'+ OBJECT_NAME(parent_object_id)
    from sys.objects
    where type = 'TR'

OPEN trigger_cursor
FETCH NEXT FROM trigger_cursor INTO @sql

WHILE @@FETCH_STATUS = 0
BEGIN
      print @sql
      --sp_executesql @sql
      FETCH NEXT FROM trigger_cursor INTO @sql
END

CLOSE trigger_cursor
DEALLOCATE trigger_cursor

A: before disabling the triggers please consider a way to preserve the data integrity, for example, if there are 10 inserts coming up and some of them fire the triggers then you disable them triggers, then next inserts don't fire the triggers - then we have a problem now. if you don't consider this then the consequences can very likely be against you and\or your company.
you can for example, if your environment and work load and how busy your system is, set the database to single user mode.
at least think about the implications in your environment.
You can also script the triggers.
Script to enable/ disable triggers - script generation
    -- this script only returns the triggers
    -- in an specific database or server triggers
use your_database

declare @TABLEIDOUT int=NULL -- this is the object_id of a table
                             -- if not null then only the triggers for that
                             -- table are considered

declare @include_server_triggers bit = 1
       -- if 1 then the server triggers are
       -- considered otherwise they are ignored

SELECT _enable_  =N'use ' + QUOTENAME(DB_NAME()) + N'; ENABLE TRIGGER '
                          + st.name + N' ON ' + st.parent_name
      ,_disable_ =N'use ' + QUOTENAME(DB_NAME()) + N'; DISABLE TRIGGER '
                          + st.name + N' ON ' + st.parent_name
      ,_name_    = st.name
      ,ST.is_disabled
FROM (
SELECT
             object_id=s.object_id
            ,parent_name  = QUOTENAME(OBJECT_SCHEMA_NAME(s.parent_id)) + '.'
             + QUOTENAME(OBJECT_NAME(s.parent_id))
            ,name = QUOTENAME(OBJECT_SCHEMA_NAME(s.object_id)) + '.'
             + QUOTENAME(OBJECT_NAME(s.object_id))
            ,s.is_disabled
            FROM sys.triggers s
            WHERE 1=1
             AND ((s.parent_id = @TABLEIDOUT) OR (@TABLEIDOUT is null))
) st
WHERE ST.name IS NOT NULL

UNION ALL

SELECT _enable_  =N'use master; ENABLE TRIGGER ' + QUOTENAME(st.name)
                  + N' ON ALL SERVER'
      ,_disable_ =N'use master; DISABLE TRIGGER ' + QUOTENAME(st.name)
                  + N'ON ALL SERVER'
      ,_name_    = st.name
      ,ST.is_disabled
FROM master.sys.server_triggers st
WHERE @include_server_triggers =1

you can check when triggers were disabled.
it is not recorded in the default trace.


Q: White blank screen in custom module production mode magento 2 I have created a custom module in Magento 2. In developer mode it is working well, however same module does not show any content in the production mode of Magento its show only white screen. There is no error in logs, apache, system, debug logs are empty. Any suggestions?

A: Ran into this error myself. In my instance the issue was with the name of the controller file.
The controller file was name /Controller/Index/index.php
When it should have been /Controller/Index/Index.php
Apparently it worked with a lower case i in developer mode but stopped working in production mode.


Q: How to avoid spurious 'unused parameter' warnings in TypeScript I've encountered this a bunch and have finally decided to figure out what the right way to do it is.  If I have an abstract parent class that declares a method, and then some of the concrete sub-classes implement real logic in their implementation (and, obviously, use the method parameters), but some of the sub-classes don't need to do anything in that method (so don't use the method parameters) - the ones that don't have to do anything generate spurious (in my view) warnings in my code.
For instance, if I have some classes that look like:
abstract class Child {
  constructor(protected name: string) {
    connsole.log(name + " was just born.");
  }

  abstract tellThemToDoSomething(command: string);
}

class GoodChild extends Child {
  constructor(name: string) { super(name); }
  tellThemToDoSomething(command: string) {
    console.log("I will do " + command);
  }
}

class BadChild extends Child {
  constructor(name: string) { super(name); }
  tellThemToDoSomething(command: string) {
    // bad children just ignore what their parents tell them
  }
}

Then I get a (TSLint? JSLint? WebStorm?) warning in WebStorm for the unused parameter in the BadChild tellThemToDoSomethign() method.
I know of a few options, but none seem great.
1) Ignore it (but that seems suboptimal, since I'll grow blind to real warnings)
2) Remove the parameter from the BadChild's method implementation (but that unfortunately removes useful information, since I may later want to implement it, and not having the signature there makes it more difficult, and I also get errors from callers expecting there to be parameters - though given that I should be able to call a method with extraneous parameters in JavaScript, I be there's a way around that problem)
3) Tell WebStorm(TSLint) to stop warning on unused parameters (but that seems suboptimal since I won't get warnings in other real problem situations)
4) Do something meaningless with the parameter so it is not unused (obviously not great)
What is do experienced Java/TypeScript coders do in situations like this?  Is there an easy way to tell WebStorm/TSLint to ignore the parameter in individual cases like this?  Or, even better, a way to tell it to ignore unused parameters in sub-class implementations of abstract methods, as long as some implementations actually use the parameters?
I'm a little unsure on where the warning is coming from, though, since my brief googling shows a TSLint warning for unused-variables but not unused-parameters, and adding a // tslint:ignore-next-line:no-unused-parameter (or no-unused-variable) didn't make the warning go away.  So I guess it's possible the warning is coming from WebStorm itself?  Further, the warning is "Unused parameter Foo: Checks JavaScript parameter, local variable, function, classes and private member declarations to be used in given file scope".  So it doesn't look like a TSLint warning.  And if I look in my WebStorm Preferences -> Languages & Frameworks -> Javascript -> Code Quality Tools, none of the linters are enabled (JSLint, JSHint, ESLint, etc.).  So any idea where the error is coming from?
I've not coded in TypeScript long enough to have a feel for what the ideal dial on this warning should be.

A: This warning is caused by JetBrains PhpStorm/WebStorm inspections.
A conventional way that is properly handled by TypeScript is to underscore unused parameters. Unfortunately, this convention isn't supported by JetBrains IDEs.
It's possible to suppress inspections in-place in some cases by triggering suggestion list with Alt+Enter/⌥+Enter and choosing Suppress for statement (this never worked for me for IDE inspections).
It's possible to suppress inspections in inspections results.
This results in adding a comment above the method and affects all unused parameters in this method signature:
// noinspection JSUnusedLocalSymbols
tellThemToDoSomething(_command: string) {}

This can be added to live templates, etc.


Q: How Can I Terminate a Thread Using a Throw Exception Method - Python I found some code online that will stop a thread via an exception after a wait period of some time.
def raise_exception(self):
  thread_id = self.get_id()
  res = ctypes.pythonapi.PyThreadState_SetAsyncExc(thread_id,
          ctypes.py_object(SystemExit))
  if res > 1:
    ctypes.pythonapi.PyThreadState_SetAsyncExc(thread_id, 0)
    print('Exception raise failure')

An exception is called after some time by:
t1 = thread_with_exception('Thread 1')
t1.start()
time.sleep(1/1000)
t1.raise_exception()
t1.join()

I would like to call an exception that would specify how many time a process occurs. Such as:
t1 = thread_with_exception('Thread 1')
t1.start()
if t1.count >= 3:
    t1.raise_exception()
    t1.join()

This however fails to call an exception when t1.count >= 3.
Can an exception not be called in this manner?

A: Rather than calling the raise_exception outside the class, calling it from within the run method for the thread will work. Ex.
def run(self):
    if count>3:
         self.raise_exception()


Q: Unable to POST data using TLS 1.2 I am trying to POST data to a server who is just using TLS1.2
When i am running the code i am getting the following response from server.
HttpResponseProxy{HTTP/1.1 415 Unsupported Media Type [Date: Wed, 07 Sep 2016 17:42:57 CST, Server: , Strict-Transport-Security: max-age=63072000; includeSubdomains; preload, Pragma: no-cache, Content-Length: 0, charset: ISO-8859-1, X-ORACLE-DMS-RID: 0, X-ORACLE-DMS-ECID: 343fa6c0-ed24-4003-ad58-342caf000404-00000383, Set-Cookie: JSESSIONID=1ZMIvt1NqrtWpHgHs4mMmYyTPUGTOQgrA9biCE3Dok5v0gDCPXu6!681252631; path=/; secure; HttpOnly;HttpOnly;Secure, Cache-Control: no-store, P3P: policyref="/w3c/p3p.xml", CP="WBP DSP NOR AMT ADM DOT URT POT NOT", Keep-Alive: timeout=5, max=250, Connection: Keep-Alive, Content-Type: text/xml, Content-Language: en] [Content-Type: text/xml,Content-Length: 0,Chunked: false]}

I am using the below code to post the data to server . I am using apache httpcomponents-client-4.5.2.
private static Registry<ConnectionSocketFactory> getRegistry() throws KeyManagementException, NoSuchAlgorithmException {
        SSLContext sslContext = SSLContexts.custom().build();
        SSLConnectionSocketFactory sslConnectionSocketFactory = new SSLConnectionSocketFactory(sslContext,
                new String[]{"TLSv1.2"}, null, SSLConnectionSocketFactory.getDefaultHostnameVerifier());
        return RegistryBuilder.<ConnectionSocketFactory>create()
                .register("https", sslConnectionSocketFactory)
                .register("https", sslConnectionSocketFactory)
                .build();
    }

    public static void main(String[] args) throws Exception
    {
        PoolingHttpClientConnectionManager clientConnectionManager = new PoolingHttpClientConnectionManager(getRegistry());
        clientConnectionManager.setMaxTotal(100);
        clientConnectionManager.setDefaultMaxPerRoute(20);
        HttpClient client = HttpClients.custom().setConnectionManager(clientConnectionManager).build();
        HttpPost  request = new HttpPost("https://someserver.com/dataupload");
        File file = new File("C://Nible//code//_client//Request.xml");
        MultipartEntityBuilder builder = MultipartEntityBuilder.create();
        builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
        builder.setContentType(ContentType.TEXT_XML);
        FileBody fileBody = new FileBody(file);
        builder.addPart("my_file", fileBody);
        HttpEntity reqEntity = builder.build();
        request.setEntity(reqEntity);
        HttpResponse response = client.execute(request);
       System.out.println(response);
    }

Can you please tell me what wrong am i doing?
I tried using below code instead of MultipartEntityBuilder. I am still getting the same error.
EntityBuilder builder = EntityBuilder.create();
builder.setFile(file);
builder.setContentType(ContentType.TEXT_XML);

If i am sending the BLANK REQUEST to server then also i am getting the same error. Blank error means i am not putting any thing in request just
HttpPost  request = new HttpPost("https://someserver.com/dataupload");
 HttpResponse response = client.execute(request);

A: I suspect of these lines in your code:
MultipartEntityBuilder builder = MultipartEntityBuilder.create();
builder.setMode(HttpMultipartMode.BROWSER_COMPATIBLE);
builder.setContentType(ContentType.TEXT_XML);

Multipart entities cannot be of content-type xml. They must be one of these types:

*

*multipart/mixed

*multipart/alternative

*multipart/digest

*multipart/parallel

(See RFC 1341 7.2)
I guess you should use one of these content-types for the multipart entity, and set text/xml as the content type of the single part:
FileBody fileBody = new FileBody(file, ContentType.TEXT_XML);

(Another issue is that I don't see necessary to send a multipart for just one file: You could leave out the MultipartEntityBuilder object and build directly a FileEntity.)


Q: Mapping attributes using @JsonProperty when binding play.data.Form from JsonNode I have the following class
public static class Thing {
    @JsonProperty("_name_")
    String name;
}

and I'm trying to bind it to the form and get instance of this class this way
ObjectNode node = Json.newObject();
node.put("_name_", "some name");

Form<Thing> thingForm = Form.form(Thing.class);
thingForm = thingForm.bind(node);
Thing thing = thingForm.get();

So, I expect that thing.name will be "some name" but it's not, it is null. I understant that @JsonProperty is for Json (de)serialization, just tried if it works. The question is how to achieve this with Play's Form?
I also tried to Register a custom DataBinder as described in docs, but its methods never gets called.
Any help is appreciated.

A: Have you tried thingForm.bindFromRequest() instead of thingForm.bind()? I am using exactly same thing where I make an ajax post with json data and it is working fine for me. It doesn't look like it has anything to do with @JsonProperty().
Are you sure if you want to have class Thing static ? I am assuming you have public getter/setters for your form properties.


Q: PaypalPlus iFrame integration with Payment Logos How can I add the payment logo to the PaypalPlus iFrame integration? We have 2 extensions for PaypalPlus, the old one shows payment logos for Paypal, direct debit etc. but the new one not.  (The Image has class class="paymentMethodIcon")
In all SDK & Integration guides I did not find any information about this.
Who can help? Is this something which depends on integration and is controlled by Paypal or is there any setting?
Thats how it should look

A: The payment wall iframe is configured by paypal with a whitelist of allowed domains (see Content Security Policy).

*

*The image URL must be https (specified in the docs)

*Your images must be on a server on the whitelist.

*This includes: The image URL can not have a custom port.

*PayPal automatically adds the domain containing the PPP script to the whitelist.

If you look into the browser console you might be able to see an error like this:
Refused to load the image 'https://my-domain.de:7443/images/payment_sofort_small.png' because it violates the following Content Security Policy directive: "img-src https://*.paypalobjects.com https://ak1s.abmr.net https://ak1.abmr.net https://ak1s.mathtag.com https://akamai.mathtag.com https://my-domain.de".
This is how it looked in my case:


Q: Why are coefficient in regression model interpreted as change in response with unit increase in that variable with others constant? Why does this interpretation make sense only when we keep other variables constant ?
After all those coefficient weren't learnt that way(keeping other constant), so unless there is strong multi collinearity why would we need to fix the other variables' values for this interpretation to make sense, have we not already taken the correlation into account in the learning step and embedded it into the coefficient for each variable ?

A: I find that it helps to think about this geometrically. Basically what linear regression with 2 or more predictors is doing is finding the (hyper-)plane that best fits the data points. So we can plot the model predictions in 3 dimensions as something like this:

The regression coefficient (i.e., slope) for a particular predictor, let's say $x_1$, is interpreted as the change in the predicted $y$-value as we move along this regression plane in a direction parallel to the $x_1$ axis, and hence perpendicular to the $x_2$ axis. Notice that this interpretation has nothing whatsoever to do with the correlation between $x_1$ and $x_2$ in the dataset. It simply states a geometric fact about what happens in the $y$ dimension as we traverse along the regression plane in a particular direction. Because the direction of movement described by any predictor slope is necessarily perpendicular to all the other predictor axes, we can intuitively imagine that each one is "holding constant" the values on the other predictors.
Now, multicollinearity will of course have an impact on what these slopes are estimated to be and what the standard errors of those estimates are. But the key point is that once we have the slope estimates in hand, their interpretation does not reference the statistical associations among the predictors in any way. They only refer to the geometry of the regression plane.

A: I think you're kind of right on this one.  A better interpretation (well, I think it's better) I often give to my students is:

If we happen to collect two new data points from the process which created the training data, and happen to find that these two data points differ in the value of one and only one feature, and that one feature differs by one unit, then we expect the value of y for those two data points to differ by the parameter estimate for that feature.

This one does away with the conceptual difficulties of the phrase "the change in".


Q: Creating Custom Query I've hit some sort of stumbling bock here, and I can't find my way over it.
I'm trying to craft a custom WP query that searches for posts by country of origin, selecting multiple countries at once.
I have a table that maps countries to regions, so the initial query will search for the selected region, and return all of the countries in that region as an array. For example, if you select Africa, it will return an array of countries within Africa.
if(!empty($_REQUEST['region'])){
     $region = $_REQUEST['region'];

    $regionresult = mysql_query("SELECT * FROM gallery_regions WHERE region='$region'") or die(mysql_error());
    $num_rows = mysql_num_rows($regionresult);

    if (!$regionresult) {
        $message  = 'Invalid query: ' . mysql_error() . "\n";
        $message .= 'Whole query: ' . $query;
        die($message);
    }
} else {
     $region = NULL;
}

That part works.
Now, I want to use the returning array to search my WP posts for any that originated from any of the countries in the array. This is the part I can't get to work:
$country_search = array(mysql_fetch_array($regionresult));
$args = array(
    'posts_per_page' => -1,
    'meta_query' => array(
        array(
            'key' => 'Country',
            'value' => '$country_search',
            'compare' => 'IN'
        )
    )
);
$query = new WP_Query( $args );

I get no results back. In fact, if include echo "$args";, what I get back is simply the word "Array." I also only want it to return results from a specific category.
I'm sure that I'm overlooking something simple. Can anyone help?
Thanks!
ty

A: You're passing '$country_search' as a literal value, it should be
'value' => $country_search

without single quotes.
Also, I recommend replacing those old mysql query functions with wpdb.

A: Try following codes:
    $country_search_array = array();
    while($row = mysql_fetch_array($regionresult)){
        $country_search_array[] = $row['country']; // Your country field name
    }
    $country_search = "'".implode("',", $country_search_array)."'";

$args = array(
        'posts_per_page' => -1,
        'meta_query' => array(
            array(
                'key' => 'Country',
                'value' => $country_search,
                'compare' => 'IN'
            )
        )
    );
    $query = new WP_Query( $args );

A: The problem was that there were two array objects:
$country_search = array(mysql_fetch_array($regionresult));
$args = array(
    'posts_per_page' => -1,
    'meta_query' => array(
        array(
            'key' => 'Country',
            'value' => '$country_search',
            'compare' => 'IN',
            'category' => 'Gallery'
        )
    )
);
$query = new WP_Query( $args );

It should have been this:
$country_search = array(mysql_fetch_array($regionresult));
$args = array(
    'posts_per_page' => -1,
    'meta_query' => array(
            'key' => 'Country',
            'value' => '$country_search',
            'compare' => 'IN',
            'category' => 'Gallery'
    )
);
$query = new WP_Query( $args );


Q: create distinct objects in a loop in js var subject = [] ;
var subjectTemplate = {GUID:"", Title:"", Description:""};
for (var x = 0; x < 5; x++) {
var  clsSubject =   subjectTemplate;

    clsSubject.GUID = id.generateRandomNumber()
    clsSubject.Title = "Intorduction to js";
    clsSubject.Description = "Subject to learn js";
    subject.push = clsSubject;

}
what is happening is that there are 5 references of the same object in the array. So after the last run; all the 5 objects in the array have the same values. The five objects in the array are identical.
I need to create 5 distinct objects with distinct values in an array.

A: After doing some research and have come with the following:
var subjects = [];
var subjectTemplate = {GUID:""};

for (var x = 0; x < 5; x++)
{
  var subject = Object.Create(subjectTemplate);
      subject.GUID = <generate GUID>;
      subjects[x] = subject;
}

A: With javascript you do not need to declare or initialize the fields when you first initialize the object.
Replace
var  clsSubject =   subjectTemplate;

with
var clsSubject = {};

With your current implementation you set all clsSubject to the same object instance, namely subjectTemplate.

A: You can just change the delcaration of clsSubject to create a new object. You can actually just fill in the properties directly if you want. Also you didn't push to the array correctly.
var clsSubject = {
    GUID: id.generateRandomNumber(),
    Title: "Intorduction to js",
    Description: "Subject to learn js"
};
subject.push(clsSubject);


Q: Como puedo animar una imagen en android me gustaría animar una imagen en android studio para que parezca que la estoy pulsando, e probado con rescalarla y volverla a poner a su tamaño original pero se hace tan rápido que no te das cuenta de que lo haya hecho
Alguna forma de hacerlos? Estoy usando una versión sdk mínima 15, me gustaría que siguiera así, aunque si hay que cambiarla tampoco habría problema
public class GameActivity extends AppCompatActivity {

private static TextView mText, Score;
private static ImageView avatar;
private static double Scor = 0;
private static double dificultadScor = 0;
private static int seconds = 0;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.layout_game);
    mText = findViewById(R.id.mText);
    avatar = findViewById(R.id.avatar);
    Score = findViewById(R.id.score);
    Scor = 0;
    SharedPreferences pr = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
    String dificultad = pr.getString("dificultad", "1");

    switch(dificultad){

        case "1":
            seconds = 30000;
            dificultadScor = 0.25;
            avatar.setImageDrawable(getResources().getDrawable(R.drawable.emadera));
            break;

        case "2":
            seconds = 15000;
            dificultadScor = 0.5;
            avatar.setImageDrawable(getResources().getDrawable(R.drawable.ehierro));
            break;

        case "3":
            seconds = 7000;
            dificultadScor = 0.75;
            avatar.setImageDrawable(getResources().getDrawable(R.drawable.eoro));
            break;

        case "4":
            seconds = 3000;
            dificultadScor = 1;
            avatar.setImageDrawable(getResources().getDrawable(R.drawable.ediamante));
            break;
    }

    countStart();

    avatar.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Scor += dificultadScor;
            Score.setText("Score: " + Scor);
            avatar.getLayoutParams().height = 119;
            avatar.getLayoutParams().width = 145;
            avatar.getLayoutParams().height = 219;
            avatar.getLayoutParams().width = 245;

        }
    });

}

@Override
protected void onResume() {
    super.onResume();

}

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

@Override
public void onBackPressed() {

    AlertDialog.Builder builder = new AlertDialog.Builder(GameActivity.this);

    builder.setTitle("Salir de la partida");
    builder.setPositiveButton("Si", new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            Intent myintent = new Intent(GameActivity.this, MenuActivity.class);
            startActivity(myintent);
            finish();
        }
    });
    builder.setNegativeButton("No", null);
    builder.create();
    builder.show();

}

public void countStart(){

    new CountDownTimer(seconds, 1000) {

        public void onTick(long millisUntilFinished) {//Cuando cambia el contador
            //Actualizamos la etiqueta que muestra el contador
            if(millisUntilFinished<7){
                mText.setTextColor(getResources().getColor(R.color.alarm));
            }
            mText.setText("Segundos restantes: " + millisUntilFinished / 1000);

        }
        //Evento que se lanza cuando acaba la cuenta atrás
        public void onFinish() {
            AlertDialog.Builder builder = new AlertDialog.Builder(GameActivity.this);

            builder.setTitle("Partida Finalizada");
            builder.setPositiveButton("Jugar otra vez", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    Scor = 0;
                    countStart();
                }
            });
            builder.setNegativeButton("Salir", new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    Intent myintent = new Intent(GameActivity.this, MenuActivity.class);
                    startActivity(myintent);
                    finish();
                }
            });
            builder.create();
            builder.show();
        }
    }.start();
}

}
Hay estaría toda la clase, la parte de las imagenes para no buscar tanto es esta
switch(dificultad){

        case "1":
            seconds = 30000;
            dificultadScor = 0.25;
            avatar.setImageDrawable(getResources().getDrawable(R.drawable.emadera));
            break;

        case "2":
            seconds = 15000;
            dificultadScor = 0.5;
            avatar.setImageDrawable(getResources().getDrawable(R.drawable.ehierro));
            break;

        case "3":
            seconds = 7000;
            dificultadScor = 0.75;
            avatar.setImageDrawable(getResources().getDrawable(R.drawable.eoro));
            break;

        case "4":
            seconds = 3000;
            dificultadScor = 1;
            avatar.setImageDrawable(getResources().getDrawable(R.drawable.ediamante));
            break;

Simplemente quiero que al pulsar sobre la imagen parezca que se realiza alguna animación de pulsación, como si la imagen se pusiera más oscura o se contraiga, etcetera etcetera.


Q: Rails - Running tests with unexpected results - should be failing but instead its passing I am doing Hartl's tutorial.
https://www.railstutorial.org/book/static_pages
On section 3.3.3
I am running test but running into unexpected results.
In my static_pages_controller_test.rb I have the following:
test "should get about" do
    get :about
    assert_response :success
 end

According to Listing 3.17, I should be getting:
AbstractController::ActionNotFound:
The action 'about' could not be found for StaticPagesController

However, the test still passes even though there is no about action defined in my static_pages_controller.rb
gemfile:
group :test do
  gem 'minitest-reporters', '1.0.5'
  gem 'mini_backtrace',     '0.1.3'
  gem 'guard-minitest',     '2.3.1'
end

Guardfile (though I'm not actively running it to execute test)
# Defines the matching rules for Guard.
guard :minitest, spring: true, all_on_start: false do
  watch(%r{^test/(.*)/?(.*)_test\.rb$})
  watch('test/test_helper.rb') { 'test' }
  watch('config/routes.rb')    { integration_tests }
  watch(%r{^app/models/(.*?)\.rb$}) do |matches|
    "test/models/#{matches[1]}_test.rb"
  end
  watch(%r{^app/controllers/(.*?)_controller\.rb$}) do |matches|
    resource_tests(matches[1])
  end
  watch(%r{^app/views/([^/]*?)/.*\.html\.erb$}) do |matches|
    ["test/controllers/#{matches[1]}_controller_test.rb"] +
    integration_tests(matches[1])
  end
  watch(%r{^app/helpers/(.*?)_helper\.rb$}) do |matches|
    integration_tests(matches[1])
  end
  watch('app/views/layouts/application.html.erb') do
    'test/integration/site_layout_test.rb'
  end
  watch('app/helpers/sessions_helper.rb') do
    integration_tests << 'test/helpers/sessions_helper_test.rb'
  end
  watch('app/controllers/sessions_controller.rb') do
    ['test/controllers/sessions_controller_test.rb',
     'test/integration/users_login_test.rb']
  end
  watch('app/controllers/account_activations_controller.rb') do
    'test/integration/users_signup_test.rb'
  end
  watch(%r{app/views/users/*}) do
    resource_tests('users') +
    ['test/integration/microposts_interface_test.rb']
  end
end

# Returns the integration tests corresponding to the given resource.
def integration_tests(resource = :all)
  if resource == :all
    Dir["test/integration/*"]
  else
    Dir["test/integration/#{resource}_*.rb"]
  end
end

# Returns the controller tests corresponding to the given resource.
def controller_test(resource)
  "test/controllers/#{resource}_controller_test.rb"
end

# Returns all tests for the given resource.
def resource_tests(resource)
  integration_tests(resource) << controller_test(resource)
end

A: Do you have a view named about in static_pages_controller's corresponding view folder?
If so, rails assumes controller action just being empty and proceeds with render.
To have test fail - rename or delete the view


Q: partial differential equation of order 6 is it possible to solve a partial differential equation of order 6 with Mathematica? I tried "DSolve[eq,u,{s,t}]" but the output is just the same as the input. I also tried to add the boundary- and initial-conditions but it doesn't help.
May you help me?
To specify my issue, i have to solve the following equation:
eq = -1.3248*^9 - 0.224*(-1.224*Derivative[0, 4][u][s, t] - 1.3248000000000002*^7*Derivative[2, 2][u][s, t]) + 0.224*Derivative[2, 4][u][s, t] + 8.28*^10*(-0.00016*(-1.224*Derivative[0, 2][u][s, t] - 1.3248000000000002*^7*Derivative[2, 0][u][s, t]) - 0.00016*(-1.224*Derivative[2, 2][u][s, t] - 1.3248000000000002*^7*Derivative[4, 0][u][s, t])) - 8.28*^10*(0.00016*Derivative[2, 2][u][s, t] + 0.00016*Derivative[4, 2][u][s, t]) - 8.28*^10*(-0.224*Derivative[2, 2][u][s, t] - 0.00016*(-0.224*Derivative[2, 2][u][s, t] + 8.28*^10*(0.00016*Derivative[2, 0][u][s, t] + 0.00016*Derivative[4, 0][u][s, t])) + 8.28*^10*(0.00016*Derivative[2, 0][u][s, t] + 0.00016*Derivative[4, 0][u][s, t]) - 0.224*Derivative[4, 2][u][s, t] + 8.28*^10*(0.00016*Derivative[4, 0][u][s, t] + 0.00016*Derivative[6, 0][u][s, t])) == 0

and
DSolve[{eq}, u, {s, t}]

just gives me the input back. Even adding boundary conditions doesn't lead to a solution.
What do I do wrong?
I hope you can help me! :)


Q: How to make two UIGestures respond simultaneously on two different views? I have View (A) has two subviews: view B and view C. View (B) that has a UILongPressGestureRecognizer and View (C) has a UIPanGestureRecognizer and is hidden by default. When I long press on a View B, view C is shown (isHidden = false).
Now, when I long press on view B, view C is shown but gesture defined in it is not responding, gesture defined in view B is still active.
I want to be able to respond to UIPanGestureRecognizer of View C when it is shown, and when I release touch I want to ended both gestures a UILongPressGestureRecognizer of View B, and UIPanGestureRecognizer of View C.
Is it possible?

A: I think there is no necessary to add UIPanGestureRecognizer to View(C), you can recognize finger position in UILongPressGestureRecognizer handle method. look at sample code
declare variables:
@IBOutlet var cView: UIView?

Here is UILongPressGestureRecognizer handle method:
 @IBAction func handleLongPressGesture(_ gesture: UILongPressGestureRecognizer) {
    switch gesture.state {
    case .began:
        cView?.isHidden = false
    case .changed:
        if let cView = cView, cView.isHidden == false {
            let location = gesture.location(in: self.cView)
            print("Finger Location - (\(location.x),\(location.y))")
        }
    case .ended, .cancelled:
        cView?.isHidden = true
    default: break
    }
}

The code performs your requirements.


Q: Outlook Manifest functional in web Outlook, won't properly install in desktop Outlook I'm working on an Outlook Add-In. I've been working so far in the web version, but my understanding is that a manifest that functions in Web should automatically also function in Desktop.
However, I'm encountering an issue where I install my add-in on the desktop, it succeeds, but then instantly disappears. If I go to the "Get Add-ins" page again and go to My Addins, my addin which I just installed does not show up.
This add-in is fully functional in web outlook, so I'm not at all sure what the issue may be. I've tried validating it using
npx office-addin-manifest validate MANIFEST_FILE

But it passes this. I've also tried enabling runtime logging, but I just get an empty log file if I install it while logging. I'm not sure where to go from here. I've confirmed that the same issue occurs on another machine.
My suspicion is that it may have something to do with the utilization of VersionOverrides 1.1 (we're using this to support pinning a task pane open), but I have no idea why this would cause an issue in Desktop. Minus the resources section, our buttons/tabs are defined with the VersionOverrides 1.1 section.
Appreciate any suggestions for further debugging!
<?xml version="1.0" encoding="UTF-8"?>
<OfficeApp
  xmlns="http://schemas.microsoft.com/office/appforoffice/1.1"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns:bt="http://schemas.microsoft.com/office/officeappbasictypes/1.0"
  xmlns:mailappor="http://schemas.microsoft.com/office/mailappversionoverrides/1.0"
  xsi:type="MailApp">

  <!-- IMPORTANT! Id must be unique for your add-in, if you reuse this manifest ensure that you change this id to a new GUID. -->
  <Id>d0aa58bd-1618-45ed-a773-9e8353a85215</Id>

  <Version>1.0.0.0</Version>
  <ProviderName>Test Name</ProviderName>
  <DefaultLocale>en-US</DefaultLocale>
  <DisplayName DefaultValue="Onvio Add-In" />
  <Description DefaultValue="Onvio Outlook Add-In For Interaction With Document Management Service"/>
  <IconUrl DefaultValue="https://img.icons8.com/clouds/2x/cloud-network.png" />
  <HighResolutionIconUrl DefaultValue="https://d1nhio0ox7pgb.cloudfront.net/_img/g_collection_png/standard/256x256/earth.png" />

 <SupportUrl DefaultValue="https://localhost:4200"/>
  <!--End Basic Settings. -->

  <Hosts>
    <Host Name="Mailbox" />
  </Hosts>
  <Requirements>
    <Sets>
      <Set Name="Mailbox" MinVersion="1.1" />
    </Sets>
  </Requirements>
  <FormSettings>
    <Form xsi:type="ItemEdit">
      <DesktopSettings>
        <SourceLocation DefaultValue="https://localhost:4200"/>
      </DesktopSettings>
    </Form>
  </FormSettings>

  <Permissions>ReadWriteItem</Permissions>
  <Rule xsi:type="RuleCollection" Mode="Or">
    <Rule xsi:type="ItemIs" ItemType="Message" FormType="Read" />
  </Rule>
  <DisableEntityHighlighting>false</DisableEntityHighlighting>
  <VersionOverrides xmlns="http://schemas.microsoft.com/office/mailappversionoverrides" xsi:type="VersionOverridesV1_0">
    <Resources>
      <bt:Images>
        <bt:Image id="Onvio.PaneButton.Icon" DefaultValue="https://i.imgur.com/FkSShX9.png" />
      </bt:Images>
      <bt:Urls>
        <bt:Url id="Onvio.FunctionFile.Url" DefaultValue="https://localhost:4200" />
        <bt:Url id="Onvio.Taskpane.Url" DefaultValue="https://localhost:4200" />
      </bt:Urls>
      <bt:ShortStrings>
        <bt:String id="Onvio.Pane.Title" DefaultValue="Onvio Side Panel" />
        <bt:String id="Onvio.Pane.Label" DefaultValue="Show Taskpane" />
        <bt:String id="Onvio.Tab.Label" DefaultValue="Onvio Tab Label" />
        <bt:String id="Onvio.OpenedMessageTools.Label" DefaultValue="Onvio.OpenedMessageTools.Label" />
        <bt:String id="Onvio.ComposeMessageTools.Label" DefaultValue="Onvio.ComposeMessageTools.Label" />
      </bt:ShortStrings>
      <bt:LongStrings>
        <bt:String id="Onvio.Pane.Description" DefaultValue="Onvio Side Panel Description" />
      </bt:LongStrings>
    </Resources>
    <VersionOverrides xmlns="http://schemas.microsoft.com/office/mailappversionoverrides/1.1" xsi:type="VersionOverridesV1_1">
      <Description resid="residDescription" />
      <Requirements>
        <Sets xmlns="http://schemas.microsoft.com/office/officeappbasictypes/1.0">
          <Set Name="Mailbox" MinVersion="1.1" />
        </Sets>
      </Requirements>
      <Hosts>
        <Host xsi:type="MailHost">
          <DesktopFormFactor>
            <ExtensionPoint xsi:type="MessageComposeCommandSurface">
              <OfficeTab id="TabDefault">
                <Group id="Message" xmlns="http://schemas.microsoft.com/office/mailappversionoverrides/1.1">
                  <Label resid="Onvio.ComposeMessageTools.Label" />

                  <Control xsi:type="Button" id="Onvio.ComposePane.Button">
                    <Label resid="Onvio.Pane.Label" />
                    <Supertip>
                      <Title resid="Onvio.Pane.Title" />
                      <Description resid="Onvio.Pane.Description" />
                    </Supertip>
                    <Icon>
                      <bt:Image size="16" resid="Onvio.PaneButton.Icon" />
                      <bt:Image size="32" resid="Onvio.PaneButton.Icon" />
                      <bt:Image size="80" resid="Onvio.PaneButton.Icon" />
                    </Icon>
                    <Action xsi:type="ShowTaskpane">
                      <SourceLocation resid="Onvio.Taskpane.Url" />
                      <SupportsPinning>true</SupportsPinning>
                    </Action>
                  </Control>
                </Group>
              </OfficeTab>
            </ExtensionPoint>
            <ExtensionPoint xsi:type="MessageReadCommandSurface">
              <CustomTab id="Onvio.OpenedMessageTools.Tabs">
                <Group id="Onvio.OpenedMessageTools.Group" xmlns="http://schemas.microsoft.com/office/mailappversionoverrides/1.1">
                  <Label resid="Onvio.OpenedMessageTools.Label" />
                  <Control xsi:type="Button" id="Onvio.Pane.Button">
                    <Label resid="Onvio.Pane.Label" />
                    <Supertip>
                      <Title resid="Onvio.Pane.Title" />
                      <Description resid="Onvio.Pane.Description" />
                    </Supertip>
                    <Icon>
                      <bt:Image size="16" resid="Onvio.PaneButton.Icon" />
                      <bt:Image size="32" resid="Onvio.PaneButton.Icon" />
                      <bt:Image size="80" resid="Onvio.PaneButton.Icon" />
                    </Icon>
                    <Action xsi:type="ShowTaskpane">
                      <SourceLocation resid="Onvio.Taskpane.Url" />
                      <SupportsPinning>true</SupportsPinning>
                    </Action>
                  </Control>
                </Group>
                <Label resid="Onvio.Tab.Label" />
              </CustomTab>
            </ExtensionPoint>
          </DesktopFormFactor>
        </Host>
      </Hosts>
    </VersionOverrides>
  </VersionOverrides>
</OfficeApp>