text:
Q: Why do 9-patch graphics size correctly in the emulator but not on a phone? I have a RelativeLayout that has a 9-patch background image. The image is a simple speech bubble with a perfectly centered "arrow" at the bottom middle.
The RelativeLayout is inflated and placed on a MapView. Using the emulator, the speech bubble can be easily pointed to a location and will expand to its contents (text, an image, or both). When I run my app on a phone however, the 9-patch doesn't stretch properly. The "arrow" for the speech bubble will be offset to the left by a very noticeable amount.
I primarily test on a Nexus S, but also a Samsung Captivate and Nexus One. Targeting SDK 7. Tested emulators for SDK 7+. Only hardware devices seem to have this problem.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
                android:layout_height="wrap_content"
                android:id="@+id/BubbleLayout"
                android:background="@drawable/bubble"
                android:layout_width="wrap_content"
                android:gravity="center_horizontal">
    <TextView android:layout_height="wrap_content"
              android:id="@+id/date"
              android:layout_width="wrap_content"
              android:maxWidth="196dp"></TextView>
    <TextView android:layout_below="@+id/date"
              android:layout_height="wrap_content"
              android:layout_width="wrap_content"
              android:maxWidth="196dp"
              android:id="@+id/summary"></TextView>
</RelativeLayout>

A: Make sure you have an mdpi and an hdpi version if you test on different densities. If you put your 9patch in res/drawable/ for instance, it will be treated as an mdpi asset and scaled up automatically on hdpi devices (Nexus S). Because it's an automatic process, the results are not guaranteed.


text:
Q: magento > how to get _defaultValues:protected i use this code to get product prices from magento:
include_once '../../app/Mage.php';
Mage::app();
$model = Mage::getModel('catalog/product');//getting product model
$collection = $model->getCollection(); //products collection
foreach ($collection as $product) //loop for getting products
{
    $model->load($product->getId());
    echo $model['price'];
}

so, when i use this script, for some products, the right prices is given, but for some products it is not the right price.
when i var_dump() the $model->load($product->getId()); the right price is always in here:
["_defaultValues:protected"]=>
  array(5) {
    ["special_price"]=>
    string(7) "32.0000"
    ["visibility"]=>
    NULL
    ["status"]=>
    string(1) "1"
    ["price"]=>
    string(8) "399.9900"
    ["name"]=>
    string(51) "Philips Home cinema met 3D Blu-ray iPod/iPhone-dock"
  }

How to change to code to get this 399,99 price, instead of the '1' I get when using $model['price']?

A: Check the DOCs
Class Mage_Catalog_Model_Product_Type_Price
$model->getPrice();

$model->getFinalPrice();

and maybe you try to run price indexer
also check if this product is grouped/configurable product so you need to use different method ( $mode->getCalculatedPrice() );

redpajama_set_name: RedPajamaStackExchange


text:
Q: PHP database foreign key I have this piece of code
CONSTRAINT has FOREIGN KEY(fk_AirFareAfID) REFERENCES AirFare(AfID)
and it's giving me this error:
#1064 - You have an error in your SQL syntax; check the manual that
corresponds to your MariaDB server version for the right syntax to use
near 'have FOREIGN KEY(fk_ChargesChID) REFERENCES Charges(ChID)

What could be the problem?
Full code of the part:
CREATE TABLE Transactions(
    TsID INT NOT NULL,
    BookingDate TIMESTAMP NOT NULL,
    DepartureDate TIMESTAMP NOT NULL,
    Passenger INT NOT NULL,
    Flight INT NOT NULL,
    TYPE BLOB NOT NULL,
    Employee INT NOT NULL,
    Charges INT NOT NULL,
    Discount INT NOT NULL,
    fk_ChargesChID INT NOT NULL,
    fk_DiscountsDsID INT NOT NULL,
    CONSTRAINT pks PRIMARY KEY(TsID),
    CONSTRAINT can have FOREIGN KEY(fk_ChargesChID) REFERENCES Charges(ChID)
)

A: Remove "can have"...
CREATE TABLE Transactions(
    TsID INT NOT NULL,
    BookingDate TIMESTAMP NOT NULL,
    DepartureDate TIMESTAMP NOT NULL,
    Passenger INT NOT NULL,
    Flight INT NOT NULL,
    TYPE BLOB NOT NULL,
    Employee INT NOT NULL,
    Charges INT NOT NULL,
    Discount INT NOT NULL,
    fk_ChargesChID INT NOT NULL,
    fk_DiscountsDsID INT NOT NULL,
    CONSTRAINT pks PRIMARY KEY(TsID),
    CONSTRAINT FOREIGN KEY(fk_ChargesChID) REFERENCES Charges(ChID)
)

... or replace it with a symbol, which is the name for the constraint. You can't use two words there. You've done this in the line above where pks is your symbol.


text:
Q: AWS EC2 Container program command line arguments I am trying to run a Play Framework application on AWS EC2 Containers. I am using sbt-ecr to build and upload the image.
Now I would like to pass different command line parameters to Play, for instance -Dconfig=production.conf.
Usually when I run it locally my command looks like this:
docker run -p 80:9000 myimage -Dconfig.resource=production.conf

The port settings can be configured separately in AWS. How can I set Play's command line parameter for AWS EC2 containers?

A: Apparently my problem was of a completely different nature and didn't have anything at all to do with the entrypoint or cmd arguments.
The task didn't start because the loggroup which was configured for the container didn't exist.
Here is how to pass parameters to an image on ECS just like on the command line or using the docker CMD instruction. Just put them in the "Command" field in the "Environment" section of the container configuration like so:
-Dconfig.resource=production.conf,-Dhttps.port=9443


text:
Q: WPF: TreeView in MVVM I have a TreeView that I (finally) have been able to populate from a database using data binding.
There are 2 objects that live in the tree:

*

*FavoriteFolder — an object that can have children: either folders or reports.

*FavoriteReport — an object that cannot have any children: when a user clicks on this item it will run a report.

Currently I have a Model-View type setup (I think), and I would like to change it to MVVM so I can do things with the TreeView-items rather than simply display them.
I have looked at many examples, but I am still new to MVVM and WPF in general, so any guidance for my particular example would be much appreciated
My two classes that exist in the TreeView are:
Folder items:
public class FavoriteFolder
{
    private string _connectionString = new ServerInfo().ConnectionString;
    private string _folderID;
    private string _parentID;
    private string _folderTitle;

    private ObservableCollection<FavoriteFolder> _folders;
    private ObservableCollection<FavoriteReport> _reports;
    private ObservableCollection<object> _children;

    public FavoriteFolder()
    {

    }

    public ObservableCollection<object> Children
    {
        get
        {
            _getChildren();
            return _children;
        }
    }

    public string FolderID
    {
        get { return _folderID; }
        set { _folderID = value; }
    }

    public string ParentID
    {
        get { return _parentID; }
        set { _parentID = value; }
    }

    public string FolderTitle
    {
        get { return _folderTitle; }
        set { _folderTitle = value; }
    }

    private void _getChildren()
    {
        _folders = new ObservableCollection<FavoriteFolder>();
        _reports = new ObservableCollection<FavoriteReport>();

        using (SqlConnection cnn = new SqlConnection(_connectionString))
        {
            cnn.Open();
            string sql = "SELECT * FROM tbl_report_folders where fdr_parent_id =" + _folderID;
            SqlCommand cmd = new SqlCommand(sql, cnn);

            SqlDataReader reader = cmd.ExecuteReader();

            while (reader.Read())
            {
                FavoriteFolder folder = new FavoriteFolder();

                folder.FolderID = reader["fdr_folder_id"].ToString();
                folder.FolderTitle = reader["fdr_folder_name"].ToString();
                folder.ParentID = reader["fdr_parent_id"].ToString();

                _folders.Add(folder);
            }

            reader.Close();

            sql = "SELECT * FROM tbl_reports where rpt_folder_id =" + _folderID;
            cmd = new SqlCommand(sql, cnn);

            reader = cmd.ExecuteReader();

            while (reader.Read())
            {
                FavoriteReport report = new FavoriteReport();

                report.ReportID = reader["rpt_report_id"].ToString();
                report.ReportTitle = reader["rpt_report_name"].ToString();
                report.ParentID = reader["rpt_folder_id"].ToString();

                _reports.Add(report);
            }
        }

        //add the children to the collection
        foreach (var folder in this._folders)
            _children.Add(folder);

        foreach (var report in this._reports)
            _children.Add(report);
    }
}

Report Items:
public class FavoriteReport
{
    private string _reportID;
    private string _parentID;
    private string _reportTitle;

    public FavoriteReport()
    {

    }

    public string ReportID
    {
        get { return _reportID; }
        set { _reportID = value; }
    }

    public string ParentID
    {
        get { return _parentID; }
        set { _parentID = value; }
    }

    public string ReportTitle
    {
        get { return _reportTitle; }
        set { _reportTitle = value; }
    }
}

And the MainWindow.xaml.cs -
public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();

        ObservableCollection<object> items = new ObservableCollection<object>();

        FavoriteFolder fdr = new FavoriteFolder();

        fdr.FolderID = "0";

        items = fdr.Children;

        this.DataContext = items;
    }
}

A: My first recommendation would be to drop in an MVVM toolkit, as it's easier than having to do everything yourself (e.g. implement the INotifyPropertyChanged interface). I use MVVM Light by Laurent Bungion.
On the assumption that you're using MVVM Light (you can extrapolate from this if you're using another toolkit)...
So, to convert this to MVVM you need to do a few things.

*

*Create defined Models. I generally use POCO's, simply defining the properties of a model. This means abstracting out your data access layer (more below).

*Create your ViewModel. This is where you'd have your properties that you're binding to in your veiw. Your ObservableCollections would sit here. Initializing an instance of the classes you created would go here.  Calls to your DAL layer would go here. (instead of in the constructor of your view, for example).
Add this ViewModel to your ViewModelLocator (I use the mvvmlocatorproperty code snippet provided in MVVM Light).
Bind your View to the ViewModel using the Locator. In your UserControl, you'd put something like this in the declaration:
DataContext="{Binding YourViewModel, Source={StaticResource Locator}}"

*I would follow Brennan Vincent's advice. I generally create a service interface (note: not a class, but an interface) that defines the methods my DAL (data access layer) will have. I do this to allow for Blendability, aka design time data. If you're not familiar with interfaces, perhaps simply a DAL class is a good way to start. Then I use dependency injection (DI) to inject an instance of my DAL Service. DI is pretty simple - in the ViewModelLocator you need to new up (instantiate) your DAL service class & pass it through your vm = New ViewModel(MyDALService dalService) call. You also then, obviously, need to accept a MyDALService reference in your ViewModel constructor. Here's an example of my EquipmentViewModel constructor on a project I've worked on:
public EquipmentViewModel(Services.IEquipmentService equipmentService)
{
    EquipmentService = equipmentService;
    LoadData();
}

This ViewModel accepts a parameter of the IEquipmentService type (which is my interface). In the LoadData method, I call the EquipmentService.GetEquipment() method of my DAL that hits my database layer.
Any questions let me know. MVVM can be a pain, but I'm very happy I stuck with it.
Good luck. :)

A: Josh Smith gave the definitive description of how to use MVVM to simplify the TreeView There's not much more I can add to it.


text:
Q: not downloading file using webclient from server I am creating a report from SSRS from C# using WebClient . But when i try to download the file this gives me exception the remote server returned an error (401) unauthorized. I have google it but not get any result to resolve this.
URl  i take reference Stack overflow Question and second link
Stack overflow Question 2 for my reference . Can you please help me to resolve this
 private void OpenSSRSLabel(int ordId) {
     try {
         string ReportURL = "http://MySERVER/ReportServer/Pages/ReportViewer.aspx?%2fSystem%2fWebOrderEntry_Label&ORDERNUM=";
         if (_orderDAC == null)
             _orderDAC = new OrderDAC();
             DataTable _dt = _orderDAC.GetOderByID(ordId);
             string FileURL = ReportURL + _dt.Rows[0]["ORDERNUM"].ToString() + "&rs:Command=Render&rs:Format=PDF";

             string filename = string.Format("OrderLabel{0}.pdf", DateTime.Now.ToString("dd-H-mmss"));

             string file = Server.MapPath("~/Temp/" + filename);
             if (System.IO.File.Exists(file)) {
                 File.Delete(file);
             }

             // Implement in Live Server
             WebClient client = new WebClient();

             client.Credentials = new NetworkCredential("MYSERVER\\Admin", "C47");
             client.Headers.Add(HttpRequestHeader.UserAgent, "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1)");
             client.DownloadFile(FileURL, file);  // Exception

             string path = Page.ResolveClientUrl("~/Temp/" + filename);
             ScriptManager.RegisterStartupScript(Page, typeof(System.Web.UI.Page), "OpenWindow", "window.open('" + path + "');", true);
    }
    catch (Exception ex) {

    }
}


text:
Q: Vue/Laravel WebSockets Listening more than one event I have some problems developing WebSockets with Laravel and Vue. Until now everything worked fine until I needed to implement a function that will listen to more events on one channel. The interesting part is that I can see in the console that both events are received but for one I'm getting that pusher has no callbacks on that channel and listener.
So what I did actually.
I created 2 events in my Laravel app like so:
    class Order implements ShouldBroadcast
    {
        use Dispatchable, InteractsWithSockets, SerializesModels;

        public $user;
        public $order;

        public function __construct($user, $order)
        {
            $this->user = $user;
            $this->order = $order;
        }

        public function broadcastOn()
        {
            return new PrivateChannel('orders');
        }

        public function broadcastAs(){
            return 'order-updated';
        }
    }

And another one is
class AddOrder implements ShouldBroadcast
{
    use Dispatchable, InteractsWithSockets, SerializesModels;

    public $order;

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

    public function broadcastOn()
    {
        return new PrivateChannel('orders');
    }

    public function broadcastAs(){
        return 'order-added';
    }
}

So the first one is for updating orders, and the second for adding. As you see they are connected to the same channel.
And in front-end I did like so:
window.Echo.private("orders").listen(".order-updated", (order) => {
            if (this.liveData) {
                let index = this.ordersList.findIndex((singleOrder => singleOrder.id === order.order.id));

                let updateOrder = {
                    updated_index: index,
                    updated_order: order.order
                };

                this.$store.commit("UPDATE_ORDER", updateOrder);
            }
        })
        .listen("order-added", (order) => {
            this.$store.commit("ADD_ORDER", order);
        });

So, as I see in the console, every WebSocket is sent as needed, but it's only listening to the first class (Order), and when I test another one (AddOrder) I can see the response in the console but after that, I have a log like:

Pusher :  : ["No callbacks on private-orders for order-added"]

I tried to replace the channel with a presence channel and public channel but I have no success. The interesting part is that I replaced listen to methods, first to listen order-added, and then order-updated, but it's only working for order-updated.
What could be a problem? Why I can't get an order-added listener?
PS: The reason AddOrder has no $user class, is because everyone can make order, and has no need for that class.


text:
Q: Why is favicon not showing? I am having a very strange problem. I have two php files in which I´m using html and there are in the same folder, but in one of that the favicon shows up and in the other it doesn´t. I have checked the code and the code of the two files is almost the same.
This code works:
<head>
        <meta charset="utf-8">
        <title>Home</title>
                <link href="../css/topbar2.css" rel="stylesheet" type="text/css">
                <link href="../css/home2.css" rel="stylesheet" type="text/css">
        <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.1/css/all.css">
                <link rel="icon" type="image/jpg" href="../img/favicon.jpg">
    </head>

In this doesn´t work:
<head>
        <meta charset="utf-8">
        <title>Edit Accounts</title>
        <link href="../css/topbar2.css" rel="stylesheet" type="text/css">
        <link href="../css/updateAccount.css" rel="stylesheet" type="text/css">
        <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.7.1/css/all.css">
        <link rel="icon" type="image/jpg" href="../img/favicon.jpg">
    </head>

EDIT:
I think I know why is this happening. Before my HTML code, I have some php code, that is this:
<?php
require_once '../config.php';
require_once '../constants/sessionVariables.php';
require_once '../db/dbConnection.php';
// Se comprueba que el usuario ha iniciado sesión. Si no es así,
// se le redirige a index.php
if (!isset($_SESSION['email'])) {
    header("Location: ../index.php");
    exit();
}

$loginURL = $gClient->createAuthUrl();

if (isset($_POST['submit'])) {
    $q = $con->real_escape_string($_POST['q']);
    $f = $con->real_escape_string($_POST['f']);
    $s = $_POST['submit'];
}
?>

I came to the conclusion that the error comes from the dbConnection.php file, but I don´t know why. This is the dbConenction.php code:
<?php
session_start();

$DATABASE_HOST = 'localhost';
$DATABASE_USER = 'root';
$DATABASE_PASS = '';
$DATABASE_NAME = 'configurator';

$con = mysqli_connect($DATABASE_HOST, $DATABASE_USER, $DATABASE_PASS,
        $DATABASE_NAME);
if ( mysqli_connect_errno() ) {
    die ('Failed to connect to MySQL: ' . mysqli_connect_error());
}

ini_set('display_errors', 1);
ini_set('log_errors', 1);
error_reporting(E_ALL);
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

A: First of all, your icon should be in your root folder.
Second, have you tried clearing your browsers cache or reloading the page with CTRL + F5?

A: Finally, the mistake was that in the dbConenction.php file when it starts the connection because it was already started before by another file. So, what I have done to resolve the problem is to put and if clause before the instruction of sessions start:
if (session_status() == PHP_SESSION_NONE) {
session_start();
}


text:
Q: Python requests throws "ValueError" for an Invalid Header This is my first post on SO, so please be easy on me.
In this program, I am trying to change userAgents after a certain number of failed attempts. There is a file of ~10000 userAgents located in the UserAgents.txt file, UTF-8 encoded.
I am writing a program in python that needs to scrape data from a website. I am getting the following error:

ValueError: Invalid header value b'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.155 Safari/537.36\n'

I realize that the 'b' in front of the string means that it is byte encoded.
The steps that I have followed include:

*

* userAgent = userAgent.encode("UTF-8").decode("UTF-8")

* userAgent = str(userAgent)

* userAgent = userAgentFile.readlines()[0]

* userAgentFile = open("UserAgents.txt", "r", encoding="UTF-8")

*I have also tried defining the user agent within the definition for the headers.

userAgentFile = open("UserAgents.txt", "r")
userAgent = userAgentFile.readline()
userAgentFile.close();

headerList = {
    "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9",
    "Accept-Encoding": "gzip, deflate",
    "Accept-Language": "en-US,en;q=0.9",
    "Upgrade-Insecure-Requests": "1",
    "User-Agent": "Mozilla/5.0 (Windows; U; Windows NT 5.2; en-US) AppleWebKit/525.13 (KHTML, like Gecko) Chrome/0.2.149.6 Safari/525.13",
    "X-Amzn-Trace-Id": "Root=1-61be9723-4cd53f9228b4db340a348137"
}

headerList["User-Agent"] = str(userAgent)
#Submit a request to our website, and with our "special" headings.
r = requests.get(f"https://www.reddit.com/r/BreadStapledToTrees/", headers=headerList)

Any help would be appreciated!
--Also, I am not actually scraping from r/BreadStapledToTrees...

A: From the error message, there is an newline character at the end of the user agent string, so strip it before sending it to requests, by changing line 14 to
headerList["User-Agent"] = userAgent.strip()


text:
Q: Saving contents of df.show() as a string in spark-scala app I need to save the output of df.show() as a string so that i can email it directly.
For ex., the below example taken from official spark docs,:
val df = spark.read.json("examples/src/main/resources/people.json")

// Displays the content of the DataFrame to stdout
df.show()
// +----+-------+
// | age|   name|
// +----+-------+
// |null|Michael|
// |  30|   Andy|
// |  19| Justin|
// +----+-------+

I need to save the above table as a string which is printed in the console. I did look at log4j to print the log, but couldnt come across any info on logging only the output.
Can someone help me with it?

A: Workaround is  to redirect standard output to variable:
val baos = new java.io.ByteArrayOutputStream();
val ps =  new java.io.PrintStream(baos);

val oldPs = Console.out
Console.setOut(ps)
df.show()
val content = baos.toString()
Console.setOut(oldPs)

Note that I have one deprecation warning here.
You can also re-implement method Dataset.showString, which generated data. It uses take in background. Maybe it's also a good moment to create PR to make showString public? :)

A: scala.Console has a withOut method for this kind of thing:
val outCapture = new ByteArrayOutputStream
Console.withOut(outCapture) {
  df.show()
}
val result = new String(outCapture.toByteArray)


text:
Q: How can I extract row whose element in 1st column is the maximum? I have following data:
eg1:
5.34   -32.82    0.71
7.65   -32.74    0.67
9.89   -32.76    0.69
13.81   -32.74    0.68
17.20   -33.27    0.71
22.83   -33.28    0.61
27.10   -33.40    0.67
29.22   -33.20    0.66

Output: Comparing max(:,1), I need to extract 29.22   -33.20    0.66
Eg2:
4.58   -49.98    1.27
5.84   -50.13    1.23
7.33   -50.15    1.24
10.39   -50.18    1.28
13.60   -50.03    1.27
17.73   -50.07    1.34
10.99   -49.90    1.41
10.81   -49.76    1.43

Output should be:17.73   -50.07    1.34
EDIT:
4.58    -49.98  1.27    5.31    -38     1.12
5.84    -50.13  1.23    7.65    -38     1.11
7.33    -50.15  1.24    9.88    -38.01  1.12
10.39   -50.18  1.28    13.78   -38     1.12
13.6    -50.03  1.27    17.2    -38.07  1.13
17.73   -50.07  1.34    22.8    -38.06  1.14
10.99   -49.9   1.41    27.19   -38.06  1.14
10.81   -49.76  1.43    29.29   -38.02  1.13

OUTPUT: executing a(a==max(a(:,1)),:) for each consecutive column
17.73   -50.07  1.34
29.29   -38.02  1.13

A: A=sortrows(A);
A(end,:)
ans =
   29.2200  -33.2000    0.6600

sortrows sorts your matrix row-wise, with the maximum element of row one obviously at the end. Therefore, extract the endrow and you're done.
Even faster without sorting your dataset:
A(A==max(A(:,1)),:)

This finds the entry in the first column where A attains its maximum and uses that as a logical index to extract the full row.


text:
Q: Logstash and nested JSON from Monlog; Why arrays are converted to JSON string? I am using PHP with Monolog. I am outputting logs to JSON file and using Gelf to Logstash which then sends logs to ElasticSearch.
The problem I have is that I am missing the extra object in Kibana and the tags field gets interpreted as string instead of nested object.
Any idea how to convince Logstash/Kibana, so the inner JSON field are parsed as fields/objects not as JSON string?
This is how it looks like in Kibana.
{
   "_index":"logstash-2018.08.30",
   "_type":"doc",
   "_id":"TtHbiWUBc7g5w1yM8X6f",
   "_version":1,
   "_score":null,
   "_source":{
      "ctxt_task":"taskName",
      "@version":"1",
      "http_method":"GET",
      "user_agent":"Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:61.0) Gecko/20100101 Firefox/61.0",
      "level":6,
      "message":"Finished task",
      "tags":"{\"hostname\":\"28571f0dc7e1\",\"region\":\"eu-west-1\",\"environment\":\"local\",\"processUniqueId\":\"5b87a4d843c20\"}",
      "url":"/assets/Logo.jpg",
      "ctxt_controller":"ControllerName",
      "memory_usage":"4 MB",
      "referrer":"https://local.project.net/account/login",
      "facility":"logger",
      "memory_peak_usage":"4 MB",
      "ctxt_timeElapsed":0.05187487602233887,
      "@timestamp":"2018-08-30T08:03:37.386Z",
      "ip":"172.18.0.1",
      "ctxt_start":1535616217.33417,
      "type":"gelf",
      "host":"18571f0dc7e9",
      "source_host":"172.18.0.8",
      "server":"local.project.net",
      "ctxt_end":1535616217.386045,
      "version":"1.0"
   },
   "fields":{
      "@timestamp":[
         "2018-08-30T08:03:37.386Z"
      ]
   },
   "sort":[
      1535616217386
   ]
}

My log looks like:
{
   "message":"Finished task",
   "context":{
      "controller":"ControllerName",
      "task":"taskName",
      "timeElapsed":0.02964186668395996,
      "start":1535614742.840069,
      "end":1535614742.869711,
      "content":""
   },
   "level":200,
   "level_name":"INFO",
   "channel":"logger",
   "datetime":{
      "date":"2018-08-30 08:39:02.869850",
      "timezone_type":3,
      "timezone":"Europe/London"
   },
   "extra":{
      "memory_usage":"14 MB",
      "memory_peak_usage":"14 MB",
      "tags":{
         "hostname":"28571f0dc7e1",
         "region":"eu-west-1",
         "environment":"local",
         "processUniqueId":"5b879f16be3f1"
      }
   }
}

My logstash conf:
input {
    tcp {
        port => 5000
    }
    gelf {
        port => 12201
        type => gelf
        codec => "json"
    }
}

output {
    elasticsearch {
        hosts => "172.17.0.1:9201"
    }
}

My monolog config:
$gelfTransport = new \Gelf\Transport\UdpTransport(LOG_GELF_HOST, LOG_GELF_PORT);
            $gelfPublisher = new \Gelf\Publisher($gelfTransport);
            $gelfHandler = new \Monolog\Handler\GelfHandler($gelfPublisher, static::$logVerbosity);
            $gelfHandler->setFormatter(new \Monolog\Formatter\GelfMessageFormatter());

            // This is to prevent application from failing if `GelfHandler` fails for some reason
            $ignoreErrorHandlers = new \Monolog\Handler\WhatFailureGroupHandler([
                $gelfHandler
            ]);
            $logger->pushHandler($ignoreErrorHandlers);

EDIT:
So far my finding is that this is caused by GelfMessageFormatter converting they arrays to JSON:
$val = is_scalar($val) || null === $val ? $val : $this->toJson($val);

When netcat is used along with the nested JSON, e.g.:
echo -n '{
"field": 1,
"nestedField1": {"nf1": 1.1, "nf2": 1.2, "2nestedfield":{"2nf1":1.11, "2nf2":1.12}}
}' | gzip -c | nc -u -w1 bomcheck-logstash 12201

then data in Kibana looks OK

A: It looks like GELF doesn't support nested data structures out of the box.
I've decided to use native Logstash UDP plugin:
input {
    udp {
        port => 12514
        codec => "json"
    }

}

along with the Monolog LogstashFormatter
$connectionString = sprintf("udp://%s:%s", LOG_UDP_LOGSTASH_HOST, LOG_UDP_LOGSTASH_PORT);
$handler = new \Monolog\Handler\SocketHandler($connectionString);
$handler->setFormatter(new \Monolog\Formatter\LogstashFormatter('project', null, null, 'ctxt_', \Monolog\Formatter\LogstashFormatter::V1));
$logger->pushHandler($handler);

The nested data ends up correctly in Kibana.


text:
Q: Very strange Find/Replace behaviour I have a Firebird database stored in Windows-1251 codepage and managed using IBExpert. I have to get some billing info using SQL, edit it and then send it to clients. I export query results into .csv (comma-separated values) format and then process a bunch of csvs into a pretty xls (with borders, fonts, etc.) using Microsoft Excel 2010. I have NO idea why, but IBExpert places a strange symbol everywhere in numeric values between decades (64 731 instead of 64731). Asc() method from VBA tells me that it's the #160 symbol in ASCII codepage.
NOW, the strangest observation I made: if you copy this symbol manually and delete it from everywhere using find/replace function of Excel, everything is OK. If you do the same thing in any text editor (e.g. good old notepad) everything is still OK. But when you try to automate the replacement using VBA, everything goes very, very wrong. No matter if you use a manually copied #160 from the csv itself or you generate it using Chr(160), if you try to delete all those, VBA also deletes half of the commas. By comma I mean generally known symbol #44, you can google "ascii" pictures and check it out. I have to mark that again, the replacement affects half the commas, however all of them actually ARE the very same symbol, I rechecked that twice.
You can look for a link to a csv below, so you can reassure yourself with the fact that I'm not crazy.
Here is the code you can use to reproduce the magic
Sub test()
    Worksheets(1).UsedRange.Replace What:=Chr(160), Replacement:=""
End Sub

I'll be very thankful to someone who will clarify this phenomenon, because I just can't believe that VBA is that buggy, I think I missed something somewhere
UPDATE: Guys, I am terribly sorry. I'm so dumb that I've uploaded the wrong csv. Here's the right one

A: I've imported the CSV to Range("A1"). Here's what I've found:

*

*$F$2 = 4 708,200

*That value is not detected as a numeric. This is due to the CHR(160) existing in the 2nd place (the "space" after 4).

*If you want that value to become 4708200 (four million...), replace CHR(160) like you've done. This removes the comma because now excel detects those values as numerics.

*Since you haven't provided correct info, Excel thinks the comma is a thousands separator.

If it should rather be 4708,2 (four thousand...), correct it during your CSV import:

*

*To import the CSV correctly, you have to put CHR(160) as a thousands separator.

*The comma will act as a decimal sign.

*This way, Excel will interpret 4 708,200 as the numeric value 4708,2 during import.

When using REPLACE in VBA, Excel assumes the comma is a thousands separator. Why? Hard to say. However, you haven't provided that it's NOT. :)
Below is the code for importing the file correctly.
With ActiveSheet.QueryTables.Add(Connection:= _
    "TEXT;H:\testfile2.csv", Destination:=Range("$A$1"))
    .Name = "testfile2.csv"
    .FieldNames = True
    .RowNumbers = False
    .FillAdjacentFormulas = False
    .PreserveFormatting = True
    .RefreshOnFileOpen = False
    .RefreshStyle = xlInsertDeleteCells
    .SavePassword = False
    .SaveData = True
    .AdjustColumnWidth = True
    .RefreshPeriod = 0
    .TextFilePromptOnRefresh = False
    .TextFilePlatform = 1251
    .TextFileStartRow = 1
    .TextFileParseType = xlDelimited
    .TextFileTextQualifier = xlTextQualifierDoubleQuote
    .TextFileConsecutiveDelimiter = False
    .TextFileTabDelimiter = False
    .TextFileSemicolonDelimiter = True
    .TextFileCommaDelimiter = False
    .TextFileSpaceDelimiter = False
    .TextFileColumnDataTypes = Array(1, 1, 1, 1, 1, 1, 1)
    .TextFileThousandsSeparator = Chr(160) ' Here's that thousands separator!
    .TextFileTrailingMinusNumbers = True
    .Refresh BackgroundQuery:=False
End With

Update: Here's the code that replaces your previous Workbooks.OpenText macro.
Sub eyecandy()
Dim SelectedItem
Dim Wb As Workbook, Sh As Worksheet
Dim WbName As String, WbFullName As String

    With Application.FileDialog(msoFileDialogFilePicker)
        .Title = "  "
        .InitialFileName = ThisWorkbook.Path & Application.PathSeparator & "*.csv"
        .AllowMultiSelect = True
        If .Show = False Then Exit Sub

        Application.ScreenUpdating = False
        For Each SelectedItem In .SelectedItems
            Set Wb = Workbooks.Add

            ' Get the file name
            WbFullName = Replace(SelectedItem, ThisWorkbook.Path & Application.PathSeparator, "")
            WbName = Replace(WbFullName, ".csv", "")

            ' Deletes unnecessary sheets
            Do Until Wb.Sheets.Count = 1
                Application.DisplayAlerts = False
                Wb.Sheets(1).Delete
                Application.DisplayAlerts = True
            Loop

            Set Sh = Wb.Sheets(1)

            With Sh.QueryTables.Add(Connection:= _
                "TEXT;" & SelectedItem, Destination:=Sh.Range("$A$1"))
                .Name = WbName
                .FieldNames = True
                .RowNumbers = False
                .FillAdjacentFormulas = False
                .PreserveFormatting = True
                .RefreshOnFileOpen = False
                .RefreshStyle = xlInsertDeleteCells
                .SavePassword = False
                .SaveData = True
                .AdjustColumnWidth = True
                .RefreshPeriod = 0
                .TextFilePromptOnRefresh = False
                .TextFilePlatform = 1251
                .TextFileStartRow = 1
                .TextFileParseType = xlDelimited
                .TextFileTextQualifier = xlTextQualifierDoubleQuote
                .TextFileConsecutiveDelimiter = False
                .TextFileTabDelimiter = False
                .TextFileSemicolonDelimiter = True
                .TextFileCommaDelimiter = False
                .TextFileSpaceDelimiter = False
                .TextFileColumnDataTypes = Array(1, 1, 1, 1, 1, 1, 1)
                .TextFileThousandsSeparator = Chr(160)
                .TextFileTrailingMinusNumbers = True
                .Refresh BackgroundQuery:=False
            End With
            Sh.Activate
            ActiveWindow.DisplayGridlines = False
            With Sh.UsedRange
                .Borders.LineStyle = xlContinuous
                .Rows(1).Font.Bold = True
                .Rows(1).Borders.Weight = xlThick
            End With
            Sh.Name = WbName
            Wb.SaveAs Filename:=WbName, FileFormat:=56
            Wb.Close SaveChanges:=False
        Next SelectedItem
        Application.ScreenUpdating = True
    End With
End Sub

A: So, as @takl suggested, the solution was to modify thousand separator property.
It's .TextFileThousandsSeparator if you are using ActiveSheet.QueryTables.Add method and .ThousandsSeparator if you are using Workbooks.OpenText method.
I really appreciate his help, but I just have to use the Workbooks.OpenText method because it supports Local property. So, here's the edited file-processing loop from my script
'walk through selected files
For Each SelectedItem In .SelectedItems
    Workbooks.OpenText _
        Filename:=SelectedItem, _
        Origin:=xlWindows, _
        StartRow:=1, _
        DataType:=xlDelimited, _
        TextQualifier:=xlTextQualifierNone, _
        ConsecutiveDelimiter:=False, _
        Semicolon:=True, _
        ThousandsSeparator:=Chr(160), _
        Local:=True


text:
Q: PHP File Include I have searched the forums already, but none of the solutions have seemed to help me.
Basically I have just installed and created a package using composer. I need to autoload the classes, sounds pretty standard.
I followed all the instructions, and have added this line of code to my script:
require_once 'vendor/autoload.php';

The vendor folder is located in the root folder of my server, here:
/root/vendor/autoload.php

So, I added
:/root

To my PHP ini file so that PHP searches in the root folder when looking for includes. I thought that should work but it's not :(
My PHP ini file now looks like this:
.:/usr/lib/php:/usr/local/lib/php:/root

The error message I am getting is this:
[14-Jul-2014 16:46:29 Europe/London] PHP Fatal error:  require_once(): Failed opening required 'vendor/autoload.php' (include_path='.:/usr/lib/php:/usr/local/lib/php:/root') in /home/owned/public_html/trythis/ow_plugins/oftokbox/bol/service.php on line 38

Any ideas?

A: You implicitly state you are using Composer for a project. By doing so you must have a composer.json file somewhere. And Composer will create a vendor folder directly in the folder containing this file.
So if you also have a file index.php in the folder containing the composer.json, to include the autoloader you would use require 'vendor/autoload.php';.
If however you follow some security guidelines and have a dedicated folder containing public files, then the file would for example be called public/index.php, and for this file to reach the autoloader, the relative path would be require '../vendor/autoload.php';.
Composer cannot give a one-instructions-fits-all direction because it depends on which folder structure you have. But including the composer autoloader is just the same task as including any other file with a relative path.


text:
Q: Shopping cart rule not applying to shipping Currently, I'm using a flat rate table to make any shipping for a cart with more than, for example, $100, become $0 instead of $3.
$shippingAddress = $quote->getShippingAddress();
 $shippingAddress->setCollectShippingRates(true)
                 ->collectShippingRates()
                 ->setShippingMethod('tablerate_bestway');

However, the client wants to do special promotions where free shipping becomes available, either through coupons or for a specific amount of time.
The problem is, the Shopping Cart Price Rules are not applying to the cart, and the shipping remains the same even when the conditions of the rule are met. For example, if I set free shipping for today, I still get $3 as shipping in the cart.

totals: {
  subtotal: 29,
  shipping: 3,
  tax: 0,
  discount: 0
  }

Do I have to check the shopping cart rules myself and force free shipping as a method? Or is something else wrong?
Edit: Here's a screenshot of the rule as requested:

A: I think the issue here is the rule isn't applied on any items. You left the conditions empty.
If you wan´t to apply the rule without conditions just set a really generic one like price over 0 or something like that.
Now the rule should be applied to the quote


text:
Q: DNS with parental control not working on (Ubuntu) Linux I'm testing the FamilyShield DNS (https://www.opendns.com/setupguide/#familyshield) on Ubuntu 20.04.2 LTS, but I'm not able to get it working.
I configured it using the NetworkManager GUI for my WI-FI connection and checks from the CLI seem right:
$ resolvectl | grep -A1 "DNS Server"
  Current DNS Server: 208.67.222.123
         DNS Servers: 208.67.222.123
                      208.67.220.123

$ ( nmcli dev list || nmcli dev show ) 2>/dev/null | grep DNS
IP4.DNS[1]:                             208.67.222.123
IP4.DNS[2]:                             208.67.220.123

I'm not using ResolvConf or DNSmasq or - AFAIK - other services: just systemd-resolve.
The local caches have been flushed:
sudo systemd-resolve --flush-caches

I even restarted the system, flushed the browser DNS caches (Chrome / Firefox) and in the case of Firefox they have been completely disabled.
Still... This machine can still surf all the adult content it likes from any browser. This is the dig reply:
$ dig youporn.com @208.67.222.123

; <<>> DiG 9.16.1-Ubuntu <<>> youporn.com @208.67.222.123
;; global options: +cmd
;; Got answer:
;; ->>HEADER<<- opcode: QUERY, status: NOERROR, id: 19497
;; flags: qr rd ra; QUERY: 1, ANSWER: 1, AUTHORITY: 0, ADDITIONAL: 1

;; OPT PSEUDOSECTION:
; EDNS: version: 0, flags:; udp: 1220
; COOKIE: 4fc7b5602d78fde916d536bb625309a0f4267b41ad8c17fa (good)
;; QUESTION SECTION:
;youporn.com.           IN  A

;; ANSWER SECTION:
youporn.com.        240 IN  A   66.254.114.79

;; Query time: 20 msec
;; SERVER: 208.67.222.123#53(208.67.222.123)
;; WHEN: dom apr 10 18:45:20 CEST 2022
;; MSG SIZE  rcvd: 84

What am I missing? Thank you

A: Thanks to Bib comment I found out the problem. Here's the UDP traceroute (port 53 is the default):
$ sudo traceroute -U 208.67.222.123

traceroute to 208.67.222.123 (208.67.222.123), 30 hops max, 60 byte packets
 1  * * *
 2  * * *
 3  * * *
 4  * * *
 5  * * *
 6  * * *
 7  * * *
 8  * * *
 9  * * *
10  * * *
11  * * familyshield.opendns.com (208.67.222.123)  41.862 ms

Not very informative by itself, but I confirmed with some DNS Leak testing tool that there's a transparent DNS proxy imposed by my ISP (Vodafone Italy), and later found out many articles about it.
I'll look for a way to bypass it. Thank you for the suggestion!


text:
Q: Solving $\tan x = x + 1$ analytically. In my books a problem is given as follows:

Prove that least positive value of x satisfying $\tan{x} = x+1$ lies in interval $(\frac{\pi}{4},\frac{\pi}{2} )$.

I tried to solve it as folllow
$$\tan{x} = x+1$$
$$\frac{\sin x}{\cos x} = x+1$$
$$\sin{x}= (x+1)\cos{x}$$
I differentiate the expression I
$$\cos{x}= \cos{x} -(x+1)\sin{x}$$
$$-(x+1)\sin x= 0$$
Here by $\sin{x} \neq 0$ because for this condition $x = \pi n$ which lies outside the interval and $x = -1$ is outright wrong
The book solves this kind of question using graph by studying the intersection of $y = \tan x$ and $y = x+1$.
SO WHY I DON'T WANT TO USE GRAPHS?
Because, the problem is we don't have graphs with us in exams and sometimes it's not feasible to draw graph by hands
So how I may go about these kind of trigonometrical equations?

A: Let $$f(x)=\tan(x)-x-1$$
Then
$$f(\frac{\pi}{4})=-\frac{\pi}{4} <0 \\
\lim_{x \to \frac{\pi}{2}} f(x)=+\infty
$$
and use the Intermediate Value Theorem...If you didn't cover that (yet), this is probably what the textbook is trying to argue.
To prove that this is the smallest positive root, you can use the fact that
$$f'(x)>0 \mbox{ on } (0, \frac{\pi}{2})$$
As for graphs, you should be able to draw the graphs of $\tan(x)$ and $x+1$ by hand in the exam. If the problem expects you to draw the graphs, the problem is chosen so that it is feasible to draw them by hand.

A:
Prove that least positive value of $x$ satisfying $\tan{x} = x+1$ lies in interval $(\frac{\pi}{4},\frac{\pi}{2} )$. $\tag{*}$

Denote
$$
f(x)=\tan x-x-1.
$$
 Then $(*)$ reduces the following problems.

*

*(a)Show that $f$ has no zero in $(0,\pi/4]$;

*(b)Show that $f$ has a zero in $(\pi/4,\pi/2)$.

For(a), can you give the monotonicity of $f$ in $[0,\pi/4]$? For (b), do you know the intermediate value theorem?

A: To demonstrate that the solution (if exist) shall be within $\pi /4$ and $\pi /2$ is actually quite straightforward
$$
0 \leqslant x < \infty \quad  \Rightarrow \quad 1 \leqslant 1 + x < \infty \quad \xrightarrow{{\tan x = 1 + x}}\quad 1 \leqslant \tan x < \infty
$$
and since $tan x$ is  increasing for $ 0 \leqslant x$
$$
1 \leqslant \tan x < \infty \quad \xrightarrow{{\tan x\;\text{increasing}}}\quad \pi /4 \leqslant x < \pi /2
$$
thus the solution shall be within the intersection of the two domains
$$
x:\;1 + x = \tan x\quad  \Rightarrow \quad x \in \left[ {0,\infty } \right)\; \cap \;\left[ {\pi /4,\pi /2} \right) = \left[ {\pi /4,\pi /2} \right)
$$
Then, that a  solution exists and is unique is given by the fact that
$$
\begin{gathered}
  \left. {\left( {1 + x} \right)} \right|_{x\, = \;\pi /4}^{}  > \left. {\tan x} \right|_{x\, = \;\pi /4}^{}  \hfill \\
  \left. {\left( {1 + x} \right)} \right|_{x\, = \;\pi /2}^{}  < \left. {\tan x} \right|_{x\, = \;\pi /2}^{}  \hfill \\
\end{gathered}
$$
and that both functions are continuous and strictly increasing in that interval.

A: You need to show that there is no root in $[0,\frac\pi4]$.
With $f(x):=\tan x-x-1$, you have $f(0)=-1$ and $f(\frac \pi4)=-\frac\pi4$. If you can show that the function is monotonic, you are done.
The first derivative is $\sec^2x-1$, which is non-negative, hence the claim.

A: I am not an expert but this might be one of the way to know the root lie in the given interval or not


text:
Q: Piping cmd output to variable in PowerShell I have the following in a PowerShell script:
cmd /c npm run build-release
$succeeded = $LastExitCode

What I'd like to do is:

*

*Pipe the output of the cmd to a variable so it doesn't write to the host

*Only if $succeeded is eq $true, Write-Host the output variable from that the cmd
How can this be done?

A: Use Invoke-Expression:
$output = Invoke-Expression "cmd /c npm run build-release"
$succeeded = $LastExitCode

if($succeeded -eq 0) {
  write-output $output
}


text:
Q: Format cell colours based on values in two columns I have a spreadsheet where I document correspondence received, and I have a column "Days open" with a basic formula to work out how many days the case has been open for. We split the senders into two categories: important and unimportant (I have a hidden column titled "important" with yes or no in the cells). The unimportant ones are allowed up to 15 days to be closed, and the important ones up to 5.
How can I format the column of "Days open" to change colour after 5 days for the important letters and after 15 for the unimportant ones?

A: Suppose:

*

*Column A is the important column

*Column B is the days open column

*Data starts from 2nd row

Then proceed as follows:

*

*Select the range that needs conditional formatting. It is possible to choose more than one column i.e. you can make the entire row red if the condition is true.

*Inside "Conditional Formatting" dialog choose "Use a formula..."

*Enter the following formula:
=IF($A2 = "yes", $B2 > 5, $B2 > 15)

*Choose desired formatting

*Done

The $ symbol in the formula allows you to copy the conditional formatting across multiple columns.

A: Use OR with AND as the formula in Conditional formatting.
This assumes A and B are you columns in respective order and you have,
Select Columns A and B, and use this rull to conditionally format the cells.:
=OR(AND(A1>=5,B1="Yes"),AND(A1>=15,B1="No"))


text:
Q: how To turn an json object to table of objects i used to push a data into array but the data was like bellow can some one tell me how to turn this object to arrray of object
d2 = {
      {
        id: "BK1",
        type: "MAGE",
        role: "DARK"
      },
      {
        id: "BK1",
        type: "MAGE",
        role: "DARK"
      },
      {
        id: "BK1",
        type: "MAGE",
        role: "DARK"
      }
    }

to this how i want it to look like:
d2 = [
      {
        id: "BK1",
        type: "MAGE",
        role: "DARK"
      },
      {
        id: "BK1",
        type: "MAGE",
        role: "DARK"
      },
      {
        id: "BK1",
        type: "MAGE",
        role: "DARK"
      }
    ]

A: You can use a for ... in loop to iterate over the keys within the object and push those onto an array:
const transformedD2 = [];

for (const key in d2) {
  transformedD2.push(d2[key]);
}

You could also use Object.values
The thing is, the object you included as an example isn't valid, as briosheje has pointed out. It only has values, no keys.


text:
Q: Split String based on comma and concate into query String in java I have a String which contains values separated by comma .Now as per my need i have to split the String by comma (,) and concatenate the Substring into query string  but i am not able to get the idea ..here is my code...I need to split the String and concatenate into the query..
Extension contains the values like 1111,2341,5028
String extension = request.getParameter("extension");
System.out.println(extension);
if(extension!=""){
//here i need to concate the substring into query delimited by comma.
query=query.concat("'").concat(" and extension='"+extension);

}

Any help will be highly appreciated..
Thanks in advance..

A: You can use split method and get the substrings one by one
for (String ext: extension.split(",")){
   // your code goes here
  }

A: Try this,
{
        String myInput = "1111,2341,5028";
        String[] splitted = myInput.split(",");

        String query = " Select * from Table where "; // something like Select * from Table where
        StringBuilder concanatedquery= new StringBuilder();

        for (String output : splitted)
        {
            concanatedquery.append(" extension = '" + output.replace("'", "''") +"'  AND ");    //replace confirms that no failure will be there if splited string contains ' and if this splitted string are numeric then remove 'replace' clause and char ' after extension = ' and before "' AND"
        }

        query = query + concanatedquery.substring(0, concanatedquery.length() - 4); //4 characters are removed as 'AND  ' will be extra at the end.
}

A: Use StringBuilder class to concatenate and build the SQL query, which has append method.
String [] parts = originalString.split(",");
StringBuilder builder = new StringBuilder();
for(String str: parts){
 builder.append(str);
builder.append(" ");
}
return builder.toString();

A: You could Split the string Like this
String str = "1111,2341,5028";
String filenameArray[] =  str.split("\\,");
// ACCESS THE ARRAY POSITION LIKE filenameArray[0],filenameArray[1]  AND SO ON


text:
Q: Colocar icono en un SelectMenu de Jquery UI Quisiera colocar un icono en el item seleccionado de un SelectMenu item.

Asi de esta manera.
He conseguido añadir los iconos en el desplegable, pero no consigo ponerlo ahi.

El codigo que he usado es este:
<div class="select-lang">
        <?
            $check = $sql->query("SELECT * FROM `".PREFIX."langs` WHERE `active` = '1' ORDER BY `int_name` ASC");
            echo "<select class='languages'>";
            while($show = $check->fetch_object()){
                echo "<option value='".$show->lang."' data-class='".$show->lang."' data-title='".$show->int_name."'>".$show->name."</option>";
            }
            echo "</select>";
        ?>
    </div>

en un principio genero toda la estructura con lo que tengo almacenado en la base de datos.
Ahora con Jquery UI los siguiente:
<script type="text/javascript">
        $(document).ready(function(){
            $.widget( "custom.iconselectmenu", $.ui.selectmenu, {
                _renderItem: function( ul, item ) {
                var li = $( "<li>", { text: item.label, "title": item.element.attr( "data-title" ) } );

                if ( item.disabled ) {
                    li.addClass( "ui-state-disabled" );
                }

                $( "<span>", {
                    style: item.element.attr( "data-style" ),
                    "class": "ui-icon " + item.element.attr( "data-class" )
                })
                .appendTo( li );

                    return li.appendTo( ul );
                }
            });
            $('.languages')
            .iconselectmenu()
            .iconselectmenu('menuWidget')
            .addClass('ui-menu-icons customicons');
        });
    </script>

Pues esta es la duda.
Saludos.

A: Si miras el código HTML generado, puedes ver que el icono viene definido por la imagen de fondo del span especificada en esta parte de tu código JS:
$( "<span>", {
    style: item.element.attr( "data-style" ),
    "class": "ui-icon " + item.element.attr( "data-class" )
})

Ese span tendrá la clase "ui-icon" y también la clase especificada en el data-class del option en el menú de selección. Por lo que, para cambiar el icono, sólo tendrías que especificar un nuevo icono en CSS. En tu caso, suponiendo que $show->lang es "es", sería algo como esto:
span.ui-icon.es {
    background-image: url(http://enlace.a.bandera.de/españa.jpg);
}

Luego para el caso de la opción seleccionada, puedes seguir un método similar pero para la clase "ui-selectmenu-text". Así sólo faltaría añadir un poco de JavaScript para actualizar la clase de "ui-selectmenu-text" cuando se pulse en una opción y cuando se cargue la página (para que la opción por defecto también tenga icono sin necesidad de pulsar nada).

Aquí dejo un ejemplo:

$(document).ready(function(){
  $.widget( "custom.iconselectmenu", $.ui.selectmenu, {
    _renderItem: function( ul, item ) {
      var li = $( "<li>", { text: item.label, "title": item.element.attr( "data-title" ) } );

      if ( item.disabled ) {
        li.addClass( "ui-state-disabled" );
      }

      $( "<span>", {
        style: item.element.attr( "data-style" ),
        "class": "ui-icon " + item.element.attr( "data-class" )
      })
      .appendTo( li );

      return li.appendTo( ul );
    }
  });
  $('.languages')
  .iconselectmenu()
  .iconselectmenu('menuWidget')
  .addClass('ui-menu-icons customicons');

  // cambiar la clase de la opción seleccionada cuando se pulsa en una de las opciones en la lista
  $("body").on("click",".ui-menu li.ui-menu-item", function() {
      var target = $(this).closest(".ui-menu").attr("aria-labelledby");
      var tclass = $(this).find("span").attr("class").replace("ui-icon ", "");
      $("#" + target).find(".ui-selectmenu-text").attr("class", "ui-selectmenu-text " + tclass);
  });

  // activar la bandera al principio
  $(".ui-selectmenu-button").each(function() {
      var tclass = $("#" + $(this).attr("id").replace("-button", "") + " option").first().attr("data-class");
      $(this).find(".ui-selectmenu-text").addClass(tclass);
  });

});
.ui-selectmenu-button {
  width:200px !important;
}

.ui-selectmenu-text {
  padding-left:40px !important;
  background-position: 13px center;
  background-repeat:no-repeat;
}

span.ui-icon.en,
.ui-selectmenu-text.en {
  background-image: url( http://icons.iconarchive.com/icons/fatcow/farm-fresh/16/flag-england-icon.png) !important;
}

span.ui-icon.es,
.ui-selectmenu-text.es {
  background-image: url( http://icons.iconarchive.com/icons/fatcow/farm-fresh/16/flag-spain-icon.png);
}

span.ui-icon.fr,
.ui-selectmenu-text.fr {
  background-image: url( http://icons.iconarchive.com/icons/fatcow/farm-fresh/16/flag-france-icon.png);
}

span.ui-icon.de,
.ui-selectmenu-text.de {
  background-image: url( http://icons.iconarchive.com/icons/fatcow/farm-fresh/16/flag-germany-icon.png);
}
<script type="text/javascript" src="http://code.jquery.com/jquery-2.1.4.js"></script>
<script type="text/javascript" src="http://code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<link rel="stylesheet" type="text/css" href="http://code.jquery.com/ui/1.11.4/themes/ui-lightness/jquery-ui.css">

<select class="languages">
  <option value="de" data-class="de" data-title="Alemán">Alemán</option>
  <option value="es" data-class="es" data-title="Español">Español</option>
  <option value="fr" data-class="fr" data-title="Francés">Francés</option>
  <option value="en" data-class="en" data-title="Inglés">Inglés</option>
</select>


text:
Q: i want to delete files with given extension I want to develop a C# application that allows users to give an extension (example: *.mp3) And then the application will remove all files that contains this extension from the hard disk.

A: This is just an example to delete files with .msi extension in C drive,
DirectoryInfo Dr = new DirectoryInfo(@"C:\");
FileInfo[] files = Dr.GetFiles("*.msi").Where(p => p.Extension == ".msi").ToArray();
foreach (FileInfo file in files)
    try
    {
        file.Attributes = FileAttributes.Normal;
        File.Delete(file.FullName);
    }
    catch
    {
    }

To get all extensions,
public List<FileInfo> GetFiles(string path, params string[] extensions)
{
    List<FileInfo> list = new List<FileInfo>();
    foreach (string ext in extensions)
        list.AddRange(new DirectoryInfo(path).GetFiles("*" + ext).Where(p =>
              p.Extension.Equals(ext,StringComparison.CurrentCultureIgnoreCase))
              .ToArray());
    return list;
}

A: Put needed path in below code and use a foreach and File.Delete.
Use
var files = System.IO.Directory.GetFiles(path, "*.txt");

A: You can use Directory.EnumerateFiles(string path, string searchPattern, SearchOption searchOption) :
var files = Directory.EnumerateFiles(directoryPath, "*.mp3", SearchOption.AllDirectories);
foreach (var item in files)
{
   try
   {
       File.Delete(item);
   }
   catch (Exception)
   { //log exception}
}


text:
Q: EFI stub kernel not booting, but black screen I'm trying to boot a Gentoo Linux with an EFI stub kernel on a Hetzner AX41-NVME server, but it only shows a blank black screen while the server hangs up.
Partition table:
root@rescue ~ # sgdisk -p /dev/nvme0n1
Disk identifier (GUID): F094B3BD-52B7-4404-BCC3-97C31B79D87B
Number  Start (sector)    End (sector)  Size       Code  Name
1            2048          526335   256.0 MiB   EF00  EFI System
2          526336         8914943   4.0 GiB     FD00  Linux RAID
3         8914944      1000215182   472.7 GiB   FD00  Linux RAID

root@rescue ~ # sgdisk -p /dev/nvme1n1
Disk identifier (GUID): CB8CDFE7-F9CC-43BD-949E-047583602A5B
Number  Start (sector)    End (sector)  Size       Code  Name
1            2048          526335   256.0 MiB   EF00  EFI System
2          526336         8914943   4.0 GiB     FD00  Linux RAID
3         8914944      1000215182   472.7 GiB   FD00  Linux RAID

RAID configuration:
root@rescue ~ # cat /proc/mdstat
Personalities : [raid1]
md2 : active raid1 nvme0n1p3[0] nvme1n1p3[1]
 495518016 blocks super 1.2 [2/2] [UU]
 bitmap: 0/4 pages [0KB], 65536KB chunk
md1 : active raid1 nvme0n1p2[0] nvme1n1p2[1]
 4189184 blocks super 1.2 [2/2] [UU]
md0 : active raid1 nvme0n1p1[0] nvme1n1p1[1]
 262080 blocks super 1.0 [2/2] [UU]
unused devices: <none>

UUID / filesystems:
rescue ~ # blkid
/dev/nvme1n1p1: UUID="e89d4289-e9f4-c257-09c5-52f1964b8610" UUID_SUB="a676ed40-b711-bbaa-c8b9-4bb8fd6da503" LABEL="rescue:0" TYPE="linux_raid_member" PARTLABEL="EFI System" PARTUUID="22ed455d-6d9f-4253-bf72-de535e8a848a"
/dev/nvme1n1p2: UUID="4e5f115e-be72-330e-ef95-7f638ca106c1" UUID_SUB="089e8879-f9b0-da15-d9a6-1af77c33d697" LABEL="rescue:1" TYPE="linux_raid_member" PARTLABEL="Linux RAID" PARTUUID="7c4361b1-7137-4935-a2ab-e9683161e303"
/dev/nvme1n1p3: UUID="75613912-6a27-381f-a550-9dee3b9b1db0" UUID_SUB="f997b923-2614-d3a8-9457-e0b8235ff49d" LABEL="rescue:2" TYPE="linux_raid_member" PARTLABEL="Linux RAID" PARTUUID="175ddaae-5aec-49d1-a839-f62b371b4360"
/dev/nvme0n1p1: UUID="e89d4289-e9f4-c257-09c5-52f1964b8610" UUID_SUB="bd60292a-2681-a980-fb15-cabdd5ed3441" LABEL="rescue:0" TYPE="linux_raid_member" PARTLABEL="EFI System" PARTUUID="b47b57a5-a617-491f-9a55-3b918525b571"
/dev/nvme0n1p2: UUID="4e5f115e-be72-330e-ef95-7f638ca106c1" UUID_SUB="30043bb0-8dc3-f507-ef24-c2ec0488f6cc" LABEL="rescue:1" TYPE="linux_raid_member" PARTLABEL="Linux RAID" PARTUUID="ea7f367b-9019-43a9-9f2c-01f754c08683"
/dev/nvme0n1p3: UUID="75613912-6a27-381f-a550-9dee3b9b1db0" UUID_SUB="61f62d14-0640-3300-7c9e-4d48d012d5b4" LABEL="rescue:2" TYPE="linux_raid_member" PARTLABEL="Linux RAID" PARTUUID="28e635c7-208f-415d-8333-369811d59533"
/dev/md0: UUID="4349-B2C7" BLOCK_SIZE="512" TYPE="vfat"
/dev/md1: UUID="a772cb17-0432-4dfd-96d9-0c90d3de1567" TYPE="swap"
/dev/md2: UUID="b16b64a2-2126-4200-a393-566aad7e3b5f" BLOCK_SIZE="4096" TYPE="f2fs"

Efibootmgr / NVRAM entries:
root@rescue ~ # efibootmgr -v
BootCurrent: 0004
Timeout: 5 seconds
BootOrder: 0011,0111,0004
Boot0004* UEFI: Built-in EFI Shell      VenMedia(5023b95c-db26-429b-a648-bd47664c8012)..BO
Boot0011* Gentoo 5.4.97 nvme0n1p1       HD(1,GPT,b47b57a5-a617-491f-9a55-3b918525b571,0x800,0x80000)/File(\EFI\BOOT\BOOTX64.EFI)
Boot0111* Gentoo 5.4.97 nvme1n1p1       HD(1,GPT,22ed455d-6d9f-4253-bf72-de535e8a848a,0x800,0x80000)/File(\EFI\BOOT\BOOTX64.EFI)

Fstab entries:
rescue ~ # cat /etc/fstab
UUID=4349-B2C7                                  /boot                   vfat    noauto,noatime,umask=0077               0 1
UUID=b16b64a2-2126-4200-a393-566aad7e3b5f       /                       f2fs    noatime,acl                             0 0
UUID=a772cb17-0432-4dfd-96d9-0c90d3de1567       none                    swap    sw                                      0 0
temp                                            /tmp                    tmpfs   noatime,nodev,nosuid,rw,size=2G         0 0
temp_portage                                    /var/tmp/portage        tmpfs   noatime,nodev,nosuid,rw,size=10G        0 0

EFI ESP partition tree:
rescue ~ # tree /boot/
/boot/
├── config-5.4.97-gentoo
├── efi
│   └── boot
│       └── bootx64.efi
└── kernel-current

Kernel cmd line:
CONFIG_CMDLINE="root=/dev/md2 net.ifnames=0 pcie_aspm.policy=performance"

Kernel configuration: Pastebin link to .config

Does anyone have ideas, do i miss something or whatever something is wrong with?
I'm out of ideas right now. :-/
Thanks in advance!

A: Looking at your Partition Map, I believe I see the issue.  The EFI Partition should not be the /boot partition
# cat /etc/fstab
# comment snip
# <fs>                                         <mountpoint>    <type>  <opts> <dump/pass>
UUID=fe110e32-ac2b-4c2c-9fe2-d7a3d774f4a5       /boot           ext4    noauto 0 2
UUID=BCF2-DB39                                  /boot/efi       vfat    noauto 0 2
UUID=abdd1226-d5d9-4515-bc5e-254e3f30820f       /               ext4    noatime 0 1
UUID=21607857-3746-4e19-aca9-6de321b18849       /home           ext4   noatime  0 1
UUID=a35b9533-9f83-4923-b4e3-a0cbae6c8522       none            swap    sw      0 0
/dev/cdrom                                      /mnt/cdrom      auto    noauto,ro 0 0

Above is a copy of my fstab fie. Note the separate entry for the EFI Partition.  The /boot partition should contain kernels and the like:
$ sudo mount /boot
Password:

$ ls /boot
efi  grub  initramfs-5.4.72-gentoo-x86_64.img  lost+found  refind_linux.conf
System.map-5.4.72-gentoo-x86_64  System.map-5.4.72-gentoo-x86_64.old  vmlinuz-
5.4.72-gentoo-x86_64  vmlinuz-5.4.72-gentoo-x86_64.old

The efi mount should contain the items in the EFI partition
$ sudo mount /boot/efi
EFI  'System Volume Information'

$ ls /boot/efi/EFI/
debian  gentoo  Microsoft  refind  tools

Each directory contains the EFI Stub loader for each OS installed on my various HDD's.  Note that rEFInd expects them named this way so that I get the appropriate OS icon when booting up.


text:
Q: Closed formula for LDU decomposition I know how LDU decomposition works and moreover, I know that these closed formulas are more difficult to compute and hence it is not done in practice, but I want to understand the following cite from Wikipedia:

Closed formula
When an LDU factorization exists and is unique, there is a closed (explicit) formula for the elements of L, D, and U in terms of ratios of determinants of certain submatrices of the original matrix A.In particular, $D_{1}=A_{1,1}$ and for i = 2 , … , n $D_i$ is the ratio of the i -th principal submatrix to the ( i − 1 )-th principal submatrix. Computation of the determinants is computationally expensive, so this explicit formula is not used in practice.

Unfortunately I do not understand how this formula looks. Especially what is the i-th principal submatrix. I am not familiar with this term and it is not explained in more detail. I tried reformulating the recursive formulas that are usually used to explicit ones but this gets very fast very messy and I did not find an easy technique for doing so.
Here is the full wikipedia article: https://en.wikipedia.org/wiki/LU_decomposition
Thank you very much in advance for your help.
EDIT: Hello,
I was thinking about it since yesterday and as soon as I post the question, I realize what part of the answer must be. The definition of principal submatrix that is meant, it also called leading principal submatrix and obtained by keeping the first i rows and column of a matrix and eliminating the others. Hence $D_i = \frac{det A_i}{det A_{i-1}}$. The part that is still missing is the formula for $L_i$ and $U_i$.

A: Use slice notation $m:n=[m,m+1,..,n]$, so that for example $A_i=A_{1:i,1:i}$. Then we want to achieve the decomposition in the step $i\to i+1$
$$
A_{i+1}=\pmatrix{A_i&A_{1:i,i+1}\\A_{i+1,1:i}&A_{i+1,i+1}}
=
\pmatrix{L_i&0\\L_{i+1,1:i}&1}
\pmatrix{D_i&0\\0&d_{i+1}}
\pmatrix{U_i&U_{1:i,i+1}\\0&1}
$$
Of course, $A_i=L_iD_iU_i$ by iteration assumption. Also from the determinant laws, $\det(A_i)=\det(D_i)$ so that $d_{i+1}=\det(A_{i+1})/\det(A_i)$.
For the other parts multiply out the matrix product
$$
=\pmatrix{L_iD_i&0\\ L_{i+1,1:i}D_i&d_{i+1}}
\pmatrix{U_i&U_{1:i,i+1}\\0&1}
=
\pmatrix{A_i&L_iD_iU_{1:i,i+1}\\L_{i+1,1:i}D_iU_i&L_{i+1,1:i}D_iU_{1:i,i+1}+d_{i+1}}
$$
to then get
$$
L_iD_iU_{1:i,i+1}=A_{:i,i+1}=(L_iD_iU_i)A_i^{-1}A_{1:i,i+1}\implies U_{1:i,i+1}=U_iA_i^{-1}A_{1:i,i+1}
\\
L_{i+1,1:i}D_iU_i=A_{i+1,1:i}=A_{i+1,1:i}A_i^{-1}(L_iD_iU_i)\implies L_{i+1,1:i}=A_{i+1,1:i}A_i^{-1}L_i
\\
d_{i+1}=A_{i+1,i+1}-L_{i+1,1:i}D_iU_{1:i,i+1}
$$
Remember that the entries of $A_i^{-1}=\frac{A_i^\#}{\det(A_i)}$ (using the adjoint/adjunct/adjugate which is the transpose of the co-factor matrix) are fractions of determinants, and for further consideration, that constructs like $A_i^\#A_{1:i,i+1}$ can be interpreted as consisting of Lagrange determinant formulas, giving $-\bigl(A_{i+1}^\#\bigr)_{1:i,i+1}$. Thus in total
$$
U_{1:i,i+1} = -\frac{U_i\bigl(A_{i+1}^\#\bigr)_{1:i,i+1}}{\det(A_i)}\\
L_{i+1,1:i} = -\frac{\bigl(A_{i+1}^\#\bigr)_{i+1,1:i}L_i}{\det(A_i)}
$$


text:
Q: Displaying Google Chart from database not showing data correctly I am making an management web application. I want to display sales and purchase graph from database. I am using php to retrieve data and ajax to display it in html page. Graph is drawing but the problem is data is not showing correctly.
Here is the link of my page:

https://smilestechno.000webhostapp.com/My/past.html

You can try it by giving this input - Categary=Purchase, View=Monthly, Year=2018, Month=Jun
Script
<script type="text/javascript">

// Load the Visualization API and the piechart package.
google.charts.load('current', {'packages':['bar']});

function drawChart() {

     var category = document.getElementById('category');
      var categorySelected = category.options[category.selectedIndex].value;
      var view = document.getElementById('view');
      var viewSelected = view.options[view.selectedIndex].value;
      var month = document.getElementById('month');
      var monthSelected = month.options[month.selectedIndex].value;
      var year = document.getElementById('year');
      var yearSelected = year.options[year.selectedIndex].value;

      var settings = {
    "url": "php/past.php",
    "method": "post",
    "headers": {
    "Content-Type": "application/x-www-form-urlencoded",
    },
    "data": {
    "category": categorySelected,
    "view": viewSelected,
    "month": monthSelected,
     "year": yearSelected
     }
    }

    $.ajax(settings).done(function(response) {
var data = google.visualization.arrayToDataTable([
['Month', 'Amount'], response
 ]);

var options = {
chart: {
  title: 'Past Performance Graph',
  subtitle: 'Duration : Jan 2018- Jun 2018',
}
};

var chart = new google.charts.Bar(document.getElementById('graph'));
chart.draw(data, google.charts.Bar.convertOptions(options));
});
}

</script>

PHP
<?php
$category = $_POST["category"];
$view = $_POST["view"];
$month = $_POST["month"];
$year = $_POST["year"];

$con = mysqli_connect("localhost","username","pw","db");

if($category == "Purchase"){
if($view == "Weekly"){
    $sql = "SELECT Date,SUM(Amount) from AccPurchase WHERE Date LIKE '$year-$month%' GROUP BY WEEK(Date)";
}else if($view == "Monthly"){
    $sql = "SELECT Date,SUM(Amount) from AccPurchase WHERE Date LIKE '$year%' GROUP BY MONTH(Date)";
}else if($view == "Yearly"){
    $sql = "SELECT Date,SUM(Amount) from AccPurchase GROUP BY YEAR(Date)";
}
}else if($category == "Sales"){
if($view == "Weekly"){
    $sql = "SELECT Date,SUM(Amount) from AccSales WHERE Date LIKE '$year-$month%' GROUP BY WEEK(Date)";
}else if($view == "Monthly"){
    $sql = "SELECT Date,SUM(Amount) from AccSales WHERE Date LIKE '$year%' GROUP BY MONTH(Date)";
}else if($view == "Yearly"){
    $sql = "SELECT Date,SUM(Amount) from AccSales GROUP BY YEAR(Date)";
}
}

$exc = mysqli_query($con, $sql);
$rows = array();
while ($row = mysqli_fetch_assoc($exc)) {
  $rows[] = array("v"=>$row["Date"], "v"=>$row["SUM(Amount)"]);
}
header('Content-Type: application/json');
echo json_encode($rows);
mysqli_close($con);
?>

I was finding solution and i got this post:

How to create DataTable for ColumnChart by JSON object?

I think i need to sand data in this format but i dont know how to send it from php in this format.
{
"cols": [
    {"id": "date", "label": "date","pattern": "","type": "string"},
    {"id": "newjobs","label": "newjobs","pattern": "","type": "number"}
],
"rows": [
    {"c": [
            {"v": "01-02-2013","f": null},
            {"v": 132,"f": null}
        ]},
    {"c": [
            {"v": "08-02-2013","f": null},
            {"v": 78,"f": null}
        ]},
    {"c": [
            {"v": "15-02-2013","f": null},
            {"v": 105,"f": null}
        ]
    },
    {"c": [
            {"v": "22-02-2013","f": null},
            {"v": 8,"f": null}
        ]}
]
}

A: first, let's give the sum calculation a name in all the sql statements...
change --> SUM(Amount) -- to --> SUM(Amount) as TotalAmount
e.g.
$sql = "SELECT Date,SUM(Amount) as TotalAmount from AccPurchase WHERE Date LIKE '$year-$month%' GROUP BY WEEK(Date)";

next, the following php will create the json in google's data table format...
$exc = mysqli_query($con, $sql);

$rows = array();
$table = array();

$table['cols'] = array(
  array('label' => 'Month', 'type' => 'string'),
  array('label' => 'Amount', 'type' => 'number')
);

while ($row = mysqli_fetch_assoc($exc)) {
  $data = array();
  $data[] = array("v" => date_format($row["Date"], "Y-m"));
  $data[] = array("v" => $row["TotalAmount"]);
  $rows[] = array('c' => $data);
}

$table['rows'] = $rows;

header('Content-Type: application/json');
echo json_encode($table);
mysqli_close($con);

note: you may want to change the date format, not exactly sure what you need here...
$data[] = array("v" => date_format($row["Date"], "Y-m"));

this will give you the format as --> 2018-06 -- for June...

finally, in the JavaScript, since you now have the correct json format,
you can create a new data table directly, without using --> arrayToDataTable,
like so...
$.ajax(settings).done(function(response) {

  var data = new google.visualization.DataTable(response);

  var options = {
    chart: {
      title: 'Past Performance Graph',
      subtitle: 'Duration : Jan 2018- Jun 2018',
    }
  };

  var chart = new google.charts.Bar(document.getElementById('graph'));
  chart.draw(data, google.charts.Bar.convertOptions(options));
});


text:
Q: How to add an if-else statement in react to read json-schema? I am very new to js and react so I hope that someone can give me an idea for this problem. My solution is very bad but I couldn't come up with a good solution. I don't know either how to add if-else statement in render. There are 6 buttons and each button is a name of a json-schema(it should be better to have a table instead of buttons but I get errors all the time with tableview).
I want to show json-schema, when user clicks a button so that the user can submit a json file.
import React, { Component, useState } from 'react';
import { Row, Col } from 'react-bootstrap';
import { withTheme } from '@rjsf/core';
import schema1 from '../schemas/schema1.json';
import schema2 from '../schemas/schema2.json';
import { Datagrid, TextField, EditButton, DeleteButton } from 'react-admin';

class MyApp extends Component {

    constructor(props) {
        super(props);
        this.clickme = this.clickme.bind(this);
    }

    ToggleGroup() {
        const theme = {
            blue: {
                default: '#3f51b5',
                hover: '#283593',

            },
            pink: {
                default: '#000000',
                hover: '#ad1457'
            }
        }

        return (<div>
            {types.map(type => (

                <Col>
                    <Col>
                        <Button
                            active={active === type}
                        >{type}</Button>
                    </Col>
                </Col>
            ))}
            <Col>
           <Form
            schema={schema1}

          />
          </Col>
        </div>
        );
    }

    render() {
        return (
            <>
                <Col>
                    <Col>
                        <text>
                            List of schemas
                        </text>
                    </Col>
                </Col>
                <this.ToggleGroup />

            </>
        );
    }
}

export default MyApp;

A: Your issue seems to be mostly with how to structure your code. This is something you can best learn by studying the code of other people. This github repository contains a lot of great bits and pieces to help you out.
To answer your question, I would recommend you to separate your components. The solution might become clear to you by itself. Maybe you can add your schemas to an object / map and then select the schema based on the activeType that you select within your ToggleGroup.
E.g.:
import schema1 from '../schemas/schema1.json';
...

const schemas = new Map([
  ['schema1', schema1],
  ['schema2', schema2],
  ...
]);

// In your Form-Component

const activeSchema = schemas.get('activeType')


text:
Q: If we know a system of PDEs is "hyperbolic" or "elliptic" or "parabolic", why do we care? I have been helping a student identify whether PDEs are hyperbolic, parabolic or elliptical, and we can do the calculation, but I don't know what that does for us.  What is that knowledge good for?  What is the point?
It seems those terms "elliptic", "parabolic" and "hyperbolic" are used in a lot of contexts, and I am wondering what those contexts have in common.  Why are those names used?

A: I'll take a stab at some of this. I use ellipticity in examples in some places, but this could be replaced with the other two for the most part.
First, I argue that words like elliptic, parabolic, and hyperbolic are used in common discourse by analysts to describe equations or phenomena via implicit analogy, and that analogy is how we think about PDE most of the time.
The truth is that we do not understand PDE very well. We barely understand the simplest examples: there are people out there right now trying to understand harmonic functions better, and harmonic functions have been studied for centuries. If you give me an arbitrary PDE, the odds of me deducing something interesting about it directly are extremely small. This isn't like with ODE, where you interpret it as a dynamical system and maybe it's complicated but at least you know more or less what to ask and to look at. With PDE, it's not clear what the right questions are to ask. Maybe you stare at it and notice that it has some trivial solution, like $0$: is this meaningful information or a random accident? Maybe it has symmetries or invariances... but how do you tell? We know from experience that maybe it makes sense to assign boundary conditions... but where, and on what, and how?
What we have going for us is experience. I have spent many (too many?) hours of my life thinking about harmonic functions, solutions to $\Delta u = 0$. I understand very little about them, but I can at least ask questions about them that turn out to be interesting. I also have some mental picture of what solutions are doing, and some ways to support this mental picture with "sophisticated PDE machinery" like the maximum principle. So when you give me some weird PDE, it's reasonable for me to ask: is this like the Laplace equation, where I can maybe ask some of my favorite questions and bring my (inadequate) arsenal of tools to bear on it?
For example, look at this PDE: $\sum_{ij}\partial_{ij}u \partial_i u \partial_j u = \nabla u \cdot D^2u \nabla u  = 0$. I don't really know whether this has enough resemblance to the Laplace equation for my knowledge of harmonic functions to be relevant, but I can try and check. Does it have a maximum principle? (yes) Can I solve the Dirichlet problem? (yes) Can I prove some regularity properties of solutions? (some, not many) Does it have some analogue to Dirichlet's principle? (no) Does it have a mean value property? (not that I'm aware of) And so on. After I study this for long enough, I might reasonably decide that, yes, the analogy to the Laplace equation here is a powerful one, and the word I use to capture that idea is "elliptic."
[I don't feel like you should be able to classify this equation as elliptic  easily, for the record; I have even seen prominent mathematicians classify it as parabolic (and not entirely ironically).]
The moral here is, if someone tells you that an equation is elliptic, what they are saying is that there are important similarities between its structure and the behavior of its solutions and the Laplace equation. They may say something very precise as well (it's elliptic in the sense of Hörmander, it's elliptic in the sense of Agmon-Douglis-Nirenberg, it's a second order fully nonlinear uniformly elliptic equation, etc.), but those are best thought of as criteria that some PDE experts felt are sufficient for a good analogy to the Laplace equation.
Three corollaries of this:

*

*There is no single particular thing "ellipticity" tells you, when used in this broad sense. "Elliptic equations are ones with a maximum principle!" Except for those elliptic systems that don't have one ... while various first-order equations do, though no one would ever call them elliptic. "Elliptic equations solve elliptic boundary value problems!" Phrasing this in a way which is not tautological is more difficult than you might think: what are the "elliptic" boundary value problems for $\Delta^2 u = 0$? We might say that most of the time elliptic equations have well-posed boundary value problems with data on the entire boundary of a domain, while parabolic and hyperbolic equations might not ... but that's a pretty weak statement. Etc.

*It's not very useful to think of these descriptors (or others like dispersive, transport, and so on) as a grand classification of PDE. You see this with things like the infinity Laplace equation above, and you see this when your class of hyperbolic or parabolic equations in your classification starts including things which defy good analogies to simpler model equations.

*The better your understanding of the model equation, the more relevance the descriptors will have to you. Saying an equation is like the Laplace equation is pointless unless you know a decent amount about harmonic functions and have a good mental picture of how you expect them to behave. This is also relevant to the OP: "I have been helping a student identify whether PDEs are hyperbolic, parabolic or elliptical." Yes, this will not be easy to motivate unless the student knows something about some equation of that type. On the bright side, students might only deal with more limited collections of equations, for which the analogies are stronger (and where maybe we can make reasonable generalizations, like "Second-order elliptic equations of the kind we saw in class have well-posed Dirichlet problems on nice domains").

Finally, as far as the names: if you try classifying second-order constant coefficient differential equations of two variables, you notice that the characteristic surfaces (which essentially determine which model equation you are most like in the strongest possible sense, linear isomorphism of the underlying space) are conic sections, and these are the possible conic sections (well, the nondegenerate ones, at any rate). I imagine in other places where analogies to conic sections or quadratic forms are appropriate, you'll see similar terminology. The connection between these actual conics and solutions to the equations is not very meaningful in general.


text:
Q: set a variable as stringvar.get() I have issue I have a code that makes a select query :
loginquery = "SELECT * from User "
loginquery = loginquery + "WHERE UserName="+ loginVar.get() +" AND Password="+ passVar.get()+""

Issue with that is that the result is
SELECT * from User WHERE UserName= AND Password=
How do I fix that?
EDIT:::::
This is my code
loginquery = ("SELECT * from User "
              "WHERE UserName=%s AND Password=%s")
bobby = (loginVar.get(),passVar.get())

and I do
(query.execute(loginquery % bobby)

my print result is:

SELECT * from User WHERE UserName=usernameentered AND Password=passwordentered

However the mysql connector comes up with this error:
mysql.connector.errors.ProgrammingError: 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'AND Password=' at line 1

Why is that?

A: You should add quotation marks around string literals:
loginquery = ("SELECT * from User "
              "WHERE UserName='%s' AND Password='%s'")


text:
Q: Problems with UINavigationController nested within moreViewController I have UITabbarMoreController which contains a few UINavigationControllers. These UINavigationControllers then contain my custom view controllers.
So the hierarchy looks something like this:
UITabbarController
 - UINavigationController
  -> my custom UIViewController
 - ...(other children of UITabbarController look the same)

From within my custom view controller I call [self parentViewController] which should return a UINavigationController. And this really happens, I really do get a UINavigationController, BUT only when the particular UINavigationController is NOT inside moreNavigationController.
Since I have many children controllers in the tabbar controller, the tabbar controller creates a moreNavigationController. If I open a viewcontroller that is under moreNavigationController and call [self parentViewController] it returns a mysterious object with class UIMoreNavigationController
I really need to get the UINavigationController that is parent of my view controller, not the UIMoreNavigationController. Also, I tried using [self navigationController] with the same result. How can I get reference to the real closest parent of my viewcontroller? Thanks for help in advance!

A: In short, you can't.
Apple always try to optimise their code. One of their optimisation here is to check whether the ViewController displayed in the list of its UIMoreNavigationController is of type UINavigationController. Because UIMoreNavigationController itself is a UINavigationController it does not want to create another UINavigationController. It's trying to avoid UINavigationController nesting.
When you look at the header file of UIMoreNavigationController you will notice it has a variable
UINavigationController* _originalNavigationController; which is accualy the original UINavigationController that you created and that you want to access. Unfortunetly you cant since UIMoreNavigationController is private.
Workaround (ugly)
Pass the reference of your NavigationController to its children when you push them on it's stack.


text:
Q: Trouble Connecting QPushButton Signal to QGraphicsView Slot I'm having trouble connecting a signal in a QPushButton to a slot in my QGraphicsView.
My Push Button Header:
class Button : public QPushButton {

    Q_OBJECT

    public://public constructors / destructors

        Button(Game_state * game_state, QWidget *parent = 0);
        ~Button();

    protected://signals / slots etc QT
        void mousePressEvent(QMouseEvent * event);//

    signals:
        void updated() { std::cout << "HELLO FROM THE UPDATED METHOD" << std::endl;}

    protected:
        Game_state * game_state;//this is the global gamestate method
        char * action_name;//this is the application name that is responsible for setting the game_state so the game controller knows what to delete / update

};

You need the Q_Object macro to compile this with slots, but when I compile I keep getting a vtable reference not found like follows:
Undefined symbols for architecture x86_64:
  "vtable for Button", referenced from:
      Button::~Button()in buttons.o
      Button::~Button()in buttons.o
      Button::~Button()in buttons.o
      Button::Button(Game_state*, QWidget*)in buttons.o
      Button::Button(Game_state*, QWidget*)in buttons.o

When I take out the macro, I can compile it fine, but I keep getting this error when I run:
Object::connect: No such signal QPushButton::updated() in implementation/game_controller.cpp:11

My game_controller extends QGRaphicsView and here is my code where I am attempting to connect the Button:
this->button = new Button(game_state);
this->proxy = new QGraphicsProxyWidget();
this->proxy = this->scene->addWidget(this->button);

connect(this->button, SIGNAL(updated()), this, SLOT(update()));

Any help would be greatly appreciated

A: Keep Q_OBJECT, you need it for moc
Don't write the body of your signal, moc generates code for all signals.
Don't handle mousePressedEvent, handle the signal clicked () which is available on QAbstractButton and all of its child classes


text:
Q: Joomla 3.2.3 Showplus Slider Not loading in chrome I have built few websites in joomla 3.2.3 and have used showplus for image slider. In chrome the slider does not load for the first time in few sites but loads in other sites. For ex:
Issue in chrome browser
The images load in this website : http://irishotel.in/
but the images don't load in this website : http://www.theplanterscourt.com/


text:
Q: How do I find out who kept a build forever? I have list of builds that were kept forever, but I can't seem to find who kept these builds. Is there a way of finding that out using the API or through the cli.

A: It's not possible. Jenkins does not record this information.


text:
Q: Connect jsp to Database - DAO Good morning, i have this problem.I should connect a database with a  DAO ( where is a query ) and , i should view  in my JSP the bean assosciate at this DAO.I implement this code but doesnt work nothing.Initially i connect a bean with the jsp and the method provajsp,then i try to connect  the bean the jsp and the DAO class,but really dont know what i do , i need a little help if its possible.thanks a lot
CLASS ORGANIC ACTION
private List<StudentNational> listStudent=new ArrayList<StudentNational>()  ;

     private List<Bean> empList = new ArrayList<Bean>();

public List<StudentNational> getListStudent() {
        return listStudent;

    }

public void setListStudent(List<StudentNational> listStudent)   {
        this.listStudent=listStudent;
    }

CLASS ORGANIC SERVICE IMPL
        @Override
    public List <Bean> provajsp() throws Exception {

        List <Bean> result = StudentNationalDAO.provajsp();
        Iterator<Bean> it = result.iterator();
        Bean obj = null;

            String name= obj.getName();
            String surname= obj.getSurname();
            return StudentNational.provajsp();

CLASS BEAN
private String name;
    private String surname;
    with getter and setter

STUDENT NATIONAL contains table with fields
table
CLASSE StudentNationalDAO IMPL
List<StudentNational> result = null;
            String sqlNative = " Select * FROM StudentNational";

            Query query = getEntityManager().createNativeQuery(sqlNative);

            result = query.getResultList();
            return result;

and the JSP which contains the iterator for view the page .


text:
Q: PHP curl POST request with JSON response I'm trying to send post data and receive an SID from an api(qbittorrent) to send with a get request later. I'm currently stuck with an OK response but the json is NULL. Here's my code:
<?php
  $ch = curl_init();
  $fields = array( 'username'=>'Admin','password'=>'mypassword');
  $postvars = '';
  foreach($fields as $key=>$value) {
    $postvars .= $key . "=" . $value . "&";
  }
  $postvars = rtrim($postvars, '&');
  $url = "https://192.123.123.123:8080/login";
  curl_setopt($ch,CURLOPT_URL,$url);
  curl_setopt($ch,CURLOPT_POST, 1);
  curl_setopt($ch,CURLOPT_SSL_VERIFYHOST, 0);
  curl_setopt($ch,CURLOPT_SSL_VERIFYPEER, 0);
  $headers= array('Accept: application/json','application/x-www-form-urlencoded');
  curl_setopt($ch,CURLOPT_HTTPHEADER, $headers);
  curl_setopt($ch,CURLOPT_FOLLOWLOCATION, 1);
  curl_setopt($ch,CURLOPT_POSTFIELDS,$postvars);
  curl_setopt($ch,CURLOPT_RETURNTRANSFER, true);
  curl_setopt($ch,CURLOPT_CONNECTTIMEOUT ,3);
  curl_setopt($ch,CURLOPT_TIMEOUT, 20);
  $response = curl_exec($ch);
  var_dump(json_decode($response, true));
  print "curl response is:" . $response;
  curl_close ($ch);
?>

You can see the API documentaiton here https://github.com/qbittorrent/qBittorrent/wiki/WebUI-API-Documentation#authorization
I was able to get the json using powershell as simply as :
$prms = @{username="Admin";password="mypassword"}
$res = Invoke-WebRequest https://192.123.123.123:8080/login -Method POST -Body prms -UseBasicParsing

but I'm unable to do so with php! If you also feel like heading me right for the get request using the SID as a cookie, i'll be more than welcome :)

A: The problem was lying there, changed:
curl_setopt($ch,CURLOPT_HTTPHEADER, $headers);

to
curl_setopt($ch, CURLOPT_HEADER, true);

And I got my json response!


text:
Q: Passing variables in URL I have an address book widget that shows if there are contents.
If there are no contents, an add button will show up. Upon pressing the add button, it will redirect to another page which will show the form.
The initial design of my website is as follows:

*

*When the user click the add button, it will direct to a page using javascript function:
document.location.href="address?addOnly=true";

*The form will display.

*If successful, there are $.post that will change the div only that will enable user to do CRUD in the address book.

The problem with the variable inside the url which is address?addOnly=true is that when the user refresh it, it will always shows the add form.
That's why i've decided to hide the implementation using $.post
$.post('address', {"listEmty":true}, function (data) {
  window.location = "address";
});

The problem with this is that it can't pass the variable at all.
My questions are:

*

*How to handle the page refresh if using the get method, which passes the paramater in the URL,

*Are there anyways in javascript/jquery to pass the variable using post method then refresh the page?

Thank you.

A: <FORM method="post" action="address" id="refresh" style="display: none;">
  <DIV>
    <INPUT type="hidden" name="addOnly" value="true">
  </DIV>
</FORM>
<SCRIPT type="text/javascript">
  document.getElementById('refresh').submit();
</SCRIPT>

What this does is create an invisible form, then immediately submits it. You can of course call the submit from within your other javascript code.


text:
Q: Создание константной строки по условию Есть код следующего вида:
std::string str;
if (x > 0) str = "positive";
else if (x < 0) str = "negative";
else str = "zero";

Хочется переписать код так, чтобы str было бы константой.
Как это сделать "красиво"? Некрасиво - создать функцию, "вычисляющую" эту строку, и вернуть её:
const std::string str = Foo ();

Или вообще создать прямо тут на месте лямбду... Но так не хочется :) .

A: const std::string str = x > 0 ? "positive" : x < 0 ? "negative" : "zero";

Так годится?

A: Ну если без функции, то можно на месте сначала задать аргументы конструктора, а затем только создавать строку с const квалификатором.
char const * psz_value{};
::std::size_t value_length{}
if (x < 0)
{
    constexpr auto const & sz_value{"negative"}
    psz_value = sz_value;
    value_length = ::std::size(sz_value) - 1;
}
else if (0 == x)
{
    constexpr auto const & sz_value{"zero"}
    psz_value = sz_value;
    value_length = ::std::size(sz_value) - 1;
}
else
{
    constexpr auto const & sz_value{"positive"}
    psz_value = sz_value;
    value_length = ::std::size(sz_value) - 1;
}
::std::string const str{psz_value, value_length};

Но я бы вообще засунул эти строки в таблицу вместо пересоздания каждый раз.

A: Если это локальная переменная, то можно объявить дополнительную константную ссылку :
std::string str_pri;
std::string const & str = str_pri ;
if (x > 0) str_pri = "positive";
else if (x < 0) str_pri = "negative";
else str_pri = "zero";

А если глобальная переменная, то можно рабочую спрятанную переменную хранить в отдельном исходнике, а в открытый доступ передавать только константную ссылку.
public.hpp :
extern std::string const & str_pub ;

private.cpp :
static std::string str_pri;
std::string const & str_pub = str_pri ;

if (x > 0) str_pri = "positive";
else if (x < 0) str_pri = "negative";
else str_pri = "zero";

A:  const int i = x < 0 ? -1 : x == 0 ? x : 1;
 const string p[3] = { "negative", "zero", "positive" };
 const string str = p[i + 1];

A: В общем случае это решается лямбдой:
const std::string str = [&]{
    std::string str;
    // str = ...
    return str;
}();

Но для такого простого случая я бы взял предложенный Harry ? :.


text:
Q: Recrawl URL with Nutch just for updated sites I crawled one URL with Nutch 2.1 and then I want to re-crawl pages after they got updated. How can I do this? How can I know that a page is updated?

A: Simply you can't. You need to recrawl the page to control if it's updated. So according to your needs, prioritize the pages/domains and recrawl them within a time period. For that you need a job scheduler such as Quartz.
You need to write a function that compares the pages. However, Nutch originally saves the pages as index files. In other words Nutch generates new binary files to save HTMLs. I don't think it's possible to compare binary files, as Nutch combines all crawl results within a single file. If you want to save pages in raw HTML format to compare, see my answer to this question.

A: You have to Schedule ta Job for Firing the Job
However, Nutch AdaptiveFetchSchedule should enable you to crawl and index pages and detect whether the page is new or updated and you don't have to do it manually.
Article describes the same in detail.

A: what about http://pascaldimassimo.com/2010/06/11/how-to-re-crawl-with-nutch/
This is discussed on : How to recrawle nutch
I am wondering if the above mentioned solution will indeed work. I am trying as we speak. I crawl news-sites and they update their frontpage quite frequently, so I need to re-crawl the index/frontpage often and fetch the newly discovered links.


text:
Q: Permanently Export PYTHONPATH OSX I've set this at the end of my .bash_profile:
export PYTHONPATH=$PYTHONPATH:/usr/local/lib/python2.7/site-packages

But it seems it's not working, because when I start the Terminal it does not recognise the modules, but if I do it directly on the Terminal it works ok, but only for that session. When I start the Terminal again, it does not work.
I'm doing something wrong?

A: .bash_profile files only get sourced by login shells. You need to logout and login again for the changes to take effect. Alternatively, use .bashrc. This gets sourced everytime a new shell opens.
It's worrying that you need to add site packages to your path. Are you sure python installed correctly? What are the values of sys.prefix and sys.exec_prefix? Python searches for site packages under these directories. See the documentation for more details.