text:
Q: Missing ; before statement in superfish I've a problem in my superfish plugin. My site works great on my pc and demo site but in original host I have error in supefish.js
firebug says "missing ; before statement"
and locates this string :
[Break On This Error]
...om:'auto'}).animate({height:0},150)})            $('.sf-menu li li').not('.current').hove...

I turned it to this but nothing changed :
...om:'auto'}).animate({height:0},150)})        ;       $('.sf-menu li li').not('.current').hove...

A: It sounds like a newline issue. I take it the superfish.js script was made on a Mac and your server is Linux? Just use your favourite text editor to convert the newlines to Windows format, which works with every kind of OS.


text:
Q: Running same background task from two activities In my app I have a background task (using AsyncTask) that downloads stuff from a web site.
This task can be called from two separate activities, and it is possible to call it twice. So in "activity1" the background task "update" is called, and runs for a while (it takes something like 5-10 seconds usually).
Then while it's running, user switches to "activity2" and runs "update" again.
This gives problems: either a crash when both try to clear the database (command: DELETE FROM table) at the same time, causing a "database locked" error. Or they try to put the same item in the database causing a duplicate.
I've tried to solve this by setting a static boolean flag to true when a task is active.
When the task is called, it will check for this flag, and if true (i.e. the same task running on another thread) it goes into a wait loop using a handler until this flag clears, and then returns. This to make sure that when the background task returns, the update has been done. I have to use a Looper for that: this sometimes fails with an error "can create only one looper per thread". And I really have it in a way that only one looper can be started, this is the offending code, which appears at the start of the background task:
    if (active) {
        Looper.prepare();
        handler = new Handler();
        handler.postDelayed(new Runnable() {
            int count = 0;

            @Override
            public void run() {
                if (active) {
                    count++;
                    if (count < 1000)
                        handler.postDelayed(this, 100);
                }
            }
        }, 100);
        Looper.loop();
        active = false;
        return "done";
    }

And to make matters worse it often seems to hang in this loop, without returning.
How to solve such a situation?

A: Why don't use synchronization instead? It sounds like a concurrency issue. Why don't you make sure that if the first background task is running then the second background task is sleeping until the first one is finished.
Or ensure somehow, that if the user switches to Activity number 2, the background task from activity number 1 is cancelled.

A: Instead of the AsyncTask you can consider to use IntentService. Have a look at the Android Service concept. The IntentService class ensures that only one request will be processed at one time.
I found this answer very useful during implementing IntentService with Activity callback communication.

A: Database locking issues solved by wrapping it into a ContentProvider. Besides problems with a method being called again before the previous instance was finished, I had the issue of different methods running in different background threads clashing while trying to write to the database.
Officially designed to allow for sharing data between apps, it also works great for sharing data between threads in a single app. The ContentProvider will make sure that no locking issues occur.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Do Paypal recurring payments have unique txn_ids? I'm using the Paypal "Subscription" button.  I have an IPN handler and overall I think I've got it all figured out.  My last problem is that apparently there's no good way to test a recurring payment (except to wait for the cycle to occur).  This issue is discussed here: [question]: Testing Paypal subscription IPN
I don't really need to test this recurring payment but I do need to know if every recurring payment will have it's own txn_id or if every payment in a subscription shares the same ID.
Thanks!

A: Yes, each recurring payment cycle will create a new transaction with its own transaction ID.
You'd link these transactions together via their recurring payments profile ID.


text:
Q: Html form input sent, then stuck in php page My situation is as follow, i have a form input in a Jquery Mobile page, and i am submitting the form with no form button. I need the returned result from the php(it is in JSON) back in the html. But at the moment when i submit the search with pressing the enter button, it links to the php page, with the returned results and just stuck there, and not back in the html page.
Thanks for your time!
Code:
$("#searchform").submit(function( event ) {
    $.ajax({
        type: "GET",
        url: "http://test.com/App/searchtest.php",
        dataType:'json',
        success: function(data){
            console.log(data);
            $("#content").append(data);
        }
    })
});

<form id="searchform" name="searchform" method="post"
        action="http://www.test.com/App/searchtest.php" data-ajax="false">
    <input type="search" id="searchinput" name="searchterm"
        value="" data-mini="true" placeholder="Where?"/>
</form>

<?php
ini_set('display_errors', 1); error_reporting(E_ALL);

include 'connect.php';

$search = ($_POST['searchterm']);
$keywords = explode (" ", $search);
$columns = array("country","name");
$andParts = array();

foreach ($keywords AS $keyword){
    $orParts = array();
    foreach($columns AS $column){
        $orParts[] = $column . " LIKE '%" . ($keyword) . "%'";
    }
    $andParts[]= "(" . implode($orParts, " OR ") . ")";
}

$and = implode ($andParts, " AND ");

$sql = "SELECT * FROM Listing WHERE $and ";

$result = mysqli_query($con,$sql);

$output = array();

// fetch your results
while( $row = mysqli_fetch_assoc($result)) {
    // add result row to your output's next index
    $output[] = $row;
}

// echo the json encoded object
echo json_encode( $output );

?>

A: The modern way to do what oskr suggests is to use .preventDefault() -
$("#searchform").submit(function( event ) {
    event.preventDefault();

    $.ajax({
        type: "GET",
        url: "http://test.com/App/searchtest.php",
        dataType:'json',
        success: function(data){
            console.log(data);
            $("#content").append(data);
        }
    })
});

A: Ben the problem with your code is that you are sending the ajax request and submitting the form at the same time, which implies linking to the php page, reloading the page and thus cancelling the ajax success handler.
To avoid this you should return false which prevents the form submission, at the end of your submit event handler or calling event.preventDefault.
I hope this helps:
$("#searchform").submit(function( event ) {
    $.ajax({
        type: "GET",
        url: "http://test.com/App/searchtest.php",
        dataType:'json',
        success: function(data){
            console.log(data);
            $("#content").append(data);
        }
    })
    return false;
});


text:
Q: R DT package button to download files does not include display tables Here is the simple example.
Suppose I am looking at the table, and I want to download the table excluding the Sepal.Length column.
What should I do? I try to toggle the Sepal.Length column out, and click on excel, but it stills gives me the whole data. I don't want it. Is there any way that I can manipulate this?
Maybe I am not familiar with how it operates in the backend, after I use row reorder extension, or search/filter tables, then the downloaded files is what table displays. So I want something similar when I hide the columns.
This is useful when I have too many columns in a table and sometimes I do not need all of them.
library(shiny)
shinyApp(
  ui = fluidPage(DT::dataTableOutput('tbl')),
  server = function(input, output) {
    output$tbl = DT::renderDataTable(
      iris, extensions = "Buttons",
      options = list(dom = "Blfrtip",
        buttons = list('copy', 'excel', 'print', 'colvis'))
    )
  }
)

I really appreciate your help.

A: You can use input$tbl_columns_selected and input$tbl_rows_selected
Here you can select rows and columns (NB : to select column click on the label below the DT)
If you want a selection only on columns then remove input$tbl_rows_selected and set target = 'column' only
library(shiny)
library(xlsx)
library(DT)

shinyApp(
  ui = fluidPage(
      DT::dataTableOutput('tbl')
      ,downloadButton("downloadData",label ="Download")
  ),

  server = function(input, output) {
    output$tbl = DT::renderDataTable(iris, selection = list(target = 'row+column'))

    myFilteredData <- reactive({
      df <- iris[input$tbl_rows_selected, input$tbl_columns_selected]
      if (length(input$tbl_columns_selected) == 1) {
        df <- as.data.frame(df)
        colnames(df) <- colnames(iris)[input$tbl_columns_selected]
      }
      df
    })

    output$downloadData <- downloadHandler(
      filename = function() {paste("test.xlsx")},
      content = function(file) {
        write.xlsx(myFilteredData(),file, row.names=FALSE)
      })
  }
)


text:
Q: Is the JDK 1.6 the development kit for Java 6? I have the following doubt. For a Spring training course they say to me that I have to prepare my environment installing the JDK 1.6 on Windows.
So what it means? That I have to install the JDK related to Java 6? Is the JDK 1.6 the development kit for the Java 6?
Is this one the correct link http://www.oracle.com/technetwork/java/javase/downloads/java-archive-downloads-javase6-419409.html ?
Is it not so old?
Tnx

A: The awnser is yes, 1.6 relates to Java 6. The newest version is Java 8 or 1.8.
You probably don't need to have Java 6 jdk to have your tutorial work, I would use at least Java 7.


text:
Q: Выборка из двух таблиц по FULL JOIN Необходимо сделать выборку из двух таблиц
main
| id | total |
| 1  |    10 |
| 2  |    20 |
timed
| id | id_main | date_from  | date_to    | total |
| 1  |       2 | 2012-03-29 | 2012-04-29 |    50 |

Сджойнить таблицы так, чтобы результат был
| id | total |
| 1  |    10 |
| 2  |    50 |

A: Так должно везде работать:
SELECT m.id AS [id],
   COALESCE(t.total, m.total) AS [total]
FROM main AS m
LEFT JOIN timed AS t
ON m.id = t.id_main;

COALESCE
A: Может быть, так (MS SQL):
SELECT m.id AS [id],
   ISNULL(t.total, m.total) AS [total]
FROM main AS m
LEFT JOIN timed AS t
ON m.id = t.id_main;


text:
Q: Unity Extension Method GameObject I'm trying to add an extension method to my gameobject, that's works, but my problem is the GameObject share the same result. My goal is to have a different result for each GameObject.
// AddExtension.cs
public static class GameObjectExtensions
{
    private static int life;
    public static int Life(this GameObject gameObject)
    {
        return life;
    }
    public static void ChangeLife(this GameObject gameObject, int numberToAdd)
    {
        life += numberToAdd;
    }
}

And in my main code, I would like to manage GameObject like :
void Start()
{

    GameObject.Find("Perso0").ChangeLife(2);
    GameObject.Find("Perso1").ChangeLife(4);

    GameObject[] rootGOs = UnityEngine.Object.FindObjectsOfType<GameObject>();
    foreach (GameObject g in rootGOs)
    {
        if(g.name == "Perso0")
        {
            Debug.Log("Perso0 : " + g.Life());
        }
        if(g.name == "Perso1")
        {
            Debug.Log("Perso1 : " + g.Life());
        }
    }
}

But both GameObject have 6 in "Life" ( 2 + 4 )
I whould like to get only 2 for "Perso0" with Life and 4 with "Perso1" with Life
Do you have some clue to helping me ?
Thank you and best Regards

A: Because your life variable is static, it's going to be the same value you're editing every time you call ChangeLife on a GameObject.
Since extension methods need to belong to static classes, and a static class can only have static members, you cannot achieve the goal you want with extension methods.
Even if you could, it's not the right way to go with the Unity paradigm. With this setup, you're essentially saying "Every GameObject in my scene has a life value," which I don't think you want to do.
Instead, you can create your own components, as below.
public class Enemy : MonoBehaviour
{
    [SerializeField] private int _initialHealth = 100;

    private int _health = -1;

    public int health { get { return _health; } }

    private void Awake()
    {
        _health = _initialHealth;
    }

    public void IncrementHealth(int health)
    {
        _health += health;
    }
}

This is just an example, but you can make something to suit your needs.

A: static applied to a member means all instances share a single copy.  That is, there's only one life variable, which is modified when you call ChangeLife() on any GameOject.
Since extension methods have to be in a static class, I don't think you can accomplish what you want this way.
However, you should be able to add custom properties to your players and other objects in Unity.  I don't remember if they're called "custom properties" exactly, but I know some of the basic tutorials like Roll-a-Ball cover this (or at least used to).


text:
Q: Creating an electronic switch for controlling a headset's control button Some background information
I have an Android based phone. The headset that came with it uses a TRRS connector. We normally have a button on the headset which when pressed, would allow you to play/pause or pick up calls.
You can read about how this works here: http://www.wisebread.com/build-a-cable-to-control-your-android-phone-while-you-drive
The sleeve of the TRRS and the ring next to it are normally open. The open circuit voltage that we get is around 2.5V (which the phone gives). When we press the button, these two connections essentially get shorted and we get a very small potential difference between these two pins. That's how the phone knows that the button was pressed.
My problem
Now, I want to control this button electronically using my microcontroller (MSP430). So, I decided to use an electronic switch.
My proposed circuit http://img832.imageshack.us/img832/2576/51364385.jpg
In the above switch, the 2.5V source on the left and the 33k resistor corresponding to it is my phone. The BJT is used for switching, and the 3.6 voltage source on the right is a high output from my micro-controller.
This is the circuit I had initially thought of (Of course, I'd add current limiting resistor in the base). The problem is, when the BJT is on, I get an expected drop of about 1.026V in the CE junction. So, the ground wire and the wire on the top are not exactly shorted, even though the BJT allows current to freely flow.
What I need
I'd like to short top write to ground electronically, just like a mechanical switch. However, is it possible to do it without using relays and other stuff. Or, people who already have knowledge working with headset buttons, can you provide me with another solution?
Something I haven't tried
A spare TRRS connector is hard to find here. So I haven't tested anything practically. SO, I'm not sure if the sleeve and the ring need to be voltage shorted, or just need to have current passing through them.
Thanks.

A: Summary:

*

*As shown Q1 is drawing many amps of base current and the NOT expected 1+V Vce is a sign that the transistor is trying to glow white hot.

*Add a sensible base resistor, say 3k to 10k, and it will work well in practice. (This is a much higher level of base drive than wold be used in most cases but will allow and extra low Vce on voltage. See below for details.

A very major problem is that you

*

*haveused an incorrect simulation, which you have stated is incorrect,

*have achieved a result that does not present what you would get in reality,

*and have then concluded that this is what would happen
when you use a different real world circuit than what you have shown.

Simulators such as SPICE can be excellent tools but you have to simulate the circuit that you intend to use as closely as possible, and you have to ensure that you do things which cause very gross departures from reality.
Consider - in your emulation, what is the base current of Q1?
 Adding a measurement of this value should be instructive, at least.
With no base resistor the base current of Q1 will probably be in the many amps range. Using a [**TO3 metal can 2N3055""] (http://www.st.com/internet/com/TECHNICAL_RESOURCES/TECHNICAL_LITERATURE/DATASHEET/CD00000895.pdf) as an example which may approach this in real life you find that at Vbe = 1.8V, Ib = 4A, so at 3.6V it would be glowing quite nicely.
Adding a base resistor to Q1 should restore reality.
You say "and expected drop of 1.026V in the CE junction" BUT this should read "a wholly and completely unexpected drop in the CE junction".
By driving the transistor in a more normal manner here is what can be expected.
 Below are graphs of the Vcesat = collector base junction voltage for a BC337 - datasheet here.
 As base current is increased to about 10% of collector current Vce drops to around 0.05V for collector currents up to about 100 mA. At the < 0.1 mA required in this case, using a base current of 1 mA or so, so that Ib >> Ic, will result in extremely low saturation (= on) voltages.

The required voltages listed in the article that you referenced are >> 0.05V (see table below) except for "play/pause" which will tolerate somewhat more than the 4 mVshown so you should have no problem with Vce levels in practice.

From Build a Cable to Control Your Android Phone While You Drive

A: You could try to connect the GNDs of the circuit and microcontroller together, and now you connect a digital output pin with a 33k to the bottom or vice versa depending on where the sensing occurs.


text:
Q: Reading Unicode characters from command line arguments using boost::program_options in Windows I have several Windows applications that read a file path from command-line arguments. Everything works flawlessly, except when passing paths with non-ANSI characters. I expected this, but don't know how to deal with it. Probably an entry-level question but that is driving me crazy.
My current code looks like:
int main(int argc, char* argv[]) {
    namespace po = boost::program_options;

    po::options_description po_desc("Allowed options");
    po_desc.add_options()
        ("file", po::value<std::string>(), "path to file");

    po::variables_map po_vm;
    try {
        po::store(po::parse_command_line(argc, argv, po_desc), po_vm);
        po::notify(po_vm);
    } catch (...) {
        std::cout << po_desc << std::endl;
        return false;
    }

    const std::string file_path = po_vm["file"].as<std::string>();

    // ...
}

I've found that if I replace the type of file_path from std::string to boost::filesystem::path, some paths are now read. I don't know exactly why but can deduce that it has to be with a translation from the Latin1 charset.
For example, having following files:
malaga.txt
málaga.txt
mąlaga.txt

The first is always read correctly, while the second one fails when using std::string file_path but not boost::filesystem::path file_path. The third one always fails.
I've tried switching the main function to int main(int argc, wchar_t* argv) and using std::wstring for the argument type, but it is not compatible with boost::program_options parser.
How can I correctly read such Unicode file names?

A: Thanks for everyone contributing with their comments, thanks to them I managed to solved my problem.
TL;DR
Here the fixed code:
int wmain(int argc, wchar_t* argv[]) { // <<<
    namespace po = boost::program_options;

    po::options_description po_desc("Allowed options");
    po_desc.add_options()
        ("file", po::wvalue<std::wstring>(), "path to file") // <<<
        ("ansi", po::value<std::string>(), "an ANSI string")
        ;

    po::variables_map po_vm;
    try {
        po::store(po::wcommand_line_parser(argc, argv) // <<<
                    .options(po_desc)
                    .run(),
                  po_vm);
        po::notify(po_vm);
    } catch (...) {
        std::cout << po_desc << std::endl;
        return false;
    }

    const boost::filesystem::path file_path = po_vm["file"].as<std::wstring>(); // <<<

    // ...
}

Explanation
First, switch to wmain and wchar_t* argv: as mentioned by @erik-sun, it is necessary to switch the entry point to an Unicode aware function. Important note: it is possible to use int main(int, wchar_t*) (in the sense it will compile) but it won't receive arguments with the correct codification and parser will fail, you have to use wmain.
Then, the Unicode support link provided by @richard-critten was very useful for understanding the compilation errors:

*

*use boost::program_options::wvalue when the type is wide-char. The internal implementation uses a string stream: the default one only works with 8-bits chars.

*use boost::program_options::wcommand_line_parser to accept wchar_t* arguments. Unfortunately, this class doesn't have an all-in-one constructor and you must use the long form for parsing the command line.

*finally, retrieve the value as std::wstring when needed.

I've extended the code snippet to show it is still compatible with std::string inputs.
Side note
My complete solution requires instantiating a Qt QApplication at some point. QApplication constructor is incompatible with the wide-char argv. As no command-line interaction is needed with the Qt part (everything is processed long before by Boost), it can be re-written to receiv fake arguments:
int fake_argc = 1;
char* fake_argv[] = {"AplicationName"};
QApplication a(fake_argc, fake_argv);


text:
Q: LASSO regression coefficient values different from regular glm So I have done a LASSO regression, and the output is about 5 coefficients and an intercept. However, if I choose the same variables (I know I shouldn't do that) as the LASSO regression find, and input them into a regular glm binomial regression, well the coefficient values are not the same. Some are close, but some are a factor 10 off.
Is that perfectly normal, or...?

A: Yes, this is perfectly normal. LASSO stands for "least absolute shrinkage and selection operator". The coefficients are shrunk towards zero as compared to nonpenalized regression such that performed by glm.
The effect of shrinkage, combined with selection, is to make the model less sensitive to the patterns in the data and thus reduce variance at the cost of some bias. According to the bias-variance trade-off, as long as variance reduction dominates the increase in squared bias, the mean squared error will be reduced.


text:
Q: CSS select element only when it contains n elements I have an html structure similar to this:

This is the node's name!

I want the div.node > div.name to have a green background but only when the div.node > div.children > div.nodes is empty.
I wanted to count all elements in the div.node > div.children and if there are only two (div.node > div.children > div.nodes and div.node > div.children > hr), I want the following div.node > div.name to have a green background.
The selector I imagined would be this: div.node > div.children:contains(2) + div.name buit obviously this doesn't work.
Any ideas to solve this issue?
Edit:
I was able to remove the div.node > div.children. Now my html structure looks like this:

This is the node's name!

With this structure I can use the :empty selector:
div.node > div.nodes:empty + hr + div.name {
  background-color: green;
}

A: There is no such thing in CSS (sadly) but you have JS.

document.querySelectorAll('.node').forEach(node => {
  const childrensCount = node.querySelectorAll('.children').length;

  if(childrensCount === 2) {
    node.querySelector('.name').style.backgroundColor = 'green';
  }
});

This is the node's name!

This is the node's name!

This is the node's name!

PS
as cloned mentioned in his comment event better approach will be to set a class like .bg-green to name when element is rendered before sending it to user browser


text:
Q: On the Calabi-Yau conjecture for minimal surfaces Colding and Minicozzi proved that any embedded minimal surface in $\mathbb{R}^3$ with finite topology must be proper and thus it can not be bounded.
Is it possible to remove the assumption "finite topology"? Have there been any progress in that direction?

A: Properness is expected to hold for finite genus embedded minimal surfaces while it seems likely that there are infinite genus counterexamples.  Both of these claims are completely open (and are extremely difficult)
Currently the best results are in a preprint of Meeks, Perez and Ros.  They assume finite genus and then make some assumptions on the ends.
The basic idea is that there is a natural topology on the space of ends. One can distinguish between limit ends and isolated ends in this topology. Here it's helpful to think of the Riemann family of examples; all the planar ends are isolated ends, but the "top" and "bottom" are limit ends as they are limits of sequences of planar ends. Notice finite topology forces all ends to be isolated.
MPR further specify that a limit end is a simple limit end if it is only approximated by isolated ends. Both limit ends in Riemann example are simple limit ends. However, it is conceivable that the topology of the ends was homeomorphic to the Cantor set then every end would be a limit end and none of them would be simple.
What MPR (essentially) show is things are nicely behaved for simple limit ends.  This gives them a number of consequences--for instance if there are a countably number of ends, then the surface is properly embedded.


text:
Q: jQuery Fileupload Angular Cancel Event I am working on jQuery file upload with Angular using this plugin http://blueimp.github.io/jQuery-File-Upload/angularjs.html
All works fine except cancel button, It cancel the file but I am getting error in console that looks like this https://www.dropbox.com/s/nup2vkwfsfslqcu/cancel_error.PNG
I have app.js
(function () {
    'use strict';

    var isOnGitHub = window.location.hostname === 'blueimp.github.io',
        url = isOnGitHub ? '//jquery-file-upload.appspot.com/' : '/api/imageUpload';

    angular.module('myApp', [
        'blueimp.fileupload'
    ])
        .config([
            '$httpProvider', 'fileUploadProvider',
            function ($httpProvider, fileUploadProvider) {
                delete $httpProvider.defaults.headers.common['X-Requested-With'];
                fileUploadProvider.defaults.redirect = window.location.href.replace(
                    /\/[^\/]*$/,
                    '/cors/result.html?%s'
                );
                if (isOnGitHub) {
                    // Demo settings:
                    angular.extend(fileUploadProvider.defaults, {
                        // Enable image resizing, except for Android and Opera,
                        // which actually support image resizing, but fail to
                        // send Blob objects via XHR requests:
                        disableImageResize: /Android(?!.*Chrome)|Opera/
                            .test(window.navigator.userAgent),
                        maxFileSize: 5000000,
                        acceptFileTypes: /(\.|\/)(gif|jpe?g|png)$/i
                    });
                }
            }
        ])

        .controller('DemoFileUploadController', [
            '$scope', '$http', '$filter', '$window',
            function ($scope, $http) {
                $scope.options = {
                    url: url
                };

                $scope.setCover = function () {

                    var fileId;
                    $('input[type="radio"]').each(function () {
                        if ($(this).is(":checked")) { fileId = $(this).attr('id'); }
                    });

                    return $http({
                        url: "/home/SetCoverImage/?fileId=" + fileId,
                        method: "post"
                    }).then(
                           function () {
                               console.log("succcess");
                           },
                           function () {
                               console.log("error");
                           }
                       );
                };

            }
        ])

        .controller('FileDestroyController', [
            '$scope', '$http',
            function ($scope, $http) {
                var file = $scope.file,
                    state;

                if (file.name) {

                    file.$destroy = function () {

                        state = 'pending';
                        return $http({
                            url: "/api/imageupload/?id=" + file.id,
                            method: "delete"
                        }).then(
                            function () {
                                state = 'resolved';
                                $scope.clear(file);
                            },
                            function () {
                                state = 'rejected';
                            }
                        );
                    };

                    file.$cancel = function () {
                        console.log("cancel individual");
                        $scope.clear(file);
                    };
                }

            }
        ]);

}());

And html defined as
<link href="~/Content/bootstrap.min.css" rel="stylesheet" />
<link href="~/Content/css/style.css" rel="stylesheet" />
<link href="~/Content/css/jquery.fileupload.css" rel="stylesheet" />
<link href="~/Content/css/jquery.fileupload-ui.css" rel="stylesheet" />

@section scripts{

}

        <input type="hidden" name="redirect" value="http://www.myapp.com">

                    Add files...
                    <input type="file" name="files[]" multiple ng-disabled="disabled">

                <button type="button" class="btn btn-warning cancel" data-ng-click="cancel()">

                    Cancel upload
                </button>

                            {{file.name}}
                            {{file.name}}

                        {{file.name}}

                    {{file.error}}

{{file.size | formatFileSize}}

                            <input type="radio" id="{{file.id}}" name="cover" /> Set Cover

                    <button type="button" class="btn btn-primary start" data-ng-click="file.$submit()" data-ng-hide="!file.$submit || options.autoUpload" data-ng-disabled="file.$state() == 'pending' || file.$state() == 'rejected'">

                        Start
                    </button>
                    <button type="button" class="btn btn-warning cancel" data-ng-click="file.$cancel()" data-ng-show="file.isUploaded">

                        Cancel
                    </button>
                    <button data-ng-controller="FileDestroyController" type="button" class="btn btn-danger destroy" data-ng-click="file.$destroy()" data-ng-hide="!file.$destroy">

                        Delete
                    </button>

                <button data-ng-click="setCover()" class="btn btn-primary" type="submit">Submit</button>

A: You can try override the progress function. It's a provisional fix.
fileUploadProvider.defaults.progress = function(e, data) {
  if (e.isDefaultPrevented()) {
    return false;
  }
  if (!data.scope.$$phase) {
    data.scope.$apply();
  }
};


text:
Q: Unable to import main file inside test I am unable to import the main file inside my tests. Here is what my directory structure looks like:
.
├── LICENSE
├── README.md
├── invoker.py
├── main.py
├── requirements.txt
├── script.py
├── template_generators
│   ├── __init__.py
│   ├── base.py
│   ├── flipper.py
│   └── psp22.py
├── templates
│   ├── flipper
│   │   ├── cargo.txt
│   │   └── flipper.txt
│   └── psp22
│       ├── cargo.txt
│       └── psp22.txt
└── tests
    ├── template_generators
    │   ├── test_flipper.py
    │   └── test_psp22.py
    └── test_cli.py

I want to import main inside test_cli.py
Here is how main.py looks like
import typer

from invoker import Invoker

def main() -> None:

    print("Welcome to Ink Wizard!")
    print("Type 1 to scaffold flipper contract")
    print("Type 2 to scaffold psp22 contract")

    contract_type = typer.prompt("Enter your choice to continue")

    if contract_type == "1":
        Invoker.flipper()
        print("flipper scaffolded")
    if contract_type == "2":
        contract_name = typer.prompt("Please enter name of contract")
        Invoker.psp22(contract_name=contract_name, mintable=mintable, metadata=metadata, burnable=burnable, wrapper=wrapper, flashmint=flashmint, pausable=pausable, capped=capped)
        print("psp22 contract scaffolded")

if __name__ == "__main__":
    typer.run(main)

Here is my test_cli.py
import typer
from typer.testing import CliRunner

import main

app = typer.Typer()
app.command()(main)

runner = CliRunner()

def test_cli() -> None:
    result = runner.invoke(app, [])
    assert result.exit_code == 0

When I run python test_cli.py, here is the error I am getting:
ModuleNotFoundError: No module named 'main'

If anyone can give me an example on how to import main inside test_cli. That would be great. Thanks

A: quite dumb answer, but whatever. If you want just test your main. you can manually paste your main inside same folder where your test is located and then it should work.


text:
Q: v-for doesn't output anything even though data is returned from the GET Creating a VUE 2 app using NUXT. My async method returns data fine. But, for some reason my v-for doesn't produce any html markup.
The test data, as returned by my node.js api, via postman, is...
{
    "status": true,
    "message": [
        {
            "rating": [],
            "_id": "5e113ce50d41592e38976e45",
            "title": "Book 2",
            "description": "This is amazon book2",
            "photo": "https://amazon-clone-v1-rg.s3.amazonaws.com/xxxxx",
            "stockQuantity": 14,
            "price": 33,
            "__v": 0
        },
        {
            "rating": [],
            "_id": "5e113cf00d41592e38976e46",
            "title": "Book 1",
            "description": "This is amazon book 1",
            "photo": "https://amazon-clone-v1-rg.s3.us-east-2.amazonaws.com/xxxxx",
            "stockQuantity": 14,
            "price": 25,
            "__v": 0
        }
    ]
}

Here's my code...
 <template>

All Products

            Add a new product
            Add a new category
            Add a new owner

{{product.title}}

              (1732)

                ${{product.price}}

            Update
            Delete

</template>

I even tried a very simple v-for loop like this, but it also returned no data...

{{product.title}}

Any suggestions would be appreciated. Thanks!

A: In your front-end you should return {products: response.message} because the field called message have yours "products" list.
or
In your API back-end should be use products instead of message to return your "product" list then you could be used as you mentioned.


text:
Q: Symfony (5.1) Doctrine Event Listener is fired but not Entity Listener Using Symfony official documentation,
I was cleaning up some code and wanted to replace a Doctrine event listener in Symfony (working):
namespace App\EventListener;

use App\Entity\Comment;
use Doctrine\ORM\Event\LifecycleEventArgs;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;

class CommentAuthorAssignmentListener
{
    private $tokenStorage;

    public function __construct(TokenStorageInterface $tokenStorage)
    {
        $this->tokenStorage = $tokenStorage;
    }

    public function prePersist(Comment $comment, LifecycleEventArgs $event)
    {
        dump($comment, $event); exit;
        $comment->setAuthor($this->tokenStorage->getToken()->getUser());
    }
}

services:
    App\EventListener\CommentAuthorAssignmentListener:
        autowire: true
        tags:
            - { name: doctrine.event_listener, event: prePersist }

With a more specific Entity listener (no error but not fired up at all):
namespace App\EventListener;

use App\Entity\Comment;
use Doctrine\ORM\Event\LifecycleEventArgs;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorageInterface;

class CommentAuthorAssignmentListener
{
    private $tokenStorage;

    public function __construct(TokenStorageInterface $tokenStorage)
    {
        $this->tokenStorage = $tokenStorage;
    }

    public function prePersist(Comment $comment, LifecycleEventArgs $event)
    {
        $comment->setAuthor($this->tokenStorage->getToken()->getUser());
    }
}

services:
    App\EventListener\CommentAuthorAssignmentListener:
        autowire: true
        tags:
            - { name: doctrine.entity_listener , entity: 'App\Entity\Comment', event: prePersist }

Some notes:

*

*I did run cache:clear

*Use case: explicitely persisting (a freshly created) Comment

A: Looks like you made a typo:
 # these are the options required to define the entity listener
 name: 'doctrine.orm.entity_listener'
 event: 'postUpdate'
 entity: 'App\Entity\User'

Notice the ".orm." in the tag name, so for your use case:
services:
    App\EventListener\CommentAuthorAssignmentListener:
        autowire: true
        tags:
            - { name: doctrine.orm.entity_listener , entity: 'App\Entity\Comment', event: prePersist }


text:
Q: Explicit template instantiation with variadic templates I have several template classes Impl (with some abstract methods) that are partially implemented in CPP files so that I need to explicitly instantiate my templates for the linker to find it, like this:
template class Impl<T0>;
template class Impl<T1>;
template class Impl<T2>;
...
template class Impl<Tx>;

As the number of types Tx grows, I would like to find a better way than to manually expand these lists of explicit instantiations in all necessary files. I thought I could use variadic templates for this, so I tried the following:
template <template <class> class, class...>
struct type_map;

template <template <class> class BaseT, class... Ts>
struct type_map<BaseT, std::tuple<Ts...>> {
    using type = std::tuple<BaseT<Ts>...>;
};

typedef std::tuple<T0, T1, T2> MyTypes;

And in the CPP file:
template class type_map<Impl, MyTypes>;

However, this didn't instantiate the templates as I intended (the linker complained about the missing symbols).
Is there a way to make this approach work (i.e. instantiate the template without instantiating an object of it) or a totally different approach that could solve my problem in this situation?

A: I don't think you can do this with variadic templates, but you can do it with the preprocessor.
I see two options. One would be to use Boost.Preprocessor:
// Definitions:
#define ARGUMENTS (T0)(T1)(T2)(T3)(Tx)

#define INSTANTIATE(maUnused, maTemplate, maType) \
  template class maTemplate<maType>;

// Usage:
BOOST_PP_SEQ_FOR_EACH(INSTANTIATE, Impl, ARGUMENTS)

BOOST_PP_SEQ_FOR_EACH(INSTANTIATE, Impl2, ARGUMENTS)

Another option would be to use the X macro trick:
x.hpp
X(T0)
X(T1)
X(T2)
X(T3)
X(Tx)

#undef X

using_file.cpp
#define X(maType) template class Impl<maType>;
#include "x.hpp"

#define X(maType) template class Impl2<maType>;
#include "x.hpp"


text:
Q: How to get Web3js to work inside a VueJS component? I want to use web3 with node and vuejs to connect to an Ethereum Parity node.

*

*I am using vue-cli with webpack.

*Parity is running on localhost.

*When I visit http://localhost:8545 I see which tells me Parity is listening.

I created the following Vue component:
<template>

{{ title }}

{{ accounts() }}

</template>

When I run npm run dev I get this:

On the console I see this:

I attempted to add an Access-Control-Allow-Origin header using this configuration code, but it did not fix it. The console error seems to indicate that the Parity node needs to set this header option.
    http: {
      root: '/root',
      headers: {
        AccessControlAllowOrigin: 'true'
      }
    },

A: The solution was to create a Parity config file named config.toml.
File Location:

*

*Windows: %UserProfile%\AppData\Roaming\Parity\Ethereum\config.toml

*Linux: ~/.local/share/io.parity.ethereum/config.toml

*macOS: $HOME/Library/Application Support/io.parity.ethereum/config.toml

File Contents:
[parity]
#  Test Network
chain = "ropsten"

[rpc]
# Allows Cross-Origin Requests from domain '*'.
cors = "*"
# Allow connections only using specified addresses.
hosts = ["", "http://localhost:8080"]

Reference:

*

*Parity configuration file documentation.

*Parity config file generator.

*Cross-Origin Resource Sharing (CORS) reference.

Thank you wostex for the comment.


text:
Q: Different text width in the same filetype in vim I am editing my markdown files which contain some code examples (like here). Is there any way to tell vim, when it is editing markdown files, to set textwidth=80 to everything except where I keep my code syntax? So for example:
Here is a text within a markdown file // textwidth=80

    puts 'Hello World' // textwidth is not specified

A: You can change the 'textwidth' setting dynamically with an :autocmd:
:autocmd CursorMoved,CursorMovedI <buffer> let &textwidth = (getline('.') =~# '^    ' ? 0 : 80)

This checks for Markdown code (indented by 4 spaces), and then clears the textwidth.

A: I don't know how to simply set tw option to meet your requirement. However I came up with a function, it could do what you want:
function! WrapMD()
   let x=&tw
   let &tw=80
   normal! gqq
   let &tw=x
endfunction

this function just does format with tw=80 on current line, after that restores your original tw setting.
You can source the function (or put it in your vimrc), and then do:
:v/\v^( {4}|\t)/call WrapMD()

at any time when you want to format your MD text.
You could also create a mapping for that or put it in a autocmd on event BufWritePre.
Here I made a gif when I test the function:

A: I frequently use pandoc to tidy up markdown: pandoc -t markdown will wrap markdown, but not code blocks. It also nicely tidies up lists and block quotes. The vim-pandoc plugin sets 'equalprg' to pandoc -t markdown --reference-links.


text:
Q: Open/write deleting txt file contents? I am bassicly trying to read a number from a file, convert it to an int, add one to it,  then rewrite the new number back to the file. However every time I run this code when i open the .txt file it is blank. Any help would be appreciated thanks! I am a python newb.
f=open('commentcount.txt','r')
counts = f.readline()
f.close
counts1 = int(counts)
counts1 = counts1 + 1
print(counts1)
f2 = open('commentcount.txt','w') <---(the file overwriting seems to happen here?)
f2.write(str(counts1))

A: Having empty files
This issue is caused by you failing to close the file descriptor. You have f.close but it should be f.close() (a function call). And you also need an f2.close() in the end.
Without the close it takes a while until the contents of the buffer arrive in the file. And it is a good practice to close file descriptors as soon as they are not used.
As a side note, you can use the following syntactic sugar to ensure that the file descriptor is closed as soon as possible:
with open(file, mode) as f:
    do_something_with(f)

Now, regarding the overwriting part:
Writing to file without overwriting the previous content.
Short answer: You don't open the file in the proper mode. Use the append mode ("a").

Long answer:
It is the intended behavior. Read the following:
>>> help(open)
Help on built-in function open in module __builtin__:

open(...)
    open(name[, mode[, buffering]]) -> file object

    Open a file using the file() type, returns a file object.  This is the
    preferred way to open a file.  See file.__doc__ for further information.

>>> print file.__doc__
file(name[, mode[, buffering]]) -> file object

Open a file.  The mode can be 'r', 'w' or 'a' for reading (default),
writing or appending.  The file will be created if it doesn't exist
when opened for writing or appending; it will be truncated when
opened for writing.  Add a 'b' to the mode for binary files.
Add a '+' to the mode to allow simultaneous reading and writing.
If the buffering argument is given, 0 means unbuffered, 1 means line
buffered, and larger numbers specify the buffer size.  The preferred way
to open a file is with the builtin open() function.
Add a 'U' to mode to open the file for input with universal newline
support.  Any line ending in the input file will be seen as a '\n'
in Python.  Also, a file so opened gains the attribute 'newlines';
the value for this attribute is one of None (no newline read yet),
'\r', '\n', '\r\n' or a tuple containing all the newline types seen.

So, reading the manuals shows that if you want the content to be kept you should open in append mode:
open(file, "a")

A: you should use the with statement. this assume that the file descriptor is closed no matter what:
with open('file', 'r') as fd:
    value = int(fd.read())

with open('file', 'w') as fd:
    fd.write(value + 1)

A: python open file paramters:
w:

Opens a file for writing only. Overwrites the file if the file exists.
  If the file does not exist, creates a new file for writing.

You can use a (append):

Opens a file for appending. The file pointer is at the end of the file
  if the file exists. That is, the file is in the append mode. If the
  file does not exist, it creates a new file for writing.

for more information you can read here
One more advice is to use with:
with open("x.txt","a") as f:
    data = f.read()
    ............

For example:
with open('c:\commentcount.txt','r') as fp:
    counts = fp.readline()

counts = str(int(counts) + 1)

with open('c:\commentcount.txt','w') as fp:
    fp.write(counts)

Note this will work only if you have a file name commentcount and it has a int at the first line since r does not create new file, also it will be only one counter...it won't append a new number.

A: You never close the file. If you don't properly close the file the OS might not commit any changes. To avoid this problem it is recommended that you use Python's with statement to open files as it it will close them for you once you are done with the file.
with open('my_file.txt', a) as f:
    do_stuff()


text:
Q: How to send deliver_sm request add user_message_reference TLV from node.js SMPP I'm using node-smpp and would like to know how to send a "deliver_sm" request and add "TLV" response to user_message_reference.
Extract of node-smpp / lib / smpp.js:
exports.addTLV = function(tag, options) {
    options.tag = tag;
    defs.tlvs[tlv] = options;
    defs.tlvsById[options.id] = options;
};

Test code:
var tlv = new Object();
tlv.tag = 0x001E; // smpp.receipted_message_id;
tlv.lenght =  msgid.lenght;
tlv.value = msgid;

smpp.addTLV(tlv,tlv);

Result:
defs.tlvs[tlv] = options;
       ^
ReferenceError: tlv is not defined

A: I'm the author of node-smpp module.
To add either a tlv parameter or a standard parameter to your PDUs you just need to add a property to the pdu with the appropriate name.
session.deliver_sm({
    source_addr: 'blahblah',
    destination_addr: 'blahblah',
    short_message: 'blahblah',
    receipted_message_id: 'blahblah',
    user_message_reference: msgid
});

This will send a deliver_sm pdu with the above parameters plus other required paramenters set to their default values.
Generally you don't need to use smpp.addTLV at all. It is for defining custom vendor specific TLVs (tags between 0x1400 and 0x3FFF).


text:
Q: Why is my component not getting re-rendered upon using setState and changing the value of state? Why is it that the component Eachcartitem is not getting re rendered although I change the state. I have this fucntion which gets called from inside the Eachcartitem component:-
cartremover(a){
     var cart1=cart;
     var firstpart=cart.slice(0,a);
     var secondpart=cart.slice(a+1,cart.length);
     var final = firstpart.concat(secondpart);
     this.setState({
        cartstate:final,
        abc:true
     })
}

The Eachcartitem is used as follows in parent component:-

                {
                    this.state.cartstate.map((cat) => (<Eachcartitem data={cat} index={this.state.cartstate.indexOf(cat)} cartremover={i=>this.cartremover()}/>))
                }

And the Eachcartitem is as follows:-
class Eachcartitem extends React.Component{
    constructor(props){
        super(props);
        this.state={
            data:this.props.data
        };

    }

    clicker(){
        this.props.cartremover(this.props.index);
    }

    render(){
        return(

{this.state.data.productName}

Rs.{this.state.data.productPrice}

Store:{this.state.data.shopName}

Quantity:{this.state.data.productQuantity}

Variant:{this.state.data.variant.quantity}

this.clicker()}>❌

        );
    }
 }
 export default Eachcartitem

But for some reason the cartitem divs are not getting changed why is it so?

A: Its because you are not passing the index of the item to the function, here:
cartremover={i => this.cartremover()}

Write it like this:
cartremover={i => this.cartremover(i)}

You don't need to pass the index to child component, use this code:
this.state.cartstate.map((cat, i) => (
    <Eachcartitem data={cat} cartremover={e => this.cartremover(i)} />
))

Now from Eachcartitem simply call that method: this.props.cartremover().
Better to use splice to remove the element at particular index, write the method like this:
cartremover(a){
    let cart = [...this.state.cartstate];
    cart.splice(a, 1);

    this.setState({
        cartstate: cart,
        abc: true
    })
}

Check working snippet:

const Temp = (props) =>

  {props.name}
  <button onClick={props.cartremover}>Delete</button>

class App extends React.Component {
  constructor() {
    super()
    this.state = {cart: ['a', 'b', 'c', 'd', 'e']}
  }

  cartremover(a){
    let cart = [...this.state.cart];
    cart.splice(a, 1);

    this.setState({
      cart,
    })
  }

  render() {
    return (

        {this.state.cart.map((cart, i) => (
          <Temp key={cart} name={cart} cartremover={e => this.cartremover(i)}/>
        ))}

    )
  }
}

ReactDOM.render(<App />, document.getElementById('app'))


text:
Q: How to call Groovy script from Scala? <?xml version="1.0" encoding="UTF-8" standalone="yes"?>
 <facts>
    <fact id="ItemPrice" displayName="Item Price">
    <defaultValue>0</defaultValue>
    <script><![CDATA[
            Double Value_Sales= 500;
            Double Unit_Sales= 10;
            Double res=Value_Sales/Unit_Sales;
            return res;
    ]]></script>
</fact>
</facts>

Above is the sample groovy script written in xml file for finding item price.
Java code for processing Groovy:
List<Fact> factList = NREUtils.readXml("/SampleDictionary.xml") //cutome API
GroovyShell shell = new GroovyShell();
String scriptStr = factList.get(0).getScript();
Script groovyScript = shell.parse(scriptStr); // return "ItemPrice" script
Binding binding = new Binding();
groovyScript.setBinding(binding);
Object val = groovyScript.run(); // **Result will be 50**

I would like the corresponding Scala code for the same.

A: Without further information on your problem, and being both languages (scala and groovy) executed over the JVM, I would suggest you just to compile your groovy code and include the jar in the classpath of the JVM running your scala code.
Here you have some ideas about how to turn groovy code into usable bytecode: http://docs.groovy-lang.org/latest/html/documentation/tools-groovyc.html
Then do just do as you would with any java library that you would like to call from scala: Using Java libraries in Scala


text:
Q: Custom streaming to read BLOBS from MS-SQL - How should I handle the connection? I have a custom stream that I am using with WCF for large BLOBs from the database.  It reads the data in chunks.
What is the best way to handle the connection for the stream?  Should I just open it at the construction or open/close it with each chuck read?
Thanks.

A: *

*Large BLOBs and UPDATETEXT (ADO.NET)

*Streaming BLOBs (ADO.NET)

*Working with binary large objects (BLOBs)

*Large Data and Streaming (WCF)

Filestream in SQL Server 2008 will save the files on the filesystem giving you streaming capabities with the use of public filesytem API along with preferred performance over normal BLOB.
From the post - Rule of thumb:
Data > 256K - Consider Filestream
Data < 256K - Keep using BLOB

A: I would load the entire blob into a memory stream then let WCF handle the Streaming and Chunking.  You can enable streaming in the transportBindings, or look into using MTOM.
[ServiceContract]
public class ContentService
{
  [OperationContract]
  public Stream GetBlob(int id)
  {
    byte[] myBlob = GetBytesFromDatabase();
    return new MemoryStream(myBlob);
  }
}

If you using SQL Server 2008 try sending the stream directly through to the WCF Client
[ServiceContract]
public class ContentService
{
  [OperationContract]
  public Stream GetBlob(int id)
  {
    return GetStreamFromDatabase(id);
  }
}

See this link on Streaming Messages with WCF


text:
Q: CakePHP2.4 Login and Redirect doesn't work on server I'm using cakePHP building a website. The login function works fine in local, but after I post them onto the server, I cannot login with existing username and password. The page doesn't either let me log in, or give me an error message which is supposed to show up when there are issues. I tried almost every solution in stackoverflow but can't solve it. Here's my code.
Model:
class User extends AppModel {

public function beforeSave($options = array()) {

/* password hashing */
if (isset($this->data[$this->alias]['password'])) {
    $this->data[$this->alias]['password'] = AuthComponent::password($this->data[$this->alias]['password']);
}
return true;
}
}

AppController:
class AppController extends Controller {

public function webroot() {

}

public $components = array('DebugKit.Toolbar','Session',
    /* add Auth component and set  the urls that will be loaded after the login and logout actions is performed */
    'Auth' => array(
        'loginRedirect' => array('controller' => 'Home', 'action' => 'index'),
        'logoutRedirect' => array('controller' => 'users', 'action' => 'login')
    )
);

public function beforeFilter() {
    /* set actions that will not require login */
    $this->Auth->allow('index','display', 'view');
}

}

UsersController:
class UsersController extends AppController {

public $components = array('Auth');

public function beforeFilter() {
     parent::beforeFilter();
$this->Auth->allow('add', 'logout');
}

public function login() {
    if ($this->request->is('post')) {
        /* login and redirect to url set in app controller */
        if ($this->Auth->login()) {
            return $this->redirect($this->Auth->redirect('/Home'));
        }
        $this->Session->setFlash(__('Invalid username or password, try again'));
    }
}

public function logout() {
     /* logout and redirect to url set in app controller */
    return $this->redirect($this->Auth->logout());
}
 public function index() {
    $this->User->recursive = 0;
    $this->set('Users', $this->paginate());
}

public function add() {
    if ($this->request->is('post')) {
        $this->User->create();
        if ($this->User->save($this->request->data)) {
            $this->Session->setFlash;
            return $this->redirect(array('controller' => 'Home','action' => 'index'));
        }
        $this->Session->setFlash(__('The user could not be saved. Please, try again.'));
    }
}
}

View:
<?php echo $this->Session->flash('auth'); ?>
<?php echo $this->Form->create('User'); ?>
<fieldset>
    <legend><?php echo __('Please enter your username and password'); ?></legend>
    <?php echo $this->Form->input('username');
    echo $this->Form->input('password');?>
</fieldset>
<?php echo $this->Form->end(__('Login')); ?>

Another glitch I think I should mention is, as the code shows, when I add a new username and pw, the page should redirect me to Home. This also works fine locally, but on server it doesn't redirect, HOWEVER, the username and password is successfully stored into database when I added it.
I'm really stuck and have no clue what the problem is, any help is appreciated, thanks.

Update
errors in error.log :
2014-05-14 05:16:21 Error: [MissingActionException] Action UsersController::js() could not be found.
Exception Attributes: array (
  'controller' => 'UsersController',
  'action' => 'js',
)
Request URL: /users/js/lightbox.min.js

2014-05-14 05:16:21 Error: [MissingActionException] Action UsersController::js() could not be found.
Exception Attributes: array (
  'controller' => 'UsersController',
  'action' => 'js',
)
Request URL: /users/js/jquery-1.11.0.min.js


text:
Q: JavaScriptSerializer is not allowed in .net core project? I am working in .net core project. I want to serialize the objects using JavaScriptSerializer.
JavaScriptSerializer Serializer = new JavaScriptSerializer();

I added the namespace using System.Web.Script.Serialization;. It throws errors. I googled it. I saw like .net core project does not have System.Web.Script.Serialization; in some sites.
Is there have any another way to serialize the objects in the .net core like JavaScriptSerializer?

A: In .net core the most common way of serializing and deserializing objects (JSON) using Newtonsoft.Json.
You need to install the Nuget Package of Newtonsoft.Json
add using a statement like:
using Newtonsoft.Json;

and use it as:
object o = JsonConvert.DeserializeObject(json1);
string json2 = JsonConvert.SerializeObject(o, Formatting.Indented);

A: Install Newtonsoft.Json and then
in Controller:
string data = JsonConvert.SerializeObject(new { MyUser = user, MyId = id });
object dataObj = JsonConvert.DeserializeObject(data);
return Json(dataObj);

and in Javascript file:
$.ajax({
   // some codes!
   success: function(data){
      var user = data.MyUser;
      var id = data.MyId
   }
});

A: For ASP.NET Core 3.1 we can use JsonSerializer.Deserialize from System.Text.Json with a string/dynamic dictionary Dictionary<string, dynamic>.
Example loading ClientApp\package.json:
using System;
using System.Text.Json;
using System.Collections.Generic;

...

var packageJson = File.ReadAllText(Path.Combine(env.ContentRootPath, "ClientApp", "package.json"));

var packageInfo = JsonSerializer.Deserialize<Dictionary<string, dynamic>>(packageJson);

Console.WriteLine("SPA Name: {0}, SPA Version: {1}",
    packageInfo["name"], packageInfo["version"]);

Of course we'll have to copy ClientApp\package.json to the publish directory using a Target > Copy command inside .csproj.


text:
Q: PHP, MYSQL and hyperlinks - linking from one page to a detail page (same table) Not sure why this page doesn't seem to be working?
Trying to get the ID from the URL and use that to filter a table.
Example URL: http://example.com/page.php?id=123G
I'm getting 0 results when I type in that URL even though I know there is a match.  Any ideas?

<?php

$id = $_GET["id"];

$servername = "INSERTSERVER";
$username = "INSERTUSER";
$password = "INSERTPASSWORD";
$dbname = "INSERTDB";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}

$pd = "

SELECT fac_id, pd, phone_pd
FROM ft_location_db
WHERE fac_id = $id

";

$result = $conn->query($pd);

if ($result->num_rows > 0) {
echo "

PD	Phone

";
// output data of each row
while($row = $result->fetch_assoc()) {
    echo "
" . $row["pd"]. "	" . $row["phone_pd"]. "

";
}
echo "
";
} else {
echo "0 results";
}

$conn->close();
?>

A: Please, see the note in the bottom of the answer.
If fac_id is a string datatype, it should be wrapped.
$pd = "
SELECT fac_id, pd, phone_pd
FROM ft_location_db
WHERE fac_id = '$id'
";

You have to use single quotes, because your query is written inside double quotes.
Using single quotes :
$pd = '
SELECT fac_id, pd, phone_pd
FROM ft_location_db
WHERE fac_id = "' . $id . '"
';

But (and -very- important), I suggest you to take a look to How can I prevent SQL injection in PHP? to secure your queries.
$stmt = $conn->prepare('
    SELECT fac_id, pd, phone_pd
    FROM ft_location_db
    WHERE fac_id = ?');
$stmt->bind_param('s', $id);
$stmt->execute();
$result = $stmt->get_result();

See also : bind_param()


text:
Q: Does Invisible mode still allow you to gain hours in-game? Invisible status (which can be access via Friends -> Invisible) has been released to the Steam client. I'm wondering - even though from your friend's perspective, you're offline - will you still gain hours in the game you're playing in?

A: Yes, you should still be gaining playtime. Hours played, achievements, and etc are not related to your friends/chat status in any way.
Invisible mode is simply a way to appear offline while still being able to game, and you can still chat with your friends online if you decide to do so.


text:
Q: Using ajax and django to delete an item in for loop Trying to delete a post/comment by using the bootstrap × on click and fade out. I have some code written up but it isn't working. I feel I am missing something so simple. Any guidance or help would be highly appreciated.
urls.py
url(r'^delete/(?P<pk>\d+)/$', views.delete, name='delete'),

views.py
@login_required
def delete(request, pk):
    warn = get_object_or_404(Warning, pk=pk)
    fop = get_object_or_404(Followers, pk=warn.person.pk)
    warn.delete()
    return redirect('yardsale.views.follower_warnings', pk=fop.pk)

template
{% for warns in warn.warnings.all %}

                {#  #}
                <button type="button" class="close">×</button>
                {#  #}

Warned:  {{ warns.publish_date }}

Warned By:  {{ warns.author }}

Warning Type: {{ warns.WarningType }}

                Description: {{ warns.descript }}

            {% endfor %}

main.js
$(".close").click(function () {
  if (confirm("Are you sure you want to delete this?")){
$.ajax({
  type: "DELETE",
  url: "{% url 'delete' pk=warns.pk %}",
  beforeSend: function(xhr) {
    xhr.setRequestHeader("X-CSRFToken", getCookie("csrftoken"));
  }
  success: function() {
    var close=$(this).parent();
    close.fadeOut(1000);
     });
    }
   })
  }
 });

A: The main.js is as follows.
$(".close").click(function () {
  var close=$(this).parent();
  if (confirm("Are you sure you want to delete this?")){
    $.ajax({
      type: "DELETE",
      url: $(this).data('url'),
      beforeSend: function(xhr) {
        xhr.setRequestHeader("X-CSRFToken", getCookie("csrftoken"));
      },
      success: function() {
        close.fadeOut(1000);
      }
    });
  }
});


text:
Q: Mixing PCL libraries and non-PCL code I did not find a similar question, lets see if that holds true :-).
I want to use C# based PCL libraries also in "normal" aka plain windows x86 C# projects (instead of just using them inside cross-platform (Xamarin) projects).
The reason for this is basically back porting for legacy projects: I want to switch to PCL code for future projects and use new features also in old code. As you can imagine, these projects are at least partially developed for older version of the C# runtime (namely 4.0).
My question is this: Can I expect the libraries to behave similar, that means if my basic unit tests pass, I am good to go? Or is there random behavior that makes it hard to validate the proper functioning of a library? I am especially worried about articles/questions I read in regards to HttpClient code behaving unexpectedly, but not even consistently wrong across various runtime versions (4.0 - 4.5). Thus the team would chase issues that cannot be reproduced and ruin the support teams weekends :-P.
I am not so sure if the question is easy to understand in all aspects, please let me know if it makes sense. If it is toooo confusing I may rephrase it after people have made suggestions... .

A: In the project properties of you PCL, you can check what versions of .Net and what Platforms you want to support.
In the background, you selection geht's mapped down to a portable subset profile where only those APIs are available, that are supported on all your selected platforms.
(PCLs are not a Xamarin specific thing though.)
There are some cases where platform implementation details leak through, for example with timers (they aren't even included in some portable subsets).
Your Unit Tests will probably pass, and once you notice some specific problems, you can still add additional testing there.
For HttpClient, I'd recommend dependency injecting some platform specific client anyway (like with modernhttpclient) just for performance reasons.


text:
Q: Jenkins Ansible plugin Permission denied (publickey,password) - failing to copy private key I'm trying to use the Jenkins Ansible plugin to deploy a project. I figured this should be pretty easy as i'm pretty familiar with both Jenkins and Ansible. However, i'm having issues getting the Ansible command to successfully execute. I believe the problem lies in the use of the credentials. We have a jenkins user that owns the Jenkins execution process and we have a jenkins user setup on the machine being deployed to. We are using SSH keys and I have added the jenkins users private key to the Jenkins credential store and selected those in the Ansible configuration. However, when i run the job, this is the snippet of my output (replaced some information).
[my-job] $ ansible-playbook my-job.yml -i inventories/dev -l 1_2_3_4 -f 1 --private-key /tmp/ssh7229752594712048879.key -u jenkins --diff --vault-password-file ~/.vault-pass

PLAY [tag_ansible_groups_my_job] ***********************

TASK [setup] *******************************************************************
fatal: [1_2_3_4]: UNREACHABLE! => {"changed": false, "msg": "Failed to connect to the host via ssh: Permission denied (publickey,password).\r\n", "unreachable": true}
    to retry, use: --limit @/data/jenkinsdata/workspace/my-job/my-job.retry

PLAY RECAP *********************************************************************
1_2_3_4              : ok=0    changed=0    unreachable=1    failed=0

FATAL: command execution failed
hudson.AbortException: Ansible playbook execution failed
    at org.jenkinsci.plugins.ansible.AnsiblePlaybookBuilder.perform(AnsiblePlaybookBuilder.java:227)
    at org.jenkinsci.plugins.ansible.AnsiblePlaybookBuilder.perform(AnsiblePlaybookBuilder.java:200)
    at hudson.tasks.BuildStepCompatibilityLayer.perform(BuildStepCompatibilityLayer.java:78)
    at hudson.tasks.BuildStepMonitor$1.perform(BuildStepMonitor.java:20)
    at hudson.model.AbstractBuild$AbstractBuildExecution.perform(AbstractBuild.java:779)
    at hudson.model.Build$BuildExecution.build(Build.java:205)
    at hudson.model.Build$BuildExecution.doRun(Build.java:162)
    at hudson.model.AbstractBuild$AbstractBuildExecution.run(AbstractBuild.java:534)
    at hudson.model.Run.execute(Run.java:1729)
    at hudson.model.FreeStyleBuild.run(FreeStyleBuild.java:43)
    at hudson.model.ResourceController.execute(ResourceController.java:98)
    at hudson.model.Executor.run(Executor.java:404)
ERROR: Ansible playbook execution failed
Finished: FAILURE

I've run the same command successfully from the Jenkins machine and it works just fine. The only difference was that I referenced the original SSH private key instead of the copied temporary key. To see if this was the issue, I decided to check the contents of the copied temporary SSH private key and the file was empty. I checked the file before the job finished executing as I am assuming it stays there for the life of the job and removed only after the job has finished executing. To verify this, I removed the use of credentials from the configuration and added in the private-key and user parameters pointing directly to the appropriate key and the job runs successfully.
[my-job] $ ansible-playbook my-job.yml -i inventories/dev -l 1_2_3_4 -f 1 --private-key ~/.ssh/id_rsa -u jenkins --diff --vault-password-file ~/.vault-pass

PLAY [tag_ansible_groups_my_job] ***********************

TASK [setup] *******************************************************************
ok: [1_2_3_4]

So, to me, it seems that Jenkins is failing to copy the SSH private key to the temporary file(s). I've tried with other SSH keys but still the same problem each time. I've tried specifying the private key in Jenkins credential store itself rather than specifying the location and that also did not work. I've checked the Jenkins logs and there is nothing that would indicate why the private SSH key would fail to copy to the /tmp directory.
I'd prefer not to reference the key directly in the additional parameters as this limits me to only keys located on that server. Any suggestions?

A: I found this solution at Edureka. It worked for me.
set "host_key_checking = False" in /etc/ansible/ansible.cfg
https://www.edureka.co/community/42595/not-able-connect-remote-host-via-jenkins-run-ansible-playbook


text:
Q: How to add a variable to another variable that's already set My homework is to create a program that takes a list of numbers and prints out the highest number divisible by four.
List would look like this:
12
16
87
58
25
73
86
36
79
40
12
89
32

Input should be:
40 because it is the highest number there divisible by four.
Here is my code:
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        int saved = 0;
        int saved2 = 0;

        for (int i = scanner.nextInt(); i % 4 == 0; i = scanner.nextInt()) {
            for (boolean bull = true; bull == true; bull ^= true) {
                if (i > saved) {
                    saved -= saved2;
                    saved += i;
                    saved2 += i;
                }
            }

            System.out.println(saved);
        }
    }
}

The input of my code is
12
16

I don't really understand why this is doing it, but it seems to me that I'm adding the variables wrong. The homework page on adding variables does not specify how to add variables to each other.
Does anyone have a tip to improve the code in anyway, or find a way to make a fix my code? Thank you.

A: welcome to Java.
First you are saying you got input, but that is output. Input is what you enter, and output is what you get printed.
Then there is a mistake in your for loops. You have too much going on in one place. By the logic which is implemented, your program will exit first level for loop whenever your entered value is not divisable by 4.
Read on for loops if you want to learn more https://www.learnjavaonline.org/en/Loops.
I recommend to start from while loops instead. The logic whould be this:
1. create variable to hold the correct answer saved
2. create another one to hold the value read from console i
3. start the while loop with condition i = scanner.nextInt()
3.1 check if the value just entered i is divisable by 4
3.2 if it is, then compare if it's larger than the one was saved before (initially saved value will be 0)
3.3 if it is larger, then assign the read value i to the saved
4. At the end of the loop, you will have the highest number divisable by four in your saved variable. Print it.

A: I will provide some help, according to
How do I ask and answer homework questions?
for (int i = scanner.nextInt(); i % 4 == 0;i = scanner.nextInt())

This only reads as long as ALL inputs are divisible by 4, that is why it ends at 16, because 87 is not divisible by 4.
for (boolean bull = true; bull == true ;bull ^= true)

This needs explanation by you, but I am pretty sure that it unconditionally executes the body of the inner loop exactly once. (Not 100% sure, because the representation of true and false could be weird in your machine. Should 0 be the representation of true, i.e. really weird, then it is an endless loop, which does not match the output you describe...)
System.out.println(saved);

This executes exactly once per input, except the last one, which is not a multiple of 4.
The value of saved is identical to input, as long as it is increasing.
These hints explain the unexpected output.
If you inspect the details of what the problem is, you should be able to improve your coding attempt.

A: This is how I super-quickly fixed in your code.
Note that there are no statements about the possible minimum value and about how do you stop the input. Therefore the solution is pretty-straightforward, it just reads the input until integers are present there.
This article may be useful about handling the input from the Scanner.
I hope the comments in the code will help. Add comments if there are any questions. Good luck!
import java.util.Scanner;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);

        int currentMax = Integer.MIN_VALUE; // you may set negative or 0 if you know that all the input is positive
//      int saved2 = 0; // no need for this variable

        while (scanner.hasNextInt()) { // you can make a better input handling, especially if you know when it should end the input. Now it will end on any non-integer input line
            int i = scanner.nextInt();

            //      for (int i = scanner.nextInt(); i % 4 == 0; i = scanner.nextInt()) {
//          for (boolean bull = true; bull == true; bull ^= true) {
                if (((i % 4) == 0) && (i > currentMax)) {
                    currentMax = i;
//                  saved -= saved2;
//                  saved += i;
//                  saved2 += i;
//              }
            }
        }

        System.out.println(currentMax); // moved out of "for" or "while" cycles. Print the value after the input has ended.
    }
}


text: Q: Is there any way to search for a particular registry key on Windows ruby I am trying to get the environment variable details of a particular user(non-administrator) from Administrator and when I was searching manually on registry editor found that its located under Computer\HKEY_USERS\S-..........\Environment. So came to the conclusion that I have to look for \HKEY_USERS\*\Environment and iterate each key to get the desired key and value. When I did google found that I have to pass the path for Win32::Registry::HKEY_USERS.open() and not suer how to pass the wildcard kind of value in the path. Any suggestion to get around this or if there is a better way (like getting the list of environment variables for the given username) to get the desired data that also would be great.


text:
Q: How can I create group of objects to store information? I have two models Pigeons and Treatment. Every pigeon can have multiple treatment. I want to create some groups of pigeon like all pigeons, cock, female, squeakers and when I want to create a treatment to select the group and assign the medication.
#models
class Pigeons(models.Model):
    ring= models.CharField(max_length=25, null=False, blank=False, unique=True)
    status = models.ForeignKey(PigeonStatus, on_delete=models.CASCADE, null=False, blank=False)
    ......

class Treatment(models.Model):
    date = models.DateTimeField(default=timezone.now, null=True, blank=True)

    # we can treat only one pigeon

    pigeon = models.ManyToManyField(Pigeons, on_delete=models.CASCADE)

    # or select group to assign medication

    group = ......
    medication = models.ForeignKey(Medication, on_delete=models.SET_NULL)

Which is the best approach to do this? I have to create a separate model that store groups or it can be in the template?

A: You need to decide the best approach for your project.  The two most common approaches would be to use a ForeignKey
group = models.ForeignKey(Sex, on_delete=models.CASCADE)

OR to use choices
SEX_OPTIONS = (
    ('male','Male'),
    ('female',Female')
)

group = models.CharField(max_length=6, choices=SEX_OPTIONS)


text:
Q: jQuery load div content only when selected I am planning to set up a lot of tabs that will contain a massive amount of HTML, and I don't won't the page to be slowed down and have all the content loaded to the DOM on page load. So how can I use jQuery to load the div content only when each tab is selected?
HTML would be something like this:

Tab 1

Tab 2

Tab 3

CONTENT

CONTENT

CONTENT

A: This would indeed be best achieved using AJAX.
You could store an array of tab content objects and load them based on tab index;

Tab 0

Tab 1

Tab 2

See jsFiddle

A: You can load neccessary data using Ajax and putting it to your div.
By the way, in this case you only need one div for the content.
jQuery(document).ready(function(){
    jQuery('#nav a').click(function(){
        jQuery.get('get_content.php',{
            content: jQuery(this).attr('href').substr(1)
        },function(data){
            jQuery('#content').html(data);
        });
        return false;
    });
});

get_content.php will receive $_GET['content'] == 'content1' or 'content2' or 'content3' depending on which button is clicked, so knowing this you should return necessary content from it.


text:
Q: Video recording of IPhone screen of total game play I want to record screen video recording during application running and unfortunately apple didn't provide any scratch code on it.
The scenario is there a 'RECORD' button and a 'STOP' button. when I touch 'RECORD', I need to take a video of the entire gameplay (Screen Video) and stop recording when I touch 'STOP'.
Is there any other method besides the screenshot method to do this?
For example - Talking Tom, Angry birds, etc.

A: Instead of taking a video, you could record the user interactions and replay them. If you use a PRNG for random events, you should also make sure to seed it with the same value while replaying a game.
Screen capture in iOS has a few problems, one of which being performance, and the other being the fact that some animations are not captured because they happen at some low level, out of sight for normal screen capturing methods.
This, of course, will only replay the game on screen.

A: if we talk about angry birds, that has been developed in COCOS2D and if your game is also developed in cocos2d, you are lucky..!! Maybe if you dig-in you could find a way to use it with UIKit as well...who knows..!!
there is a cocos2d 3rd party utility named -Kamcord that can be used for recording gameplay.
kamcord.com
COCOS2D Kamcord archive link

A: We provide an SDK called "Everyplay" that allows you to do exactly what you're looking for. It's free to use, and is lightweight.
We provide out-of-the-box integrations for Unity3D, cocos2d (1.x, 2.x), cocos2d-x, and you can of course integrate to a custom OpenGL-based game engine.
The documentation is available at https://developers.everyplay.com/doc
The documentation contains an example app key to use when developing, but you can of course sign up for your own client key at https://developers.everyplay.com/


text:
Q: Automatic start of an EC2 instance with auto-scaling I do not know much about how AWS works since the person who set the whole thing up does not work with us anymore, and I do not specialize in Amazon at all.
I need to set up an auto-scaling on my EC2 instance. I am currently reading all available tutorials to learn the how-to, but there is one thing I cannot find at all. The auto-scaling automaticaly start new instance of EC2 but I cannot find anything about how to do anything in those instance.
Currently, to start our webservices, we need to log into the instance, pull the code from git and launch the whole thing with PM2. I cannot find anything about how to do all those things automatically at the start of the instance.
I think this is supposed to be basic stuff, but as I said, I know next to nothing about how to start, and I do not have much time to learn (my boss just told me I had to be done by the end of the week !)
So if anyone know where to learn this, that would be really helpful. Thanks!

A: You need a Launch Configuration for setting up an Auto Scaling Group (ASG). The Launch Configuration is where you define all your instance configurations such as type, disk size, security groups, etc. One of these configurations is AMI ID. The AMI ID refers to the image to be used when launching a new instance in the ASG. So you basically need to launch a machine, install everything needed on it, create an image out of it, create a launch configuration using that image, and use that launch configuration in your ASG. This way you do not need to go to the newly added servers every time. But if you like them to run the updated (last) version of your application, you should have a scheduled job in your image which is triggered on-start. This job is responsible for copying the files (e.g. compiled files) from somewhere (a deployment machine for instance) to the newly added instance and then starting it.

A: The method for configuring an Amazon EC2 instance does not actually require Auto Scaling. The two main options for configuring an instance are:

*

*Launching from a pre-configured AMI that already contains the desired software, or

*Running a startup script via User Data, which executes once the instance has launched

You can choose one of the above and then test it by launching an instance via the management console or from a script that calls the AWS Command-Line Interface (CLI).
To incorporate it into Auto Scaling, configure the Auto Scaling Launch Configuration with the same parameters and then each new instance launched by Auto Scaling will automatically be configured.


text:
Q: Python does not stop reading from stdin buffer In Node.JS, I spawn a child Python process to be piped. I want to send a UInt8Array through stdin. So as to notify the size of the buffer data to be read, I send the size of it before. But it doesn't stop reading for the actual data from the buffer properly after a specified size. As a result, the Python process doesn't terminate forever. I've checked that it takes bufferSize properly and converts it into an integer. In the absence of size = int(input()) and python.stdin.write(bufferSize.toString() + "\n") and when the size of the buffer is hardcoded, it works correctly. I couldn't figure out why it does not end waiting after reading for the specified amount of bytes.
// Node.JS
const python_command = command.serializeBinary()
const python = spawn('test/production_tests/py_test_scripts/protocolbuffer/venv/bin/python', ['test/production_tests/py_test_scripts/protocolbuffer/command_handler.py']);

const bufferSize = python_command.byteLength
python.stdin.write(bufferSize.toString() + "\n")
python.stdin.write(python_command)

# Python
size = int(input())
data = sys.stdin.buffer.read(size)

In a nutshell, the problem arises from the fact that putting normal stdin input() firstly and then sys.stdin.buffer.read. I guess the preceding one conflicts with the successive one and precludes it to work normally.

A: There are two potential problems here. The first is that the pipe between node.js and the python script is block buffered. You won't see any data on the python side until either a block's worth of data is filled (system dependent) or the pipe is closed. The second is that there is a decoder between input and the byte stream coming in on stdin. This decoder is free to read ahead in the stream as it wishes. Reading sys.stdin.buffer may miss whatever happens to be buffered in the decoder.
You can solve the second problem by doing all of your reads from the buffer as shown below. The first problem needs to be solved on the node.js side - likely by closing its subprocess stdin. You may be better off just writing the size as a binary number, say uint64.
import struct
import sys

# read size - assuming its coming in as ascii stream
size_buf = []
while True:
    c = sys.stdin.buffer.read(1)
    if c == b"\n":
        size = int(b"".join(size_buf))
        break
    size_buf.append(c)

fmt = "B" # read unsigned char
fmtsize = struct.calcsize(fmt)
buf = [struct.unpack(fmt, sys.stdin.buffer.read(fmtsize))[0] for _ in range(size)]
print(buf)


text:
Q: how to search in a ArrayList? I have to search a contact by name, surname or telephone number.
how can i do that?
I think i can't use java 8 stream in this case...
Another thing... I have to press "2" two times in order to see all the contact list but the if implementation seems right to me.
The code:
import java.util.ArrayList;
import java.util.Scanner;

public class Test1 {
public static void main(String args[]) {
    Scanner in = new Scanner( System.in );
    ArrayList<Contatto> cont = new ArrayList<Contatto>();
    int a;
    try{
        while (true){
            System.out.println("Per inserire nuovo contatto premere 1");
            System.out.println("Per visionare l'elenco dei contatti premere 2");
            System.out.println("Per cercare un contatto premere 3");
            a= in.nextInt();
            //if you press1 you add new contact
            if (a == 1){
                cont.add(new Contatto());
            }
            //if you press2 you'll see all the contact list.
            else if (a == 2){
                for (Contatto tmp : cont){
                    String tm = tmp.dammiDettagli(tmp);
                    System.out.println(tm);
                }
            }
            //if you press 3 you'll be able to search a contact by name or
            //surname or telephone number
            else if (a == 3){
                System.out.println("Cerca contatto:");
                }
            else {
                System.out.println("Inserimento dati errato");
                }
            }

    }finally {
        in.close();
    }
}
}

and this is the public class Contatto:
import java.util.Scanner;

public class Contatto {
private String nome;
private String cognome;
private String num_Tel;
Contatto(){
    @SuppressWarnings("resource")
    Scanner in = new Scanner( System.in );
        System.out.println("Creazione nuovo contatto...");
        System.out.println("Inserire il nome:");
        //set name
        setNome(in.next());
        System.out.println("Inserire il cognome:");
        //set surname
        setCognome(in.next());
        System.out.println("Inserire il numero di telefono:");
        //set telephone number
        setNum_Tel(in.next());
}
//method to search contact
public String cercaContatto(String in){
}
public String dammiDettagli(Contatto contatto){
    return getNome() +" "+ getCognome() +" "+ getNum_Tel();
}
public String getNome() {
    return nome;
}
public void setNome(String nome) {
    this.nome = nome;
}
public String getCognome() {
    return cognome;
}
public void setCognome(String cognome) {
    this.cognome = cognome;
}
public String getNum_Tel() {
    return num_Tel;
}
public void setNum_Tel(String num_Tel) {
    this.num_Tel = num_Tel;
}
}

A: This could be done in Java 8 as next:
Optional<Contatto> result = cont.stream().filter(c ->
    (nome == null || nome.equalsIgnoreCase(c.getNome()))
        && (cognome == null || cognome.equalsIgnoreCase(c.getCognome()))
        && (num_Tel == null || num_Tel.equals(c.getNum_Tel()))
).findFirst();

Assuming that nome, cognome and num_Tel are String representing your query's criteria.
If nome, cognome and num_Tel are Optional<String> representing your query's criteria, it will then be:
Optional<Contatto> result = cont.stream().filter(c ->
    nome.map(s -> s.equalsIgnoreCase(c.getNome())).orElse(true)
        && cognome.map(s -> s.equalsIgnoreCase(c.getCognome())).orElse(true)
        && num_Tel.map(s -> s.equals(c.getNum_Tel())).orElse(true)
).findFirst();

A: You can Add a method for each type of search that you are performing and call that method in choice "3". The method is simple and pretty straightforward, for example, for searching by phone number
private static Contatto SearchContattoNumber( ArrayList<Contatto> cont, int number ) {
  for (Contatto tmp : cont){
    if (tmp.getNum_Tel() == number) return tmp;
  }
  return null;
}

And you would create such a method for each Search option, and then decide which search you're gonna use by asking the user just like you did ask for what operation you will perform


text:
Q: Tooltips for multiple line graphs in D3 I am new to D3 and my requirement is to get multiple line graphs and provide tooltips for them.
I could get the multiple line graphs to appear but i am going wrong in getting multiple tooltip points.
I am new to javascript as well. So any help will be much appreciated.
Here is my code.

A: When you are creating the second point, nothing actually happens. The .data() function will try to match the data elements you pass to what you have selected (in this case one circle) and will succeed here. This means that your enter selection is empty and nothing happens.
The d3 way is to pass in all the data you want to use to create elements at once and handle accordingly in the functions to set attributes etc. That is, your code should look something like
svg.selectAll("circle")
   .data(D3Obj)
   .enter().append("circle")
   .attr("fill", function(d, i) { if(i == 0) { return "red"; } else { return "steelblue"; } })
   .attr("r", 2)
   .attr("cx", xx)
   .attr("cy", yy)
   .on("mouseover", function(d) { showData(this, d.returns);})
   .on("mouseout", function(){ hideData();});

This will create two circles and attach the corresponding listeners to them.


text:
Q: Popup SendMessage to Background Service Worker (MV3) Cannot Establish Connection Update
It seems like webpack is causing the issues.
If I replace the dist/background.js with:
console.log("background is running"); // Now visible ✅

const handler = (req, sender, sendResponse) => {
  switch (req.type) {
    case "message":
      sendResponse({ data: "hi" });
      break;

    default:
      break;
  }
};

chrome.runtime.onMessage.addListener(handler);

Both the console log (in service worker) and response (in popup) are observed. Also, there are no errors.
Time to investigate further
Update #2
Upon further inspection, I noticed that the webpack output is wrapped in a function, but never called:
{
    /***/ "./src/background.ts":
      /*!***************************!*\
  !*** ./src/background.ts ***!
  \***************************/
      /***/ (function () {
        console.log("background is running");
        const handler = (req, sender, sendResponse) => {
          switch (req.type) {
            case "message":
              sendResponse({ data: "hi" });
              break;
            default:
              break;
          }
        };
        chrome.runtime.onMessage.addListener(handler);

        /***/
      }) // <==== adding () will make it an IIFE and everything works!
  },

Question is how to automate this?
Update #3
Seems like the IIFE trick I mentioned above only works when there are no imports in background.js. As soon as I add any import, I get an error that the background script is not valid.
Adding module type property to background does not help:
// manifest.json
{
  ...
  "background": {
    "service_worker": "background.js",
    "type": "module"
  },
  ...
}

Update #4
Turns out this was caused by vendor splitting optimization in webpack:
// webpack.config.json
{
  ...
  optimization: {
    runtimeChunk: "single",
    splitChunks: {
      cacheGroups: {
        vendor: {
          test: /[\\/]node_modules[\\/]/,
          name: "vendors",
          enforce: true,
          chunks: "all",
        },
      },
    },
  },
  ...
}

Once I removed this, everything started working properly!
Would be nice to keep this around, but it is just an optimization after all, so if it breaks things, best to get rid of it.
How I figured this out? Well as I mentioned, everything worked a couple of commits ago. Back then I didn't have this optimization, so I tried removing it again, and everything started working again like magic.
Original Question
I had this working previously, so I am sure my setup is correct, but regardless of what I try, I now get

Unchecked runtime.lastError: Could not establish connection. Receiving end does not exist.

Also, I cannot find a solution online which indicates anything that differs from my setup.
Here is a MWE
dist folder structure:
dist/background.js
dist/index.html
dist/manifest.json
dist/popup.js
dist/runtime.js
dist/vendors.js
other misc files

// manifest.json
{
  ...
  "background": {
    "service_worker": "background.js"
  },
  ...
}

// src/components/App.tsx
export default function App(): JSX.Element {
  ...

  useEffect(() => {
    chrome.runtime.sendMessage({ type: 'someMessage' }, ({ data }) => {
      console.log(data);
    });
  }, []);

  ...
}

// src/background.ts
import { TSentResponse } from "./typings/background";
import { executeResponse } from "./utils/background";

console.log('sanity check'); // <=== does not fire

// also doesn't seem to be called
const handleMessage = (req: { type: string }, sender: chrome.runtime.MessageSender, res: (response?: unknown) => void) => {
  switch (req.type) {
    case 'someMessage':
      // an IIFE (worked fine before)
      break;

    default:
      break;
  }

  return true; // due to asynchronous nature
};

chrome.runtime.onMessage.addListener(handleMessage);

My service worker is registered properly:

When I said above that I cannot see the logs for background, I mean when I check in the service worker dev tools (from above image), not the popup dev tool.
When I open the popup, I get the following errors:

Unchecked runtime.lastError: Could not establish connection. Receiving end does not exist.

Error handling response: TypeError: Cannot destructure property 'data' of 'undefined' as it is undefined.

I also don't see the service worker actually being registered - it did register before...

Is this a bug with MV3?
My repository (not fully up to date, but can be used to quickly check the above)

A: Follow these steps:

*

*To send a message from the popup.js to the background service worker, first you need to get  current tab id. to get the current tab id do as below:
popup.js
const messageKey = 'key-message-from-popup-to-background';

// Listen to get current tab info from the content_popup
document.addEventListener('_listener_getCurrentTabInfo', function (e) {
    const tab = e.detail.response;

    // Send a message to the background,js
    chrome.tabs.sendMessage(tab.id, messageKey);
});

// Send message to content_popup to get current tab info
document.dispatchEvent(new CustomEvent('_dispatch_getCurrentTabInfo'));

content_popup.js
const config = {
    scripts: [
        // add ".js" files to web_accessible_resources in manifest.json
        "popup/popup.js"
    ]
};

// Listen to get current tab info from the background.js
document.addEventListener('_dispatch_getCurrentTabInfo', function (e) {

    // Key to help
    const type = 'get_current_tab_info';

    // Send a message to the background.js to get current tab info
    chrome.runtime.sendMessage({type: type}, response => {
        document.dispatchEvent(new CustomEvent('_listener_getCurrentTabInfo', {detail: {'response': response}}));
    });
});

// prepare and add scripts
var scriptList = config['scripts'];

for (var i = 0; i < scriptList.length; i++) {
    var s = document.createElement('script');
    s.src = chrome.runtime.getURL(scriptList[i]);
    s.onload = function () {
        this.remove();
    };
    (document.head || document.documentElement).appendChild(s);
}

background.js
// Get messages
chrome.runtime.onMessage.addListener(function (request, sender, sendResponse) {

    // If request related to fetch data from API
    if (request.url && request.url !== '') {

        // Fetch http request and send back the response
        fetch(request.url, request.init).then(function (response) {

            return response.text().then(function (text) {
                sendResponse([{
                    body: text,
                    status: response.status,
                    statusText: response.statusText,
                }, null]);
            });
        }, function (error) {
            sendResponse([null, error]);
        });

        // If request do not related to fetch data from API
    } else {
        detectMessageType(request, sender, sendResponse);
    }

    return true;
});

function detectMessageType(request, sender, sendResponse) {

    // Check background request type
    if (request && request.type) {
        switch (request.type) {
            case 'get_current_tab_info': {
                getCurrentTabInfo(tab => {

                    // Send current tab info back to content_popup
                    sendResponse(tab);
                });

                break;
            }
        }
    }
});

function getCurrentTabInfo(callback) {
    chrome.tabs.query({
        active: true,
        currentWindow: true
    }, function (tab) {
        callback(tab[0]);
    });
}

*Get message in contentScript
chrome.runtime.onMessage.addListener((message, sender, response) => {
    const message = message;
    // Write your codes
});

*This is the project structure (partial)
Project
  -- popup
  ---- popup.js
  ---- content_popup.js
  ---- popup.html
  ---- popup.css
  -- content_extension.js
  -- background.js
  -- manifest.js

*Add the following code to the end of the body tag inside the popup.html file
<script src="content_popup.js"></script>

*Update the manifest.json file like below
"manifest_version": 3,
.
.
.
"content_scripts": [
    {
        "js": [
            "content_extension.js"
        ]
    }
],
"action": {
    "default_icon": ...,
    "default_title": ...,
    "default_popup": "popup/popup.html"
},
"background": {
    "service_worker": "background.js"
},
"web_accessible_resources": [
    {
        "resources": [
            "popup/popup.html",
            "popup/popup.js"
        ]
    }
],
...