text:
Q: C++ colon syntax with function body I've encountered an example (for a trivial function-try-block), from which seems to utilize one of the more obscure of aspects of C++ syntax to which (like most obscure aspects of the language) I can not seem to find documentation for.
I've searched the Google to no avail, with all searches returning (rather uselessly) only for constructor initialization (which I'm familiar with), but what I would like to know is the importance of the body: and handler: statements in this constructor block:
class foo{
    foo() try
    //initalizer list that could throw
    {
    body:
       //do stuff that could possibly throw
    } catch(std::exception &e) {
    handler:
       throw;
    }
};

The original author abruptly adds this syntax in a single example and I would like to know the implications of such linguistic constructs

A: The XXX: is a label.  It doesn't serve any functional purpose in the code you posted.  It may have been put in by the author to help them organize the code.
You can use labels with goto statements, as in goto XXX; to jump to that point in your code, although I'll leave it up to you to decide if that is a good think or now.

A: foo::foo()
try
{
body:
   //... do stuff that could possibly throw
}
catch(std::exception &e){
handler:
   throw;
}

That piece of code has two rather unusual constructs. The first is what you already pointed out and has already been explained in mjk's answer: body and handler are labels. Labels are used for gotos, and that in turn can be used for flow control (determining where the code should continue executing). Now, gotos should rarely be used, as there are very few cases where they cannot be substituted by other flow controls (if,for,while,do...) that would make it more readable. Since gotos are rarely used, labels are also rarely used.
The second interesting construct is the function-level try block:
foo::foo()
try {
} catch (std::exception const &) {
}

Note that there try catch is not inside the constructor body, but actually outside the {}. This is also a rare construct. It was designed to support catching an exception during the evaluation of the initializer list in the constructor (which in the code above is implicit). If the type has a base, or members whose constructors could throw, the constructor's body would never be evaluated and a regular try-catch would not be useful to treat that exception. The function level try block encloses also the initializer list and will catch any exception thrown during the evaluation of the different submember's constructors. It is a rarely used construct since you cannot really do much in the catch block. The exact state of what has been or has not been constructed is unknown and cannot be verified so the only possible use is to rethrow either the same exception or a different one. The syntax in a more complete example would be:
T::T()
try
   : base1(args), base2(), member1(), member2() //...
{
   // body
} catch (exception1 const& ex1) {
   // ...
   throw; // rethrow same exception
} catch (exception2 const& ex2) {
   // ...
   throw different_exception();
}


text:
Q: Android- dynamic overridePendingTransition duration I am creating an android launcher and am pretty far into it. I ran into a problem though. I need to allow the users to enter the transition duration from activity to activity from setting. The problem is that since the structure of overridePendingTransition is
overridePendingTransition(int,int);
instead of
overridePendingTransition(Animation,Animation);
which means that well I dont know how to set the animation speed dynamicly. I know how to set duration in the anim xml but that is not changable. here is a clip of what I have

Intent LaunchIntent = getPackageManager().getLaunchIntentForPackage(packages[position]);
startActivity(LaunchIntent);
overridePendingTransition(R.anim.in,android.R.anim.out);
I need to set animation speed dynamicly

A: You need to declare your own Animation like a regular class (means not in xml) and use it.

redpajama_set_name: RedPajamaStackExchange


text:
Q: HTTP Post request to external API works in Postman, but not React component (net::ERR_ABORTED 400) I am making an HTTP Post request to the ClickUp external API from a react component. This API does require Auth, which I've tested in Postman, successfully. That's whats throwing me. Postman successfully Posts the JSON object I formatted from ClickUps API docs, yet when I copy the code snipped from Postman, and plant it into my application, I receive a general, net::ERR_ABORTED 400 error.
Based on research so far, I've found it is frequently a client side syntax error. I've cleared my DNS, cache, triple checked the URL (its the exact same URL that works in Postman). I'm using JavaScripts native fetch API to execute the request, however I did test with axios, and got the same result. I post the data in an onClick here:
return (
        <>

Contact

                <Input
                    id='name'
                    onChange={handleInputChange}
                    name="name"
                    placeholder="name"
                />
                <Input
                    id='email'
                    onChange={handleInputChange}
                    name="email"
                    placeholder="email"
                />
                <Input
                    id='phone'
                    onChange={handleInputChange}
                    name="phone"
                    placeholder="phone"
                />
                <TextArea
                    id='message'
                    onChange={handleInputChange}
                    name="message"
                    placeholder="Leave a message!"
                />
                <FormBtn
                    id='Button'
                    disabled={!(formObject.name && formObject.message && (formObject.phone || formObject.email))}
                    onClick={(event) => {
                        handleFormSubmit(event);
                        postClickUp();
                    }}
                >{buttonText}</FormBtn>

This calls the postClickUp function, taken line for line, from Postman, where the post executes successfully:
function postClickUp() {
    var myHeaders = new Headers();
    myHeaders.append("Authorization", "removed_for_privacy_reasons");
    myHeaders.append("Content-Type", "application/json");

    var raw = JSON.stringify({
        "name": formObject.name,
        "description": "New Task Description",
        "assignees": [
            14917287
        ],
        "tags": [
            "contact"
        ],
        "status": "To do",
        "priority": null,
        "due_date": 1508369194377,
        "due_date_time": false,
        "time_estimate": 8640000,
        "start_date": 1567780450202,
        "start_date_time": false,
        "notify_all": true,
        "parent": null,
        "links_to": null,
        "check_required_custom_fields": true,
        "custom_fields": [
            {
                "id": "041c6ec7-59d6-45c7-9cad-67f54d677be4",
                "value": formObject.email
            },
            {
                "id": "546bbe4b-2fa6-49e9-bb7c-3c111aec15eb",
                "value": formObject.message
            },
            {
                "id": "865c7fe2-d4c9-4464-9d71-cc4d190eab98",
                "value": `+1 ${formObject.phone}`
            }
        ]
    });

    var requestOptions = {
        method: 'POST',
        headers: myHeaders,
        mode: 'no-cors',
        body: raw,
        redirect: 'follow'
    };

    fetch("https://api.clickup.com/api/v2/list/116273262/task", requestOptions)
        .then(response => response.text())
        .then(result => console.log(result))
        .catch(error => console.log('error', error));
};

The onClick also calls a handleFormSubmit() function, that is working properly, posting the data to a MongoDB using an API I built for this app.
function handleFormSubmit(event) {
    event.preventDefault();
    if (formObject.name && formObject.phone || formObject.email) {
        contactAPIFunctions
            .saveContact({
                name: formObject.name,
                phone: formObject.phone,
                email: formObject.email,
                message: formObject.message
            })
            .then(() => {
                clearState();
            })
            .catch((err) => console.log(err));
    };
};

However, I'd like it if I can post the data to my database with the handleFormSubmit() --that is working-- as well as send the data to an external API to create tasks in my project management software.
The primary key has been removed for privacy reasons, however, I've confirmed that its correct. Its the same key i'm using in postman where my request posts the data fine.

A: I ran into the same issue and found out it's because api.clickup.com currently doesn't support CORS requests as they omit the Access-Control-Allow-Origin header (if not more limitations). I've searched their documentation and user settings but can't find any references that would help.
As an alternative I'll have to spin up a backend-of-choice to proxy my app's requests.


text:
Q: Execute closure from another method in an extension Swift I have a class that is a delegate to a custom modal view, therefore it has a method for when the modal has been dismissed. I am extending that class and in the extension I have a method that accepts a completion closure.
I can't write in the main implementation of the class or the modal's implementation - only the extension.
I want to execute the closure when the modal is dismissed, but I can't seem to figure it out on my own. Is it even possible?
Here is an example of what I want to do:
extension MyClass {
    func method(completion: (Int) -> ()) {
        // showing the modal
    }
}

extension MyClass: ModalDelegate {
    func modalDismissed() {
        // here I want to execute the completion passed to method()
    }
}

A: Assign the completion as a variable to a MyClass's property in method and call it in modalDismissed:
class MyClass {
    var classCompletion: (() -> ())?
}

extension MyClass {
    func method(completion: @escaping () -> ()) {
        classCompletion = completion
    }
}

extension MyClass: ModalDelegate {
    func modalDismissed() {
        classCompletion?()
    }
}

Update: If you can't "write in the main implementation of the class", here's a method using static property. This is a hack and has many limitations but does the work. Otherwise without writing to the main implementation you can't do anything.
extension MyClass {
    static var classCompletion: (() -> ())?

    func method(completion: @escaping () -> ()) {
        MyClass.classCompletion = completion
    }
}

extension MyClass: ModalDelegate {
    func modalDismissed() {
        MyClass.classCompletion?()
    }
}


text:
Q: How to set each perl script's perl path for a conda build I've been banging my head against this for awhile now and I need some help.  I have a nice little perl package I developed.  Works great.  It has a simple install procedure:
perl makefile.PL
make
make install

I've been trying to write my first ever conda recipe so that I can eventually use it to create a package on galaxy that automatically installs via bioconda.
The problem is that the procedure above isn't enough for a conda build.sh script and I don't know how to make the shebang line of the installed perl script have the correct perl path.  I first tried this:
perl Makefile.PL INSTALL_BASE=${PREFIX} INSTALLDIRS=site
make
make install

based on stuff I've seen in other recipes, but this results in an error:
/Users/rleach/local/miniconda3/conda-bld/vcfsamplecompare_1538773699290/test_tmp/run_test.sh: /Users/rleach/local/miniconda3/conda-bld/vcfsamplecompare_1538773699290/_test_env_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_placehold_pla/bin/vcfSampleCompare.pl: /Users/rleach/local/miniconda3/conda-bld/vcfsamplecompare_1538773699290/_build: bad interpreter: No such file or directory
Tests failed for vcfsamplecompare-v2.005-pl526_0.tar.bz2 - moving package to /Users/rleach/local/miniconda3/conda-bld/broken

I noticed in the build output a note like this:
Renaming build prefix directory,  /Users/rleach/local/miniconda3/conda-bld/vcfsamplecompare_1538773699290/_build_env  to  /Users/rleach/local/miniconda3/conda-bld/vcfsamplecompare_1538773699290/build_prefix_moved_vcfsamplecompare-v2.005-pl526_0_osx-64

So on a hunch, I added this after my make install:
sed -i.bak 's|_build_env|build_prefix_moved_vcfsamplecompare-v2.005-pl526_0_osx-64|g' ${PREFIX}/bin/vcfSampleCompare.pl

And that worked!  (Anyway, it got me past the first error - now it complains about the module it was also supposed to install not being in @INC.  - one thing at a time though...)
The problem is, I don't know where to find the string "build_prefix_moved_vcfsamplecompare-v2.005-pl526_0_osx-64".  It's obviously going to be different on different systems.  If I assume that "build_prefix_moved_" is static, I know which environment variables will give me "vcfsamplecompare", "v2.005", and "64" (maybe even "osx") - but I cannot find anything that has the value "pl526_0", so I don't seem to have the ability to fully build the string on my own...
So what's the conventional wisdom here?  How should I be setting the perl interpreter path at the top of the scripts in the package?

A: As I had suspected, you shouldn't have to provide INSTALL_BASE=${PREFIX} or even PREFIX=${PREFIX} to Makefile.PL in order for it to work.  The fact that the script being found on the PATH has the wrong perl interpreter path suggests that there may be some compiled version of perl that is available when running the script which is different from the one that was used when building the script.  This is consistent with the issue with the different paths in @INC.
It turned out that the meta.yaml file had perl in 2 places: under requirements:build: and requirements:host: and thus 2 different versions of perl were in use during the build versus running on the host.  By removing the one under requirements:build: in the meta.yaml file, there's only 1 version of perl and the conflict is resolved.  All that's needed in the build.sh file is:
perl Makefile.PL INSTALLDIRS=site
make
make install

Just be sure that the meta.yaml has:
requirements:
  build:
    - make
  host:
    - perl
  run:
    - perl

It may be tempting to put perl under the build section because you're using a call to perl in the build.sh script, but it's there on the host when the build is done.


text:
Q: org.openqa.selenium.WebDriverException: unknown error: cannot find MSEdge binary error using EdgeDriver and Selenium on Mac through Java I have trouble running MS Edge test on MAC using Selenium Remote web driver.
I tried to set System property for edge binary as below:
dc = DesiredCapabilities.edge();
System.setProperty("webdriver.edge.driver", "/Users/username/Softwares/Work/jars/msedgedriver");
dc.setCapability("edge_binary","/Applications/Microsoft Edge Beta.app");

I checked that msedge driver version and version of MS Edge browser that I have installed.
Both are - 80.0.361.48
This is the log on Selenium node:

020-02-11 18:06:37.533:INFO:osjshC.ROOT:qtp1800659519-12: org.openqa.selenium.remote.server.WebDriverServlet-59309333: Initialising WebDriverServlet
  18:06:37.551 INFO - Found handler: org.openqa.selenium.remote.server.commandhandler.BeginSession@47c6497e
  18:06:37.555 INFO - /session: Executing POST on /session (handler: BeginSession)
  18:06:37.632 INFO - Capabilities are: Capabilities {MicrosoftEdge_binary: /Applications/Microsoft Edg..., browserName: MicrosoftEdge, platform: MAC, version: }
  18:06:37.633 INFO - Capabilities {MicrosoftEdge_binary: /Applications/Microsoft Edg..., browserName: MicrosoftEdge, platform: MAC, version: } matched class org.openqa.selenium.remote.server.ServicedSession$Factory (provider: org.openqa.selenium.edge.EdgeDriverService)
  Starting MSEdgeDriver 80.0.361.48 (e1a3ff36578e440880567e6adcbeab38ec2956fa) on port 31883
  Only local connections are allowed.
  Please protect ports used by MSEdgeDriver and related test frameworks to prevent access by malicious code.

Exception that I get when running code is as

org.openqa.selenium.WebDriverException: unknown error: cannot find MSEdge binary
  Build info: version: '3.7.1', revision: '8a0099a', time: '2017-11-06T21:07:36.161Z'
  System info: host: '****-MacBook-Pro.local', ip: 'fe80:0:0:0:14d9:68c6:7d2c:87a%en0', os.name: 'Mac OS X', os.arch: 'x86_64', os.version: '10.15.2', java.version: '1.8.0_152'
  Driver info: driver.version: unknown

A: This error message...
org.openqa.selenium.WebDriverException: unknown error: cannot find MSEdge binary
Build info: version: '3.7.1', revision: '8a0099a', time: '2017-11-06T21:07:36.161Z'
System info: host: '****-MacBook-Pro.local', ip: 'fe80:0:0:0:14d9:68c6:7d2c:87a%en0', os.name: 'Mac OS X', os.arch: 'x86_64', os.version: '10.15.2', java.version: '1.8.0_152'
Driver info: driver.version: unknown

...implies that the program was unable to locate MSEdge binary within your system.
Your main issue is the incompatibility between the version of the binaries you are using as follows:

*

*Though you are using compatable versions of MS Edge Driver v80.0 and MS Edge Browser v80.0

*Your Selenium Client version is 3.7.1 of 2017-11-06T21:07:36.161Z which is almost 2.5 years older.

*But your JDK version is 1.8.0_152 which is pretty ancient.

So there is a clear mismatch between JDK v8u152 , Selenium Client v'3.7.1 , MS Edge Driver v80.0 and the MS Edge Browser v80.0

Solution
Ensure that:

*

*JDK is upgraded to  current levels JDK 8u241.

*Selenium is upgraded to  current levels Version 3.141.59.

*Take a System Reboot.

*Execute your @Test as non-root user.


text:
Q: Show that different right cosets of different subgroups are different. For $H, H'$ subgroups of $G$, and $H \neq H'$, show that $Hg \neq H'g'$ for each $g, g' \in G$.
I think I want to show the contrapositive, that if for some $g, g'$ we have $Hg = H'g'$ then $H = H'$. But I'm not sure how to go about this.

A: $$
gH = g'H' \implies g'^{-1}gH = H'
$$
Since $e \in H'$ there must exist some $h \in H$ such that $g'^{-1}gh = e$.
$$
g'^{-1}gh = e \implies g'^{-1}g = h^{-1}
$$
The right hand side is in $H$ so the left hand is also in $H$, so $g'^{-1}gH = H = H'$


text:
Q: Office 365 New Library Experience and Metadata Navigation Is anyone aware of a way to use the 'New experience' type layout for a document library in Sharepoint Online in addition to the Key Filters box exposed by Metadata Based Nav?
I have enabled Metadata Nav and assigned fields as key filters, but they only show when using the Classic experience (under Advanced settings for the library) - if using the New experience, the left hand pane just has the quick launch links, and no key filters. Can't see them anywhere else either.
Does this seem to be a by-design thing, or am I missing something?

A: Managed metadata navigation is only available in the classic mode experience. If that is necessary, revert your library in the Advanced Settings to classic mode.
Features available only in classic mode
The Ribbon

*

*The Ribbon itself

*Certain features available through the Ribbon:

*

*Popularity trends

*Tags & Notes

*Quick Edit

*RSS Feed

*Most Popular Items

*Connect to Outlook

*Connect to Office

*Export to Excel

*Form Web Parts

*Edit Library

*New Quick Step

View features

*

*Item totals

*Custom styles (such as Basic Table or Document Details)
Navigation features

*

*Tree view

*Metadata navigation and filtering

*Managed navigation

*Per-location views

*Customized navigation links on publishing sites

Library features

*

*External data columns

*Geolocation columns

*Content organizer

*Follow feature

Customizations

*

*Minimal Download Strategy (MDS)

*SharePoint Server Publishing

*JSLink code on fields or views

*CustomActions that include ScriptBlock or ScriptSrc properties
CustomActions that do not include ScriptBlock or ScriptSrc properties will continue to work as expected

https://support.office.com/en-us/article/Differences-between-the-new-document-library-experience-and-classic-mode-30e1aab0-a5cc-4363-b7f2-09e2ae07d4dc?ui=en-US&rs=en-US&ad=US


text:
Q: SSH password entered too many times Connection refused I tried connecting to my new installed Ubuntu 12 server via SSH and I was asked for my password. (I had used "myusername@ipadress" to connect)
After entering the right password a few times (with no luck; access denied) I started getting an error directly telling me that the connection was refused without asking me for a password anymore.
It seems like I have managed to blacklist myself. It has been like this for about 2 hours now, is there a quick solution for this?

A: If you haven't installed ssh-server yet, you need to install it by running:
sudo apt-get install openssh-Server,
You may also need to check if the default SSH Port 22 is open on your Router/Firewall. You may also need to change the default port under /etc/ssh/sshd_config.

A: I was using a virtual server from ionos together with plesk panel. The same as the operator is stating happend to me: I entered a wrong password three times and the result was 'connection refused' errors on subsequential requests.
Solving the problem was rather easy: On plesk/home you got 'ip address banning'. Visiting those tab it was easy to unban my ip-address.
Afterwards I could login with correct password.


text:
Q: Java ArrayList with condition I have a question about if condition in ArrayList, Please see code:
public class Test {

    public static void main(String[] args) {

        ArrayList<BankAccount>accounts=new ArrayList<BankAccount>();
        BankAccount Mary=new BankAccount(1,50);
        BankAccount Lucy=new BankAccount(2,100);
        BankAccount Lily=new BankAccount(3,20);
        BankAccount Pete=new BankAccount(4,200);
        BankAccount Paul=new BankAccount(5,30);

        accounts.add(Mary);
        accounts.add(Lucy);
        accounts.add(Lily);
        accounts.add(Pete);
        accounts.add(Paul);

        double min = accounts.get(0).getBalance();
        int poorestPerson = accounts.get(0).getAccountNumber();
        for(BankAccount a:accounts) {
            if(a.getBalance()<min) {
                poorestPerson=a.getAccountNumber();
            }
        }
        System.out.println("Poorest person is "+poorestPerson);
    }
}

The result is always 5, but the correct print should be 3, when I add :
  poorestPerson=a.getAccountNumber();
  **min=a.getBalance();**

It prints right answer, my question is how does this command vary the result?Cheers.
I have understood how does this command work, but could someone please explain if I do not write min=a.getBalance(); , how does the condition work and why does it print the last element?

A: this should fix your problem
 if(a.getBalance()<min){
            poorestPerson=a.getAccountNumber();
            min=a.getBalance();
        }

A: Your problem is that you don't set min when changing poorestPerson in the if in the loop

A: double min=accounts.get(0).getBalance();

This line gets the first element as reference to the smallest value in the list. Either the algorithm finds a smaller value than this one, or just returns the first one.
You could even set double min = Integer.MAX_VALUE;
If you don't update that value each time your find a smaller one, then there's not point in searching for it, since you already have it (first element in list).
min=a.getBalance();

Thus, this line is required.

A: Actually it does check and get 3 but after that when it reaches the 5th, it also checks if 30 < 50 which is true. You need to update min so that it can verify against all the min's that come to be true in comparisons.
if(a.getBalance()<min){
    poorestPerson=a.getAccountNumber();
    min = a.getBalance(); // the new min
}


text:
Q: Avoiding jiggle in palettes I have a palette containing a Grid with dynamics. As it runs it jiggles horizontally. Here's a minimal example:
CreatePalette[
 Dynamic[Grid[{{"Some text of unknown length",
     DateString["SecondShort"]}}, BaseStyle -> 15],
  UpdateInterval -> 1], Saveable -> False]

I don't want to just set WindowSize because I don't know the size before it's run, and unfortunately Grid doesn't have like an ImageMargins or ImagePadding or anything like that. I'm sure there must be some simple way of doing this.

A: Let's assume that the content's size is unknown up front but stays more or less the same later. You can adjust the size after it appears by using current value of WindowSize or to do this up front by using Rasterize[whatever, "RasterSize"].
Let's try with the former one as Rasterize needs to be adjusted to use palettes' styles anyway.
CreatePalette[
 DynamicModule[{},
  Pane[
   Dynamic[
    Grid[{{"Some text of unknown length", DateString["SecondShort"]}},
      BaseStyle -> 15], UpdateInterval -> 1],
   Full,
   FrameMargins -> 5,
   Alignment -> {Left, Center}
   ],
  SynchronousInitialization -> False,
  Initialization :> (
    CurrentValue[EvaluationNotebook[], WindowSize] =
     1.05 AbsoluteCurrentValue[EvaluationNotebook[], WindowSize]
    )
  ]
 , Saveable -> False

 ]

Does it fit your needs?


text:
Q: Flutter firebase_admob show only once The following code show the banner ad at the bottom of the application and show interstitial ad when click. Interstitial ad is shown when the button is pressed. The problem is, when the app start and click button for the first time, the interstitial is shown but the interstitial is not shown starting from second time.
There are no errors and all log message show success. Is my code error? I'm testing on android device.
import 'package:firebase_admob/firebase_admob.dart';
import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {

  final admobAppId = 'ca-app-pub-3940256099942544~3347511713';
  final bannerId = 'ca-app-pub-3940256099942544/6300978111';
  final interstitialId = 'ca-app-pub-3940256099942544/1033173712';

  BannerAd bannerAd;
  InterstitialAd interstitialAd;

  MyApp() {
    FirebaseAdMob.instance.initialize(appId: admobAppId);
    makeBannerAd();
    initInterstitialAd();
  }

  makeBannerAd() {
    bannerAd = BannerAd(
        adUnitId: bannerId,
        size: AdSize.smartBanner,
        listener: (MobileAdEvent me) {
          print('MobileAdEvent $me');
        });
    bannerAd
      ..load()
      ..show();
  }

  initInterstitialAd() {
    interstitialAd = InterstitialAd(
        adUnitId: interstitialId,
        listener: (MobileAdEvent me) {
          print(
              '========== Interstitial ad mobile ad event =========== \n $me');
          if (me == MobileAdEvent.closed) {
            print('Interstitial closed');
            loadInterstitialAd();
          }
        });
    loadInterstitialAd();
  }

  loadInterstitialAd() {
    interstitialAd.load().then((val) {
      if (val) {
        print('Interstitial ad loaded callback success');
      } else {
        print('Interstitial ad loaded callback failed');
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('AdMob plugin test'),
        ),
        body: Center(
          child: RaisedButton(
            child: Text('Show Interstitial!'),
            onPressed: () {
              interstitialAd.show().then((val) {
                if (val) {
                  print('Interstitial ad show callback success');
                } else {
                  print('Interstitial ad show callback fail');
                }
              });
            },
          ),
        ),
      ),
    );
  }
}

Update
Following is the code with dispose(). It show up to 2 times.
class MyApp extends StatelessWidget {

  final admobAppId = 'ca-app-pub-3940256099942544~3347511713';
  final bannerId = 'ca-app-pub-3940256099942544/6300978111';
  final interstitialId = 'ca-app-pub-3940256099942544/1033173712';

  BannerAd bannerAd;
  InterstitialAd interstitialAd;
  MobileAdTargetingInfo mobileAdTargetingInfo;

  MyApp() {
    FirebaseAdMob.instance.initialize(appId: admobAppId);
    makeBannerAd();
    initInterstitialAd();
  }

  makeBannerAd() {
    bannerAd = BannerAd(
        adUnitId: bannerId,
        size: AdSize.smartBanner,
        listener: (MobileAdEvent me) {
          print('Banner => MobileAdEvent $me');
        });
    bannerAd
      ..load()
      ..show();
  }

  initInterstitialAd() {
    interstitialAd = InterstitialAd(
        adUnitId: interstitialId,
        listener: (MobileAdEvent me) {
          print(
              '========== Interstitial ad mobile ad event =========== $me');
          if (me == MobileAdEvent.closed) {
            print('Interstitial closed');
            interstitialAd.dispose().then((val){
              if(val){
                loadInterstitialAd();
              }else{
              }
            });
          } else if (me == MobileAdEvent.failedToLoad) {
            print('Interstitial failed to load');
            loadInterstitialAd();
          }
        });
    loadInterstitialAd();
  }

  loadInterstitialAd() {
    interstitialAd.load();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('AdMob plugin test'),
        ),
        body: Center(
          child: RaisedButton(
            child: Text('Show Interstitial!'),
            onPressed: () {
              interstitialAd.show();
            },
          ),
        ),
      ),
    );
  }
}

A: I modified and fixed the code as follow and I also posted in the github issue. Now, whenever the button is pressed the ad is shown. I tested 10+ times and it work well. It seem InterstitialAd need to create every time the ad is wanted to show. But I don't know exactly. If there is someone who knows why, please explain me.
import 'package:flutter/material.dart';
import 'package:firebase_admob/firebase_admob.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  BannerAd myBanner;

  MyApp() {
    FirebaseAdMob.instance.initialize(appId: FirebaseAdMob.testAppId);
    myBanner =
        BannerAd(adUnitId: BannerAd.testAdUnitId, size: AdSize.smartBanner);
    myBanner
      ..load()
      ..show();
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text("Interstitial Ad test"),
        ),
        body: Center(
          child: RaisedButton(
            child: Text("Interstitial ad"),
            onPressed: () {
              InterstitialAd interstitialAd = new InterstitialAd(
                  adUnitId: InterstitialAd.testAdUnitId,
                  listener: (MobileAdEvent e) {
                    print("Mobile ad event => $e");
                  });
              interstitialAd.load().then((val) {
                interstitialAd.show();
              });
            },
          ),
        ),
      ),
    );
  }
}

A: I had the same issue and resolved it with the InterstitialAd object as shown:
InterstitialAd myInterstitial() {
    return InterstitialAd(
      adUnitId: InterstitialAd.testAdUnitId,
      targetingInfo: targetingInfo,
      listener: (MobileAdEvent event) {
        if (event == MobileAdEvent.failedToLoad) {
          interstitialAd..load();
        } else if (event == MobileAdEvent.closed) {
          interstitialAd = myInterstitial()..load();
        }
      },
    );
  }
@override
void initState() {
    FirebaseAdMob.instance.initialize(appId:
        FirebaseAdMob.testAppId);
    interstitialAd = myInterstitial()..load();
    super.initState();
}
@override
void dispose() {
    interstitialAd?.dispose();
    super.dispose();
}

Call method:
interstitialAd
  ..load()
  ..show();

From my understanding, you can use the listener to recursively call the initial InterstitialAd object when the event is closed. My source is from Tensor Programming Youtube Channel He explains it much better than me.

A: I faced the same problem. The solution is simple.
Just use interstitialAd.dispose() to dispose the ad so that a new interstitial ad get loaded the next time.

A: Leave an example of the way I work.
I hope it helps.
void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Intersticial',
      navigatorKey: Get.key, // use get: ^1.6.3
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Flutter Intersticial'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);
  final String title;

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

class _MyHomePageState extends State<MyHomePage> {

  InterstitialAd _interstitialAd;

  InterstitialAd createIntersticialAd(){
    return InterstitialAd(
      adUnitId: AD_MOB_AD_INTERSTICIAL_1_ID,
      targetingInfo: AdMobUtil.targetingInfo,
      listener: (MobileAdEvent event) {
        print("InterstitialAd event is $event");
        // Dispose InterstitialAd
        if (event == MobileAdEvent.closed)
           dispose();
      },
    );
  }

  @override
  void dispose() {
    //
    // dispose intersticialAd
    //
    _interstitialAd?.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              'Go to second page',
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () {
          //
          // create intersticialAd and send by parameter
          //
          _interstitialAd ??= createIntersticialAd();
          Get.to(SecondPage(interstitialAd: _interstitialAd,));
        },
        tooltip: 'Go to Second page',
        child: Icon(Icons.arrow_forward),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }
}

class SecondPage extends StatefulWidget {
  //
  // define intersticial  final
  //
  final InterstitialAd interstitialAd;

  const SecondPage({Key key, this.interstitialAd}) : super(key: key);

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

class _SecondPageState extends State<SecondPage> {

  @override
  Widget build(BuildContext context) {
    return Container();
  }

  @override
  void dispose() {
    //
    // show intersticial ad
    //
    widget.interstitialAd..load()..show();
    super.dispose();
  }
}

The banner will open when you return from the second page.
I used this package for navigation: https://pub.dev/packages/get
If helped mark as useful ..;)

A: May be am late here but this might help for future viewers. Here is the most efficient and best method to this, so that you can watch ads one after another. For all types of ads, here I have given examples of Interstitial and Rewarded, the same logic for others. Also here you can find how to load the ad again after it failed.
Full code:
InterstitialAd _interstitialAd;
  RewardedAd _rewardedAd;

      void interstitialAdload () {
        InterstitialAd.load(
            adUnitId: '<test ad>',
            request: AdRequest(),
            adLoadCallback: InterstitialAdLoadCallback(
              onAdLoaded: (InterstitialAd ad) {
                // Keep a reference to the ad so you can show it later.
                this._interstitialAd = ad;
                ad.fullScreenContentCallback = FullScreenContentCallback(
                  onAdShowedFullScreenContent: (InterstitialAd ad) =>
                      print('$ad onAdShowedFullScreenContent.'),
                  onAdDismissedFullScreenContent: (InterstitialAd ad) {
                    print('$ad onAdDismissedFullScreenContent.');
                    ad.dispose();
                  },
                  onAdFailedToShowFullScreenContent: (InterstitialAd ad, AdError error) {
                    print('$ad onAdFailedToShowFullScreenContent: $error');
                    ad.dispose();
                  },
                  onAdImpression: (InterstitialAd ad) {
                    interstitialAdload(); // <<<-------------- LOAD AD AGAIN WHEN THE USER WATCHES IT SO THAT ITS READY TO BE WATCHED JUST AFTER THE IMPRESSION OCCURS
                    print('$ad impression occurred.');
                  }
                );
              },
              onAdFailedToLoad: (LoadAdError error) {
                interstitialAdload(); // <<<-------------- LOAD AD AGAIN IF IT FAILS
                print('InterstitialAd failed to load: $error');
              },
            ));
      }

      void rewardedAdLoad() {
        RewardedAd.load(
            adUnitId: '<test ad>',
            request: AdRequest(),
        rewardedAdLoadCallback: RewardedAdLoadCallback(
        onAdLoaded: (RewardedAd ad) {
        print('$ad loaded.');
        // Keep a reference to the ad so you can show it later.
        this._rewardedAd = ad;
        ad.fullScreenContentCallback = FullScreenContentCallback(
          onAdShowedFullScreenContent: (RewardedAd ad) =>
              print('$ad onAdShowedFullScreenContent.'),
          onAdDismissedFullScreenContent: (RewardedAd ad) {
            print('$ad onAdDismissedFullScreenContent.');
            ad.dispose();
          },
          onAdFailedToShowFullScreenContent: (RewardedAd ad, AdError error) {
            print('$ad onAdFailedToShowFullScreenContent: $error');
            ad.dispose();
          },
          onAdImpression: (RewardedAd ad)
          {
            print('$ad impression occurred.');
            rewardedAdLoad(); // <<<-------------- LOAD AD AGAIN WHEN THE USER WATCHES IT SO THAT ITS READY TO BE WATCHED JUST AFTER THE IMPRESSION OCCURS
          }
        );
        },
        onAdFailedToLoad: (LoadAdError error) {
          rewardedAdLoad(); // <<<-------------- LOAD AD AGAIN IF IT FAILS
        print('RewardedAd failed to load: $error');
        },
        )
        );
      }

      void showInterstitialAd() {
        _interstitialAd.show();
      }

      void showRewardedAd() {
        _rewardedAd.show(onUserEarnedReward: (RewardedAd ad, RewardItem rewardItem) {
          // Reward the user for watching an ad.
          reward();
        });
      }


text:
Q: How to make progress bar disappear once web view is loaded? I am developing the WebView for my project.
I have used the WebView with progress bar.
The progress bar loads properly when WebView loads. After Loading the page the progress bar is not disappearing.
How to make its visibility gone.
I will share the code. I have created webview with progress bar.
public class MainActivity extends Activity {
  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    String url = "https://rnbazar.com/";
    setContentView(R.layout.activity_main);
    final WebView myWebView = (WebView) findViewById(R.id.webview);
    WebSettings webSettings = myWebView.getSettings();
    webSettings.setJavaScriptEnabled(true);
    //myWebView.setWebViewClient(new WebViewClient());
    myWebView.getSettings().setUseWideViewPort(true);
    myWebView.getSettings().setLoadWithOverviewMode(true);
    myWebView.loadUrl(url);
    myWebView.setWebViewClient(new MyWebViewClient());

    myWebView.setWebViewClient(new WebViewClient() {
      @Override public void onReceivedError(WebView view, int errorCode,
        String description, String failingUrl) {
        myWebView.loadUrl("file:///android_asset/error.html");
      }
    });
  }

  private class MyWebViewClient extends WebViewClient {
    @Override
    public void onPageStarted(final WebView myWebView, final String url,
      final Bitmap favicon) {
      ProgressBar bar = (ProgressBar)
      myWebView.findViewById(R.id.progressBar);

      bar.setVisibility(View.VISIBLE);
      super.onPageStarted(myWebView, url, favicon);

    }

    @Override
    public boolean shouldOverrideUrlLoading(WebView myWebView, String url) {

      myWebView.loadUrl(url);
      return true;
    }

    @Override
    public void onPageFinished(WebView myWebView, String url) {
      ProgressBar bar = (ProgressBar)
      myWebView.findViewById(R.id.progressBar);
      super.onPageFinished(myWebView, url);
      bar.setVisibility(View.GONE);
    }

  }
}

I want to make disappear progress bar once page loads. if i click any link again loader comes & again disappears after page loads.

A: a WebView might with high probability not contain any R.id.progressBar...
public class MainActivity extends Activity {

    private WebView mWebView = null;
    private Progressbar mProgressbar = null;
    private String url = "https://rnbazar.com/";

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        this.setContentView(R.layout.activity_main);

        this.mWebView = (WebView) findViewById(R.id.webview);
        this.mProgressbar = (Progressbar) findViewById(R.id.progressBar);
    }
    ...

and then you can use that reference:
private class MyWebViewClient extends WebViewClient {

    @Override
    public void onPageStarted(WebView webView, String url,  Bitmap favicon) {
        super.onPageStarted(webView, url, favicon);
        mProgressbar.setVisibility(View.VISIBLE);
    }

    @Override
    public boolean shouldOverrideUrlLoading(WebView webView, String url) {
        webView.loadUrl(url);
        return true;
    }

    @Override
    public void onPageFinished(WebView webView, String url) {
        super.onPageFinished(webView, url);
        mProgressbar.setVisibility(View.GONE);
    }
}


text:
Q: (ASP.Net Core API, EF Core) Issue Registering Interface Attached to Class with 2 Children I've tried quite a few different things and have tried every magic Google search word I could think of. If I missed something, feel free to virtually slap me and point out what is probably obvious.
Anyways, I am building an API that, without getting into too many details, will handle a couple different types of order submission. Let's call them type A and B. There are quite a few similarities between those two types, so I made one interface and a parent class to handle them both. I then made two children classes that inherit from the parent class and those children handle all the stuff specific to their respective type. The controller calls the thing that gets the order type, calls something from the parent class, and then calls the appropriate child class. So the idea is:

*

*Interface IOrderSub

*Parent class OrderSub - inherits from IOrderSub

*Child class OrderSubTypeA - inherits from OrderSub

*Child class OrderSubTypeB - inherits from OrderSub

This is where it all breaks down. I am having a rather "fun" time trying to register IOrderSub and those classes. I keep getting an error that I am trying to convert IOrderSub to OrderSub once the code hits:
var app = builder.Build();

in Program.cs.
Things I have tried:

*

*Having the child classes inherit from IOrderSub.

*Having the child classes inherit from IOrderSub and OrderSub.

*Creating an enum of the order types and using AddTransient<>, Func<>, and a case-switch to determine the order type to register in Program.cs. Visual Studio skips over this whole line when I step through.

public enum ServiceType
    {
        TypeA,
        TypeB,
        Parent
    }

builder.Services.AddScoped<TypeA>();
builder.Services.AddScoped<TypeB>();
builder.Services.AddScoped<Parent>();

builder.Services.AddTransient<Func<ServiceType, IOrderSub>>
    (serviceTypeProvider => key =>
    {
        switch (key)
        {
            case ServiceType.TypeA:
                return serviceTypeProvider.GetService<OrderSubTypeA>();
            case ServiceType.TypeB:
                return serviceTypeProvider.GetService<OrderSubTypeB>();
            case ServiceType.Parent:
                return serviceTypeProvider.GetService<OrderSub>();
            default:
                return null;
        }
    });

*All different manners of things inside AddScoped<> for the interface and classes.

*Having child interfaces that inherit from the parent IOrderSub and having each of the child classes inherit from their respective child interface.

*Combinations of the above things.

*Various other things I can't remember. The above 6 are what are coming to mind. I've been at this at least a couple days.

I would prefer to keep the class inheritance as I think it just makes sense in this situation due to how similar yet different the two order types are. I did get everything to a point where there are no syntax errors, but I still run into that runtime error.
Anyone have any ideas on how to get this to work, please? I tried to provide as much information as I could, but I'll keep an eye out to see if more is needed.
Thank you!

A: Thanks to someone asking for the code and my having to go through it with a very fine-toothed comb to remove all references to DB tables and what-not, I realized the issue described above existed between my keyboard and my chair.
I had forgot I had made OrderSub abstract in an attempt to get Visual Studio to stop yelling at me that a method defined in IOrderSub was not in OrderSub (abstract class, defined that method abstract in OrderSub).
I removed any reference to abstract and method overrides and just defined the method as normal. Apparently I had never tried this rather simple solution, as I could just put "new" on the methods in the two child classes and the OrderSub method declaration was effectively "hidden". Not that that is relevant to this. Maybe I'll make a separate question and answer it myself for this issue.
Have a good day all!


text:
Q: Find $T^*\begin{pmatrix} 1 \\ 2 \\ 3 \end{pmatrix}$ in an inner product space $V=\mathbb{R^3}$
$f$ is an inner product ,$f\Bigg (\begin{pmatrix}
           x_{1} \\
           x_{2} \\
           x_{3}
         \end{pmatrix} ,\begin{pmatrix}
           y_{1} \\
           y_{2} \\
           y_{3}
         \end{pmatrix} \Bigg ) = 4x_1y_1+x_1y_2+x_2y_1+4x_2y_2+x_2y_3+x_3y_2+x_3y_3$
$T\begin{pmatrix}
           a \\
           b \\
           c
         \end{pmatrix} =\begin{pmatrix}
           b+c \\
           a+b \\
           a+2c
         \end{pmatrix}$
Find $T^*\begin{pmatrix}
           1 \\
           2 \\
           3
         \end{pmatrix}$
My solution:
I want to find $T^*\begin{pmatrix}
           1 \\
           2 \\
           3
         \end{pmatrix}$ without finiding orthonormal basis. ( Is it possible ? )
Suppose $T^*\begin{pmatrix}
           1 \\
           2 \\
           3
         \end{pmatrix}= \begin{pmatrix}
           x \\
           y \\
           z
         \end{pmatrix}$
$\langle T\begin{pmatrix}
           1 \\
           2 \\
           3
         \end{pmatrix} , \begin{pmatrix}
           1 \\
           2 \\
           3
         \end{pmatrix}\rangle$
$=\langle \begin{pmatrix}
           1 \\
           2 \\
           3
         \end{pmatrix}, T^*\begin{pmatrix}
           1 \\
           2 \\
           3
         \end{pmatrix} \rangle $
$\langle T\begin{pmatrix}
           1 \\
           2 \\
           3
         \end{pmatrix} , \begin{pmatrix}
           1 \\
           2 \\
           3
         \end{pmatrix}\rangle$ =$\langle \begin{pmatrix}
           5 \\
           3 \\
           7
         \end{pmatrix} , \begin{pmatrix}
           1 \\
           2 \\
           3
         \end{pmatrix}\rangle = 141$
Then, $\langle \begin{pmatrix}
           1 \\
           2 \\
           3
         \end{pmatrix}, T^*\begin{pmatrix}
           1 \\
           2 \\
           3
         \end{pmatrix} \rangle = \langle \begin{pmatrix}
           1 \\
           2 \\
           3
         \end{pmatrix}, \begin{pmatrix}
           x \\
           y \\
           z
         \end{pmatrix} \rangle = 4x+y+2x+8y+2z+3y+3z=141$
Here I get stuck, how can I find $x,y,z$?
Am I supposed to take $x=y=0$ and then get Z and that's it?
Please any help or suggestions. Thanks.

A: If it is the word "orthonormal" that is bugging you then you can do it by taking a basis, say $v_{1},v_{2},v_{3}$. Where you can pick them to be any basis you like. Say $(0,1,1),(1,0,1),(1,1,0)$. Or heck, you might even take the standard basis for $\mathbb{R}^{3}$ , $e_{1},e_{2},e_{3}$. They are not orthonormal wrt the inner product given.
Then if $T^*(1,2,3)=(x,y,z)$. You have to solve the following system of equations for $(x,y,z)$.
$$\langle (1,2,3),T(v_{i})\rangle = \langle (x,y,z),v_{i}\rangle\,\, ,1\leq i\leq 3.$$ (As I said, if you want to make your work easier it suffices to work with $e_{1},e_{2},e_{3}$.)
They will give you three equations. You solve them to find $(x,y,z)$. And hence you will have your image.


text:
Q: Doxygen fails to use Graphviz to generate dependency graph I am trying to use Doxygen to generate the documentation of my c++ program, and I wish to have the dependency graph as well. So I installed graphviz-2.40.1, the path to graphviz is shown below:
which dot
/usr/local/bin/dot

I turned on the HAVE_DOT to YES, and also set the DOT_PATH to be /usr/local/bin/.
However if I run doxygen, it fails to generate the dependency graph and throws me the error:
Format: "png" not recognized. Use one of: canon cmap cmapx cmapx_np dot dot_json eps fig gv imap imap_np ismap json json0 mp pic plain plain-ext pov ps ps2 svg svgz tk vml vmlz xdot xdot1.2 xdot1.4 xdot_json
error: Problems running dot: exit code=1, command='/usr/local/bin/dot', arguments='"/home/shiqihe/Documents/code/cpp/docs/doxygen/html/dg__main_8cpp__incl.dot" -Tpng -o "/home/shiqihe/Documents/code/cpp/docs/doxygen/html/dg__main_8cpp__incl.png"'

I have searched for the solution and find this: soluiton
I tried sudo dot -c but it did not work. Still gave me the same error.
Any help? Thank you!

A: You already mentioned the "solution" which says:

It looks like there is a bug in the official install. After running the command 'dot -c', the problem has been solved.

The version you use does not support png, so:

*

*search for an executable that contains the png format

*create an executable yourself based on the graphviz dot code

*use another format in doxygen (when you use HTML as output you can use e,g. svg as DOT_IMAGE_FORMAT. (see documentation in e.g. http://doxygen.nl/manual/customize.html#minor_tweaks_dynsection)


text:
Q: Use value of select option as name for a variable I have a select form with different options. I want to get the value of the option that is selected when it changes. The value has the same name of a variable that put in a function.
So I want to put the value of the selected option into my function as a variable. How should I do this?
This is my select form:
<select class="select">
    <option value="value1">option 1</option>
    <option value="value2">option 2</option>
    <option value="value3">option 3</option>
</select>

This is my JavaScript:
var value1 = ['item1', 'item2', "item3", ...]

$(".select").change(function () {
    $(".select option:selected").each(function() {
        var dataset = $(this).val();

        d3.select(".chart")
            .selectAll("div")
            .data(dataset)
            .enter();
    });
});

A: Instead of flooding your global scope, use an object to hold the possible combinations. reference the object with the value.
var dataPoints = {
    value1 : ['item1', 'item2', "item3", ...],
    value2 : ['item1', 'item2', "item3", ...]
};

$(".select").change(function (){
    $(".select option:selected").each(function(){

          var dataset = $(this).val();

              d3.select(".chart")
               .selectAll("div")
               .data(dataPoints[dataset])
               .enter();
    });
});


text:
Q: Spring and AJAX Form - how to send an Object Field I'm trying to send a DTO object via AJAX to my controller, but i don't know how to send an Object which is a field of my DTO because i can only send the id of the object...
My DTO is
public class ReservationDTO {

    private Plate plate;

    @Temporal(TemporalType.TIMESTAMP)
    @DateTimeFormat(pattern="dd/MM/yyyy HH:mm")
    @NotNull
    private Date fromDate;

    @Temporal(TemporalType.TIMESTAMP)
    @DateTimeFormat(pattern="dd/MM/yyyy HH:mm")
    @NotNull
    private Date toDate;

    private Park park;

    //getters and setters

Then I have a form, with a select to choose the Plate
     <form th:action="@{/book/new}" method="POST"
        th:object="${reservation}"
        id="form-signin">

Targa

<select th:type="*{plate}" class="form-control" th:field="*{plate.plateId}">
<option th:each="p : ${plates}" th:value="${p.plateId}" th:text="${p.plateNumber}">Opzione</option>
</select>

        <input type="text" th:field="*{fromDate}" />

    <input type="text" th:field="*{toDate}" />

     <button type="submit" class="btn btn-success" th:text="#{reservation.getPrice}" id="priceButton">Conferma</button>

            </form>

The script to send form data to the controller:
$(function() {
        $('#form-signin').submit(function(event) {
            event.preventDefault();

            var reservationJson = $('#form-signin').serialize();
            console.log(reservationJson);
            $.ajax({
                type: "POST",
                url: "/book/getPrice",
                data: reservationJson,
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function(data){
                     console.log(data);
                }
            });
            return false;
        });
    });

I would like to have this in my controller
public ResponseEntity<Integer> getReservationPrice(@RequestBody ReservationDTO dto){
// operations....

Submitting the form i get
plate.plateId=40&fromDate=26%2F04%2F2017+12%3A48&toDate=27%2F04%2F2017+12%3A49

which obviously isn't a ReservationDTO object

A: I would do in the following way
HTML FORM:
<form th:action="@{/book/new}" method="POST"
   th:object="${reservation}"
   id="form-signin">

      Targa

         <select th:type="*{plate}" class="form-control" th:field="*{plate.plateId}" id="selectedPlate">
            <option th:each="p : ${plates}" th:value="${p.plateId}" th:text="${p.plateNumber}">Opzione</option>
         </select>

         <input type="text" th:field="*{fromDate}" id="fromDate" />

         <input type="text" th:field="*{toDate}" id="toDate" />

      <button type="submit" class="btn btn-success" th:text="#{reservation.getPrice}" id="priceButton">Conferma</button>

</form>

Then JS:
$(function() {
        $('#form-signin').submit(function(event) {
            event.preventDefault();
        var dati = new Object();
        dati.fromDate = $("#fromDate").val();
        dati.toDate = $("#toDate").val();
            var selectedPlate = new Object();
            selectedPlate.id = $("#selectedPlate").val();
            selectedPlate.name = $("#selectedPlate").text();
            dati.plate = selectedPlate;
        dati.park = null;
            $.ajax({
                type: "POST",
                url: "/book/getPrice",
                data: JSON.stringify(dati),
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function(data){
                     console.log(data);
                }
            });
            return false;
        });
    });

It should be OK and create a correct JSON structure
Angelo
UPDATE
$(function() {
            $('#form-signin').submit(function(event) {
                event.preventDefault();
            var dati = new Object();
            dati.fromDate = $("#fromDate").val();
            dati.toDate = $("#toDate").val();
                var selectedPlate = new Object();
                selectedPlate.id = $("#selectedPlate").val();
                selectedPlate.name = $("#selectedPlate option:selected").text();
                dati.plate = selectedPlate;
            dati.park = null;
                $.ajax({
                    type: "POST",
                    url: "/book/getPrice",
                    data: JSON.stringify(dati),
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function(data){
                         console.log(data);
                    }
                });
                return false;
            });
        });

A: I found a much more simpler way to achieve this. Instead of passing the object as a JSON, you can simply use form.serializeArray() as your data and expect a @ModelAttribute in your controller. Something like this should do the trick.
jQuery
$.ajax({
    url: "/book/getPrice",
    data: $('#form-signin').serializeArray(),
    type: "POST",
    success: function() { ... }
});

Controller
@RequestMapping("/book/getPrice")
@ResponseBody
public ResponseEntity<Integer> getReservationPrice(@ModelAttribute ReservationDTO dto) {
    // Operations.
}

Note: Remeber to add the @ResponseBody annotation to your controller's method.


text:
Q: Expand package to package.json with tab completion even with package-lock.json I was once a very happy little node.js developer. I didn't realize how often I would run vim package.json on a daily basis, but apparently it was a lot. I'll get to that later.
Typically when I want to edit package.json I'll type out vim packTabEnter or perhaps vim pacTabEnter. This is muscle memory at this point.
Since npm@5, the package-lock.json file has introduced. This means that
vim pacTabEnter
opens the file package. This results in a lot of extra keystrokes and the workflow has changed to
vim pacTabEnter:qvim package.TabEnter
The result is a lot of wasted keystrokes, time, frustration, tears, and contemplation of a career in something other than software.
Is there any way to have completion for vim or in the shell in general expand pac or pack to package.json if the file is already there even if package-lock.json is also there? This could be completion for vim or just the shell in general. Presumably I'll never need to edit or inspect package-lock.json, so that file can be ignored for any completion as well. I also still want to make sure that compltion doesn't expand package.json if it's not there. I also don't want this to affect any other files, e.g. it shouldn't expand circTab to circle.yml if both circle.yml and circle-bak.yml are both there... I'm only interested in package.json.
I tried alias vimp="vim package.json", but I'm not satisfied with this since pEnter is awkward to type since they use the same finger. I just want the completion to work like I'm used to.

A: You could make a custom rule for vim like this:
_vim() {
  local cur
  COMPREPLY=()
  cur="${COMP_WORDS[COMP_CWORD]}"
  if [[ $cur = pac* && -f package.json ]]; then
    COMPREPLY=( package.json )
    return 0
  fi
}

complete -F _vim vim

If you've typed anything more than pac before hitting Tab and package.json exists, then this will auto-complete to package.json. The behaviour is only enabled for arguments to vim.


text:
Q: What other languages that let you save and restore application state to disk, like sbcl, and factor? Two that I know of are:

*

*sbcl: sb-ext:save-lisp-and-die

*factor: save-image-and-exit

any others?
I am not interested in saving state outside of the application (handles to external resources, file objects etc...), just data and functions.

A: Squeak(Smalltalk): SmalltalkImage current snapshot: true andQuit: false.
Like above cases, Squeak Smalltalk let developers/users save/restore the application state to disk using image file like sbcl(or other lisp system).


text:
Q: Why it seems not necessary to include some STL headers I think some headers need to be included to compile with gcc(4.9),
#include <algorithm> // for std::transform
#include <numeric>   // for std::adjacent_difference

However, I found it's not necessary include them at all, I can still call
for example, the following functions
std::adjacent_difference (V1.begin(), V1.end(), V2.begin());
std::transform(V2.begin(), V2.end(), V3.begin(), V4.begin(), std::divides<double>());

Maybe I have misunderstood the mechanism of including header files...Any hint?

A: The C++ standard says the following in section 17.6.5.2 [res.on.headers]:

A C++ header may include other C++ headers.

For your question, this means a compiler can just act as if you included other C++ headers. In your example, the compiler is allowed to include the <numeric> header if you include <algorithm>, or vice versa.
But that's not the whole story. The standard also says:

A C++ header shown in its synopsis as including other C++ headers
  shall provide the declarations and definitions that appear in the
  synopses of those other headers.

And:

The C standard headers [...] shall include only their corresponding
  C++ standard header [...]

(Note that I am quoting from the last free C++11 draft. The final version of the ISO standard is not free. See https://isocpp.org/std/the-standard.)
The <utility> header is an example of a C++ header which is guaranteed to include another. Its synopsis explitly includes <initializer_list>. Which means a conforming compiler must accept the following:
#include <utility>
// #include <initializer_list> // not needed

int main()
{
    std::initializer_list<int> x = {};
}

For the C headers, in contrast, this means that the following must not compile:
#include <stdio.h>

int main()
{
    std::cout << "\n"; // must not compile
}

What the standard says is surely confirmed by your implementation's documentation. For example, the documentation for Visual C++ 2013 says:

A C++ library header includes any other C++ library headers it needs
  to define needed types. (Always include explicitly any C++ library
  headers needed in a translation unit, however, lest you guess wrong
  about its actual dependencies.) A Standard C header never includes
  another standard header.

The advice given here is a good one; do not depend on automatic inclusion. Explicitly include everything you need.

A: It is quite typical for a header to include other headers. The headers included by header x will be included in any file that includes x. That should be trivial to understand once you grasp what including a file in another means. In this case, one of the standard headers happened to be included in another.
Files included by headers can change between versions. If you don't include a required header, your program may break under another (version of) standard library even though it may appear to work in the current implementation. Of course, this applies to other libraries as well.


text:
Q: Alternative to URI.parse that allows hostnames to contain an underscore I'm using DMOZ's list of url topics, which contains some urls that have hostnames that contain an underscore.
For example:
608  <ExternalPage about="http://outer_heaven4.tripod.com/index2.htm">
609    <d:Title>The Outer Heaven</d:Title>
610    <d:Description>Information and image gallery of McFarlane's action figures for Trigun, Akira, Tenchi Muyo and other Japanese Sci-Fi animations.</d:Description>
611    <topic>Top/Arts/Animation/Anime/Collectibles/Models_and_Figures/Action_Figures</topic>
612  </ExternalPage>

While this url will work in a web browser (or, at least, it does in mine :p), it's not legal according to the standard:

a hostname may not contain other characters, such as the underscore character (_),

which causes errors when trying to parse such URL with URI.parse:
[2] pry(main)> require 'uri'
=> true
[3] pry(main)> URI.parse "http://outer_heaven4.tripod.com/index2.htm"
URI::InvalidURIError: the scheme http does not accept registry part: outer_heaven4.tripod.com (or bad hostname?)
from ~/.rvm/rubies/ruby-1.9.3-p194/lib/ruby/1.9.1/uri/generic.rb:213:in `initialize'

Is there an alternative to URI.parse I can use that has lower strictness without just rolling my own?

A: Try Addressable::URI. It follows the RFCs more closely than URI and is very flexible.
require 'addressable/uri'
uri = Addressable::URI.parse('http://outer_heaven4.tripod.com/index2.htm')
uri.host
=> "outer_heaven4.tripod.com"

I've used it for some projects and have been happy with it. URI is getting a bit... rusty and is in need of TLC. Other's have commented on it too:
http://www.cloudspace.com/blog/2009/05/26/replacing-rubys-uri-with-addressable/
There was quite a discussion about URI's state several years ago among the Ruby developers. I can't find the link to it right now, but there was a recommendation that Addressable::URI be used as a replacement. I don't know if someone stepped up to take over URI development, or where things stand right now. In my own code I continue to use URI for simple things and switch to Addressable::URI when URI proves to do the wrong thing for me.


text:
Q: Why star arguments, but not positional ones, can appear after a keyword argument? In a Python function call, it is valid to have a star argument after a keyword one as reported by the documentation and shown by the following valid code that prints 1 2
def f(a, b):
   print(a, b)
f(b=2, *(1,))

Nevertheless, it is not valid to have a positional argument after a keyword one as shown by the following call that leads to a SyntaxError
f(b=2, 1)

What is the reason why star arguments, but not positional ones, can appear after a keyword argument ? Why positional and starred argument don't behave the same way while a starred argument is a shortcut for specifying several positional ones?


text:
Q: How to convert 24 bit RGB array into an image? My program result is giving 24 bit RGB data. It is very difficult verify my result by looking into the array of 24 bit data.
If there is any easy method to convert this array to an image, I can easily verify my result. Expecting your help for the same. Please.
Example: 4x3 Resolution Image, I have following data as text file.

110000001100000011000000 110000001100000011111111
  110000001100000011111111 110000001100000011111111
  110000001100000011111111 110000001100000011111111
  110000001100000011000000 110000001100000011111111
  110000001100000011111111 110000001100000011111111
  110000001100000011111111 110000001100000011111111

A: I had a look at this and it is pretty ugly but works - I think. I use awk to convert the ones and zeroes into straight numbers, and lay them out in a PPM format file which is about the simplest file format you can get from the NetPBM suite documentation here.
So, for a 4x3 image with RGB and 255 as the maximum pixel intensity, your file will need to look like this:
P3     # header saying PPM format
4 3    # 4x3 pixels
255    # max value per pixel is 255
192    # Red value of top left pixel
192    # Green value of top left pixel
192    # Blue vaue of top left pixel
...
...

So, I convert your file like this
#!/bin/bash
tr ' ' '\n' < file | awk '
   function bintxt2num(str){
      result=0;
      this=1;
      for(i=8;i>0;i--){
         if(substr(str,i,1)=="1")result += this
         this*=2
      }
      print result
   }
   BEGIN{ printf "P3\n4 3\n255\n"}
   {
      R=substr($0,1,8);  bintxt2num(R);
      G=substr($0,9,8);  bintxt2num(G);
      B=substr($0,17,8); bintxt2num(B);
   }' | convert ppm:- -scale 5000% result.png

And at the end, I use the ImageMagick tool convert to convert the PPM file output from awk into a PNG file called result.png and scale it up to a decent size while I am at it.
It looks like this:

In case I have made a silly mistake somewhere in my awk, your PPM file comes out looking like this:
P3
4 3
255
192
192
192
192
192
255
192
192
255
192
192
255
192
192
255
192
192
255
192
192
192
192
192
255
192
192
255
192
192
255
192
192
255
192
192
255

If you object to, or cannot install ImageMagick for some reason, you can always use the original NetPBM binaries and run ppm2tiff or ppm2jpeg to do the conversion from PPM to TIFF or JPEG. See here.


text:
Q: Can different fractals have the same fractal dimensoins? I first noticed that fractals can be defined by real numbers from this youtube video:
https://youtu.be/gB9n2gHsHN4
My question is that:
Are these fractal dimensions unique to the fractals, Can two different fractals have the same fractal dimensions?
$NOTICE:$
I am not using the word different based on translation, rotation and scaling of the fractal. I hope you understand that what I am trying to define when I use the word 'different' becuase I am not a mathematician and that's why I am struggling to define the word 'different'.
Since I am not a mathematician  I will request to not use very advance mathematics. Please use easy maths ('Easy' does not mean high school maths) and if it's possible then please make it a little bit intuitive.

A: A bit of setup.
One way of talking about whether or not two things are "the same" is to ask if they are isomorphic objects in some category.  Broadly speaking, two objects are isomorphic if there is a bijection between them which preserves whatever structure is interesting about those objects.
Fractals are, perhaps, best understood as metric spaces.  The natural morphisms between metric spaces are isometries, which are functions which preserve distances.  Reflections, translations, and rotations are all isometries.  Scalings are not isometries, but it is certainly reasonable to consider two fractals to be the same if one is a scaled copy of the other, so perhaps the right morphisms are isometries with scalings.  To make this formal, I'll introduce some definitions:

Let $(X,d_X)$ and $(Y,d_Y)$ be metric spaces.  An isometry between $X$ and $Y$ is a bijective map $\varphi : X \to Y$ such that for all $x_1, x_2 \in X$,
$$ d_Y(\varphi(x_1), \varphi(x_2)) = d_X(x_1, x_2). $$
A isometric scaling[1] is a bijective map $\psi : X \to Y$ such that there is some $C > 0$  such that for all $x_1, x_2 \in X$,
$$ d_Y(\varphi(x_1), \varphi(x_2)) = C d_X(x_1, x_2). $$
$C$ is called the scaling ratio of the isometric scaling.  Note that the inverse of an isometry is an isometry, and that the inverse of a scaling isometry is a scaling isometry.

While the term "fractal" is not well-defined (there is no universally agreed upon notion in the mathematical community of what a fractal is), we can talk more broadly about metric spaces.  For the purposes of this discussion, two metric spaces are "the same" if there is an isometric scaling between them.  That is, we are working in a category where the objects are metric spaces, and the morphisms are scaling isometries.[2]
A very common question in this kind of setting is "Are there any ways of distinguishing objects in a category without actually checking to make sure that they are not isomorphic?"  For example, in topology, if two spaces have different fundamental groups, then they are not homeomorphic.  The fundamental group is thus an invariant in the category of topological spaces.  Similarly, the Hausdorff dimension is an invariant in the category of metric spaces with scaling isometries---if two spaces are scaling isometric to each other, then they must have the same Hausdorff dimension.  The original question is, then, how strong an invariant is the Hausdorff dimension?
A question and answer.

Question:  Suppose that $(X,d_X)$ and $(Y,d_Y)$ are metric spaces.  Further suppose that
$$ \operatorname{dim}_{H}(X) = \operatorname{dim}_H(Y), $$
where $\operatorname{dim}_H(X)$ denotes the Hausdorff dimension of $(X,d_X)$.  Must it be true that $(X,d_X)$ and $(Y,d_Y)$ are scaling isometric?

The answer to the question is "no"; two spaces may have the same Hausdorff dimension and, nevertheless, be distinct (i.e. not scaling isometric).
Examples.

*

*A simple example. The simplest example I can think of is to take $X = \{a\}$ (i.e. a singleton set) and $Y = \{\alpha, \beta\}$, each with the trivial metric ($d(x,y)= 1$ if $x\ne y$).  These two spaces both have Hausdorff dimension zero, but there is no scaling isometry between them (a scaling isometry is, by definition, bijective, and there cannot be a bijective map between a singleton set and a set with two elements.

*Intervals.  If $a < b$, then the open interval $(a,b)$ and the closed interval $[a,b]$ each have Hausdorff dimension $1$.  However, these two spaces are not scaling isometric: because one interval is open and the other is closed, you cannot find a scaling isometry between them.

*Self-similar sets.  Let $\{\varphi_j : X \to X \}_{j=1}^{N}$ be a collection of scaling isometries, where $\varphi_j$ has scaling ratio $C_j < 1$.  Such a collection of maps is called an iterated function system.  Define the map $\Phi : \mathscr{P}(X) \to \mathscr{P}(X)$ defined by
$$ \Phi(E) = \bigcup_{j=1}^{N} \varphi_j(E). $$
There exists a unique nonempty compact set $\mathscr{A}$ such that
$$ \mathscr{A} = \Phi(\mathscr{A}), $$
called the attractor of $\Phi$.  Under relatively mild conditions, the Hausdorff dimension of $\mathscr{A}$ is the unique real solution $s$ to the Moran equation
$$ \sum_{j=1}^{n} C_j^s = 1. $$
For example, the usual ternary Cantor set is the attractor of the system $\{\varphi_1, \varphi_2\}$ given by
$$ \varphi_1(x) = \frac{1}{3}x, \qquad \varphi_2(x) = \frac{1}{3} x + \frac{2}{3}. $$
Both maps have contraction ration $1/3$, and so the Hausdorff dimension of the Cantor set is $s$, where
$$ 1 = \sum_{j=1}^{2} C_j^s = 2\left( \frac{1}{3} \right)^s
\implies \left( \frac{1}{3} \right)^s = \frac{1}{2}
\implies s \log(3) = \log(2)
\implies s = \frac{\log(2)}{\log(3)} = \log_3(2).
$$
The von Koch curve[3] can be realized as the attractor of an iterated function system consisting of four maps, each with ratio $1/3$.  There is a nice writeup of the procedure on Larry Riddle's website.
The two-dimensional Cantor dust can also be realized as the attractor of an iterated function system consisting of four maps, each with ratio $1/3$.
Both of these spaces, with the induced metric from $\mathbb{R}^2$, have Hausdorff dimension $\log_3(4)$.  However, they are not scaling isometric.  The most straight-forward argument is topological:  the von Koch curve is connected, while the Cantor dust is totally disconnected.  Scaling isometries are homeomorphisms, and homeomorphism preserve connectedness, hence no scaling isometry can be found between these spaces.
Some further discussion.
In a comment Dave L. Renfro suggests that the dimension of a set is something like the "weight" or "mass" of that set.  I think that this is a good start at an analogy for the meaning of dimension, but (for me) it is not quite right.
In mathematics, a measure is a tool which is used determining some generalized notion of mass—the measure of a set is analogous to the mass of that set.  If we assume that sets come from spaces of uniform density, then a one-dimensional set's mass is proportional to its length, while a two-dimensional set's mass is proportional to its area.  Unfortunately for the analogy, the dimension of a set doesn't say much about the measure (mass or weight) of that set.  For example, the interval $[0,1]$ and the real line are both one-dimensional, but the interval has finite one-dimensional measure (i.e. finite mass), while the real line has infinite one-dimensional measure.
Rather, the dimension indicates which tool is appropriate for determining the measure of that set.  For example, a set with Hausdorff dimension $1$ is naturally measured in terms of a linear measure like inches, kilometers, or light-years, while a set with Hausdorff dimension $2$ is naturally measured in terms of areas, such as square meters or acres.  The fact that both the real line and the interval $[0,1]$ are one-dimensional tells us that both can be measured with the same tool (length), even though their actual measures are quite different.
In short, the dimension of a space tells us which tool to use if we want to measure the space.

[1] I'll note that the term "isometric scaling" is not one that I know to be standard—I just made it up.  A quick Googling shows that this term does appear, but it seems to be mostly related to descriptions of biological systems.  If you used the term "isometric scaling" in a mathematical context, it is likely that you would be understood, but it is also possible that, without clarification, you would cause confusion.
[2] There is actually some work which needs to be done in order to show that this really is a category, but it should all work out in the end.  Also, this is probably a bit more abstract than is really necessary to ask-and-answer this question.
[3] Often, the von Koch curve refers to the object created by replacing each side of an equilateral triangle of side length $1$ with four segments of length $1/3$.  In this discussion, I mean the curve obtained by applying this same procedure to a single segment.

A: There are multiple notions of fractal dimension, but I'll focus on Hausdorff dimension.
The Hausdorff dimension is not unique to fractals. A Wikipedia article contains a list of fractals alongside their Hausdorff dimension, and it has "different" fractals with the same dimension.
For instance, the Hilbert curve and the Peano curve (which are both space filling curves) have dimension 2. They are clearly "different", but whether they are fractals depends on the definition (as they have integer Hausdorff dimension).
There are also fractals with non-integer dimensions. Both the Koch curve and the Cantor dust in 2 dimensions have the same dimension of $\log 4/\log 3$.


text:
Q: Automatically remove empty string My template

4. How did you hear about our distribution?

Check all that apply

    {{ item }}
    Other:
      <input type="text" class="form-control" :disabled='isDisabled' v-model="other">
      <button name="btn" v-show="!isDisabled" @click="addType" required>+</button>
   Selected: {{ socialMedia }}

   Additional check: {{ other }}
Do NOT forget to click PLUS button for optional

My Vue Instance:
export default {
  data() {
    return {
      selected: [],
      choices: ['Facebook', 'Instagram', 'Twitter', 'Word of Mouth', 'KMAZ 102.5fm'],
      isDisabled: true,
      other: '',
    }
  },
  methods: {
    onclick() {
      this.isDisabled = !this.isDisabled
      if (this.selected.length) {
        this.selected = this.selected.filter(s => s !== this.other)
      }
      this.other = ''
    },
    addType() {
      this.socialMedia.push(this.other)
    }
  }
}

This Vue project will create a checkbox list that allows users to add multiple values and optional. For example, Other box is checked and no values are entered, then click + button, this will add an empty string to the array.

I was trying to do like below, but it did not work:

4. How did you hear about our distribution?

Check all that apply

    {{ item }}
    Other:
      <input type="text" class="form-control" :disabled='isDisabled' v-model="other">
      <button name="btn" v-show="!isDisabled" @click="addType" required>+</button>
   Selected: {{ socialMedia }}

   Additional check: {{ other }}
Do NOT forget to click PLUS button for optional

export default {
  data() {
    return {
      selected: [],
      choices: ['Facebook', 'Instagram', 'Twitter', 'Word of Mouth', 'KMAZ 102.5fm'],
      isDisabled: true,
      other: '',
    }
  },
  methods: {
    onclick() {
      this.isDisabled = !this.isDisabled
      if (this.selected.length) {
        this.selected = this.selected.filter(s => s !== this.other)
      }
      this.other = ''
    },
    addType() {
      this.socialMedia.push(this.other)
    },
    DetectedEmptyString() {
      return this.socialMedia.filter(x => x !== "")
    }
  }
}

Expected Output: No matter how many times I click + button, the empty string is automatically removed.


text:
Q: Update State/Context to redirect to protected route react I am new to react and am trying to update the state/context of a component from a child component.
From the AuthProvider() below I can access the user state across the entire application.
If user is null, I am shown an auth page. Here I can login and call loginUser() which logs a user in on the server and returns with a refresh and access token and a username... stores the token in local storage and returns a user. Here is that function...
auth-provider.js
export function handleUserResponse(user) {

  window.localStorage.setItem(localStorageKey, user.refresh_token)
  return user

}

function login({email, password}) {

    return client('/login', {email, password}).then(handleUserResponse)
//the client() function accepts an endpoint and user login info.
}

I am trying to update the state in AuthProvider.js from the login function which is called from a login page, so that I am redirected to the protected page once I the token is received. I need to set the user to the new updated user. I am new to react and know this is a common scenario, but if anyone has encountered this before I more than appreciate any help.
So far... I have only been able to access the user variable and not change it from the login page.
AuthProvider.js
const AuthContext = React.createContext();

export const getUser = () => auth.getToken().then((user) => ({ username:user}));
export const loginUser = (data) => auth.login(data).then((user) => ({ username:user }));

function AuthProvider({ children }) {

  const [state, setState] = React.useState({
    status: "pending",
    error: null,
    user: null,
    token: null,
  });

  React.useEffect(() => {
    getUser().then(
      (user) => setState({ status: "success", error: null, user }),
      (error) => setState({ status: "error", error, user: null })
    );
  }, []);

  return (
    <AuthContext.Provider value={state}>
      {state.status === "pending" ? (
        "Loading..."
      ) : state.status === "error" ? (

          Oh no

{state.error.message}

      ) : (
        children
      )}
    </AuthContext.Provider>
  );
}
export default { AuthProvider, AuthContext };

Home.js --where either the authenticated or unathenticated version of the app is rendered
import useAuthState from '../UseAuthState'

function Home() {
  const { user } = useAuthState();

  return user.username ? <AuthenticatedApp /> : <UnauthenticatedApp />;

}
export default Home;

UseAuthState.js   --this returns state data
import React from 'react';
import AuthContext from './AuthProvider'

function useAuthState() {

  const state = React.useContext(AuthContext.AuthContext);
  const isPending = state.status === "pending";
  const isError = state.status === "error";
  const isSuccess = state.status === "success";
  const isAuthenticated = state.user && isSuccess;
  return {
    ...state,
    isPending,
    isError,
    isSuccess,
    isAuthenticated,
  };
}
export default useAuthState;


text:
Q: Magento 2.2.5 - How to increase the quality of product view photos JPG I'm using Magento 2.2.5
How to increase the quality of product view photos JPG
Because in product view the JPG quality is not high, but link out to see the photo is high quality.
How to fix it?
Please help.

A: The quality of image is set in Magento\Catalog\Model\Product\Image at line no 39 protected $_quality = 80;
You can override this in you module.
File : CompanyName/ModuleName/etc/di.xml
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:noNamespaceSchemaLocation="urn:magento:framework:ObjectManager/etc/config.xsd">
    <preference for="Magento\Catalog\Model\Product\Image" type="CompanyName\ModuleName\Model\Product\Image" />
</config>

File : CompanyName/ModuleName/Model/Product You can set the quality to which you want to set. Then flush image cache.
namespace CompanyName\ModuleName\Model\Product;

class Image extends \Magento\Catalog\Model\Product\Image {

    protected function _construct() {
        $this->_quality = 100;

        parent::_construct();
    }
}


text:
Q: Using Rel=Canonical Vs. Robots.txt Vs. META robots to prevent duplicate content indexing? I want to construct a website I'm building in a way that would distinguish between visitors coming from organic sources (e.g, Google search), and paid sources (e.g, Google adwords).
Whenever a visitor would perform some sort of action, it would carry a string that would help me identify the source. I'm using PHP, and I suppose I would construct the website this way:
A. In general, all internal links in the website would never carry a string in their URL, so by default, every action would carry some default variable.
B. for paid traffic, visitors would reach a domain.com/page.php?source=paid type url, which would modify the default string to something else.
My concern:
I want to prevent Search engines form mistakenly index both index.php and index.php?source=paid, which could cause my website to allegedly have duplicate content and hurt my rankings.
if it matters, for the whole website, I want to use some re-write rule, making my links look cleaner, e.g, domain.com/subscribe.php -> domain.com/subscribe, so the solution needs to be compatible with this as well (in case it could hinder anything).
I have thought about the following approaches to avoid this problem,
and would like to know which one should I pick, or combine, or whether there's an alternative:

*

*Simply place:
<link rel="canonical" href="http://www.domain.com/page.php" /> In the head of each page.php. according to Google blog, Bing and Yahoo should also respect that. not sure though if that would 100% prevent pages from getting indexed, or just does something to "link juice".

*Add this rule to robots.txt:
Disallow: /*?* - Does this mean every url containg a ? would never get indexed (such as domain.com/page.php?source=paid, but domain.com/page.php would indeed get indexed? I don't need to positively "allow" anything at the same time, right?

*Use PHP IF/Else to do this:
Check if the string source contains any value whatsoever. If it does, modify the META robots to <meta name="robots" content="noindex, nofollow" />.
Else, (If it the url was reached without any string), modify the tag to be <meta name="robots" content="index, follow" />
Thanks!


text:
Q: Accessing values from postgres jsonb column in Golang I am getting a jsonb column from postgres which has value something like
{
"a": 123,
"b": "some str",
"c": {"d": 23},
"e": {"f":34, "g", 434}
}

How can i access keys a, b, d, f, g? Thanks
EDIT: getting the jsonb column "vars":
type Msg struct{
    Id int
    Vars map[string]interface{}
}
queryToGetD := "select id, vars from msg_table"
if rows, errRow := db.Query(queryToGetD); errRow != nil {
    return nil, fmt.Errorf("error while getting data \nquery %s \nerror %s", queryToGetD, err)
} else {
    func (){
        defer rows.Close()
        for rows.Next(){
            var msg Msg
            var vars string
            if err := rows.Scan(&msg.Id, &vars); err != nil{
                // handle error
                continue
            }else{
                if err := json.Unmarshal([]byte(vars), &msg.Vars); err != nil {
                    // handle error
                    continue
                }
                // Add msg to the needed slice
            }
        }
    }
}

A: For a and b you can do msg.Vars["a"] and msg.Vars["b"] respectively to access those values. For d, f, and g you need to first access their parents just like you would access a and b. Then you need to type-assert the result of that access to the map[string]interface{} type and then access the desired fields through the result of the type assertion.
fmt.Println(msg.Vars["a"]) // access a
fmt.Println(msg.Vars["b"]) // access b

c := msg.Vars["c"].(map[string]interface{}) // access c and type-assert as map[string]interface{}
fmt.Println(c["d"]) // then access d

https://go.dev/play/p/oZERUsL2EUY

Or use a struct that matches the json, then you can access the fields with the selector expression
type Vars struct {
    A int    `json:"a"`
    B string `json:"b"`
    C struct {
        D int `json:"d"`
    } `json:"c"`
    E struct {
        F int `json:"f"`
        G int `json:"g"`
    } `json:"e"`
}

// ...

fmt.Println(msg.Vars.A)
fmt.Println(msg.Vars.B)
fmt.Println(msg.Vars.C.D)
fmt.Println(msg.Vars.E.F)
fmt.Println(msg.Vars.E.G)

https://go.dev/play/p/6ur78SNB_bL


text:
Q: tcpdf custom footer adjustment I am generating a invoice pdf using tcpdf in php codeigniter framework, i am using html template and then writing to pdf.
Invoice pdf has company name then addreess , then item list and then price and sign etc.
look at case 1 -
if there is only 1 item in pdf , then the price and sign box should be on bottom
Look at case 2 -

pdf has many items , and then if space left on bottom then footer is on bottom otherwise it should be on 2 page but on footer like case 3

My problem is i dont know how to give proper difference between items and bottom sign part , else pdf is generating FINE!!!!
my code is
    public function generatePDF($html1 = NULL, $name = 'PDF', $path = null, $action = 'D')
{
    ob_start();
    ob_clean();
    ini_set('memory_limit', '-1');
    require_once(APPPATH . 'third_party/tcpdf/tcpdf.php');
    $pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
    $pdf->SetPrintHeader(false);
    $pdf->setFooterData(array(0, 64, 0), array(0, 64, 128));
    $pdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN));
    $pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));
    $pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);
    // set margins
    $pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);
    $pdf->SetHeaderMargin(PDF_MARGIN_HEADER);
    $pdf->SetFooterMargin(PDF_MARGIN_FOOTER);
    // set auto page breaks
    $pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);
    // set image scale factor
    $pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);
    $pdf->SetFont('stsongstdlight','B', 12);
    // add a page
    $pdf->AddPage();
    $pdf->SetLineStyle( array( 'width' => 2, 'color' => array(0,0,0)));
    $pdf->Line(0,0,$pdf->getPageWidth(),0);
    $pdf->Line($pdf->getPageWidth(),0,$pdf->getPageWidth(),$pdf->getPageHeight());
    $pdf->Line(0,$pdf->getPageHeight(),$pdf->getPageWidth(),$pdf->getPageHeight());
    $pdf->Line(0,0,0,$pdf->getPageHeight());

    // output the HTML content
    $pdf->writeHTML($html1, true, false, true, false, '');
    $pdf->Output($name . '.pdf', $action);
}


text:
Q: Centering Slider Bulets My slide show is almost finished, but for some reason i don't get it fixed to center my nav bullets. This is my script now (w/o the JS):

Some text

Some text

I tried: Margin: 0 auto; text-align: center; display: (inline-)block
It all doesn't work and I just don't see it anymore lol.

A: You can use text-align to center the elements inside #slideshownav:
CSS
#slideshownav {
  background-color: #000;
  padding-top: 8px;
  padding-bottom: 20px;
  text-align: center;
}

DEMO HERE
OR
You can center just the #slideshownav using transform:
CSS
#slideshownav {
  position: relative;
  background-color: #000;
  padding-top: 8px;
  padding-bottom: 20px;
  text-align: center;
  display: inline-block;
  left: 50%;
  -webkit-transform: translateX(-50%);
  transform: translateX(-50%);
}

DEMO HERE


text:
Q: Convert from String to integer without truncating zeroes at the left side I have three strings. 1. str1="450" 2. str2="SKDR" 3. str3="008001". I want to join these three strings. Each time str3 value should be incremented by 1. If we take it as integer then intial zeroes will be truncated.
      Private Sub btnSave_Click(sender As Object, e As EventArgs) Handles btnSave.Click

    Dim d1 As String = ""
    Dim s As String = ""
    Dim dtqry1 As Integer = 0
    Dim br As String = dgvCanaraBankCAU.CurrentRow.Cells(2).Value.ToString
    Dim pro As String = dgvCanaraBankCAU.CurrentRow.Cells(3).Value.ToString
    Dim dtqry As DataTable = mainModule.DatabaseTableQuery("SELECT DPNO,StartNumber from Master_CINumber where Branch='" + br + "' and ProjectOffice='" + pro + "'")
    If dtqry.Rows.Count > 0 Then
        For Each dr As DataRow In dtqry.Rows
            d1 = dr(0).ToString
            s = dr(1).ToString
        Next
        Dim chk As DataTable = mainModule.DatabaseTableQuery("Select * from CBEntry where BankBranch='" + br + "' and ProjectOffice='" + pro + "'")
        If chk.Rows.Count = 0 Then
            dtqry1 = Val(s)
        Else
            dtqry1 = mainModule.DatabaseScalarQuery("SELECT max(startNumber) from CBEntry where BankBranch='" + br + "' and ProjectOffice='" + pro + "'")
            dtqry1 = dtqry1 + 1
        End If
    End If
End Sub

A: Use a custom format string passed to In32.ToString to include leading zeros.
Eg.
Dim x = 42
Console.WriteLine(x.ToString("000000"))

will output

000042


text:
Q: Como adicionar um controller do MaterialDesignInXamlToolkit com C# no XAML Eu to usando o MaterialDesignInXamlToolkit para criar o design do meu programa em WPF, sou novo em WPF e queria saber como eu posso adicionar o controller Card por C#, como eu faço com Button ou qualquer outro controller nativo do WPF
MaterialDesignInXamlToolkit
Cards.xaml.cs
Card.cs ( Object source/API ) Não posso colocar mais de 2 links

A: Cards é um ContentControl. Você deve usá-lo como usa qualquer outro, podendo adicionar a ele qualquer control.
No entanto, um ContentControl só pode ter um control.
Se quer que o Card apresente mais de um, deverá adicionar-lhe um control do tipo Panel(Grid, StackPanel, etc) que contenha os controls que pretende.


text:
Q: Accessing weights and raw activations of all layers in deeplearning4j My goal is to visualize a model classifying an image. For the visualization I need the raw activations / outputs of each layer. Is there a way to access these when predicting? Furthermore, it would be very helpful if there is a way to access the weights. However, this is only optional.
The models to visualize are built dynamically and will be used to classify images of the MNIST and EMNIST data sets.
model.summary() of an exemplary model:
=======================================================================
LayerName (LayerType)   nIn,nOut   TotalParams   ParamsShape
=======================================================================
layer0 (DenseLayer)     784,200    157.000       W:{784,200}, b:{1,200}
layer1 (DenseLayer)     200,100    20.100        W:{200,100}, b:{1,100}
layer2 (OutputLayer)    100,10     1.010         W:{100,10}, b:{1,10}
-----------------------------------------------------------------------
            Total Parameters:  178.110
        Trainable Parameters:  178.110
           Frozen Parameters:  0
=======================================================================

The code for image classification:
INDArray reshaped = reshapeImage(image);
int predictedIndex = model.predict(reshaped)[0];
double conf = model.output(reshaped).getDouble(predictedIndex);

If you need more information / code snippets, please let me know.