text:
Q: IOS 5 - Tab Bar Controller with Table View Controller issue I'm working on my first iPhone app in IOS 5 using storyboards. The root controller is a TabBar Controller that segues to a Table View Controller (TBarController) embedded in Navigation Controllers.
There are Detail Disclosure buttons on each cell if the Table View controller.  There is very little code at issue involved in the Table View controller:
-(void)tableView:(UITableView *)tableView
accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath

TBarAppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
UITabBarController *tabBarC = appDelegate.tabBarController;

Using the debugger, the issue is that tabBarC is 'nil' when I click on the Detail Disclosure.
Any ideas would be greatly appreciated.  This is my first post to SO— please forgive the newbie character of the post.


text:
Q: What is the correct version of HighchartsReact to use with React 15.4.2? I am trying to use HighchartsReact in a SharePoint Framework (SPFx) web part for SP 2016.
Because I'm stuck in SP 2016, I am stuck using the following versions of things:

*

*SPFx 1.1

*Node 8.17.0

*React 15.4.2

I absolutely cannot go to a higher version of Node or React.
Which version of HighchartsReact will work with this configuration?  I've tried a bunch of them, and they all throw errors.
All the major version 1 releases (1.1.0, 1.2.0, 1.3.0, 1.4.0, 1.5.2) all throw this error in React:

Element type is invalid: expected a string (for built-in components)
or a class/function (for composite components) but got: undefined.
Check the render method of MyChart

The early major version 2 releases (I tried 2.0.0 and 2.1.3 specifically) throw this error in the browser console:

Uncaught (in promise) TypeError: f.default.createRef is not a function
at new t (HighchartsReact.js:6:28)

With version 2.1.0, 2.1.3 and 2.2.2 I get a Typescript error in VS Code where my <HighchartsReact /> component is red underlined and the error is apparently:

'HighchartsReact' cannot be used as a JSX component.

but 2.1.0 and 2.1.3 still build, but 2.2.2 does not.
Versions 3.0.0 and 3.1.0 throw this error in the console:

Uncaught (in promise) Error: ***The value for "error" must not be
undefined

but also show a different error in the SPFx workbench UI:

Original error: Error loading
https://component-id.invalid/d0f2d321-9397-4488-9d9c-346e28ab3e54_0.0.1
Object(…) is not a function

So every single version of HighchartsReact is throwing some sort of error when trying to use it with Node 8.17 and React 15.4.2.
What can I do to use it if I can't up my Node or React versions?

A: You can relatively easily create your own wrapper for a Highcharts chart in React.
For the first step please check source code of the current wrapper version: https://github.com/highcharts/highcharts-react/blob/master/src/HighchartsReact.js
All you need to do is to create HTML container for a chart, create the chart in componentDidMount and handle chart update in componentDidUpdate.
Proposed implementation for React 15.4.2:
class HighchartsReact extends React.Component {
  componentDidMount() {
    const props = this.props;
    const H = props.highcharts;
    const constructorType = props.constructorType || "chart";
    // Create chart
    this.chart = H[constructorType](this.container, props.options);
  }
  componentDidUpdate() {
    const props = this.props;
    const H = props.highcharts;
    const constructorType = props.constructorType || "chart";

    if (props.allowChartUpdate !== false) {
      if (!props.immutable && this.chart) {
        this.chart.update(props.options, ...(props.updateArgs || [true, true]));
      } else {
        this.chart = H[constructorType](this.container, props.options);
      }
    }
  }
  componentWillUnmount() {
    this.chart.destroy();
  }
  render() {
    var self = this;
    var containerProps = this.props.containerProps || {};
    // Add ref to div props
    containerProps.ref = function (container) {
      self.container = container;
    };
    // Create container for our chart
    return React.createElement("div", containerProps);
  }
}

Live demo: https://codesandbox.io/s/highcharts-react-demo-nd8uv3?file=/HighchartsReact.jsx

redpajama_set_name: RedPajamaStackExchange


text:
Q: htaccess php version change & wrong encoding I'm strugelling with strange problem. My hosting provider do not offer cpanel with PHP config option (i know, disaster). For the purpouses of my website I had to change PHP version from 5.2 to 5.5. So admin told me i can use htaccess and command: AddHandler php5.5-fastcgi php
And ok - it activates proper PHP version, but what is totally strange -> change totally my mysql database encoding. The output is following - all posts, pages etc. which were previously displayed in my native language (polish) right now do not display polish diacritic symbols. I've tried to change the whole database collation to UTF8_general_CI yet it didnt solve the problem. I use wordpress as cms, but the issue appears also in my own cms, as well as plain php with mysql. Any ideas how to change that? thanks!


text:
Q: Execute a java class method from JSP in Spring MVC I'm working e-commerce store project using spring mvc. In a JSP login page, i need to check user name and user password after clicking submit button. If all information are ok then i'm gonna go to the next page, otherwise stay on the same page.
This is my Administrator class(Model) Administrator.java
@Entity
@Table(name="ADSMINISTRATOR")
public class Administrator {
    @Id
    private String userName;
    private String userPassword;
    //getter and setter
}

This is my controller class AdministratorController.java
@Controller
@RequestMapping(value="/administratorController")
public class AdministratorController {
    @RequestMapping(value="/loginForm.html")
    public ModelAndView getAdministratorLoginForm() {
        return new ModelAndView("Administrator");
    }

    public ModelAndView goToMainPage(@ModelAttribute("administrator") Administrator administrator) {
        //Checking userName and userPassword here
        //if ok then
        return new ModelAndView("mainPageDemo");
    }

}

And this is my JSP(View) Administrator.jsp

 User Name: 	 <input type="text" name="userName" value="" placeholder="User Name"></input>

 User Password: 	 <input type="text" name="userPassword" value="" placeholder="User Password"></input>

<input type="submit"></input>

Now When I click submit button in Administrator.jsp page, I need to execute goToMainPage() method in AdministratorController.java class. How can i do this?


text:
Q: Desplazamiento de Imágenes con Bootstrap 4 Requiero saber que codificación debo aplicar para que independientemente del orden del div de texto e imagen, siempre la imagen se desplace hacia abajo en modo tablet o md.
Ejemplo:
ENTRADA 1

                    TEXTO

                    IMAGEN

ENTRADA 2

                    IMAGEN

                    TEXTO

En la primera entrada coloco el div de texto y después el div de imagen.
En la segunda entrada coloco el div de imagen y después el div de texto.
Deseo que cuando este en pantalla modo tablet o md, las imágenes se desplacen hacia abajo, porque actualmente, en la segunda entrada me pone la imagen hacia arriba en vez de hacia abajo.
Gracias Anticipada.

A: Una buena solución para tu problema es trabajar con 'flexbox'. Te permitirá color los elementos como necesitas y moverlos de una maner sencilla. A continuación de dejo un ejemplo de como puedes hacer para la necesidad concreta que planteas:

      .row {margin-bottom: 50px;}
      .conFlex{display:flex; flex-direction: column;}

      .texto {padding:50px 100px; background-color: aqua; color: yellowgreen; font-size: 1em;font-weight: bold;}
      .imagen {padding:50px 100px; background-color: rebeccapurple; color: whitesmoke; font-size: 1em;font-weight: bold;}

      /*@media only screen and (max-width:768px)*/@media only screen and (max-width:500px){
        .container .conFlex {display:flex; flex-direction: row-reverse; flex-wrap: wrap-reverse;}
      }
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">

                            IMAGEN

                        TEXTO

                TEXTO

                    IMAGEN

En este ejemplo he dejado comentado el 'breakpoint' de tablet y puesto uno de menores dimensiones para que si quieres probar aquí reduzcas el ancho de la pantalla con el inspector o manualmente para que veas como funciona el código y cambia los elementos de posición.
Además te copio aquí un enlace que te puede resultar de ayuda a la hora de aplicar 'flexbox': css triks


text:
Q: php: error variable undefined I have a "Notice: undefined variable" error that I cannot solve:

Notice: Undefined variable: Nom in C:\wamp\www\cible_envoi.php on line 22

Could you please have a look at the code below and explain me what's wrong? Thanks!
cible_envoi.php:
<?php
try
{
    $bdd = new PDO('mysql:host=localhost;dbname=chansonniersduquebec.com', 'root', '');
}
catch (Exception $e)
{
    die('Erreur : ' . $e->getMessage());
}

$req = $bdd->prepare('INSERT INTO chansonniersduquebec.com (Nom) VALUES(?)');
$req->execute(array($_POST['Nom'])); // *** Line 22 ***

Incription.html:
<form id="Formulaire" name="Formulaire" method="post" action="cible_envoi.php">

Nom (votre nom d'artiste de préférence!)
      *
      <input type="text" name="Nom" id="Nom"/>

   ...
   <input type="submit" name="Soumettre" id="Soumettre" value="Soumettre" />
</form>

A: $bdd is out of scope.
     <?php
//Try this

    try
     {
        $bdd = new PDO('mysql:host=localhost;dbname=chansonniersduquebec.com', 'root', '');

         // Insertion du message à l'aide d'une requête préparée
          $req = $bdd->prepare('INSERT INTO chansonniersduquebec.com (Nom) VALUES(?)');

          $req->bindParam(1, $nom);

          $nom = $_POST['Nom'];

          $req->execute();
      }
      catch (Exception $e)
      {
        die('Erreur : ' . $e->getMessage());
      }

  ?>

or
<?php
//Try this
       $bdd = null;
    try
     {
        $bdd = new PDO('mysql:host=localhost;dbname=chansonniersduquebec.com', 'root', '');

      }
      catch (Exception $e)
      {
        die('Erreur : ' . $e->getMessage());
      }

         // Insertion du message à l'aide d'une requête préparée
          $req = $bdd->prepare('INSERT INTO chansonniersduquebec.com (Nom) VALUES(?)');

          $req->bindParam(1, $nom);

          $nom = $_POST['Nom'];

          $req->execute();

  ?>

please, also make your input name and ID one word (Styles joués).


text:
Q: in Bixby input-view how do I match multiple concepts in a multicheckbox select I am asking the user to fill in a form that includes a multiple checkbox form element to provide true/false values for multiple concepts.
So I have a view like this:
input-view{
    match:PremiumContent

  message("Which of the following features do you need?")

    render{
    form{
      elements{
        checkbox{
          id(premiumcontent)
          type (PremiumContent)
          primary-text (Yes, I want to provide premium content.)
          secondary-text (We recommend providing a free tier.)
          value(true)
        }
        checkbox{
          id(searchabletext)
          type (SearchableText)
          primary-text (Yes, I want to provide searchable text.)
          secondary-text (Passages of one to three paragraphs work well.)
          value(true)
        }
        checkbox{
          id(twittersearch)
          type (TwitterSearch)
          primary-text (Yes, I want to pull permissioned Twitter results into my capsule.)
          secondary-text (AltBrains supports the full twitter search syntax.)
          value(true)
        }
         checkbox{
          id(carousel)
          type (Carousel)
          primary-text (Yes, I want an image gallery.)
          secondary-text (JPG or PNG at least 720 x 480.)
          value(true)
        }
      }
          on-submit{
        goal:PremiumContent
        value:viv.core.FormElement(premiumcontent)
      }
    }
  }
}

that would replace four individual view pages for PremiumContent, SearchableText, Carousel, and TwitterSearch. But I don't know how to construct the Match query.    How should I handle this?

A: I would try making a parent Boolean and then have each of PremiumContent, SearchableText, TwitterSearch, and Carousel either take the role of that parent boolean or extend it. You would then use that parent boolean in the match pattern.
So something like:
boolean (Parent) {}

and either
boolean (PremiumContent) {
  role-of (Parent)
}
boolean (SearchableText) {
  role-of (Parent)
}
...

or
boolean (PremiumContent) {
  extends (Parent)
}
boolean (SearchableText) {
  extends (Parent)
}
...

and then your match pattern would be:
match: Parent

and your on-submit should be something like:
on-submit {
  goal: Parent
  value-set: Parent {
    viv.core.FormElement (premiumcontent)
    viv.core.FormElement (searchabletext)
    ...
  }
}

Alternatively you could make a structure with the four different boolean properties and then use the structure in the match pattern. So something like:
structure (Thing) {
  property (premiumContent) {
    type (PremiumContent)
  }
  ...
}

And then your match pattern would be:
match: Thing

and then your on-submit would be:
on-submit {
  goal: Thing
  value: Thing {
    premiumContent: viv.core.FormElement (premiumcontent)
    ...
  }
}

A: Create a structure that contains all of the boolean as property.
Use the following as an example. Read more here
input-view {
  match: Person (this)

  message {
    template (Fill in your information)
  }

  render {
    form {
      // the intent that will be used when the form is submitted
      on-submit {
        goal: viv.tutorial.Person
        value: viv.tutorial.Person {
          wineClubJoined: viv.core.FormElement(wineclub)
          beerClubJoined: viv.core.FormElement(beerclub)
        }
      }
      elements {
        checkbox {
          id ("wineclub")
          type (WineClubJoined)
          primary-text (Join the wine club)
          secondary-text (We will invite you to our monthly wine events)
          value ("#{raw(this.wineClubJoined)}")
        }
        checkbox {
          id ("beerclub")
          type (BeerClubJoined)
          primary-text (Join the beer club)
          secondary-text (We will invite you to our monthly beer events)
          value ("#{raw(this.beerClubJoined)}")
        }

      }
    }
  }


text:
Q: AutoReconnect with multiple server uri's Consider the scenario where I have below code.
MqttConnectOptions connOpt = new MqttConnectOptions();
connOpt.setServerURIs(new String[]{"tcp://localhost:1883", "tcp://some-other-host:1883"});
connOpt.setAutomaticReconnect(true);
client.setCallback( new TemperatureSubscriber() );
client.connect(connOpt);

So when I say connect, it connects to localhost.
Then I get connection lost, due to say any reason. So at this point of time, since automaticReconnect is true, will it connect to localhost or some-other-host ?

A: Let me show how to find such answers yourself -
First you visit the Github repository for Paho source code.
Then you enter setAutomaticReconnect into the search field:

This is of course just the public name. You need to spot the corresponding private member.
In the MqttConnectOptions.java with the very simple code you find that member:
private boolean automaticReconnect = false;

Then you perform another search, this time for the automaticReconnect word:

And that leads you to the hint in the MqttAsyncClient.java file -
    // Insert our own callback to iterate through the URIs till the connect
    // succeeds
    MqttToken userToken = new MqttToken(getClientId());
    ConnectActionListener connectActionListener = new ConnectActionListener(this, persistence, comms, options,
            userToken, userContext, callback, reconnecting);
    userToken.setActionCallback(connectActionListener);
    userToken.setUserContext(this);

Finally, in the ConnectActionListener.java file you can confirm that the URLs are being tried one after each other:
  /**
   * The connect failed, so try the next URI on the list.
   * If there are no more URIs, then fail the overall connect.
   *
   * @param token the {@link IMqttToken} from the failed connection attempt
   * @param exception the {@link Throwable} exception from the failed connection attempt
   */
  public void onFailure(IMqttToken token, Throwable exception) {

    int numberOfURIs = comms.getNetworkModules().length;
int index = comms.getNetworkModuleIndex();
    ...
    ...
 comms.setNetworkModuleIndex(index + 1);


text:
Q: Camcorder and GPS together in App Inventor I am trying to record the position of the device continuously while capturing video. But as soon as the camcorder is invoked the GPS freezes at that point and updates only after the video capture has been complete. Is there a way to solve the same.
The aim is to record the track of the moving vehicle while capturing the video.
As soon as the video recording starts the Coordinates recorded in the file becomes stagnant and the last gets repeatedely stored in the file. The coordinates update only after the video recording is finished.

A: Store the lat/long values in a list instead of using the File component like this

As you can see from the Do it result, it works fine Note: I did not enable bluetooth for the test, so therefore I got 0,0...


text:
Q: What is the process of a UIViewController birth (which method follows which)? There are many methods to override, like initWithNibname:, awakeFromNib, loadView, viewDidLoad, viewDidAppear:, layoutSubviews, and I just cannot decide in which order gets these method called.
I just override one of them "by heart".
Any detailed explaination?

A: from Apple UIViewController documentation:

When you define a new subclass of UIViewController,  you must specify the views to be managed by the controller. There are two mutually exclusive ways to specify these views: manually or using a nib file.     If you specify the views manually, you must implement the loadView method and use it to assign a     root view object to the view property. If you specify views using a nib file, you must not      override loadView but should instead create a nib file in Interface Builder and then    initialize your view controller object using the initWithNibName:bundle: method. Creating views using a nib file is often simpler because you can use the Interface Builder application to create and configure your views graphically (as opposed to programmatically). Both techniques have the same end result, however, which is to create the appropriate set of views and expose them through the view property.

From the top of my head:

*

*initWithNibname

*loadView (load stuff manually)

*viewDidiLoad

*viewDidAppear

no clue where layoutSubviews enters

A: I revisited this lately and created a test project: https://github.com/Janek2004/ViewControllerTest
Run the project on the iOS simulator to see the order of execution of the UIViewController subclass methods.
Order might be different whenever we use Nib file instead of the storyboard or load view controller programmatically.

*

*-[ViewController initWithCoder:]  Unarchive data from nib or storyboard

*-[ViewController awakeFromNib] Prepares the receiver for service after it has been loaded from an Interface Builder archive, or nib
file.

*-[ViewController loadView]  You should never call this method directly. The view controller calls this method when its view
property is requested but is currently nil. This method loads or
creates a view and assigns it to the view property.

*-[ViewController viewDidLoad]  This method is called after the view controller has loaded its view hierarchy into memory.

*-[ViewController viewWillAppear:] This method is called before the receiver's view is about to be added to a view hierarchy and before
any animations are configured for showing the view.

*-[ViewController viewWillLayoutSubviews]  Called to notify the view controller that its view is about to layout its subviews.When a
view's bounds change, the view adjusts the position of its subviews.
Your view controller can override this method to make changes before
the view lays out its subviews.

*-[ViewController viewDidLayoutSubviews]  Called to notify the view controller that its view has just laid out its subviews. When the
bounds change for a view controller's view, the view adjusts the
positions of its subviews and then the system calls this method.
However, this method being called does not indicate that the
individual layouts of the view's subviews have been adjusted. Each
subview is responsible for adjusting its own layout.

*-[ViewController viewDidAppear:] Notifies the view controller that its view was added to a view hierarchy. You can override this method
to perform additional tasks associated with presenting the view.

*-[ViewController viewWillDisappear:] Notifies the view controller that its view is about to be removed from a view hierarchy.This
method is called in response to a view being removed from a view
hierarchy. This method is called before the view is actually removed
and before any animations are configured. Notifies the view
controller that its view was added to a view hierarchy. You can
override this method to perform additional tasks associated with
presenting the view.

*-[ViewController viewDidDisappear:]  Notifies the view controller that its
view was removed from a view hierarchy.

A: There is a lot going on behind the scenes with Cocoa view and viewController management.
1. The viewController object
At its most basic, a viewController is a generic controller object. When it is first allocated an initialized, it has no view object associated with it. The view is only instantiated when (and if) it is required. So, without considering the view, the lifecycle of a viewController is the same as any other object:
UIViewController * myVC = [[UIViewController alloc] initWith...];
...
[myVC release];

The designated initializer for viewControllers is -initWithNibname:bundle:. If you specify a nib, the viewController can automagically load its view from that nib and connect any IBOutlets that you have defined (see below for more details).
2. Loading and unloading the view
A viewController will load its view as required. This usually happens when the -view method is called for the first time, and can happen at any time in your program, depending on how you initialize your UI. The view may also be destroyed and reloaded several times during the lifetime of your program, agan depending on how you manage your UI. When the viewController has identified that its view is required but not yet loaded, the -loadView method will be called. The basic message flow goes something like this:
view
  loadView
  viewDidLoad

Note that if you override the -view method, -loadView and viewDidLoad will not be called automatically. If you override -loadView, you must set the viewController's view property. Otherwise, the next call to -view will trigger the loading process again.
The view may also be unloaded at any time during the lifetime of your program simply by setting the view property to nil. The default implementation of -didReceiveMemoryWarning will do this automatically, as long as the view does not have a superview (i.e. if it is not currently part of the active view heirarchy). The message flow goes as follows:
view = nil
   viewDidUnload

2a. Loading the view programmatically
If you choose to override -loadView, you can create a view, subviews, other viewControllers, and any connections between these objects in any way you please. Of course, this means that you are also responsible for memory management with respect to the objects that you create. If your subclass overrides -loadView, it should be initialized using nil for both nibName and bundle.
2b. Loading the view from a nib
If you use a nib file, the default implementation of -loadView will automatically open that nib file, instantiate its objects, add any connections between them, and take care of the memory management for you.
Things get a little more tricky with nib files, since so much happens behind the scenes. The -awakeFromNib method is called for every object that is instantiated when a nib file is loaded, and there is no guarantee that the other objects in the nib file will have been fully loaded when it is called.
3. Displaying views
-viewWillAppear:, -viewDidAppear:, -viewWillDisappear: and -viewDidDisappear: are only called when the view is being displayed or hidden on-screen, especially during animated transistions from one view to another. These methods may be called many times during the lifetime of your program, as views are swapped in and out in your navigation scheme.
4. View layout
The -layoutSubviews method is not part of UIViewController. It is called for UIView objects when their bounds have been changed. If you use a custom UIView subclass in your program, this method can be used to do custom subview layout instead of relying on Cocoa's default autoresizing methods.
5. Putting it all together
Because of the complexity, there are many different ways for this process to occur, but a normal timeline could look something like this:
-[viewController initWithNibname:Bundle:]
-[viewController awakeFromNib]
-[viewController loadView]
-[view awakeFromNib]
-[viewController viewDidLoad]
-[viewController viewWillAppear]
-[viewController viewDidAppear]
...
-[viewController viewWillDisappear]  // user navigated away
-[viewController viewDidDisappear]
...
-[viewController viewWillAppear]     // user navigated back
-[viewController viewDidAppear]
...
-[viewController viewWillDisappear]  // user navigated away
-[viewController viewDidDisappear]
...
-[viewController setView:nil]        // memory warning, perhaps
-[viewController viewDidUnload]
...
-[viewController loadView]           // user navigated back
-[view awakeFromNib]
-[viewController viewDidLoad]
-[viewController viewWillAppear]
-[viewController viewDidAppear]
...

A: Another key moment in the process is when layoutSubviews is called on any subviews.  It is at this point, and not any sooner, that any constraints configured in storyboard have been applied.  If you need to make any adjustments to subviews of a view, based on it's constrained coordinates, you have to do it in layoutSubviews.  If you do it in viewDidLayoutSubviews, that will be too soon, as those subviews have not yet had their constraints applied (because as the documentation says "Each subview is responsible for adjusting its own layout".)  And if you do it in viewDidAppear, that will be too late obviously, as the user will see your subviews change coordinates.  So, the other vital step in the process is:
-viewController viewWillAppear
-viewController viewWillLayoutSubviews
-viewController viewDidLayoutSubviews
---> viewController.[any subview] layoutSubviews
-viewController viewDidAppear

A: I generally solve this question by putting an NSLog (or breakpoints) in all of these delegates, including the app launch delegate, and following the order in the debugger.

A:
-- This is related to view only:
-viewWillAppear:
-viewDidAppear:
-viewWillDisappear: and
-viewDidDisappear:

are only called when the view is being displayed.

-viewController viewDidLoad
-viewController viewWillAppear
-viewController viewDidAppear

other methods

-viewController viewDidDisappear
-viewController viewWillDisappear
-viewController viewDidUnload

A: I want to thank e.James for his excellent description.  I cannot yet comment on a post, but for a quick visual illustration, refer to this flow chart in the View Controller programming guide.  And I realize that this is off-topic, but for a graph of the app launch sequence, refer to the iOS Application Programming Guide.


text:
Q: Fragment null pointer exception when using viewPagerInstance.setCurrentItem(int position) I have 10 Fragment lists. I am able to swipe and update value of current Fragment. At top of each Fragment i have a list of number like page1, page2, page3...page15
so now i am also want to jump in clicked page fragment. so i am using
viewPagerInstance.setCurrentItem(int position)

it works if i jump left of right page of current page. but if i clicked on another page like as i am in page2 and want to go page10. it give me null pointer exception.
i got null error in my resources ( button). is onCreateView working correctly? because all resource has already initialized. so it should not be null.
please help expert
my adapter
public class MyPageAdapter extends FragmentStatePagerAdapter {
private List<Fragment> fragments;

public MyPageAdapter(FragmentManager fm, List<Fragment> fragments) {
    super(fm);
    this.fragments = fragments;
}

@Override
public Fragment getItem(int position) {
    return this.fragments.get(position);
}

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

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

    mView = inflater.inflate(R.layout.scorecardtabswingfragment,
            container, false);

    puttsBtnList = new ArrayList<Button>();
    puttsBtnList.add((Button) mView.findViewById(R.id.puttsBtn0));
    puttsBtnList.add((Button) mView.findViewById(R.id.puttsBtn1));
    puttsBtnList.add((Button) mView.findViewById(R.id.puttsBtn2));
    puttsBtnList.add((Button) mView.findViewById(R.id.puttsBtn3));
    puttsBtnList.add((Button) mView.findViewById(R.id.puttsBtn4));
    puttsBtnList.add((Button) mView.findViewById(R.id.puttsBtn5));
    puttsBtnList.add((Button) mView.findViewById(R.id.puttsBtn6));
    puttsBtnList.add((Button) mView.findViewById(R.id.puttsBtn7));
    puttsBtnList.add((Button) mView.findViewById(R.id.puttsBtn8));
    puttsBtnList.add((Button) mView.findViewById(R.id.puttsBtn9));
    puttsBtnList.add((Button) mView.findViewById(R.id.puttsBtn10));
    puttsBtnList.add((Button) mView.findViewById(R.id.puttsBtn11));
    puttsBtnList.add((Button) mView.findViewById(R.id.puttsBtn12));

    holeTitle = new TextView[18];
    holeTitle[0] = (TextView) mView.findViewById(R.id.tv_hole1);
    holeTitle[1] = (TextView) mView.findViewById(R.id.tv_hole2);
    holeTitle[2] = (TextView) mView.findViewById(R.id.tv_hole3);
    holeTitle[3] = (TextView) mView.findViewById(R.id.tv_hole4);
    holeTitle[4] = (TextView) mView.findViewById(R.id.tv_hole5);
    holeTitle[5] = (TextView) mView.findViewById(R.id.tv_hole6);
    holeTitle[6] = (TextView) mView.findViewById(R.id.tv_hole7);
    holeTitle[7] = (TextView) mView.findViewById(R.id.tv_hole8);
    holeTitle[8] = (TextView) mView.findViewById(R.id.tv_hole9);
    holeTitle[9] = (TextView) mView.findViewById(R.id.tv_hole10);
    holeTitle[10] = (TextView) mView.findViewById(R.id.tv_hole11);
    holeTitle[11] = (TextView) mView.findViewById(R.id.tv_hole12);
    holeTitle[12] = (TextView) mView.findViewById(R.id.tv_hole13);
    holeTitle[13] = (TextView) mView.findViewById(R.id.tv_hole14);
    holeTitle[14] = (TextView) mView.findViewById(R.id.tv_hole15);
    holeTitle[15] = (TextView) mView.findViewById(R.id.tv_hole16);
    holeTitle[16] = (TextView) mView.findViewById(R.id.tv_hole17);
    holeTitle[17] = (TextView) mView.findViewById(R.id.tv_hole18);

    for(ImageButton b: firBtnList) {
        b.setOnClickListener(this);
    }

    for(Button b: penaltyBtnList) {
        b.setOnClickListener(this);
    }

    for(Button b : puttsBtnList) {
        b.setOnClickListener(this);
        }

    for(Button b : storksBtnList) {
    b.setOnClickListener(this);
    }

    for(TextView tv : holeTitle) {
        tv.setOnClickListener(this);
    }
    gpsBtn.setOnClickListener(this);

    toggleBtnPlayed.setOnClickListener(this);
    //TextView tv_hole = (TextView) mView.findViewById(R.id.tv_hole);
    //tv_hole.setText("Hole:"+getArguments().getInt("holeNum"));

    doneBtn.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View paramView) {

            if(APIUtil.isNeedForUpdate)
                //update hole Golfer Scorecard.
                new UpdateHoleGolferScorecard(APIUtil.holeno_Update, APIUtil.score_Update,
                        APIUtil.fir_Update, APIUtil.gir_Update, APIUtil.played_Update, APIUtil.putts_Update).execute();

            getActivity().finish();
            Intent intent = new Intent(getActivity(), ScorecardsActivity.class);
            intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            startActivity(intent);
        }
    });

    swingBtn = (Button) mView.findViewById(R.id.swingBtn);
    swingBtn.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {

        }
    });

    return mView;
}

update
i am using setMenuVisibility of visible property. i think it is calling first and after that onActivityCreated(). I putt my all code into onActivityCreated() and working now. resource is initialized. but is it possible call
onActivityCreated first and after that setMenuVisibility. because for some reason i used it.

A: Finally Solved my problem.
mViewPager.setOffscreenPageLimit(17);

i loaded my all pages.
I am using setMenuVisibility() because i don't want to load previous and next page update. i want to load my current page only. so it called first when page changed.


text:
Q: How can I recover text from the Snap app 'Notes'? How can I recover text from the Snap app 'Notes'?
After some nearby lightning the motherboard is toast...but the SSD is intact. Other files are OK, but I have lost all my current notes which were in the little snap app 'Notes' by Ruby Mamistvalove.
I've looked here :
volume de 500 GB home / joe / snap / notes
but the 3 folders are empty - 4, common and current. Is this where the app would normally store text or am I looking in the wrong place?
On a new PC I've now installed Ubuntu 22.04.1 LTS and started the Snap app 'Notes' but it doesn't show the old texts! Thanks for any help you can give.

A: The notes are stored in a text file here:
~/snap/notes/current/.config/Awesomeness/Notes.ini


text:
Q: How to attach Jar in Blackberry Now days I am getting a problem in attaching JAR files in Blackberry.....
I am using Eclipse 3.5 and I am using Facebook Jar SDK , in my Application.
I am doing the following things for attach the Jar in my Application

*

*Copy the Jar in my Application Resources

*Right Click on MyProject "Properties" , then a window appear I select "Java Buid Path" and select "Libraries"  and select "Add JAR" option ...and last I give the path of Jar wher I put it.

*And Go to "Order and Export"  and select the Added Jar (Check Mark ), then press Ok

Application compiles fine , but when I click on Application Icon it gives me Message Verification code error in particular Module
Why this Error come .. please explain me
Thanks

A: The step you are missing is called "preverifying" the jar file.
There is a very good answer on how to run preverify.exe at this link: Blackberry 5.0 - Add reference to a Java Library Project.
Other related posts are:

*

*Blackberry: Verificattion error when using Library project as External Jar

*http://supportforums.blackberry.com/t5/Java-Development/quot-Project-0-has-to-have-a-jad-file-file-if-it-exports-a/ta-p/502501

*http://ahmadferdous.blogspot.com/2009/03/how-to-import-kxml-jar-file-to-your.html


text:
Q: Зачем нужен return при повторном вызове функции из кода? Есть функция, которая перемножает цифры одного числа до тех пор, пока не получится однозначное число.
Пример:

999 --> 2
9*9*9 = 729
7*2*9 = 126
1*2*6 = 12
1*2 = 2

Я написал функцию, но она почему-то возвращает значение undefined:
function persistence(num) {
    num = String(num);
    let newNum = 1;
    for (i = 0; i < num.length; i++) {
        newNum = newNum * Number(num[i]);
    };
    if (newNum > 9) {
        persistence(newNum);
    } else {
        return newNum;
    }
 }

Путем долгих проб я нашел решение:
function persistence2(num) {
    num = String(num);
    let newNum = 1;
    for (i = 0; i < num.length; i++) {
        newNum = newNum * Number(num[i]);
    };
    if (newNum > 9) {
        return persistence2(newNum);
    } else {
        return newNum;
    }
 }

Здесь добавлен еще один return в момент перезапуска функции при обнаружении двузначного числа, но зачем там нужен этот return я до сих пор понять не могу, можете мне объяснить, прочему оно работает.

A: Чтоб понять, что идет не так в функции persistence давайте мысленно её продебажим:

*

*Подадим ей на вход число 25.

*После цикла в newNum будет число 10

*10 больше 9, значит мы будем делать persistence(newNum);

*Далее мы снова попадаем в нашу функцию, на вход пришло 10

*Считаем произведение, получаем 0

*0 меньше, чем 9, тогда мы возвращаем 0

*Вернулись к первому вызову.

И тут вы должны были понять, где проблема. Когда мы вернулись обратно, мы никуда не присвоили значение, полученное из функции.
Мало того, далее мы просто вышли из неё т.к. после вызова persistence(newNum); нет никакого кода.
Однако что же тогда вернет наша функция? А ничего она не вернет, что вы и получили.
Во втором же варианте, когда в newNum хранится число больше 9, оно в любом случае вернет его обратно и так, обратной рекурсией дойдет до места, где вы вызывали функцию.
На случай, если вы всё еще не поняли в чем проблема, попробуйте посидеть с дебагером, поэтапно разбирая что делает код (рекомендую взять число 999 т.к. там много итераций, где можно посмотреть на работу программы и число 24 т.к. там будет всего 1 итерация)


text:
Q: Limit users from pushing/pulling specific Docker images in AWS ECS Repo Is there a way to give users permission only to push/pull specific Docker images they own in AWS ECS Repo?

A: By this time you might have the solution, but sharing some info here:
Consider 2 users with the following permissions:
ecr-user with policy ARN:  arn:aws:iam::aws:policy/AdministratorAccess who have admin permissions for all resources in AWS:
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": "*",
            "Resource": "*"
        }
    ]
}

vault-user with policy ARN :arn:aws:iam::aws:policy/service-role/AmazonECSTaskExecutionRolePolicy who has limited permissions:
{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Effect": "Allow",
            "Action": [
                "ecr:GetAuthorizationToken",
                "ecr:BatchCheckLayerAvailability",
                "ecr:GetDownloadUrlForLayer",
                "ecr:BatchGetImage",
                "logs:CreateLogStream",
                "logs:PutLogEvents"
            ],
            "Resource": "*"
        }
    ]
}

You can get this info from IAM->Users and click on the Policy name attached to the user.
Consider below 2 repositories which are associated with users ecr-user and vault-user

the repo ecr-permissions is linked with ecr-user with the following permissions:
{
  "Version": "2008-10-17",
  "Statement": [
    {
      "Sid": "denyAdmin",
      "Effect": "Deny",
      "Principal": {
        "AWS": "arn:aws:iam::****:user/ecr-user"
      },
      "Action": [
        "ecr:BatchGetImage",
        "ecr:DescribeImages",
        "ecr:ListImages",
        "ecr:PutImage",
        "ecr:PutLifecyclePolicy",
        "ecr:UploadLayerPart"
      ]
    }
  ]
}

So with the above policy, you can even restrict admin user(ecr-user) to push to this repo.
$ docker push ****.dkr.ecr.us-east-1.amazonaws.com/ecr-permissions:1.0
The push refers to repository [****.dkr.ecr.us-east-1.amazonaws.com/ecr-permissions]
fe6a7a3b3f27: Layer already exists
d0673244f7d4: Layer already exists
d8a33133e477: Layer already exists
denied: User: arn:aws:iam::****:user/ecr-user is not authorized to perform: ecr:UploadLayerPart on resource: arn:aws:ecr:us-east-1:****:repository/ecr-permissions with an explicit deny

Similarly, you can allow non-admin/user[in this case vault-user] with read-only permission on ECR repo can push docker images by tuning the ECR repo policies as shown below.

{
  "Version": "2008-10-17",
  "Statement": [
    {
      "Sid": "pushDocker",
      "Effect": "Allow",
      "Principal": {
        "AWS": "arn:aws:iam::****:user/vault-user"
      },
      "Action": [
        "ecr:BatchCheckLayerAvailability",
        "ecr:BatchGetImage",
        "ecr:CompleteLayerUpload",
        "ecr:GetDownloadUrlForLayer",
        "ecr:InitiateLayerUpload",
        "ecr:PutImage",
        "ecr:UploadLayerPart"
      ]
    }
  ]
}

Before adding the above policy:

$ docker push ****.dkr.ecr.us-east-1.amazonaws.com/rlokinen/first-ecr:0.3
The push refers to repository [****.dkr.ecr.us-east-1.amazonaws.com/rlokinen/first-ecr]
fe6a7a3b3f27: Layer already exists
d0673244f7d4: Layer already exists
d8a33133e477: Layer already exists
denied: User: arn:aws:iam::****:user/vault-user is not authorized to perform: ecr:InitiateLayerUpload on resource: arn:aws:ecr:us-east-1:****:repository/rlokinen/first-ecr

after adding the policy:

$ docker push ****.dkr.ecr.us-east-1.amazonaws.com/rlokinen/first-ecr:0.3
The push refers to repository [****.dkr.ecr.us-east-1.amazonaws.com/rlokinen/first-ecr]
fe6a7a3b3f27: Layer already exists
d0673244f7d4: Layer already exists
d8a33133e477: Layer already exists
0.3: digest: sha256:dc85890ba9763fe38b178b337d4ccc802874afe3c02e6c98c304f65b08af958f size: 948

These policies are defined per REPO in ECR. ECR->Repositories-><REPO-NAME>permissions.

A: You can configure IAM users within your account to push and pull images.
{
  "Version": "2008-10-17",
  "Statement": [
    {
      "Sid": "AllowPushPull",
      "Effect": "Allow",
      "Principal": {
        "AWS": [
          "arn:aws:iam::aws_account_id:user/push-pull-user-1",
          "arn:aws:iam::aws_account_id:user/push-pull-user-2"
        ]
      },
      "Action": [
        "ecr:GetDownloadUrlForLayer",
        "ecr:BatchGetImage",
        "ecr:BatchCheckLayerAvailability",
        "ecr:PutImage",
        "ecr:InitiateLayerUpload",
        "ecr:UploadLayerPart",
        "ecr:CompleteLayerUpload"
      ]
    }
  ]
}

Reference: documentation


text:
Q: NSUserDefaults work different on Iphone and Simulator I'm using NSUserDefaults to save an integer on another view controller so that when this one is pushed I know which image to use. For some reason the simulator only uses image1 while my phone only uses image2. What can I do?
if ([[NSUserDefaults standardUserDefaults] integerForKey:@"key"] == 1){

    leftStill = [UIImage imageNamed:@"image1.png"];

}

if ([[NSUserDefaults standardUserDefaults] integerForKey:@"key"] == 2) {

    leftStill = [UIImage imageNamed:@"image2.png"];

}

[imageView setImage:leftStill];

A: Did you call - (BOOL)synchronize; after setting the value in NSUserDefaults?

A: Are you starting with a nil/unallocated leftImage and imageView before this code block?
Since you're testing an integer value, I wonder if the following code might not work better for you, potentially avoiding not only the two readings of the value that your code is currently doing, which might be the cause of the issue, but also the use of the intermediary holder leftImage itself:
switch([[NSUserDefaults standardUserDefaults] integerForKey:@"key"]) {
  case 1:
    [imageView setImage:[UIImage imageNamed:@"image1.png"];
    break;
  case 2:
    [imageView setImage:[UIImage imageNamed:@"image2.png"];
    break;
  default:
    break;
}

A: You would do something like the following when you store the value in NSUserDefaults:
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setInteger:1 forKey:@"key"];
[defaults synchronize];

The synchronize does happen periodically on its own but you have no guarantee when it will happen.  So I usually synchronize any time I am setting a value for a key in NSUserDefaults.
You may want to also consider something better suited for the task you are trying to accomplish, like using prepareForSegue.


text:
Q: run Ms Fakes unit test on jenkins build server without installing visual studio? How to run Ms Fakes Unit test on Jenkins without installing Visual Studio?
Which DLLs are required from visual studio setup to run Fakes unit test on Jenkins Build Server?
We have tried to use VSTest.Console.exe for  ms fakes unit test, but on Jenkins it is giving error that "UnitTestIsolation instrumentation failed to initialize. Please restart Visual Studio"

A: You would need to install VS Ultimate and Premium to run Fakes


text:
Q: Parsing rules file, c# regex not seeing pattern I have taken my regex from python and try to make work in c#, while i get no errors, it does not display any output and during debug, i do not see the output varible get populated with any data, here is snippet:
StringWriter strwriter = new StringWriter();
rule = sr.ReadLine();
do
{
    Regex action = new Regex(@"^#\w+(?<action>(alert)\\s+(tcp|udp)\\s+(.*?)\\('*}))");
    Regex message = new Regex("(?<msg>[\\s(]*\\((.*)\\)[^)]*$)", RegexOptions.IgnorePatternWhitespace);
    Regex content = new Regex("(?<content>[\\s(]*\\((.*)\\)[^)]*$)", RegexOptions.IgnorePatternWhitespace);
    Match result = action.Match(rule);
    //String repl = Regex.Replace(rule, "[\\;]", ",");
    //Match mat = action.Match(repl);
    Console.WriteLine(result.Groups["action"].Value);
    //writer.WriteLine(result.Groups["action"].Value + "," + result.Groups["msg"].Value + "," + result.Groups["content"].Value + "," + result.Groups["flow"].Value + "," + result.Groups["ct"].Value + "," + result.Groups["pcre"].Value + "," + result.Groups["sid"].Value);
} while (rule != null);

result does not show anything, what have i missed, these are almost the same one that i have working in the python script.

A: Since you're using string literals for the first regex, don't double escape!
^#\w+(?<action>(alert)\\s+(tcp|udp)\\s+(.*?)\\('*}))
                      ^            ^        ^

=>
^#\w+(?<action>(alert)\s+(tcp|udp)\s+(.*?)\('*}))

With the input, there were a couple of more things wrong with the regex and this one should bring you in the right direction:
^#\s*(?<action>alert\s+(?:tcp|udp)\s+(.*?)\([^)]*\))

regex101 demo
If you don't want the part within parentheses, you can omit the last part:
^#\s*(?<action>alert\s+(?:tcp|udp)\s+(.*?)\()


text:
Q: Need help to decide about datastructure of my project I try to index lots of words and group them in different files. I mean for each alphabet character I consider a file, like a.txt,b.txt,...
My idea is this structure but I am looking for better strcucture because for each hashmap's key (word) has one file and no need to have other hashmap.
HashMap<String, HashMap<String,ArrayList<Posting>>>

for example
 HashMap<"book", HashMap<"b.txt",ArrayList<Posting>>>
 HashMap<"baby", HashMap<"b.txt",ArrayList<Posting>>>

A: Why do you need a nested hashmap? You can always conclude the file name from the word itself. Alternatively - wrap the word and file name in the object that will be used as a key in single level hashmap.


text:
Q: Delay between requests in Apify Apify's legacy Crawler had a randomWaitBetweenRequests option :

This option forces the crawler to ensure a minimum time interval between opening two web pages, in order to prevent it from overloading the target server.

Do Apify Actors have a similar setting ?  If so, how does it impact the Actor Units computation ?

A: There are no options like that in apify/web-scraper, which should replace legacy crawler option.
But there is a way how to implement this yourself in pageFunction. You can simply use context.waitFor() function and pass there random time in ms.
async function pageFunction(context) {
    const { request, log, jQuery } = context;

    // To be able to use jQuery as $, one needs save it into a variable
    // and select the inject jQuery option. We've selected it for you.
    const $ = jQuery;
    const title = $('title').text();

    log.info(`URL: ${request.url} TITLE: ${title}`);

    // This waits time in ms, which getRandomWait returns.
    await context.waitFor(getRandomWait());

    // To save data just return an object with the requested properties.
    return {
        url: request.url,
        title
    };
}

If you want to have this option in apify/web-scraper, you can submit an issue on GitHub repo.


text:
Q: Determining if two line segments intersect with a tolerance I'm using this code that was posted as an answer to this question: How do you detect where two line segments intersect?
It is my understanding that this function only returns an intersection point if the two line segments exactly intersect. I need to modify this function to include a tolerance so it returns an intersection point if the line segments nearly intersect (i.e. within a 0.01 range). I don't really understand the maths that underpins this function so I was hoping that someone could help.
Thanks
// Returns 1 if the lines intersect, otherwise 0. In addition, if the lines
// intersect the intersection point may be stored in the floats i_x and i_y.
char get_line_intersection(float p0_x, float p0_y, float p1_x, float p1_y,
    float p2_x, float p2_y, float p3_x, float p3_y, float *i_x, float *i_y)
{
    float s1_x, s1_y, s2_x, s2_y;
    s1_x = p1_x - p0_x;     s1_y = p1_y - p0_y;
    s2_x = p3_x - p2_x;     s2_y = p3_y - p2_y;

    float s, t;
    s = (-s1_y * (p0_x - p2_x) + s1_x * (p0_y - p2_y)) / (-s2_x * s1_y + s1_x * s2_y);
    t = ( s2_x * (p0_y - p2_y) - s2_y * (p0_x - p2_x)) / (-s2_x * s1_y + s1_x * s2_y);

    if (s >= 0 && s <= 1 && t >= 0 && t <= 1)
    {
        // Collision detected
        if (i_x != NULL)
            *i_x = p0_x + (t * s1_x);
        if (i_y != NULL)
            *i_y = p0_y + (t * s1_y);
        return 1;
    }

    return 0; // No collision
}

EDIT: for clarification, the image below depicts the sort of scenario whereby two line segments would nearly intersect.
Nearly intersecting lines - image

A: I am not a graphics expert, but this is what I would do:
For each endpoint: See if a circle centered on the endpoint with a radius of threshold intersects the other line segment. Then the lines nearly intersect.

A: It's still not clear precisely what you want to count as a "near intersection". In your example image you could find an intersection by extending each line (in both directions) by the chosen tolerance amount, and then checking for an (exact) intersection between the extended lines.
If you want to detect intersections of lines at more acute angles, you could expand each line into a rectangular area (with a width determined by the tolerance) and then check for overlap between the rectangular regions.
In both cases the tolerance amount would mean something slightly different. You didn't define it in your question. What precisely does the tolerance value mean? Is it the amount by which one of the lines needs to be extended to form an intersection with the other? Is it a maximum distance between any point on each line that can be considered an intersection? etc.


text:
Q: connected to wifi but no internet, network-manager restart temporarily resolves this problem Since some time I am having this issue with my wifi connection. The wifi is connected and I am browsing the internet but the suddenly there is no internet access any more and the wifi symbol shows connected but no internet access. This problem appears randomly sometimes right after start sometimes not at all for hours. The first time when this problem appeared it occurs very rarely. But recently it is happening every 30 seconds.
Every time I get no connection I use the command:
sudo service network-manager restart

After the network-manager has restarted the connection works again until the connection is lost once more. The intervals of loosing the connection are becoming smaller and smaller. Sometimes I have to restart the manager 10 times in 10 minutes but then suddenly the connection wont break any more and it works for hours.
I have tried a lot of different things from other questions here in this forum but nothing has solved the problem. Other computers in the network do not have this problem.
I don't know how to narrow it down, now. Is there anything I can do to check? This is what I have checked so far:

*

*When the error occurs, I can not ping ip addresses.

*I have checked
this but it seems to be another problem:
connected to wifi but no internet - ubuntu 18.04
Would you recommend to reinstall the network-manager?
Thanks for your help :)


text:
Q: Mono.switchIfEmpty with Mono.then evaluation order I build the reactive pipeline like this on netty server with spring web-flux:
someService.getSettings(key) //Mono<Settings>
        .filter(Settings::isEnabled)
        .switchIfEmpty(Mono.error(
            new Exception("Setting is disabled.")
        )).then(/*Mono representing API fetch*/ someApi.fetch(param));

As per my understanding, whenever the Settings::isEnabled would return false, the pipeline would be empty and I will get a Mono representing error. However, this behavior does not happens. My someApi.fetch(param) call always fires without the filter Mono being completed. So even if Settings::isEnabled is false or true, someApi.fetch(param) is always fired without completion of Mono.filter.
How do I make sure that error is thrown if filter returns empty Mono and the fetch call happens only when I have checked that the setting is not disabled?

A: this is still java: this call to someApi.fetch(param) is not done inside a lambda, so it can't be lazy. the moment the execution reaches the then line, your fetch method is called. the Flux.defer operator is tailor-made to wrap that call and make it lazy.


text:
Q: OMDB API: Any way to specify a *minimum* year on a movie title query? I'm loving the OMDB API but one issue I'm having is that sometimes during a title query, an older movie will be returned instead of the one I'm looking for.
For example, there's a movie called "Eye in the Sky" coming out in 2016. But when I query http://www.omdbapi.com/?t=eye+in+the+sky&type=movie, I get an older movie from 2007.
But I'm also not sure what the exact year is of the movie I'm looking for (only that it will be at least 2014). Is there any way to set a minimum year for this type of thing? How would you handle this?

A: please use url as http://www.omdbapi.com/?t=eye+in+the+sky&type=movie&year=2016, instead of http://www.omdbapi.com/?t=eye+in+the+sky&type=movie.


text:
Q: Can USB data transfer between Arduino and Android with the 5V power line disconnected still work? I am using an Android tablet to talk to an Arduino board in a project which will need to run for many hours. It is all being powered off one lead acid 12V battery.
I would like to run the Android off its own power line so I would have the D+ and D- and GND connected straight to the Arduino and the power coming from another reg (of course both using same ground). This is to ensure that I can send enough current to power the Android.
But I also want to have a switch (maybe a FET or even relay or what not) in between which can cut off the power all together to the Android and still maintain a data connection. So that I can even further save power by running the Android to a lower power threshold until I begin charging it.
Is this possible?

A: It is not unusual to have a USB device draw its power from a source other than the USB connection; such a configuration is called "self-powered" and the device's datasheet will give the exact schematic, components, and sometimes even PCB layout to make such a thing possible. It is resistances placed on the D+ and D- lines that announce presence rather than any connection to the 5V line.


text:
Q: why css3 calc doesn't work for height of div I'm trying to use calc() to set my content's height to 100% - 50px, however it doesn't work as expected.
here is my fiddle file
I cannot figure out why, can anyone please help?

A: The issue is the body margin, just zero it out and you should get the desired layout:

body {
  height:100%;
  margin:0;
}
html{
  height:100%;
}
#content{
    height: -moz-calc(100% - 50px);
    height: -webkit-calc(100% - 50px);
    height:calc(100% - 50px);
    background:blue;
    overflow-y:scroll;
}
footer {
    position:fixed;
    bottom:0;
    width:50%;
    height:50px;

    background-color:green;
}

fsdfsa
    fsadf
    as
    fas
    df
    asdf
    saf
    afsdfsa
    fsadf
    as
    fas
    df
    asdf
    saf
    afsdfsa
    fsadf
    as
    fas
    df
    asdf
    saf
    afsdfsa
    fsadf
    as
    fas
    df
    asdf
    saf
    afsdfsa
    fsadf
    as
    fas
    df
    asdf
    saf
    afsdfsa
    fsadf
    as
    fas
    df
    asdf
    saf
    afsdfsa
    fsadf
    as
    fas
    df
    asdf
    saf
    afsdfsa
    fsadf
    as
    fas
    df
    asdf
    saf
    afsdfsa
    fsadf
    as
    fas
    df
    asdf
    saf
    afsdfsa
    fsadf
    as
    fas
    df
    asdf
    saf
    afsdfsa
    fsadf
    as
    fas
    df
    asdf
    saf
    afsdfsa
    fsadf
    as
    fas
    df
    asdf
    saf
    afsdfsa
    fsadf
    as
    fas
    df
    asdf
    saf
    afsdfsa
    fsadf
    as
    fas
    df
    asdf
    saf
    afsdfsa
    fsadf
    as
    fas
    df
    asdf
    saf
    afsdfsa
    fsadf
    as
    fas
    df
    asdf
    saf
    afsdfsa
    fsadf
    as
    fas
    df
    asdf
    saf
    afsdfsa
    fsadf
    as
    fas
    df
    asdf
    saf
    afsdfsa
    fsadf
    as
    fas
    df
    asdf
    saf
    afsdfsa
    fsadf
    as
    fas
    df
    asdf
    saf
    afsdfsa
    fsadf
    as
    fas
    df
    asdf
    saf
    afsdfsa
    fsadf
    as
    fas
    df
    asdf
    saf
    afsdfsa
    fsadf
    as
    fas
    df
    asdf
    saf
    afsdfsa
    fsadf
    as
    fas
    df
    asdf
    saf
    afsdfsa
    fsadf
    as
    fas
    df
    asdf
    saf
    afsdfsa
    fsadf
    as
    fas
    df
    asdf
    saf
    afsdfsa
    fsadf
    as
    fas
    df
    asdf
    saf
    afsdfsa
    fsadf
    as
    fas
    df
    asdf
    saf
    afsdfsa
    fsadf
    as
    fas
    df
    asdf
    saf
    afsdfsa
    fsadf
    as
    fas
    df
    asdf
    saf
    afsdfsa
    fsadf
    as
    fas
    df
    asdf
    saf
    afsdfsa
    fsadf
    as
    fas
    df
    asdf
    saf
    afsdfsa
    fsadf
    as
    fas
    df
    asdf
    saf
    afsdfsa
    fsadf
    as
    fas
    df
    asdf
    saf
    afsdfsa
    fsadf
    as
    fas
    df
    asdf
    saf
    afsdfsa
    fsadf
    as
    fas
    df
    asdf
    saf
    afsdfsa
    fsadf
    as
    fas
    df
    asdf
    saf
    afsdfsa
    fsadf
    as
    fas
    df
    asdf
    saf
    afsdfsa
    fsadf
    as
    fas
    df
    asdf
    saf

this is not last line

last line

    i am footer

A: you also have to add 100% height to your html:
html {height:100%;}


text:
Q: In Scala, multiple objects with main method can be present in a single file and run individually . What is the reason behind this? I wrote below code in scala 3 in a single file
@main def main11 =
  println("main11 printed something")

object Main10 extends App {
  println("Main10 Executed !!".toUpperCase())
  main11
}

object Main2  {
  def main(args: Array[String]): Unit = {
    println("Main2 can run too !!".toUpperCase())
    Main10
  }
}

It compiles fine and I can run any of these main11 Main2 Main10 in the IDE.
What is reason for this ?
Eg.
main11 output :
main11 printed something

Main2 output :
 MAIN2 CAN RUN TOO !!
 MAIN10 EXECUTED !!
 main11 printed something

Usually in other languages I see 1 main class in 1 file.

A: Scala has idiomatic concepts which require multiple classes/objects/traits within the same file such as

*

*companion objects

*algebraic data types

However in general it is not best practice to define arbitrary multiple classes/objects/traits within the same file unless they are tightly related. The fact that your objects happen to have each a main method is not relevant as it is just considered a regular method.


text:
Q: Is there a defined operator or notation for a row by row scalar product of column vector and matrix? Is there a defined operator or notation for a row by row scalar product of column vector and matrix?
For example if
$$
\vec{x} = \begin{pmatrix} 2 \\ 3 \end{pmatrix}, \ \ \ \  A = \begin{pmatrix} a & b &
 c\\ d & e & f \end{pmatrix}
$$
Then using this operator product would be
$$
\vec{x} \odot A = \begin{pmatrix} 2a & 2b & 2c\\ 3d & 3e & 3f \end{pmatrix}
$$
Note that this is equivalent to Hadamard product if $x$ was repeated to match the columns of $A$:
$$ \begin{pmatrix} \vec{x} & \vec{x} & \vec{x} \end{pmatrix}  \circ A $$
I tried using the outer product of vectors as well as the it's generalization the Kronecker product, but I couldn't seem to replicate the exact behavior.
Thanks in advance,
Also not sure how to properly tag this, so I'm going to leave this with the tag of Tensor Products.

A: Define a new tensor $\delta_{ijk}$ such that
$$\delta_{ijk}=\begin{cases}
1&\text{if}\;i=j=k\\
0&\text{otherwise}\\
\end{cases}$$
where $i$, $j$ and $k$ range over the number of rows of your matrix. Then in the summation convention:
$$(\vec x\odot A)_{il}=\delta_{ijk}x_jA_{kl}$$


text:
Q: Error when cloning a project from GitLab, but not when cloning a project from GitHub I am maintaining several different projects on both GitHub (public) and GitLab (private).
For some reason, I recently started getting an error when cloning my projects on GitLab:
The project you were looking for could not be found

I get the same error when trying to push or pull.
It used to work for one of my GitLab projects up until recently, when I encountered an error my other GitLab project, tried to resolve it, and ended up getting this error both of them.
I don't get this error on any of my GitHub projects.
Here are the URLs that I am using:

*

*GitHub: https://github.com/path_to/my_project1.git

*GitLab: https://gitlab.com/path_to/my_project2.git
For a Git client, I am using TortoiseGit-2.5.0.0-64bit.
Side note:
Perhaps my problem is that there are several entities here which I am really unable to understand the hierarchy between them:

*

*TortoiseGIT (locally)

*Git for Windows (locally)

*GitHub / GitLab (remotely)

I guess I should configure my credentials (username, password and perhaps SSH public/private keys) somewhere, but I'm not really sure where.
I tried both on TortoiseGIT, and in my account on GitLab.


text:
Q: Why are these two definitions of a trading strategies as discrete processes equivalent? This is my first time asking a question here, so please tell me if there is something I should ask differently.
We are in the setting of $(\mathbb R^n, \mathcal F, \mathbb Q)$ being a probability space, and $(S_t)_{t=1}^n$ where $S_t \colon \mathbb R^n \rightarrow R, (x_1,\ldots ,x_n) \mapsto x_t$ being a martingale  in its own filtration denoted $(\mathcal F_t)_{t=1}^n$.
Now I am finding two definitions for a trading strategy:

*

*A trading strategy $ (\xi_t)_{t=1}^n $ is a predictable process, meaning that $\xi_t $ is $\mathcal F_{t-1}$-measurable,

*A trading strategy $ \Delta = ( \Delta_{t} )_{t=0}^{n-1} $ consists of bounded Borel measurable functions $\Delta_t\colon \mathbb R^t \rightarrow \mathbb R$ where $0\leq t < T$.

The explanation given for equivalence was that for a discrete process $(\xi_t)_{t=1}^n$  it holds that $(\xi_t)_t$ is predictable in the first sense if and only if $\xi_t \overset{\mathbb Q\text{-a.s.}}{=} \Delta_{t-1} (x_1,\ldots ,x_{t-1}) $ for some bounded measurable functions $\Delta_t\colon \mathbb R^t\rightarrow \mathbb R$. Again the filtration is the natural filtration of the coordinate process.
The backwards implication is clear (at least I hope I'm not making a mistake by thinking it is) and the forward implication  is supposed to follow from some basic transformation lemma, however the only one I'm finding is the martingale transformation, with which I don't see a solution.
My question is why are the two definitions equivalent, and if it is indeed by the explanation given above, which transformation lemma is used and how?


text:
Q: Spring Boot Batch ResourcelessTransactionManager DataSourceProperties$DataSourceBeanCreationException I'm trying to setup a spring boot batch project that uses a ResourcelessTransactionManager transaction manager using Java Configuration, but I'm having no luck.
The reason I am trying to do this is that I don't want any state persisted, and I'd prefer not to waste memory with hsqldb if I don't want it to begin with.  I have an existing Spring Batch project that is not using Spring Boot, and it is working with no persistance and without hsqldb.
I'm using this sample project as the base (but with hsqldb removed), and this other answer as a reference but I keep getting this exception:
Caused by: org.springframework.boot.autoconfigure.jdbc.DataSourceProperties$DataSourceBeanCreationException: Cannot determine embedded database driver class for database type NONE. If you want an embedded database please put a supported one on the classpath. If you have database settings to be loaded from a particular profile you may need to active it (no profiles are currently active).
    at org.springframework.boot.autoconfigure.jdbc.DataSourceProperties.determineDriverClassName(DataSourceProperties.java:218) ~[spring-boot-autoconfigure-1.4.0.RELEASE.jar:1.4.0.RELEASE]
    at org.springframework.boot.autoconfigure.jdbc.DataSourceConfiguration.createDataSource(DataSourceConfiguration.java:42) ~[spring-boot-autoconfigure-1.4.0.RELEASE.jar:1.4.0.RELEASE]
    at org.springframework.boot.autoconfigure.jdbc.DataSourceConfiguration$Tomcat.dataSource(DataSourceConfiguration.java:55) ~[spring-boot-autoconfigure-1.4.0.RELEASE.jar:1.4.0.RELEASE]
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_73]
    at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) ~[na:1.8.0_73]
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) ~[na:1.8.0_73]
    at java.lang.reflect.Method.invoke(Unknown Source) ~[na:1.8.0_73]
    at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:162) ~[spring-beans-4.3.2.RELEASE.jar:4.3.2.RELEASE]
    ... 56 common frames omitted

This is what I modified:
@SpringBootApplication
@EnableBatchProcessing
@Configuration
public class SampleBatchApplication {

    @Autowired
    private JobBuilderFactory jobs;

    @Autowired
    private StepBuilderFactory steps;

    @Bean
    protected Tasklet tasklet() {

        return new Tasklet() {
            @Override
            public RepeatStatus execute(StepContribution contribution,
                    ChunkContext context) {
                return RepeatStatus.FINISHED;
            }
        };

    }

    @Bean
    public Job job() throws Exception {
        return this.jobs.get("job").start(step1()).build();
    }

    @Bean
    protected Step step1() throws Exception {
        return this.steps.get("step1").tasklet(tasklet()).build();
    }

    public static void main(String[] args) throws Exception {
        // System.exit is common for Batch applications since the exit code can be used to
        // drive a workflow
        System.exit(SpringApplication
                .exit(SpringApplication.run(SampleBatchApplication.class, args)));
    }

    @Bean
    ResourcelessTransactionManager transactionManager() {
        return new ResourcelessTransactionManager();
    }

    @Bean
    public JobRepository getJobRepo() throws Exception {
        return new MapJobRepositoryFactoryBean(transactionManager()).getObject();
    }

}

What do I need to do to make it use the ResourcelessTransactionManager?
EDIT: Added clarity around why I want the ResourcelessTransactionManager to work.

A: Your problem seem to be no data source available in your configuration. Spring Batch needs database so persist its state.
Spring Boot can automatically configure in memory DB if you have some on classpath. Example application you are referring to has HSQL included in POM here: https://github.com/spring-projects/spring-boot/blob/v1.4.0.RELEASE/spring-boot-samples/spring-boot-sample-batch/pom.xml#L26
So to fix your problem, define access to your Database.

A: Below are some basic spring boot properties to set up data sources. By looking at driver class , boot can infer your db type and can auto create DataSource bean.
spring.datasource.driver-class-name
spring.datasource.url
spring.datasource.username
spring.datasource.password
spring.datasource.tomcat.max-active
spring.datasource.tomcat.initialSize
spring.datasource.tomcat.maxIdle

Last three properties are for setting up connection pools in container.
Explicit DataSource information is missing and no in-memory database is provided in classpath.
Fix issue by explicitly providing entries in application.properties or by including in-memory db ( H2 , HSQL etc ) in class path.
Your configuration looks OK for not using any data sources ( i.e. if you have configured ResourcelessTransactionManager & MapJobRepository ) as long as you don't use EnableAutoConfiguration but your stack trace indicates usage of Boot with EnableAutoConfiguration.
I guess, selective disabling of data source is not allowed, see question
EDIT: I was able to fix error in your code by adding @SpringBootApplication(exclude={DataSource.class,DataSourceAutoConfiguration.class})
Logs dumped this - after bean creation process,
Exclusions:
org.apache.tomcat.jdbc.pool.DataSource

org.springframework.boot.autoconfigure.jdbc.DataSourceAutoConfiguration


text:
Q: How to Update/Tag/Publish a module repo My notes show I used yarn publish next in the past, which i thought did the following

*

*prompt for version

*update package.json w/ version

*create a commit/tag w/ version

*publish the commit to the registry

Unfortunately this command signature doesn't exist in the docs, and from the following I think the command thinks I am trying to publish a tarball file named "next"
> yarn publish next
yarn publish v1.22.19
`error Passed folder/tarball doesn't exist,`

What yarn publish command should I use instead? OR, can this only be accomplished with multiple steps?


text:
Q: Curved border on one side still shows thin line on the other sides when background is transparent, ONLY in mobile - why does this happen? Lately, I've gotten into making CSS art and I noticed something that I don't understand about CSS borders.
If I style an element to be rounded with a transparent background, and set a border on only one side, there's still a faint line on all the other sides that shows up only on mobile.

div {
  width: 300px;
  height: 150px;
  background: transparent;
  border-top: 5px solid purple;
  border-radius: 50%;
}

Compare the following CodePen on a PC vs phone to see what I mean:
https://codepen.io/aradevich/pen/mdrLvqx
Screenshot:
ellipse with 5px top border
This effect is particularly bothersome when it skews facial features in CSS art, like with the eyes here on mobile: https://codepen.io/aradevich/pen/qBaxQye?editors=1100
Does anyone know why this happens, and how I can address it?
Thank you!

A: As far I know, maybe it's caused by browser rendering. So, the solution is change the graphic image to SVG or PNG instead of css.

A: Here is a different idea to have the same result without the border issue:

div.box {
  width: 300px;
  height: 150px;
  background:
    /*  150 = width/2   70 = height/2 - 5px of border */
    radial-gradient(151px 70px at bottom, transparent 98%,purple)
    top/100% 50% no-repeat;
  border-radius: 50% 50% 0 0;
}


text:
Q: How to encode string in android & decode string on servlet? I am trying to encode a parameters in android before sending it to the servlet. I used Base64 class of android & i am able to encode.But on servlet there is no anroid.util so i try to decode through org.apache.axiom.om.util so is there any comman class for both servlet & android. I am not using jdk 1.8.
Thanks in advance.


text:
Q: How to append new data to the log file in PostgreSQL I am migrating oracle code to postgresql where i need to append the query to existing log file.
Basically i want equivalent of oracle command " SPOOL test.log APPEND " in PostgreSQL . Is there a way to do that?
I tried to append new data to the log  file using \o or \o+ or copy in PostgreSQL but it overwrites the log file.
My code is something like this :
Oracle:
spool test.log
select  uid from users where uid='1111';
spool off

select sysdate from dual;
//other business logic code
                                                      -
spool test.log append
select balance from balances where uid='1111';
spool off

Postgresql:
\o test.log
select  uid from users where uid='1111';
\o

select current_date;
//other business logic code
                                                       -
\o test.log
select balance from balances where uid='1111';
\o

I want the two queries in \o block to append to same file in PostgreSQL.

A: You could use
\o | cat >> test.log

on UNIX platforms.


text:
Q: Why instance variable inside Custom Exception Mapper has to be static? I have implemented a custom exception mapper in order to throw the bad request in my application. Here's the code:
CustomFilterBadRequest:
package com.test.exceptions;

import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;
import java.util.Date;

public class CustomFilterBadRequest extends Exception implements
        ExceptionMapper<CustomFilterBadRequest> {

    private String uriInfo;

    public CustomFilterBadRequest() {
        super("Invalid Request. Please try again with the valid request");
    }

    public CustomFilterBadRequest(String uriInfo, String message) {
        super(message);
        this.uriInfo = uriInfo;
    }

    @Override
    public Response toResponse(CustomFilterBadRequest exception) {
        return Response.status(400).entity(new ErrorDetails(new Date(),
                400, "bad request", exception.getMessage(),this.uriInfo)).type(MediaType.APPLICATION_JSON).build();
    }
}

Issue:
Note:
In this example, I have an instance variable called uriInfo.
From another service, I do :
throw new CustomFilterBadRequest("uri","message")

Immediately, the constructor gets called and my uriInfo is set to the value "uri". After this, toResponse method gets called.My uriInfo instance variable is reset. why? Whereas, when I made the instance variable to be static, the value is retained.
I am unable to get any documentation on this. Please help.
*****UPDATE*****
When the REST End point related to this exception is invoked, the default constructor of CustomFilterBadRequest is invoked creating an object with state uriInfo initialized to null. Let's call this object as object1.
when we do throw new CustomFilterBadRequest("uri","msg"), an object is created with state uriInfo initialized to the value uri. Let's call this object as object2.
JAX-RS Runtime maps the CustomFilterBadRequest exception to the exception mapper which is also CustomFilterBadRequest here. Hence toResponse method gets called. It gets uriInfo from object1. (which is obviously null here)
And there's no necessity that we should use only class variables inside Custom exception mappers.
This kind of implementation is quite confusing. I have updated with the straightforward implementation in the answer below.

A: The problem is that the toResponse(...) method is called on the instance of CustomFilterBadRequest that is registered with the JAX-RS runtime. If the no-arg constructor is used in registration that is why uriInfo always has it's default value of null.
I would recommend that you have your exception defined in one class, and you Exception handler defined in another.
Exception:
public class CustomBadRequest extends Exception {

  private String uriInfo;

  public CustomBadRequest() {
    super("Invalid Request. Please try again with the valid request");
  }

  public CustomBadRequest(String uriInfo, String message) {
    super(message);
    this.uriInfo = uriInfo;
  }

  public String getUriInfo() {
    return uriInfo;
  }
}

ExceptionMapper:
@Provider
public class CustomFilterBadRequest implements ExceptionMapper<CustomBadRequest> {

  @Override
  public Response toResponse(CustomBadRequest exception) {
    return Response.status(400).entity(new ErrorDetails(new Date(),
      400, "bad request", exception.getMessage(),exception.getUriInfo())).type(MediaType.APPLICATION_JSON).build();
  }
}

A: I understood the reason behind the issue.
Whenever we hit the end point, default constructors of exception mappers registered with the jersey is called and objects of each type are created with state initialized to default values of its type.
When the custom exception is thrown, the custom exception object is created and JAX-RS runtime searches for the exception mapper to map the exception. If none is found, it just maps to the default exception mapper. If the custom exception mapper is found, toResponse method is called. In this case, we should get the states of customexception from its object itself inside the toResponse method.
I needed this to obtain uriInfo inside exceptionmapper.
Here's the working code:
CustomFilterBadRequest.java
public class CustomFilterBadRequest extends Exception {

public CustomFilterBadRequest(String message) {
    super(message);
}

}
CustomFilterBadRequestExceptionMapper.java
public class CustomFilterBadRequestExceptionMapper implements ExceptionMapper<CustomFilterBadRequest> {

private UriInfo uriInfo;

public CustomFilterBadRequestExceptionMapper(@Context UriInfo uriInfo) {
    this.uriInfo = uriInfo;
}

@Override
public Response toResponse(CustomFilterBadRequest exception) {
    return Response.status(400).entity(new ErrorDetails(Instant.now(),
            400, "bad request", exception.getMessage(),this.uriInfo.getPath())).type(MediaType.APPLICATION_JSON).build();
}

}
Thanks a lot everyone for the response.

A: Im pretty sure this is all you have to do:
CustomFilterBadRequest:
package com.test.exceptions;

import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
import javax.ws.rs.ext.ExceptionMapper;
import java.util.Date;

public class CustomFilterBadRequest extends Exception implements
        ExceptionMapper<CustomFilterBadRequest> {

    private String uriInfo;

    public CustomFilterBadRequest() {
        super("Invalid Request. Please try again with the valid request");
    }

    public CustomFilterBadRequest(String uriInfo, String message) {
        super(message);
        this.uriInfo = uriInfo;
    }

    @Override
    public Response toResponse(CustomFilterBadRequest exception) {
        return Response.status(400).entity(new ErrorDetails(new Date(),
                400, "bad request", exception.getMessage(),exception.uriInfo)).type(MediaType.APPLICATION_JSON).build();
    }
}

I just changed this.uriInfo to exception.uriInfo
Basically, when you throw a CustomFilterBadRequestException, JAX-RS creates a new instance to map the exception you threw. This new instance has a default value of uriInfo. So thus it is not saved.
Whatever you do, don't make uriInfo static. That would cause huge concurrency issues.


text:
Q: "socket.io.js" was blocked due to MIME type I'm trying to learn Socket.io but I can't make a working project because every one I make gets a MIME type mismatch.
ERROR:
The resource from "http://localhost:5500/socket.io/socket.io.js" was blocked due to MIME type ("text/html") mismatch (X-Content-Type-Options: nosniff).
To test this I found a working chat app project from Github and tested that code and got the same problem. That code can be found at: https://github.com/bradtraversy/chatcord
The code seems to correctly create a socket.io instance:
const app = express();
const server = http.createServer(app);
const io = socketio(server);

// Set static folder
app.use(express.static(path.join(__dirname, 'public')));

...

const PORT = process.env.PORT || 3000;

server.listen(PORT, () => console.log(`Server running on port ${PORT}`));

The HTML connects the JS with the line:
<script src="/socket.io/socket.io.js"></script>

This MIME type message is followed by an "io is not defined" error in reference to the client code:
const socket = io();

This MIME type appears on Firefox but not on Chrome, it doesn't and only gives a 404 not found. I don't know if that's just a browser difference.

A: Actually, the browser cannot download the javascript file at http://localhost:5500/socket.io/socket.io.js. Consequently, the io() method isn't defined.
You can try load the file from CDN, as mentioned in the documentation. Replace
<script src="/socket.io/socket.io.js"></script>

by :
<script src="https://cdn.socket.io/3.1.3/socket.io.min.js" integrity="sha384-cPwlPLvBTa3sKAgddT6krw0cJat7egBga3DJepJyrLl4Q9/5WLra3rrnMcyTyOnh" crossorigin="anonymous"></script>

EDIT :
I tried to reproduce your problem, but I cannot. So, I provide the maximum information of my environment for you to reproduce the result:

*

*I use the repository chatcord (clone and run npm run dev)

*My server runs on port 3000.

*My node version: v14.17.0

*My npm version: v7.13.0

*My system: Windows 10

The project works without any modification. When I tried to use socket.io from a CDN, I need to use the same version with the installed module on the server-side (^2.0.4 based on package.json)


text:
Q: how can I bind properties of an object that is already a property of an already bound object? I'm having a problem trying to bind the properties of an object, that is already a property of another object. When I bind the properties of the upper object, everything goes ok, but when I try to bind the properties of one property, it doesn't display anything.
Here is my code: xaml
    <Window x:Class="WpfTutorialSamples.ListView_control.ListViewColumnSortingSample"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="ListViewColumnSortingSample" Height="200" Width="550">
    <Grid Margin="10">
        <ListView Name="lvUsers">
            <ListView.Resources>
                <Style TargetType="ListViewItem">
                    <Setter Property="HorizontalContentAlignment" Value="Stretch" />
                </Style>
            </ListView.Resources>
            <ListView.View>
                <GridView>
                    <GridViewColumn Width="120" DisplayMemberBinding="{Binding Transponder}">
                        <GridViewColumn.Header>
                            <GridViewColumnHeader Tag="Transponder" Click="lvUsersColumnHeader_Click">Transponder</GridViewColumnHeader>
                        </GridViewColumn.Header>
                    </GridViewColumn>
                    <GridViewColumn Width="80" DisplayMemberBinding="{Binding Tipo}">
                        <GridViewColumn.Header>
                            <GridViewColumnHeader Tag="Tipo" Click="lvUsersColumnHeader_Click">Tipo</GridViewColumnHeader>
                        </GridViewColumn.Header>
                    </GridViewColumn>
                    <GridViewColumn Width="110" DisplayMemberBinding="{Binding Destruida}">
                        <GridViewColumn.Header>
                            <GridViewColumnHeader Tag="Destruida" Click="lvUsersColumnHeader_Click">Destruida</GridViewColumnHeader>
                        </GridViewColumn.Header>
                    </GridViewColumn>
                    <GridViewColumn Width="80" >
                        <GridViewColumn.Header>
                            <GridViewColumnHeader Tag="Combustible">Combustible</GridViewColumnHeader>
                        </GridViewColumn.Header>
                        <GridViewColumn.CellTemplate>
                            <DataTemplate>

                                <ComboBox  SelectionChanged="ComboBox_StopChanges" DataContext="{Binding Combustible}">
                                    <ComboBox.Resources>
                                        <SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}">White</SolidColorBrush>
                                    </ComboBox.Resources>

                                    <ComboBox.Items>
                                        <StackPanel Orientation="Horizontal">
                                            <StackPanel>
                                                <StackPanel Name="stckContentLeft">
                                                    <Label BorderBrush="White" BorderThickness="1" Content="Loaded :" FontSize="12" FontWeight="SemiBold" Foreground="Black" Height="25" HorizontalAlignment="Left" Margin="2,2,0,0" VerticalAlignment="Top"  Width="95"/>
                                                    <Label BorderBrush="White" BorderThickness="1" Content="Used :" FontSize="12" FontWeight="SemiBold" Foreground="Black" Height="25" HorizontalAlignment="Left" Margin="2,2,0,0" VerticalAlignment="Top"  Width="95"/>
                                                </StackPanel>
                                            </StackPanel>
                                            <StackPanel>
                                                <StackPanel Name="stckContentRigth">
                                                    <TextBox Name="textBoxLoaded" Height="25" Width="115" MaxLength="3" Margin="2,2,0,0" BorderBrush="Black" BorderThickness="1" FontSize="12" FontWeight="SemiBold" HorizontalAlignment="Left" Text="{Binding Cargado}" VerticalAlignment="Top" />
                                                    <TextBox Name="textBoxUsed" Height="25" Width="115" MaxLength="3" Margin="2,2,0,0" BorderBrush="Black" BorderThickness="1" FontSize="12" FontWeight="SemiBold" HorizontalAlignment="Left" Text="{Binding Usado}" VerticalAlignment="Top" />
                                                </StackPanel>
                                            </StackPanel>
                                        </StackPanel>
                                    </ComboBox.Items>
                                </ComboBox>

                            </DataTemplate>
                        </GridViewColumn.CellTemplate>
                    </GridViewColumn>
                </GridView>
            </ListView.View>
        </ListView>
    </Grid>
</Window>

And the c# code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Media;

namespace WpfTutorialSamples.ListView_control
{
    public partial class ListViewColumnSortingSample : Window
    {
        private GridViewColumnHeader listViewSortCol = null;
        private SortAdorner listViewSortAdorner = null;

        public ListViewColumnSortingSample()
        {
            InitializeComponent();
            List<User> items = new List<User>();
            items.Add(new User() { Transponder = "M001", Tipo = "UH60", Destruida = Estado_Aeronave.Destruida, combustible = new Combustible() {Cargado = 4000, Usado = 3000} });
            items.Add(new User() { Transponder = "M002", Tipo = "UH70", Destruida = Estado_Aeronave.Funcional, combustible = new Combustible() { Cargado = 3000, Usado = 2000 } });
            items.Add(new User() { Transponder = "M003", Tipo = "UH80", Destruida = Estado_Aeronave.Funcional, combustible = new Combustible() { Cargado = 2000, Usado = 1000 } });
            items.Add(new User() { Transponder = "M004", Tipo = "UH90", Destruida = Estado_Aeronave.Destruida, combustible = new Combustible() { Cargado = 1000, Usado = 500 } });
            lvUsers.ItemsSource = items;
        }

        private void lvUsersColumnHeader_Click(object sender, RoutedEventArgs e)
        {
            GridViewColumnHeader column = (sender as GridViewColumnHeader);
            string sortBy = column.Tag.ToString();
            if (listViewSortCol != null)
            {
                AdornerLayer.GetAdornerLayer(listViewSortCol).Remove(listViewSortAdorner);
                lvUsers.Items.SortDescriptions.Clear();
            }

            ListSortDirection newDir = ListSortDirection.Ascending;
            if (listViewSortCol == column && listViewSortAdorner.Direction == newDir)
                newDir = ListSortDirection.Descending;

            listViewSortCol = column;
            listViewSortAdorner = new SortAdorner(listViewSortCol, newDir);
            AdornerLayer.GetAdornerLayer(listViewSortCol).Add(listViewSortAdorner);
            lvUsers.Items.SortDescriptions.Add(new SortDescription(sortBy, newDir));
        }

        private void ComboBox_StopChanges(object sender, SelectionChangedEventArgs e)
        {
            ComboBox snd = sender as ComboBox;
            snd.SelectedIndex = -1;
        }
    }

    public enum Estado_Aeronave { Destruida, Funcional };

    public class Combustible
    {
        public int Cargado { get; set; }
        public int Usado { get; set; }
    }

    public class User
    {
        public string Transponder { get; set; }

        public string Tipo { get; set; }

        public Estado_Aeronave Destruida { get; set; }

        public Combustible combustible { get; set; }
    }

    public class SortAdorner : Adorner
    {
        private static Geometry ascGeometry =
                Geometry.Parse("M 0 4 L 3.5 0 L 7 4 Z");

        private static Geometry descGeometry =
                Geometry.Parse("M 0 0 L 3.5 4 L 7 0 Z");

        public ListSortDirection Direction { get; private set; }

        public SortAdorner(UIElement element, ListSortDirection dir)
            : base(element)
        {
            this.Direction = dir;
        }

        protected override void OnRender(DrawingContext drawingContext)
        {
            base.OnRender(drawingContext);

            if (AdornedElement.RenderSize.Width < 20)
                return;

            TranslateTransform transform = new TranslateTransform
                    (
                            AdornedElement.RenderSize.Width - 15,
                            (AdornedElement.RenderSize.Height - 5) / 2
                    );
            drawingContext.PushTransform(transform);

            Geometry geometry = ascGeometry;
            if (this.Direction == ListSortDirection.Descending)
                geometry = descGeometry;
            drawingContext.DrawGeometry(Brushes.Black, null, geometry);

            drawingContext.Pop();
        }
    }
}

If you could help I would forever be thankful to you.
Have a nice day.

A: Set the DataContext to the actual attribute name:
<ComboBox  SelectionChanged="ComboBox_StopChanges"  DataContext="{Binding combustible}">

And the TextBox Bindings to the according members:
<TextBox Name="textBoxLoaded" Height="25" Width="115" MaxLength="3" Margin="2,2,0,0" BorderBrush="Black" BorderThickness="1" FontSize="12" FontWeight="SemiBold" HorizontalAlignment="Left" Text="{Binding Path=Cargado}" VerticalAlignment="Top" />

<TextBox Name="textBoxUsed" Height="25" Width="115" MaxLength="3" Margin="2,2,0,0" BorderBrush="Black" BorderThickness="1" FontSize="12" FontWeight="SemiBold" HorizontalAlignment="Left" Text="{Binding Path=Usado}" VerticalAlignment="Top" />

A: Add the following to the User class:
    public Combustible[] CombustibleArray
    {
        get { return new[] {combustible}; }
    }

Then instead of binding the ComboBox to combustible, bind it to CombustibleArray, like this:
<ComboBox  SelectionChanged="ComboBox_StopChanges" DataContext="{Binding CombustibleArray}">

The reason your code is not working is that ComboBox data context is expecting some kind of array. It will use the first item in the array for the first item in the ComboBox. And this is exactly what my suggested modifications will do.


text:
Q: How to insert undefined value as null for pg node js Is there a better method of inserting a variable that is undefined as null using pg
const pg = require('pg');
a = a? a: null  // hope to remove this line
b = b? b: null  // hope to remove this line
c = c? c: null  // hope to remove this line

client.query('INSERT INTO abc(a,b,c) VALUES($1,$2,$3)', [a,b,c], function(err, result) {
  //do something here
})

so that don't have to check every variable and substitute "" for undefined before

A: you can define a undefined variable using || operator.
Ex
var a ;
var b = a || null;

A: You can check the value with Boolean like
let test = null;
let b = `test is ${Boolean(test) == false ? "null" : ",'" + test + "'"}`;


text:
Q: server1 & server2.. because w/same firm.. ssh connection shows private ip.. how to enforce public ip being using during ssh's? server1 has a private and public ip.
server2 has a private and public ip.
generally.. if server1 to ssh to server2 ..
server2 would recognize server1 by it's public ip.
but because both servers are with the same firm..
i suppose they have configured it to use "private ip" when ssh ing to each other.
i connected to server1 from server2 then checked to see what my ip is ( server2 ) and i noticed it is not the public ip of server2 but rather the private ip of server2.
i want to disable this feature..
i would like servers to communicate only via their public ip's..
how to midigate this issue ?

A: You should specify the public IP address when connecting to the other server.
If your servers are f.e. configured like this:
Server1: 192.168.0.1 (private), 12.34.56.1 (public)
Server2: 192.168.0.2 (private), 12.34.56.2 (public)

You should connect from server1 to server2 using
ssh 12.34.56.2

This will ensure the connection happens using the public network.
If you want to refer to the server by name (ssh server2) and you want the name to automatically be mapped to the server's public IP address, you should add entries in the hosts files of both servers, telling them their names are to be mapped to their public IPs:
    12.34.56.1 Server1
    12.34.56.2 Server2

A: If you REALLY want to ensure you only communicate via the public interfaces, then have the ssh sever(s) only listen for connections on the public interfaces.  Assuming you're using openssh or some variant open your /etc/ssh/sshd_config (that's a common path for it) and add:
ListenAddress <your.public.ip.address>

If you have lines such as this in there:
ListenAddress ::
ListenAddress 0.0.0.0

Comment them out (you may have them already commented out as I believe all interfaces is the default)
Then follow Massimo's advice above for using proper IP address and/or hosts entries.


text:
Q: Using os.walk to find and print names of my files, but unable to open them? Path name issue? My relevant code block is as follows:
path = "\\Users\\Harmless\\Documents\\untitled"
cellorder = []
cellcont = []
for roots, dirs, files, in os.walk(path):
    for file in natural_sort(files):
        if "Row" in file:
            cellorder.append(file)
            with open(file,'r') as txt:
                print txt.readlines
            #print "file = %s" % file

This would successfully list all the files I want to open (as commented out), but when I try to pass in the filename the same way it was printed in order to read it:
IOError: [Errno 2] No such file or directory: 'Row0Col0Heat.txt'

How can I fix this? Do I need to reference the entire path name and string substitute in each filename? If so, why? Is there a better way to reference/utilize paths?

A: Try using the absolute path of the file, you can get the absolute path by
abs_file_path = os.path.abspath(file)

since you already have the base path, you can also use:
abs_file_path = os.path.join(path, file)

Hope it helps


text:
Q: How to get first zeroes and add to the power? I have a variable in visual basic 2010, with the value of 0,000041 and how to make this value like this? 4.1E-5
Thank you.

A: the values are the same but if you want to print it or get a string out of it you can use the "E" or "e" format string:
(0.000041).ToString("E");

which should give you something like "4,100000E-005"
you can even specify how many significant digits you like with a number after:
(0.000041).ToString("e1");

gives you "4,1e-005"
you can find this and much more in the MSDN Docs


text:
Q: Sqoop is creating too many tiny files when importing data from database I have created an automated process that incrementally imports data from database to hdfs using sqoop. Now, instead of making files as big as the block size hadoop is creating multiple tiny files. How do I instruct sqoop to make files as big as the block size?

A: The number of files should be at most equal to your number of mappers .. Based on the size of your data, I would suggest perform the incremental updates using 1 mapper, however even doing this,  creating 1 file, you could be getting files smaller to the blocksize. You can solve this creating a different process to merge small files.

A: Based on the number of records inserted in database, sqoop incremental job create files on the HDFS, -m 1 can be passed in the sqoop command to get a single output file on hdfs.
when ever lesser records are inserted in the database, if sqoop got those records and writes in multiple files then sqoop merge job can help.


text:
Q: Is the error reporting in Collectors.toMap() broken? List<String> strings = Arrays.asList("3","55","3");
Map<String,Integer> map = strings
    .stream()
    .collect(Collectors.toMap(s ->s, s -> s.length()));

returns
java.lang.IllegalStateException: Duplicate key 1

where I would expect Duplicate key 3

A: This was fixed in Java 9. Now the error message is correct:
java.lang.IllegalStateException: Duplicate key 3 (attempted merging values 1 and 1)

A: Seems, like this was a bug in JDK 8 but is no longer the case as of JDK 9. Reason one being that I cannot replicate it on JDK 9 and reason two this link provided by @Zircon derives about the issue and it being fixed as of JDK 9.
Seems like there have been several posts about this issue, another link being:
https://bugs.openjdk.java.net/browse/JDK-8040892
which itself is a duplicate of few other posts.

A: Yes it's a bug but there is another way of converting this into a map which is by using identity function:
List<String> strings = Arrays.asList("3","55","3");
Map<String, List<String>> map = strings.stream()
                .collect(Collectors.toMap(Function.identity(), Arrays::asList));

By doing this you will get correct error which is
java.lang.IllegalStateException: Duplicate key [3]

For array with unique values
List<String> strings = Arrays.asList("3","55","4");

result would be
{55=[55], 3=[3], 4=[4]}