text:
Q: Updating some parts of a Backbone Marionette ItemView I'm a new to Backbone.js and also to Backbone.Marionette and I'm having some troubles trying to follow the best patterns for my application.
I'm creating a mobile web application encapsulated by PhoneGap. I have a common layout (Facebook like): 2 sidebars, a main header and a content zone where all the views are loaded.
My initialization code for a Backbone.Marionette application is:
var App = new Backbone.Marionette.Application();

App.addRegions({
    leftRegion: '#left-drawer',
    rightRegion: '#right-drawer',
    headerRegion: '#header',
    contentRegion: '#content',
    mainRegion: '#main'
});

This are my regions where the content will be attached. Later, just after initialize the router I have the next:
App.headerRegion.show(App.Views.Header);
App.leftRegion.show(App.Views.LeftSidebar);
App.rightRegion.show(App.Views.RightSidebar);

This will load my content to this new regions. The problem occurs in the HeaderView. The template for my Header view:
<button id="open-left"></button>

<button id="open-right"></button>

The ItemView it's very simple too:
var HeaderView = Backbone.Marionette.ItemView.extend({
    template: _.template(template),
});

In some parts of the app I don't want to use the  in the header. Some pages of the app will need to update this to a text, for example something like
Settings
. My question is, what's the best way to do it? Or better, what is the way to do it? Right now I don't know where to start and the only idea I've in mind is to create
a new ItemView with another template.
Thanks in advance!

A: Marionette provides a useful function for this case, getTemplate, and you use this function isntead of the template : template declarations, like this.
SampleView = Backbone.Marionette.ItemView.extend({
   getTemplate: function(){
      if (this.model.get("foo"))
          return "#sample-template";
      else
          return "#a-different-template";
   },
});

So in the parts of yur application where you need a diferent template wihtout image you just change modify a value on the view or your model that can be used in this function to made the change on the template at the time you call render.


text:
Q: Why can't one build Voronoi regions on only 2 points? Using Qgis 3.2 or python's geovoronoi, the Voronoi algorithm does not work on 2 points. I expected that the bounding box between the 2 points would have been cut in half but got errors instead. Qgis stating that at least 3 points are needed.
I'm interested in the reason why at least 3 points are needed for Voronoi?

A: I can't fully answer this, but I can confirm that it if you bypass the check for two points, it will almost always work, generating two Voronoi Polygons.
The source code for the Voronoi Polygons tool is in a file called VoronoiPolygons.py.

*

*On Windows, this is in qgis\python\plugins\processing\algs\qgis.

*On macOS it's in QGIS.app/Contents/Resources/python/plugins/processing/algs/qgis. (You can look inside a .app in the Finder by right-clicking on it and selecting "Show Package Contents".

As of QGIS 3.22.0, lines 151 to 160 of this file were:
if len(pts) < 3:
    raise QgsProcessingException(
        self.tr('Input file should contain at least 3 points. Choose '
                'another file and try again.'))
# Eliminate duplicate points
uniqueSet = set(item for item in pts)
ids = [pts.index(item) for item in uniqueSet]
sl = voronoi.SiteList([voronoi.Site(i[0], i[1], sitenum=j)
                       for (j, i) in enumerate(uniqueSet)])
voronoi.voronoi(sl, c)

Note that it checks the number of points, then removes duplicates. This means there are 3 ways you can see what happens running the algorithm on 2 points:

*

*Create a point layer with 3 points, 2 of them with duplicated coordinates. The uniqueSet line will reduce this to 2 points.

*Close QGIS, back up your existing VoronoiPolygons.py, edit the if len(pts) < 3: to if len(pts) < 2, and restart QGIS. When you finish, restore the original VoronoiPolygons.py. Seriously. Don't leave edited files within your QGIS installation. You could cause a lot of damage that way.

*Create a script or a whole plugin that duplicates VoronoiPolygons.py, including the voronoi.py file it imports. Then experiment on that as in step 2, but without messing with any of your existing files.

What I've seen from any of these methods is results like the ones below. The top row shows 2 points in various orientations. The bottom row shows 3 points for comparison.

*

*Most of the time, it generates the Voronoi Polygons we expect.

*If the points are all in line horizontally or vertically, it outputs the error message The extent of the input points is not a polygon (all the points are on a vertical or horizontal line) - cannot make a Voronoi diagram! and exits without generating anything.

*In the specific case I've highlighted in red, where the two points are in line southwest to northeast, it outputs an error message of the type Feature could not be written to Voronoi_polygons_db6ff839_d2b5_45fe_a6ab_5ea2c5613d41: Could not add feature with geometry type LineString to layer of type Polygon and generates the southwest triangle but not the northeast one.

This happened at a variety of origin positions and scales, but if someone wants to duplicate it and has trouble, below is a file where it happened to me.
Longitude,Latitude,Name
10,10,Northeast
-10,-10,Southwest

I've investigated some of this, and it seems that the output from one of the algorithm steps only defines 2 points when it should be at least 4 (a triangle with the start and end point repeated). This is why it gets treated as a LineString, but can't by added to a Polygon layer.
Were the developers of the Voronoi polygons tool aware of this error and prevented it running on 2 points to avoid it happening? Possibly.
I hope this answers some of your questions. If you experiment with running the algorithm on 2 points, please let us know if you get the answers you expect.
Edited 11th March 2022
I have run many test cases through VoronoiPolygons.py. The VoronoiPolygons.clip_voronoi() method doesn't allow for a few unusual cases. These are only likely to appear with "toy problems" created to test it, and are highly improbable with "real world" inputs. I will be writing up an issue report for these, but it's relevant to the question, so I will document it here first. As also noted in the comments, none of these problems happen with QgsGeometry.voronoiDiagram().
As of QGIS 3.22.0, here are the problems:

*

*If a single polygon should have points in diagonally opposite corners, it will be created missing both of them, as in the diagrams above.

*If a polygon should be a triangle going to the very northeast, southeast and southwest corners of the bounding box, it will miss the northeast corner and therefore be treated as a LineString rather than a Polygon. This can only happen with a square bounding box and 2 points, one in the northeast and the other in the southwest corner. The existing check in VoronoiPolygons.processAlgorithm() requiring 3 or more points therefore prevents this from happening in most cases except in issue 3 below.

*VoronoiPolygons.processAlgorithm() counts the number of points before removing duplicates, which is the only way to cause issue 2.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Bluetooth Mouse stops working after a few seconds (NetworkManager issue) My Microsoft Designer Bluetooth Mouse will stop working after a short time.
UPDATE: It is a general bluetooth problem. I tried sending files from my mobile to my laptop and received only 1 file. The Bluetooth connection stalled afterwards.
I am running the latest openSUSE Tumbleweed on a Lenovo T460s. First I was running openSUSE Leap 42.2 with Kernel 4.0.36 and the Bluetooth Mouse worked flawlessly, but on older Kernels there is an issue with Skylake Processors so that my system would freeze - https://forums.opensuse.org/showthread.php/521718-Frequent-lockups-freezes .
I was able to pin down the problem to the following:
sudo systemctl stop NetworkManager

The mouse will work flawlessly. As soon as I start the NetworkManager the mouse will stop working and the Bluetooth Icon in Gnome Shell will signal Bluetooth connection forever. I could then run:
sudo systemctl restart bluetooth

which will make the mouse work for only a few seconds.
Here comes the even stranger part. If I exclude the wlan0 interface in /etc/NetworkManager/NetworkManager.conf
[keyfile]
unmanaged-devices=interface-name:wlan0

The mouse will work again flawlessly but of course I don't have WiFi managed by NetworkManager which is undesirable.
So something from NetworkManager is interfering with bluetooth as long as wlan0 device is managed.

Specs:
mike@think:~> cat /etc/issue
Welcome to openSUSE Tumbleweed 20161226 - Kernel \r (\l).
mike@think:~> uname -a
Linux think.suse 4.9.0-2-default #1 SMP PREEMPT Fri Dec 16 19:51:27 UTC 2016 (6fbc0c0) x86_64 x86_64 x86_64 GNU/Linux
mike@think:~> sudo dmidecode -t bios
# dmidecode 3.0
Getting SMBIOS data from sysfs.
SMBIOS 2.8 present.

Handle 0x000C, DMI type 0, 24 bytes
BIOS Information
    Vendor: LENOVO
    Version: N1CET52W (1.20 ) <-- latest
...
mike@think:~> sudo systemctl status bluetooth
● bluetooth.service - Bluetooth service
   Loaded: loaded (/usr/lib/systemd/system/bluetooth.service; enabled; vendor preset: disabled)
   Active: active (running) since Fri 2017-01-06 11:27:31 CET; 17min ago
     Docs: man:bluetoothd(8)
 Main PID: 1191 (bluetoothd)
   Status: "Running"
    Tasks: 1 (limit: 512)
   CGroup: /system.slice/bluetooth.service
           └─1191 /usr/lib/bluetooth/bluetoothd

Jan 06 11:27:31 think systemd[1]: Starting Bluetooth service...
Jan 06 11:27:31 think bluetoothd[1191]: Bluetooth daemon 5.43
Jan 06 11:27:31 think bluetoothd[1191]: Starting SDP server
Jan 06 11:27:31 think systemd[1]: Started Bluetooth service.
Jan 06 11:27:31 think bluetoothd[1191]: Bluetooth management interface 1.14 initialized
Jan 06 11:27:32 think.suse bluetoothd[1191]: Failed to obtain handles for "Service Changed" characteristic
Jan 06 11:27:32 think.suse bluetoothd[1191]: Sap driver initialization failed.
Jan 06 11:27:32 think.suse bluetoothd[1191]: sap-server: Operation not permitted (1)
Jan 06 11:27:34 think.suse bluetoothd[1191]: Endpoint registered: sender=:1.26 path=/MediaEndpoint/A2DPSource
Jan 06 11:27:34 think.suse bluetoothd[1191]: Endpoint registered: sender=:1.26 path=/MediaEndpoint/A2DPSink
mike@think:~> nmcli -v
nmcli tool, version 1.4.4

I have also tried udev rules using vendor and productid for my mouse and bluetooth hub leveraging NM_UNMANAGED (man NetworkManager) without success.
I tried turning on DEBUG logging in NetworkManager.conf (man NetworkManager.conf) but can see nothing interesting when the mouse failure occurs. The same applies if I start usr/lib/bluetooth/bluetoothd -n --debug 2>&1 debugging. Nothing to see.
I am out of options. Any help is appreciated, because I would like to have a mouse and internet access at the same time :)
UPDATE lspci
mike@think:~> sudo lspci -nnk | grep -iA2 net
00:1f.6 Ethernet controller [0200]: Intel Corporation Ethernet Connection I219-LM [8086:156f] (rev 21)
    Subsystem: Lenovo Device [17aa:2233]
    Kernel driver in use: e1000e
--
04:00.0 Network controller [0280]: Intel Corporation Wireless 8260 [8086:24f3] (rev 3a)
    Subsystem: Intel Corporation Device [8086:0130]
    Kernel driver in use: iwlwifi

I was able to improve the situation by disabling bt_coex in iwlwifi module:
cat /etc/modprobe.d/50-iwlwifi.conf
options iwlwifi bt_coex_active=0

The only issue left right now is that after wakeup from suspend I have to restart bluetooth service to make it work again. Restarting NetworkManager still kills bluetooth, but when I connect my mouse after WiFi is established the connection will not stall anymore and disconnects/reconnect (turning off the mouse) are handled without errors.

A: Since I deactivated bt_coex the problem is solved for me. If I don't connect the mouse too fast after wake up from suspend (i.e.: wait for WiFi to be established), everything works fine.


text:
Q: Google search: Is it possible to exclude search results that have punctuation between the quoted terms? In other words, if I search for "beer can", I'll get a number of results that include phrases like "... beer. Can ...". I want to exclude all results that do not contain the term "beer [space] can". I want to remove all possibility of punctuation from the results.
I thought typing "-." or "-'.'" would work, but it doesn't.

A: Don't know if it helps, but have you tried [beer can]? Possibly with additional exclude phrases such as -"beer cans", -"beercan" etc.?


text:
Q: turn off pre-compile for a single asp.net page I need to modify a single user control that is typically deployed with a compiled dll to production.  Is it possible to force a single page to use a deployed code behind rather than what is in the dll?
Does that make sense?  I basically want to deploy a ascx file along with the ascx.cs file, when the rest of the site uses the dll.
I doubt this is possible, thought I'd check.


text:
Q: Unable to delete and update JSON string C# I am creating an application that asks the user the put data. The data is then stored to a structured JSON file. So far the user can enter as many data as they can, and I can display the values of the JSON on a textboxes if they decided to see old data.
I need to give the user the ability to Delete and Update the data when required.
Below is how the JSON strings look like. Click here to see the application interface
[
  {
    "Record": 1,
    "IPaddress": "168.147.8.343",
    "Machinename": "taurus",
    "username": "root",
    "password": "root",
    "sourcefolder": ".../.../.../...",
    "destfolder": ".../.../.../...",
    "filextension": "db",
    "removedownloaded": 0
  },
  {
    "Record": 2,
    "IPaddress": "178.255.255.1",
    "Machinename": "sami",
    "username": "sami",
    "password": "sami",
    "sourcefolder": "././././.",
    "destfolder": "././././.",
    "filextension": "json",
    "removedownloaded": 0
  },
  {
    "Record": 3,
    "IPaddress": "255.255.255.255",
    "Machinename": "root",
    "username": "taurus",
    "password": "taurus",
    "sourcefolder": "............/............./",
    "destfolder": "............/............./",
    "filextension": "txt",
    "removedownloaded": 0
  },
  {
    "Record": 4,
    "IPaddress": "168.147.8.343",
    "Machinename": "taurus",
    "username": "root",
    "password": "root",
    "sourcefolder": ".../.../.../...",
    "destfolder": ".../.../.../...",
    "filextension": "db",
    "removedownloaded": 0
  },
  {
    "Record": 5,
    "IPaddress": "168.147.8.343",
    "Machinename": "taurus",
    "username": "root",
    "password": "root",
    "sourcefolder": ".../.../.../...",
    "destfolder": ".../.../.../...",
    "filextension": "db",
    "removedownloaded": 0
  },
  {
    "Record": 6,
    "IPaddress": "168.147.8.343",
    "Machinename": "taurus",
    "username": "root",
    "password": "root",
    "sourcefolder": ".../.../.../...",
    "destfolder": ".../.../.../...",
    "filextension": "db",
    "removedownloaded": 0
  }
]

This is what I did to allow the user to create a new JSON file every time they enter a new data.
private void button4_Click(object sender, EventArgs e)
{
    if (MessageBox.Show("Are you sure you want to Add", "ADD", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
    {

        filePath = @"C:\Users\Sami\Desktop\Companies\Nautitech Mining Systems Pty Ltd\Code\JSON\app-db.json";
        // Update json data string
        //jsonData = JsonConvert.SerializeObject(DataloggerList);
        //System.IO.File.WriteAllText(filePath, jsonData);
        string text = File.ReadAllText(filePath);

        var currentList = JsonConvert.DeserializeObject<List<Datalogger>>(text);

        //Create new Datalogger

        Datalogger myself = new Datalogger

        {

            Record = ++count,
            IPaddress = textBox2.Text,
            Machinename = textBox8.Text,
            username = textBox4.Text,
            password = textBox3.Text,
            sourcefolder = textBox7.Text,
            destfolder = textBox6.Text,
            filextension = textBox5.Text,

        };

        if (currentList != null && currentList.Any())
        {
            var lastRecordNumner = currentList.OrderBy(q => q.Record).Last().Record;
            myself.Record = lastRecordNumner + 1;

        }
        else
        {
            currentList = new List<Datalogger>();
        }

        currentList.Add(myself);

        string output = Newtonsoft.Json.JsonConvert.SerializeObject(currentList, Newtonsoft.Json.Formatting.Indented);
        Console.WriteLine(output);
        File.WriteAllText(filePath, output);
    }
    else
    {
        this.Activate();
    }

}

When the user click on First, Last, Forward and Backward the data will be displayed on the textbox and I need to user to update and save the data when needed. I have tried this but I didn't work:
private void button1_Click(object sender, EventArgs e)
{
    if (MessageBox.Show("Are you sure you want to Save", "SAVE", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
    {
        Datalogger myself = new Datalogger
        {
            Record = ++count,
            IPaddress = textBox2.Text,
            Machinename = textBox8.Text,
            username = textBox4.Text,
            password = textBox3.Text,
            sourcefolder = textBox7.Text,
            destfolder = textBox6.Text,
            filextension = textBox5.Text,

        };
        filePath = @"C:\Users\Sami\Desktop\Companies\Nautitech Mining Systems Pty Ltd\Code\JSON\app-db.json";
        // Serialize it.

        string serializedJson = JsonConvert.SerializeObject(myself);
        // Print on the screen.
        Console.WriteLine(serializedJson);
        string output = Newtonsoft.Json.JsonConvert.SerializeObject(myself, Newtonsoft.Json.Formatting.Indented);

        File.WriteAllText(filePath, output);
    }
    else
    {
        this.Activate();
    }

}

Any Thoughts?

A: As an example of the above comments:
Note that for this to work you need to set the textbox for the Record field to the value of the Record from the DataLogger class everytime you change the data displayed by your textboxes - Do not try to calculate this by yourself, always use the value present in the DataLogger instance. When you add an element always calculate the next value using the Count method from the List global instance
First, be sure to have a class level variable to hold your list
public class FormForDataLogger : Form
{
     private List<DataLogger> currentData = null;

     // also keep this in one place (but is better if you read it from the config file
     private string filePath = @"C:\Users\Sami\Desktop\Companies\Nautitech Mining Systems Pty Ltd\Code\JSON\app-db.json";

     .....

Now in the Form constructor load this data from the file
 public FormForDataLogger()
 {
    if(File.Exists(filePath))
    {
        string text = File.ReadAllText(filePath);
        currentData = JsonConvert.DeserializeObject<List<Datalogger>>(text);
    }
    else
        currentData = new List<DataLogger>();
 }

Now when you want to add data
 private void btnAdd_Click(object sender, EventArgs e)
 {
    Datalogger myself = new Datalogger
    {
        Record = currentData.Count + 1;
        IPaddress = textBox2.Text,
        Machinename = textBox8.Text,
        username = textBox4.Text,
        password = textBox3.Text,
        sourcefolder = textBox7.Text,
        destfolder = textBox6.Text,
        filextension = textBox5.Text,
    };
    currentData.Add(myself);

    string output = Newtonsoft.Json.JsonConvert.SerializeObject(currentData, Newtonsoft.Json.Formatting.Indented);
    File.WriteAllText(filePath, output);
}

when you want to update data
 private void btnModify_Click(object sender, EventArgs e)
 {
     int record = Convert.ToInt32(txtRecord.Text);
     DataLogger logger = currentData.FirstOrDefault(x => x.Record == record);
     if(logger != null)
     {
         // update logger with your textboxes data
         logger.IPaddress = textBox2.Text;
         logger.Machinename = textBox8.Text;
         logger.username = textBox4.Text;
         logger.password = textBox3.Text;
         logger.sourcefolder = textBox7.Text;
         logger.destfolder = textBox6.Text;
         logger.filextension = textBox5.Text;

         // Save everything
         string output = Newtonsoft.Json.JsonConvert.SerializeObject(currentData, Newtonsoft.Json.Formatting.Indented);
         File.WriteAllText(filePath, output);

     }
}

Delete is similar
when you want to update data
 private void btnDelete_Click(object sender, EventArgs e)
 {
     int record = Convert.ToInt32(txtRecord.Text);
     DataLogger logger = currentData.FirstOrDefault(x => x.Record == record);
     if(logger != null)
     {
         currentData.Remove(logger);
         // Save everything
         string output = Newtonsoft.Json.JsonConvert.SerializeObject(currentData, Newtonsoft.Json.Formatting.Indented);
         File.WriteAllText(filePath, output);

     }


text:
Q: ListView and ContextMenu Is it possible to implements working with context menu inside ListView class? It is no onContextItemSelected() method here. I don't want write a code with context menu inside Activity class.
Thank you!

A: This would break the Android UI pattern pretty badly. Activity (and in recent versions Fragment) is responsible for displaying widgets like menus. Pushing this functionality down into a View will make your app a mystery.
You can get what you want by defining an interface, say ContextPopupDelegate with functions to build and handle selections in a context menu, then have your new View implement this interface. Any activity using your view delegates to the interface methods.


text:
Q: How to modify cookie names without the blocking version of WebRequest (using Manifest V3) I developed a Chrome extension that allows me to edit cookie names before each request and after each response in order to manage different sessions on different Chrome tabs (basically, something akin to Firefox containers).
I want to start porting it to Manifest V3 since I used Manifest v2 and the blocking version of webRequest in the background script, like this:
   chrome.webRequest.onBeforeSendHeaders.addListener((data) => {
      ...
   }, { urls: ["https://*/*", "http://*/*"] }, ["blocking", "requestHeaders", "extraHeaders"]);

   chrome.webRequest.onHeadersReceived.addListener((data) => {
      ...
   }, { urls: ["https://*/*", "http://*/*"] }, ["blocking", "responseHeaders", "extraHeaders"]);

What I was doing in the listener callbacks was basically adding a special token (which identifies its tab session) to the name of each cookie received in that "special" isolated tab and removing it before sending it back to the server. This approach was working but now, without being able to block the requests/responses, it doesn't anymore.
I was trying to switch to chrome.declarativeNetRequest but it seems way too limited with its static rules. I tried using updateDynamicRules() with the "type" : "modifyHeaders" action with Cookie and Set-cookie headers inside a non-blocking webRequest listener but it doesn't work.
How can I achieve something like this and port this extension with the new Manifest V3 and/or declarativeNetRequest?


text:
Q: How do I get out of root@ubuntu:~# I powered off my pcDuino system and now I am getting errors and eventually ending up in root@ubuntu:~#. When I try to "exit" the root super user it only shows my last login on tty1 as being in root. I was just in file manager or text editor when I powered down. I have no idea how I got to root or how to get out of it and back to my normal account.
I edited the network file per instructions:
$ sudo vi /etc/network/interfaces
# interfaces(5) file  used by ifup(8) and ifdown(8)
auto  lo
iface lo inet loopback

change to:
auto eth0
iface eth0 init dhcp

Somehow that left an /etc/network/interfaces.swp swap file out there.
I have been getting:
[13.998774] init: Plymouth main process (77) terminated with status 127
{14.053176} init: ureadahead main process (79) terminated with status 5
but the system would come up after a delay.

I am trying to develop a STABLE and SECURE commercial product on the pcDuino3.
Typing startx ran several messages across the screen VERY FAST and then killed the system. I am sorry I have no idea what this thing is running. The ads say Ubuntu 12 but now I get a screen saying Linaro 12.07 (GNU/Linux 3.4.79+ armv71). I have whatever was shipped preinstalled on a pcDuino3. I hope this helps.

A: You probably will need to backup and reinstall your system.
(There should be an error that causes your boot to drop into shell. Not unless you're willing to tinker with the system, then the easiest path is probably just to reinstall your system.)
Where to start tinkering:
Type startx on the tty and see what the error says and follow troubleshooting from there.


text:
Q: How can I make sure no duplicates occur when making a site that preorders tickets? I am making a website in which people can select which tickets they want and they just get an ID to go pay and pick them up to the desired location.
I have a PHP function that actually checks if the tickets are already booked before allowing people to reserve them, but I just found out that if 2 people happen to click the "booking" button within the same second, my system reserves the places twice.
Is there a way to prevent this? My current code works well except for what I've said, it's here:
$f1="";
    $f2="";

    $sqlAP="SELECT * FROM apartados";
                if ($resultAP = mysql_query($sqlAP)) {
                    while ($rowAP = mysql_fetch_array($resultApP)) {
                        $f = $rowAP['funcion'];
                        $lugar=$rowAP['lugar'];
                        $count++;
                            if($f=="F1"){
                            $f1.=($lugar. " ");
                            }else if($f=="F2"){
                            $f2.=($lugar. " ");
                            }

                    }
                }
            $sqlPag2="SELECT * FROM pagados";

                if ($resultPag2 = mysql_query($sqlPag2)) {
                    while ($rowPag2 = mysql_fetch_array($resultPag2)) {
                        $f = $rowPag2['funcion'];
                        $lugar=$rowPag2['lugar'];
                        $count++;
                        if($f=="F1"){
                            $f1.=($lugar. " ");
                            }else if($f=="F2"){
                            $f2.=($lugar. " ");
                            }
                    }
                }
            $func1= explode(" ",$f1);
            $func2= explode(" ",$f2);
        $repetidos=0;

        for($int=0;$int<$cant;$int++){
            $helper=0;
            while($func1[$helper]){
                if($func1[$helper]==$lugar[$cant]){
                    $repetidos++;
                    }
                $helper++;
                }
            }
        for($int=0;$int<$cant2;$int++){
            $helper=0;
            while($func2[$helper]){
                if($func2[$helper]==$lugar2[$cant2]){
                    $repetidos++;
                    }
                $helper++;
                }
            }

This takes from the database what has been booked (apartados) and paid (pagados) and then checks for repeated seats trying to get booked (repetidos) after this comes an if just looking for repetidos > 0, it works, except on the instance I described earlier. Could anyone let me know how I can avoid this?

A: *

*Give each ticket a unique id.

*Insert
the tickets in to a "reserved" table.

*Do this in a transaction, so all
tickets commit at once.

*Put a unique
constraint on the ticket id in the
reserved table.
If you get an error during your insert, then someone else has already reserved one of the tickets.

A: PHP + MySQL transactions examples
Use transactions.  They'll make your life a lot easier when you need to do multiple queries that can't be done in parallel.

A: The proper way to do this would be to design the database with a unique constraint on the seat/ticket column, then insert a new reservation in one atomic query. If a reservation already exists for this seat, the database will complain and you can handle that complaint in your code. It won't be possible to insert two identical seat reservations into the database. Selecting all records and looping through them in your application is, sorry, ludicrous.

A: When worried if the same seats are going to be reserved at the same time you can use MySQL table locks.  When locked, no one else can write to that table.  The process would look something like this:

*

*lock table

*check if seats are available

*reserve seats for this user if available or return error if not

*unlock table

This will prevent tickets being reserved twice as no other scripts can access the table until it is unlocked (other requests get 'queued' if they happen at the same time)


text:
Q: Installing brew on 22.04.1 LTS WSL getting Error: Failed to install ruby 2.6.8_1! i just installed ubuntu 22.04.1 LTS WSL on my windows 11
I opened the console and I tried to install brew using this command line
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"

But I'm getting this error
Pouring portable-ruby-2.6.8_1.x86_64_linux.bottle.tar.gz
/usr/bin/gzip: 1: ELF: not found
/usr/bin/gzip: 3: : not found
/usr/bin/gzip: 4: Syntax error: "(" unexpected
tar: Child returned status 2
tar: Error is not recoverable: exiting now
Error: Failed to install ruby 2.6.8_1!
Error: Failed to install Homebrew Portable Ruby and cannot find another Ruby 2.6.8!
If there's no Homebrew Portable Ruby available for your processor:
- install Ruby 2.6.8 with your system package manager (or rbenv/ruby-build)
- make it first in your PATH
- try again

Any solution??


text:
Q: How to open a vue component in new tab without page load by vue router? Is it possible to open a Vue component in new tab by vue router without page reload.
Normal Way :
<a href="http://example.com" target="_blank">HtmlExample </a>

Vue Router
<router-link to="/example" target="_blank">Vue Router Example </a>

It's works properly but i need it without page reload.

A: If I understood your issue correctly: new pages are always going to be loaded, since it's a vue lifecycle. Vue lifecycles. But what you can do here is to use browser's local storage. And when the component is mounted for example, you can share the data from your previous page.


text:
Q: Remove one of multiple background images using Jquery when using multiple layered backgrounds in css3, how can I peel away the layers using jquery on click events?
body {
background:url(./images/bg2.jpg), url(./images/bg1.jpg);
}

so in this case one background will show up on top of another. I want to use jquery to just remove the top background. any ideas?

A: Use this to remove the first background:
var bg = $("body").css("background");
var bgs = bg.split(',');
bgs.splice(0,1);
$("body").css("background", bgs.concat());

A:  var currentsBodyBg = $('body').css('background');
    // DELETE every backgrounds after the first;
    var new =currentsBodyBg.replace(/,.*/gi, ";");
    $('body').css('background', new);

A:     var b = $('body');
    var images = b.css('background-image').split(',');
    b.css('background-image', images[1]);

A: You have to use background-image instead of background, otherwise the returned string contains no-repeat top left scroll transparent ore something else too.
The topmost background-image is the first in the comma-separated list of urls. Splitting the string at each , gives an array of all urls. slice(1) returns an array with all items after the first.
join(',') converts that array back to a string with , between the items.
var $body = $("body");
var imgs = $body.css("background-image").split(',');
$body.css("background-image", imgs.slice(1).join(','));

You can have that as an oneliner, but with one disadvantage: $("body") is created two times:
$("body").css({backgroundImage: $("body").css("backgroundImage").split(',').slice(1).join(',')});


text:
Q: Get Users' profile data from facebook I need to fetch user profile data using Facebook graph API. I can search by name with search endpoint. I can receive a list of users with name and Id, but I can't get any additional information about them, even if it is opened and I can see it on a user's Facebook page. How is it possible to retrieve other user's profile data (not profile of authorized user)?

A: You can only get additional data if that user authorizes your App. Everything else would be a privacy issue. It does not matter if the data is available on facebook.com, Apps can´t access a user profile without authorization.


text:
Q: Changing or updating the passphrase in gcp lamp vm I am trying to download files from a particular folder from one of my vm's on gcp using the following command
gcloud compute scp --recurse VM_NAME:REMOTE_DIR LOCAL_DIR
After running the command the gcp terminal asks me for a passphrase.
I enter the passphrase and get a message saying
ERROR: (gcloud.compute.scp) [/usr/bin/scp] exited with return code [1].
My qs: How do I change or update the passphrase?
Note: The passphrase was set by running the following command:
gcloud auth login
What I have already done?

*

*Tried restarting and reloading apache2.

*Searched online for the issue using popular search engines.

*The solution mentioned here How do I change my private key passphrase? will not work because it asks for the old passphrase to change it

A: You have an issue with a proper ssh-key authorization. You may actually try the gcloud compute config-ssh first but I'd advise to go through the answers and documentation first to understand what you're doing.
I've found two answers for a similar questions that may help you:

*

*retrieving gcp passhprase

*scp exiting with error 1
Also have a look at the documentation that describes authorising ssh to your VM's:

*

*Authorizing Cloud SDK tools

*gcloud compute config-ssh


text:
Q: Read only kibana dashboard for AWS Elasticsearch 6.3 I have a requirement of sharing just Kibana dashboard in view only access mode with customers.
This is the first time I am working with Elasticsearch and Kibana. And this is my first Stackoverflow question. So, kindly bear with me.
Our team is using AWS Elasticsearch service with ES version 6.3,
AWS does not provide access to ElasticSearch server and Kibana app server.
Kibana has native support for Read Only dashboard as mentioned here -
Kibana dashboard only mode.
Kibana 6.0 onwards there is support for read only dashboard feature.
Also, there is X-pack plugin for Kibana versions not natively supporting this feature.
With AWS ES Service, I installed standalone Kibana on a separate EC2 instance to use its readonly native feature.
Download Kibana6.2.4
Using AWS docs, I have configured kibana.yml
Standalone Kibana looked exactly same as the one default with AWS ES, there is no options for user management.
I installed X-pack plugin with kibana6.2.4 using following command:
sudo ./bin/kibana-plugin install x-pack

I got following exceptions :
Authentication Exception :: {"path":"/_xpack","statusCode":401,"response":"{\"Message\":\"Your request: '/_xpack' is not allowed.\"}"}

If I use kibana6.3, it automatically starts throwing errors -
Authentication Exception :: {"path":"/_xpack","statusCode":401,"response":"{\"Message\":\"Your request: '/_xpack' is not allowed.\"}"}

If I disable x-pack security feature,
xpack.security.enabled: false

kibana server will go indefinitely into an optimization mode on my aws ec2 t2.micro instance, cpu consumption would go upto 100% and after sometime instance stops responding.
I found that some changes are required in elasticsearch.yml which resides on the ElasticSearch cluster instance which we don't have access to.
I raised a support ticket to AWS and they said, view only kibana dashboard is not possible as of now. I have requested them to make it a feature request which they accepted but there is no ETA given
Then, again I went further to find other solutions.
I found that, a proxy setup can be used to restrict some ES REST API calls to make the kibana dashboard browsing experience as read only.
Here are some links which I used -
Nginx configuration for Kibana-ElasticSearch read-only/read-write access
Kibana readonly over internet
Elasticsearch readonly rest plugin
The rest plugin above requires access to ElasticSearch server which I don't have.
As another try, using links above, I setup an AWS EC2 t2.micro instance and configured nginx to serve as proxy to restrict backend ElasticSearch api calls to make Kibana read only.
Here is my configuration snippet in nginx.conf -
  set $posting 11;
  if ( $request_method !~ ^(GET|POST|OPTIONS|HEAD)$ )                     { return 405; }
  if ( $request_method = POST )                                           { set $posting 1; }
  if ( $request_uri ~ ^/(.+)/(_search)(.*)$ ) { set $posting "${posting}1"; }
  if ( $request_method ~ ^(GET|OPTIONS|HEAD)$ )                           { set $posting 11; }
  if ( $posting != 11 ) { return 403; }

  # for elb health checks
  location /status {
    root /usr/share/nginx/html/ ;
  }

  location / {
    proxy_set_header Host search-<ES_DOMAIN>-<CRYPTO_STRING>.ap-south-1.es.amazonaws.com;
    proxy_set_header X-Real-IP <PUBLIC IP>;

    proxy_http_version 1.1;
    proxy_set_header Connection "Keep-Alive";
    proxy_set_header Proxy-Connection "Keep-Alive";
    proxy_set_header Authorization "";

    proxy_pass https://search-<ES_DOMAIN>-<CRYPTO_STRING>.ap-south-1.es.amazonaws.com/;
    proxy_redirect https://search-<ES_DOMAIN>-<CRYPTO_STRING>.ap-south-1.es.amazonaws.com/_plugin/kibana/ http://<PUBLIC IP>/kibana/;
  }

With this nginx setting, Kibana's Discover/Timelion/Dev Tools/Management page links wont work for save/delete, which is good.
Discover page goes blank, which is the right thing as no body can send their own queries.
Visualize and Dashboard both work similarly, they show their item lists, which is fine, but after that both pages don't open any real graphs.
I want even Visualize page should go blank but not the Dashboard page.
When I looked into firefox/chrome browser inspect/dev tools, both Visualize and Dashboard pages make calls using following apis -
"_plugin/kibana/api/saved_objects/_bulk_get",
"_msearch",
"_plugin/kibana/api/timelion/run"
I am not sure how to stop all UI elements to work except view only links in Dashboard, even Visualize page should be fully restricted.
I am trying to keep only Dashboard open for viewing its predefined graphs without any edit, save or delete options.
After some research with Stackoverflow, I got few answers which are either old or not relevant or even requires access to ES/Kibana server which I don't have.
These are the Stackoverflow links:-
Is custom kibana plugin installation in aws elasticsearch possible
Kibana read only dashboard
How to block selected kibana subpages using nginx
Kibana dashboard only mode
Another approach is given at this link, Applying read only permission to kibana dashboard
But this would lock the .kibana index and it would be a problem for other users using it.
Any help or pointers would be highly appreciated. I am not able to solve this for many days by myself.


text:
Q: django DurationField: Edit only hours and minutes in admin UI? I have a Recipe model that has a few DurationField attributes:
class Recipe(models.Model):
    # ...
    prep_time    = models.DurationField(default=timedelta())
    cooking_time = models.DurationField(default=timedelta())
    total_time   = models.DurationField(default=timedelta())

On the django admin UI, I have the ability to edit the seconds field for these three attributes. Is there any way to limit an admin user to just be able to edit the hours/minutes of a DurationField? I don't really need this level of granularity here and am wondering if there's an alternative to storing the times purely as floats and then converting on my view.


text:
Q: Regex Lookahead in Oracle SQL I'm trying to find certain strings in my tables.
I need to display only the records that have those characters.
For example I have this table:
TABLE_A
=================
 # | COL_A
=================
 1 | ABC
 2 | _ABC_
 3 | _ABCD_ABC_
 4 | ABCD

I want to select all records that has ABC but not ABCD.
In the example table above, records 1, 2 and 3 should be displayed.
The best I came up with now currently is this:
SELECT * FROM TABLE_A WHERE REGEXP_LIKE(COL_A, 'ABC[^D]{1,}', 'inm');

The problem with the statement above is that if there's only ABC at the end of the data, it won't be displayed.
PS: Is this even doable in pure SQL?

A: You can use [^D]|$ to match a non-D character or the end-of-line:
SELECT *
FROM   TABLE_A
WHERE  REGEXP_LIKE(COL_A, 'ABC([^D]|$)', 'i');

A: You can do this with like:
where '_' || col_a || '_' like '%$_ABC$_%' escape '$'

However, storing multiple codes in a single column is not the SQLish way to store data.  You should fix your data structure, particularly if you care at all about performance.

A: Look for rows where 'ABC' is preceeded by the start of the line or an underscore and proceeded by an underscore or the end of the line.
SQL> with table_a(ID, col_a) as (
     select 1, 'ABC'        from dual union all
     select 2, '_ABC_'      from dual union all
     select 3, '_ABCD_ABC_' from dual union all
     select 4, 'ABCD'       from dual
   )
   select id, col_a
   from table_a
   where regexp_like(col_a, '(^|_)ABC(_|$)');

        ID COL_A
---------- ----------
         1 ABC
         2 _ABC_
         3 _ABCD_ABC_

SQL>


text:
Q: Get data from link I'm trying to get a unique code from a link that I email out. The link that I send is "website.com/redeem.php?code=xxxxxxxxxx" I'm trying to capture the x's in order to compare it to a list of codes in a text document. Any help is appreciated. My knowledge of php is little.
The only thing I knew to try:
$code=$_POST['code'];

echo $code;

A: What you are looking for is $_GET.
$code = $_GET['code'];
echo $code;

Reading material:
http://php.net/manual/en/reserved.variables.get.php
http://php.net/manual/en/reserved.variables.post.php

A: The URL is using a querystring which is passed as $_GET - not $_POST. Try this:
$code = $_GET['code'];
echo $code;

A: URI params provides as a $_GET array in php. Try $_GET['code']
You can also use $_REQUEST array.
It is merged $_POST, $_GET and $_COOKIE


text:
Q: Should I recalculate tf-idf after each item is added to the index? For example, I have a document of 100 records, do I have to recalculate tf-idf when adding each entry (because idf "number of documents where the term")?
Or is tf-idf counted for every search query?
If that's the case, and search engines use that algorithm, then isn't that slow?


text:
Q: Is this stochastic matrix has a steady state equivalent to Perron Frobenius theorem?
This is the capture from Lay-linear algebra. I am trying to find the proof under this specific statement, but I cannot find it online. Rather, I've seen Perron Frobenius theorem which is very close to this(I am not sure), something about maximal eigenvalue is $1$ involving contraction mapping.
I am wondering if anyone could help me out to prove this specific statement if they are not equivalent, or redirect me to the proof of this specific statement.

A: From a stochastic matrix $P^{n \times n}$ we can compute the distribution of the Markov chain in  $X_{n+1}$ from induction computing the distribution of $X_{n}$ using the law of total probability.
Observe that the space $X$ is finite, with $\mathbb{X}=\{v_{1},v_{2},\dots,v_{n}\}$ we can describe the probability mass function as a vector :
$$\pi = (\pi(v_{1},\pi(v_{2},\dots,\pi(v_{n})))) $$
or $$\pi_{n+1} = \pi_{n}P$$
where in the rhs is the regular matrix multiplication.
Defining the power $$P^{n} =\{p^{(n)}(x,y) \}_{x,y \in \mathbb{X}}$$ of a stochastic matrix $P$ for $n \in \mathbb{N}_{0}$ and using the Fubinni - Tonelli theorem we have:
$P^{0}=I$ and in general $$P^{n}=P^{n-1}P $$ for $n \in \mathbb{N}$
Diagonilizing the matrix $P$ we will obtain the eigenvalue decomposition looking like :
$$P^{n} = \begin{pmatrix}
1 & u_{1}\\
1 & u_{2}
\end{pmatrix}\begin{pmatrix}
1 & 0\\
0 & \lambda^{n}
\end{pmatrix}\begin{pmatrix}
1 & u_{1}\\
1 & u_{2}
\end{pmatrix}^{-1}$$
taking the limit where $\lim_{n \to \infty} \lambda^{n}$ we can reach the limiting distribution.
Doing so we have : $$\pi_{n} = \pi_{0}P^{n}$$.
Observe at last that the initial vector distribution does not play any role at all in the limiting distribution.The steady state is been obtained by taking the limit in the second or in the $n^{th}$ eigenvalue.
In general $$P^{n} = Q\Lambda^{n}Q^{-1}$$ and taking the $\lim_{n \to \infty}$


text:
Q: Sql LIKE in Arabic? Consider this sample:
CREATE TABLE #tempTable
(name nvarchar(MAX))

INSERT INTO #tempTable VALUES (N'إِبْرَاهِيمُ'), (N'إبراهيم')

SELECT * FROM #tempTable WHERE name = N'إبراهيم'
SELECT * FROM #tempTable WHERE name LIKE N'%إبراهيم%'

Both selects only return إبراهيم but not إِبْرَاهِيمُ. How can I make it ignore these non-alphabetical characters in search? In other words, I want to get all similar words, including those with non-alpha characters.

A: You do not do it. Simple. NOTHING about arabic here - you have the same problem in english.

How can I make it ignore these non-alphabetical characters in search?

Like numbers? NOT AT ALL. Not with "standard SQL Syntax".
If you can, put a full text index on the field. And use the full text search syntax in your query. This is what it is for.

A: There is a thread over at sql stackexchange that has a workaround for this issue.
https://dba.stackexchange.com/questions/14153/treating-certain-arabic-characters-as-identical

A: Unfortunately, there is no case sensitive Arabic language, and of course, both select statements will return 'إبراهيم' because they were ordered to do that.
This is a problem we have been suffering from for a very long time, people always look for 'احمد' when it's written 'أحمد' and they won't find it.

A: this is a solution 100%:
$yourChaine = \Transliterator::create('NFC; [:Nonspacing Mark:] Remove; NFC')
                                ->transliterate($yourChaine);


text:
Q: The trackpad on my HP ProBook 4540s notebook suddenly stopped working on Ubuntu 12.04 The trackpad on my HP ProBook 4540s notebook worked perfectly on both Windows and Ubuntu 12.04.
Then suddenly it stopped working on Ubuntu 12.04 but it work perfectly on Windows 7.
How can I enable the trackpad on Ubuntu 12.04?

A: Try updating your drivers, remove the battery, turn the PC off and unplug all external devices.
If nothing of the previous worked for you, call HP, they will replace the TouchPad.

A: See the value of TouchpadOff using:
synclient -l | grep TouchpadOff

If it's set to one, just enter this to enable it back:
synclient TouchpadOff=0


text:
Q: What is the meaning of className variableName; variable declaration in java? I am a beginner in Java. I am unable to understand what className variableName; means.
e.g in given code what does Node Next; mean?
class Node {
    int data;
    Node next;
    Node(int d) {
        data = d;
        next = null;
        }
   }

A: className- here is Node,variableName the name of your variables,like for int->data,for Node->next.
Node next - is a pointer to the next element.

A: Names are necessary for referencing and reusing of classes, instances, etc.
Next is a pointer to another node, this is usually done when you create a data structure respectively a list.
class **Node (class name)** {
    int **data (variable name)**;
    Node **next (variable name)**;
    Node(int d) {
        data = d;
        next = null;
    }
}


text:
Q: pdflatex not found while installing "R" software on Ubuntu 19.04 I am trying to install R software on Ubuntu 19.04, by compiling the installer on my system. Several libraries are missing, but I managed to install them all, apart from one called 'pdflatex'.
    make[1]: Entering directory '/home/giulio/Desktop/r-base_3.6.1.orig/R-3.6.1/src/library'
'pdflatex' is needed to make vignettes but is missing on your system.

I didn't manage to find how to install on the web, could you help me with this issue?
Best
Giulio

A: You need to install the texlive-latex-base package, which provides this utility:
sudo apt-get install texlive-latex-base

And also please note, that R is packaged in Ubuntu as r-base and r-base-dev packages (see search results, you will get R 3.5.2). You do not need to compile R by yourself (usually).
If you need R 3.6 - use binary repository from R-CRAN.


text:
Q: UIView Animation Options Repeat count I'm having some issue with my Swift code, I'm trying to make an UIImageView object fade away and reappear once, but having some issues with having the animation to play only once.
@IBOutlet weak var ball: UIImageView!

@IBAction func onFadeClick(_ sender: Any) {
   UIView.animate(withDuration: 1, delay: 0.0, options: [.repeat, .autoreverse], animations: {
      self.ball.alpha = 0.0
      }, completion: nil)
}

I have attempted to read the documentation and previous questions but all have mentioned to use setAnimationRepeatCount, but xcode has an error stating that it is depreciated in iOS13 (which also does not work). Is there any built in functions I could use to stop the animation after it playing once? I have read somewhere saying using a callback function and reinitialize the animation but I am not exactly sure how to do that. Or is it a better idea to use UIViewPropertyAnimator instead of UIView.animate?
I'm just starting to learn Swift, any help or guidance is appreciated!

A: You can use the following to achieve your goal :
UIView.animateKeyframes(withDuration: 2, delay: 0, options: [], animations: {
    UIView.addKeyframe(withRelativeStartTime: 0, relativeDuration: 0.5) {
         self.ball.alpha = 0.0
    }
    UIView.addKeyframe(withRelativeStartTime: 0.5, relativeDuration: 0.5) {
         self.ball.alpha = 1
    }
}) { (isFinished) in

}

A: Swift 5.x
The current iOS syntax replacement for deprecated approach could be writed like the example below:
UIView.animate(withDuration:1,
               delay: 0.5,
               options: [.curveEaseInOut, .autoreverse, .repeat]) {
     UIView.modifyAnimations(withRepeatCount: 3, autoreverses: true) {
        print("repeated stuff")
     }
} completion: { _ in
     print("done")
}

A: The iOS 13 replacement for the deprecated approach is https://developer.apple.com/documentation/uikit/uiview/3043564-modifyanimations. Example:
UIView.animate(withDuration:1, animations: {
    UIView.modifyAnimations(withRepeatCount: 3, autoreverses: true, animations: {
       // whatever
    })
})

However, the deprecated approach does still work; it is just deprecated.

A: instead of the last }) use:
}, completion: { finished in
    self.alpha = 1
})


text:
Q: not getting conflicts from git rebase as expected I have two branches:

*

*dev: A-B-C

*feature: A-Z
When I checkout feature and do git rebase dev I get:
First, rewinding head to replay your work on top of it...
Fast-forwarded feature to dev
But my feature branch looks like A-Z-B-C instead of A-B-C-Z; dev and feature are the same because they share the same files and they are now in the same state (C) whereas I was expecting to get conflicts.
Can somebody help?


text:
Q: What is the best way of storing string data I am keep hearing that many string containers so i am confused. What are those and which is the best one

*

*string builder

*arraylist

*list<>

I know it may depend how big your string is and how much modification exists but generally which one of them a programmer prefer?

A: The best way to store string data is in a string.
That's why it's there for.
If you want to manipulate a string that's a different story - since strings are immutable, any change you need to make will create a new string, meaning new memory allocation and sometimes extra time.
When concatenating strings, I think I remember the magic number is about 5 or 6 - so anything less than 6 parts is better to concatenate using the string concatenation operator (+), and anything more it's better to use a StringBuilder. Do not use string.Format to concatenate strings, it has a massive overhead and very poor performance compared to the other two options I've mentioned.


text:
Q: Set DateTimeIndex format when using TimeGroupper In the following snippet I want to do the format transformation inplace without having to keep another temporary variable (df)
df = other_df.set_index('datetime_created').groupby(pd.TimeGrouper("M")).aggregate({...complex dict...})
df.index = df.index.format(formatter=lambda x: x.strftime('%b %Y'))
df.plot.bar(sharex=True, stacked=True)

A: I guess you could just format the axis after plotting? One example:
df = pd.DataFrame(np.random.rand(10,2),
                 index=pd.date_range('2005-01-01', freq='M', periods=10))
ax = df.plot(kind='bar', sharex=True, stacked=True)
ax.set_xticklabels([x.strftime('%b %Y') for x in df.index])
plt.show()


text:
Q: Relative URL to a sub-directory in HTML Can we create a relative link in HTML? For example, how can I write a relative URL on this page

http://www.example.com/dir/sub-dir

to this sub page

http://www.example.com/dir/sub-dir/sub-sub-dir

Is this even possible in HTML?

A: You could do:
LINK1

or just
LINK2

http://www.w3.org/TR/WD-html40-970917/htmlweb.html

A: Well.... just write it relative:
Text


text:
Q: How to drop minutes in R? I have a DateTime object in R.
tempDateTime<-as.POSIXct("2017-07-13 01:40:00 MDT")

class(tempDateTime)

[1] "POSIXct" "POSIXt"
I would like to drop the minutes from the DateTime object. ie have "2017-07-13 01:00:00 MDT"
Is there a simple way to do this?

A: In Base R
trunc(tempDateTime, units = "hours")
# "2017-07-13 01:00:00 AEST"

This works because the round function in base R has a method to handle POSIX objects.
From ?round.POSIXt

Round or truncate date-time objects.

As @Thelatemail points out, this returns a POSIXlt object, so you may want to wrap the result in as.POSIXct() again.

Another note, POSIXct is an object that stores the number of seconds since "1970-01-01 00:00:00" (the Unix epoch).
as.numeric(tempDateTime)
# 1499874000

So the manual way to round-down the hours would be
as.POSIXct(floor(as.numeric(tempDateTime) / 3600) * 3600, origin = "1970-01-01")

A: Try this:
library(lubridate)

> floor_date(tempDateTime, "hour")
[1] "2017-07-13 01:00:00 PDT"


text:
Q: Date difference by different intervals I am writing a query to get difference between two dates in three different intervals.
ID , D1           , D2
1  , '2013-01-01' , '2013-01-01'
2  , '2013-01-01' , '2013-02-01'
3  , '2013-01-01' , '2013-03-01'
4  , '2013-01-01' , '2013-07-01'

I want result by three categories : 1st week, one month and then 3 months,6 months, 9 months,etc..
case when round((DATEDIFF(D2,D1))/7,0) < 1 then  '1st week'
when round((DATEDIFF(D2,D1))/7,0) >1 and round((DATEDIFF(D2,D1))/7,0) <5  then  'one month'
when ????

For the rest I am out of thinking.

A: when YEAR(D2)*4+QUARTER(D2)-YEAR(D1)*4-QUARTER(D1)=1 then 'one quarter'

Then you can count quarters 3, 6, 9 monthes = 1, 2, 3 quarters accordingly


text:
Q: Web Server Performance based on CPU I have web server with ubuntu 12.04 64bit. While doing some heavy stress testing with jmeter on application that's at that server, I noticed that I'm starting to reach server capabilities. I'm using amazon aws and I can increase server CPU/RAM. So my question is this, would increasing CPU help with performance? If so, what apache/mysql config parameters should I increase? I thought to increase mysql/apache max connections, but mysqltuner shows me that I'm not fully using all connections (currently mysql is set to 500 max connections).
Some other info about server:

*

*PHP 5.3.1 with APC

*MySQL 5.5.35. 3 MyISAM tables, 1 InnoDB table.

*Apache 2.2 with prefork.

Since I'm using Redis to store most of my data, mysql database is really small, so I don't think increase mysaim/innodb buffers would help. That's why I think tuning Apache parameters should help.
Apache prefork config:
StartServers       100
MinSpareServers    75
MaxSpareServers    100
ServerLimit       500
MaxClients        500
MaxRequestsPerChild  5000

MaxKeepAliveRequests 500

Current amazon server: CPU 8 cores, 16 GB RAM. Available server: 16 Cores, 24 GB RAM.
Any thoughts/advices really appreciated, as it would save me time that I would spend on testing new server.


text:
Q: cordova app to wp8 window.location not working windows phone I have created an app with jquery mobile and html5. I created a wp8 package using cordova for the same and have openend the solution with visual studio. The issue I am facing is that the window.location is not working. I have given
window.location.href='home.html#basic' making it redirect to a particular div. I also tried window.location.replace. Using show and hide dive makes the functionality work but many css issues are coming when i use div show and hide. I have gone through many previous questions but still not found any solution. Please help.

A: Hi all it worked i changed it to  $.mobile.changePage('#basic'); and it worked


text:
Q: Why does text form field re-render when user clicks on it in Flutter? Why does text form field re-render when user clicks on it in Flutter?
My Flutter form contains a TextFormField for Name. When my user clicks on it, the entire form immediately re-renders (reloads), making it impossible for my user to enter anything.
Code
The TextFormField is commented so that you can easily find it.
You'll notice that this page also contains a second field that works perfectly.  It's a Switch inside a StatefulBuilder that handles setting a TextEditingController for  _importantController.
<!-- language: flutter -->
    import 'package:cloud_firestore/cloud_firestore.dart';
    import 'package:dropdown_search/dropdown_search.dart';
    import 'package:flutter/material.dart';

    class CrudPage2 extends StatefulWidget {
      final String docId;
      const CrudPage2({Key? key, required this.docId}) : super(key: key);

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

    class CrudPage2State extends State<CrudPage2> {

      late String name = "";
      late bool isImportant = false;

      final TextEditingController _nameController = TextEditingController();
      final TextEditingController _importantController = TextEditingController();

      Stream<DocumentSnapshot<Object?>> groceryItem(docID) =>
        FirebaseFirestore.instance
          .collection("groceries")
          .doc(docID)
          .snapshots();

      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(
            leading: IconButton(
              icon: const Icon(Icons.arrow_back),
              onPressed: () => Navigator.of(context).pop(),
            ),
            title: Text("Grocery Item"),
          ),
          body: SizedBox(
            width: double.infinity,
            child: Padding(
                padding: EdgeInsets.only(
                    bottom: MediaQuery.of(context).viewInsets.bottom + 20),

                child: StreamBuilder<DocumentSnapshot>(
                    stream: groceryItem(widget.docId),
                    builder: (BuildContext context, AsyncSnapshot<DocumentSnapshot> streamSnapshot) {

                      if (streamSnapshot.connectionState == ConnectionState.waiting) {
                        print("****** Loading ******");  // debugging
                        return const Text("Loading");

                      } else if (streamSnapshot.hasData) {

                        if (widget.docId != "NEW") {
                          // Retrieve existing item
                          var jsonData = streamSnapshot.data?.data();
                          Map<String, dynamic> myData = jsonData as Map<String, dynamic>;
                          name = myData['name'];
                          isImportant = myData['important'];
                        }

                        _nameController.text = name;
                        if (isImportant) {
                          _importantController.text = "true";
                        } else {
                          _importantController.text = "false";
                        }

                        return Column(
                          mainAxisSize: MainAxisSize.min,
                          crossAxisAlignment: CrossAxisAlignment.start,
                          children: [

                            //--------------------------------------------------------
                            // PROBLEM: Clicking on this field re-renders entire form.
                            Flexible(
                              child: TextFormField(
                                controller: _nameController,
                                decoration: const InputDecoration(labelText: 'Name'),
                              ),
                            ),
                            //--------------------------------------------------------

                            // No problem with this switch
                            StatefulBuilder(
                              builder: (BuildContext context, StateSetter importantStateSetter) {
                                return Row(
                                  children: [
                                    const Text("Important: "),
                                    Switch(
                                      value: isImportant,
                                      onChanged: (value) {
                                        importantStateSetter(() => isImportant = value);
                                      },
                                    ),
                                  ],
                                );
                              },
                            ),

                            Row(
                              mainAxisAlignment: MainAxisAlignment.center,
                              children: [
                                SizedBox(
                                  child: ElevatedButton(
                                      child: const Text('Cancel'),
                                      onPressed: () async {
                                        Navigator.of(context).pop();
                                      }),
                                ),
                                const SizedBox(
                                  width: 10,
                                ),
                                SizedBox(
                                  child: ElevatedButton(
                                    child: const Text("Submit"),
                                    onPressed: () async {
                                      final String name = _nameController.text;

                                      if (widget.docId == 'NEW') {
                                        addGroceryItem(name, 1.0, "test",
                                            isImportant);
                                      } else {
                                        updateGroceryItem(widget.docId, name,
                                            1.0, "test", isImportant);
                                      }

                                      // Clear the text fields
                                      _nameController.text = '';
                                      _importantController.text = "";

                                      // Hide the bottom sheet
                                      Navigator.of(context).pop();

                                    },
                                  ),
                                )
                              ],
                            ),
                          ],
                        );
                      } else {
                        return const Text("No Data");
                      }
                    })

            ),
          ),
        );
      } // Widget Build

      //-------------------------------------------------------------
      // Add New Grocery Item
      //-------------------------------------------------------------
      Future<void> addGroceryItem(
          String name, double quantity, String category, bool isImportant) async {
        await FirebaseFirestore.instance.collection('groceries').add({
          "active": true,
          "name": name,
          "quantity": quantity,
          "category": category,
          "important": isImportant
        });
      }

      //-------------------------------------------------------------
      // Update Existing Grocery Item
      //-------------------------------------------------------------
      Future<void> updateGroceryItem(String docID, String name, double quantity,
          String category, bool isImportant) async {
        await FirebaseFirestore.instance.collection('groceries').doc(docID).update({
          "active": true,
          "name": name,
          "quantity": quantity,
          "category": category,
          "important": isImportant
        });
      }

    }

I added print("****** Loading ******"); line to help debug.  When user clicks on text form field, the Console displays:
I/flutter (28767): ****** Loading ******
I/flutter (28767): ****** Loading ******

Why is the stream refreshing every time this widget is clicked?
Thank you for your time!

A: After a lot of Googling, I decided that my problem was coming from doing this entirely wrong.  Here are some of the changes I made:

*

*Pass-in values as JSON object parameter

*Eliminate call to Firebase

*Eliminate Stream Builder

Code below solves my problem using these changes:
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';

class CrudPage2 extends StatefulWidget {
  final String docId;
  final Object? docSnap;
  const CrudPage2({Key? key,
    required this.docId,
    required this.docSnap})
      : super(key: key);

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

class CrudPage2State extends State<CrudPage2> {

  //--- Form State Variables...
  late String name = "";
  late bool isImportant = false;

  //--- Controllers for Form Fields...
  final TextEditingController _nameController = TextEditingController();
  final TextEditingController _importantController = TextEditingController();

  @override
  initState() {
    super.initState();

    if (widget.docId != "NEW") {
      Map<String, dynamic> myData = widget.docSnap as Map<String, dynamic>;
      name = myData['name'];
      isImportant = myData['important'];
    }

    _nameController.text = name;

    if (isImportant) {
      _importantController.text = "true";
    } else {
      _importantController.text = "false";
    }

  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        leading: IconButton(
          icon: const Icon(Icons.arrow_back),
          onPressed: () => Navigator.of(context).pop(),
        ),
        title: Text("Grocery Item"),
      ),
      body: SizedBox(
        width: double.infinity,
        child: Padding(
            padding: EdgeInsets.only(
                top: 20,
                left: 20,
                right: 20,
                bottom: MediaQuery.of(context).viewInsets.bottom + 20),
            child: Column(
                mainAxisSize: MainAxisSize.min,
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [

                  TextFormField(
                    controller: _nameController,
                    decoration: const InputDecoration(labelText: 'Name'),
                  ),

                  StatefulBuilder(
                    builder:
                        (BuildContext context, StateSetter importantStateSetter) {
                      return Row(
                        children: [
                          const Text("Important: "),
                          Switch(
                            value: isImportant,
                            onChanged: (value) {
                              importantStateSetter(() => isImportant = value);
                            },
                          ),
                        ],
                      );
                    },
                  ),

                  Row(
                    mainAxisAlignment: MainAxisAlignment.center,
                    children: [

                      SizedBox(
                        width: 110,
                        child: ElevatedButton(
                            style: ButtonStyle(
                                backgroundColor:
                                MaterialStateProperty.all(
                                    Colors.grey),
                                padding: MaterialStateProperty.all(
                                    const EdgeInsets.all(5)),
                                textStyle: MaterialStateProperty.all(
                                    const TextStyle(fontSize: 24))),
                            child: const Text('Cancel'),
                            onPressed: () async {
                              Navigator.of(context).pop();
                            }),
                      ),

                      SizedBox(
                        width: 200,
                        child: ElevatedButton(
                          style: ButtonStyle(
                              backgroundColor:
                              MaterialStateProperty.all(Colors.green),
                              padding: MaterialStateProperty.all(
                                  const EdgeInsets.all(5)),
                              textStyle: MaterialStateProperty.all(
                                  const TextStyle(fontSize: 24))),
                          child: const Text("Submit"),
                          onPressed: () async {
                            final String name = _nameController.text;

                            if (widget.docId == 'NEW') {
                              addGroceryItem(name, 1.0, "Test",
                                  isImportant);
                            } else {
                              updateGroceryItem(widget.docId, name,
                                  1.0, "Test", isImportant);
                            }

                            // Clear the text fields
                            _nameController.text = '';
                            _importantController.text = "";

                            // Hide the bottom sheet
                            Navigator.of(context).pop();

                          },
                        ),
                      )
                    ],
                  ),

              ]
            )
          )
        ),

    );

  } // Widget Build

  Future<void> addGroceryItem(
      String name, double quantity, String category, bool isImportant) async {
    await FirebaseFirestore.instance.collection('groceries').add({
      "active": true,
      "name": name,
      "quantity": quantity,
      "category": category,
      "important": isImportant
    });
  }

  Future<void> updateGroceryItem(String docID, String name, double quantity,
      String category, bool isImportant) async {
    await FirebaseFirestore.instance.collection('groceries').doc(docID).update({
      "active": true,
      "name": name,
      "quantity": quantity,
      "category": category,
      "important": isImportant
    });
  }

}

Any comments and/or suggestions are still appreciated.
I hope this helps someone else in the future.


text:
Q: Help with CreateDate and Test.isRunningTest i had a post but accidentally deleted my account -hits Head-
the original post contained my question of how do i test createdDate.hour() if i cannot modify the createddate even to test an account creation.
someone led me down a different path, to test using the Test.isRunningTest() method in the trigger to allow the test to enter the main if statement without challenging the created date. but we were unfinished in resolving the problem.
private void sendAlertsPrivate(List<JungoLeadsFrc__JungoLeads__c> lstNewLead, Boolean passTestDate)
{
    List<JungoLeadsFrc__JungoLeads__c> lstLeadToUpdate = new List<JungoLeadsFrc__JungoLeads__c>();
    List<Contact> lstTempContact = new List<Contact>();
    List<Task> lstTaskToInsert = new List<Task>();
    List<Messaging.SingleEmailMessage> lstMail = new List<Messaging.SingleEmailMessage>();
    User addUser = [SELECT Alias,Email,Id FROM User WHERE Name = 'Jason Frangoulis' LIMIT 1];
    for(JungoLeadsFrc__JungoLeads__c objLead: lstNewLead)
    {
        Integer objCreatedDate = objLead.CreatedDate.hour();
        if(passTestDate)
        {
            if(objLead.JungoLeadsFrc__Zillow_Recipient_Email__c != NULL)
            {
                objCreatedDate = 10;
            }
            else
            {
                objCreatedDate = 20;
            }
        }

        if(objLead.JungoLeadsFrc__Zillow_Recipient_Email__c != null)
        {
            lstLeadToUpdate.add(new JungoLeadsFrc__JungoLeads__c(
            Id = objLead.Id,
            OwnerId = addUser.Id,
            JungoLeadsFrc__LeadSource__c = 'Zillow',
            JungoLeadsFrc__Stage__c = 'New'));
        }
        else
        {
            lstLeadToUpdate.add(new JungoLeadsFrc__JungoLeads__c(
            Id = objLead.Id,
            OwnerId = addUser.Id,
            JungoLeadsFrc__LeadSource__c = 'Personal',
            JungoLeadsFrc__Stage__c = 'New'));
        }

        if(objCreatedDate >= 18 || objCreatedDate <= 8 || passTestDate)
        {

            //Task: After Hours ALERT

            //Email
            if(objLead.JungoLeadsFrc__EmailAddress__c != null)
            {
                //email html

            }

            else
            {
               //Email if No Email Address to SF ADMINS

            }
        }

        else
        {

            //Task "Call New Lead"

            // Task "NEW LEAD RECIEVED"

            if(objLead.JungoLeadsFrc__EmailAddress__c != null)
            {

                //Email if recieved 9-5pm
            }

            else
            {
               //Email if NO Email Address
            }
    }

    //send email
    if(!lstMail.isEmpty())
    {
        Messaging.sendEmail(lstMail);
    }

    //Insert Tasks
    if(!lstTaskToInsert.isEmpty())
    {
        insert lstTaskToInsert;
    }

    //update Record
    if(!lstLeadToUpdate.isEmpty())
    {
        update lstLeadToUpdate;
    }

}

and the Trigger:
trigger JungoLeadTrigger on JungoLeadsFrc__JungoLeads__c(after insert){
JungoLeadFollowup objHandler = new JungoLeadFollowup();
if(Trigger.isAfter && Trigger.isInsert){

    if(Test.isRunningTest()) {
        objHandler.leadAlerts(Trigger.New, true);
    }
    else {
        objHandler.leadAlerts(Trigger.New, false);
    }

}

i get about 48% code coverage now. creating records with all 4 combinations of having and not null emailAddress and zillow_recipient_email__c being null and not null. so im in need of help.
Test.setCreatedDate:
    @isTest static void sixToNine()
{

    JungoLeadsFrc__JungoLeads__c sixToNine = new JungoLeadsFrc__JungoLeads__c(
    JungoLeadsFrc__EmailAddress__c = 'jdoe@example.com');
    insert sixToNine;
    Test.setCreatedDate(sixToNine.Id, DateTime.newInstance(2016, 8, 21, 19, 0, 0));
    Test.startTest();
    JungoLeadsFrc__JungoLeads__c jungo = [SELECT Id, CreatedDate FROM JungoLeadsFrc__JungoLeads__c WHERE JungoLeadsFrc__EmailAddress__c = 'jdoe@example.com'];
    System.assertEquals(sixToNine.CreatedDate, DateTime.newInstance(2016, 8, 21, 19, 0, 0));
    Test.stopTest();
}

Test.setCreatedDate does not execute anything in the primary if statement.
this is the original 6pm to 8.59am code block.
if(objLead.CreatedDate.hour() >= 18 || objLead.CreatedDate.hour() <= 8)

A: I agree with Adrian in the comments that:

Honestly, you should basically never use Test.isRunningTest

However I do have some good news...

the original post contained my question of how do i test createdDate.hour() if i cannot modify the createddate even to test an account creation.

Actually, if you're using Test Classes, you can change the CreatedDate.
@isTest
private class SetCreatedDateTest {
    static testMethod void testSetCreatedDate() {
        Account a = new Account(name='myAccount');
        insert a;
        Test.setCreatedDate(a.Id, DateTime.newInstance(2012,12,12));
        Test.startTest();
        Account myAccount = [SELECT Id, Name, CreatedDate FROM Account
                             WHERE Name ='myAccount' limit 1];
        System.assertEquals(myAccount.CreatedDate, DateTime.newInstance(2012,12,12));
        Test.stopTest();
    }
}

Take a look at the Spring '16 Release Docs here.
Long story short, if you orginal question asked how to change the CreatedDate in unit tests, do it this way. Otherwise I'd suggest not going down said different path. This will allow the test to enter the main if statement with changing the created date

A: This wasnt a very popular thread, and trouble shooting of Test.setCreatedDate() did not get very far. errors in comments.
Since there are conditions for both with and without having an Zillow email and as well as having an email address. the If cannot check against weather there is an email address.
Integer objCreatedDate = objLead.CreatedDate.hour();
  if(passTestDate)
    {
      if(objLead.JungoLeadsFrc__Zillow_Recipient_Email__c != NULL)
      {
          objCreatedDate = 10;
      }
      else
      {
          objCreatedDate = 20;
      }
    }

change Email field not being null to First Name not being null.
Integer objCreatedDate = objLead.CreatedDate.hour();

if(passTestDate)
    {
        if(objLead.JungoLeadsFrc__FirstName__c  != null)
            {
                objCreatedDate = 20;
            }
            else
            {
                objCreatedDate= 10;
            }
    }

this will penetrate the first if statement by setting objCreatedDate to 20 if there is a first name.
Test Method:
Method 1:

*

*New Lead

*FisrtName

*EmailAddress

Method 2:

*

*New Lead

*FisrtName

*Zillow Recipient EmailAddress

Method 3:

*

*New Lead

*No Name

*Zillow Recipient EmailAddress

Method 4:

*

*New Lead

*No FisrtName

*EmailAddress

Resulting in:
@isTest
private class jungoLeadFollowupTest
{
    @isTest static void one()
    {
        JungoLeadsFrc__JungoLeads__c one = new JungoLeadsFrc__JungoLeads__c(
        JungoLeadsFrc__FirstName__c = 'bryan',
        JungoLeadsFrc__EmailAddress__c = 'c@c.com' );
        insert one;
    }

    @isTest static void two()
    {
        JungoLeadsFrc__JungoLeads__c two = new JungoLeadsFrc__JungoLeads__c(
        JungoLeadsFrc__FirstName__c = 'bryan',
        JungoLeadsFrc__Zillow_Recipient_Email__c = 'c@c.com');
        insert two;
    }

    @isTest static void three()
    {
        JungoLeadsFrc__JungoLeads__c three = new JungoLeadsFrc__JungoLeads__c(
        JungoLeadsFrc__Zillow_Recipient_Email__c = 'c@c.com');
        insert three;
    }

    @isTest static void four()
    {
        JungoLeadsFrc__JungoLeads__c four = new JungoLeadsFrc__JungoLeads__c(
        JungoLeadsFrc__EmailAddress__c = 'c@c.com' );
        insert four;
    }
}

100% code coverage!
thank you all for the help!


text:
Q: How to restore cassandra snapshot on a new single node cassandra I have done a snapshot of one of the key space which has 10 column family. There are 10 snapshot folder under each of column family folder.i want to restore these snapshot in one the development server (single node).
How can i easily restore it on a development using sstanbleloader
Dev node is on a Windows 2012 Standard Server
Prod is on a Windows 2012 Ent.Edition Server

A: You probably don't need to use sstableloader in this case. I think the most straightforward method would be the "Node restart method" described here.
There are plenty of details in the docs, but basically: stop the node, remove data files from data directories, and replace with snapshot files.


text:
Q: Abstract definition of inner product: Where does the conjugate symmetry requirement come from and what conjugate property? In various texts and articles I've read which take aim to define properties in their most abstract and general terms, without reference to any particular sets or fields, the inner product is defined on a vector space with three conditions: left-linearity, positive definiteness, and conjugate symmetry.
When I in turn seek to define the property of conjugacy in the same abstract sense, these same sources tell me that it isn't a rigorously defined property in mathematics, and that it depends on a context and special applications, wherein conjugacy is defined. Often times in reference to inner products, conjugates are defined in the very familiar complex number space most of us would think of... the conjugate self-symmetric reals or the complex numbers are used in practice, but we need not define a conjugate in this typical way, nor are we required to define conjugates on real or complex numbers at all but on general elements of some other space. Im fine with this, I suppose.
But I come back to the definition of inner product, and am left wondering what kind of conjugate is being referred to. Does it matter?  Do the authors of these articles have it in their head on some level they're talking about complex numbers? Maybe any definition of conjugacy can be used and it really doesnt matter. But why is the condition in the definition at all?

What is so special about an otherwise undefinable operation (i.e. conjugacy) that makes it a required condition for another definable operation (i.e. inner product)?


text:
Q: QT: Remove space between QLabel in QGridLayout I Added some QLabels with different colors to A QGridLayout as Layout of a QWidget,
now I have a spacing between each Qlabel to the next and I want to remove it. I tried to set the margin of the Labels to "0" and the Alignment of the GridLayout to "0" but it didnt worked very good. i thought the space is maybe the border of the Labels but i checked.
do you have any idea?

A: Didnt belive i missed this :O thank yout Mat
the solutions was:
layout->setHorizontalSpacing(0);
layout->setVerticalSpacing(0);

thanks

A: You can try setting the spacing:

layout->setSpacing(0);

If that doesn't do it, you can also try setting the contents margins to zero:

layout->setContentsMargins(0,0,0,0);


text:
Q: requirejs optimize html and remove from dist I have a requirejs configuration that uses !text plugin.
When I run optimize, it works pefectly, but requirejs also copies all html files.
If I try to use
fileExclusionRegExp: /.*\.html/

then text plugin raise error
text!views/main.html: Error: ENOENT, no such file or directory ...

Are there some way to no copy html files to destination dir without raise text plugin error?
This is my config:
baseUrl: 'js',
appDir: 'src',
dir: 'dist',
mainConfigFile: 'src/main.js',
keepBuildDir: false,
optimize: "uglify2",
generateSourceMaps: true,
removeCombined: true,
preserveLicenseComments: false,
fileExclusionRegExp: /.*\.less|.*\.html/,
paths: {
  'main': '../main',
},
modules: [
  {
    name: "main",
    include: ['requirejs']
  }
],
optimizeAllPluginResources: true


text:
Q: Having trouble creating a DTO class for the following JSON I am trying to create Dto class in Java for a json which is similar to this.
    {
    "abcList":[
        {
            "keyA":"valA",
            "lstB":[{
                "keyC":"valC"
            },{
                "keyC":"valC1"
            }]
        },{
            "keyA":"valA",
            "lstB":{
                "keyC":"valC2"
            }
        }
    ]
}

Is the Json even valid? Inside the list abcList, the first object has a list "lstB" and in the second object, the field "lstB" is not a list.
If the json is valid, how would I create the corresponding Java Classes?
This does not work.
class TopObject{
        List<ABC> abcList;

    }
    class ABC{
        public String keyA;
        public List<B> lstB;
    }
    class B{
        public String keyC;
    }

I mean I can parse it successfully with gson, iterating through every element of the json with a code like below,
if(lstB.isJsonArray()){
                System.out.println("lstb is array");
                List<B> arLstB = parseBArray(lstB);
                abc.setLstB(arLstB);
            }else{
                System.out.println("lstb is not array");
                B b = parseB(lstB);
                abc.addB(b);
            }

but the original json is very large and i will end up writing the iterating logic for days. I want a solution where I can annotate it properly and do the mapping in one shot like this.
gson.fromJson(jsonInString, TopObject.class);


text:
Q: [HELP]Ubuntu Installation process? I wanted to install Ubuntu 15.10 64 bit.
I have windows 32 bit installed and i want to install Ubuntu alongside windows(I don't want my data to be deleted).
I have 4 drives C: , D: , E: , :F and i want to install on e drive only. I have 250 GB space in E drive of which i want only 100 GB .
Can anyone give me detailed steps according to my criteria?
Regards!

A: Boot into your live CD , select "Try Ubuntu". Search GParted Partition Editor in dash board, And free 100GB of space from your E drive. Then apply the changes.
Now click on install Ubuntu (which should be on your Desktop) and follow the Instructions given in the following link.
How to use manual partitioning during installation?
I think there is complete details in the given link for you to install Ubuntu alongside windows.
Happy Installing.


text:
Q: Why do I get an import error for zmq but only from command line? Well the subject says it all. I can run the same file in pycharm without problems.
Putting import zmq in a file reproduces it. Never had a problem with zmq before running the program from command line.

A: The reported problem probably means that you do not use the same python interpreter in terminal and pycharm.
If you call python and have the import error, you can install pyzmq for your python interpreter with command.
python -m pip install pyzmq

A: i have actually solved it by using the -m option: >python -m, I would like to know  why that worked.


text:
Q: how to add "manually created" resources to the cloudformation template I initially created all my resources in AWS manually. Now I'm trying to use CloudFormation (SAM) templates to create all my new resources. Is there any way I can all my old (manually created) resource to this CF template and hence forth use this CF to make modification to those old resources?

A: You can import existing resources in your new stack !
https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/resource-import-existing-stack.html

A: Not possible to add existing resources to a cloudformation template and have them managed from there on in with Cloudformation - but you can have a look at using CloudFormer (https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/cfn-using-cloudformer.html) to create a cloudformation template for you from existing resources.
It won't manage the existing resources, but it will create a template so that you can launch the same resources again.

A: This is now possible with an update from AWS, see here for more details
https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/resource-import.html

A: This is unfortunately not possible.
To manage resources with CloudFormation, they have to be created first by CloudFormation.
You will need to find some sort of "migration path" from your existing resources to the ones created by CloudFormation.

A: It is not possible to add existing resources to CloudFormation template directly, but you can deploy a CloudFormer stack to create a template from existing resources.
https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/cfn-using-cloudformer.html
After successful creation of that template, you can use the cross-stack reference in which you can define parameters to import/export values of existing resources.
https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/intrinsic-function-reference-importvalue.html
Also, for more details of how to define parameters and import/export values, you can go through the below link:
https://aws.amazon.com/premiumsupport/knowledge-center/cloudformation-reference-resource/
Note: After deployment of the template created by CloudFormer, you can vanish your existing resources as it newly deployed through the stack.
Hope this helps!


text:
Q: How do i draw a ball when a button is pressed? in my game i have the following code
private void Form1_Paint(object sender, PaintEventArgs e)
    {
        paper = e.Graphics;
        paddle.drawPaddle(paper);
        ball.drawBall(paper);
        bricks.drawBricks(paper);
    }

What i want is so that when i click a button the ball is drawn, but only when i click the button, so i want to place the drawball in this part of the code
private void button1_Click(object sender, EventArgs e)
    {

    }

how do i do this because as far as im aware you only draw the ball under "form paint"

A: Add a special flag for storing your ball's visibility:
private bool _isVisible = false;

private void Form1_Paint(object sender, PaintEventArgs e)
{
    paper = e.Graphics;
    paddle.drawPaddle(paper);
    if (_isVisible)
    {
         ball.drawBall(paper);
    }
    bricks.drawBricks(paper);
}

private void button1_Click(object sender, EventArgs e)
{
    _isVisible = true;
    // Now you need to invalidate the form to get it repainted
    Refresh();
}


text:
Q: c - passing a pointer to a function with a parameter of void* variable I want to pass a pointer to a variable. Sometimes it would be an integer and sometimes maybe a character. In the example below i pass the pointer p to CreateObject but when i try to retrieve the value of the variable the pointer points to i get an awkward result:
int i =0;
int *p = malloc(sizeof(int));
*p = i;

ObjectP object = CreateObject(p);

Say i want to cast it back to an int and display it:
void CreateObject(void *key)
{
   printf("%d\n", (int)key);
}

I get: 160637064 instead of 0. What am i getting instead of the integer i assigned previously and how do i retrieve it instead of the current value?

A: This:
(int) key

is not dereferencing the pointer to access the data it points at, it's re-interpreting the pointer value (the address) itself as the integer.
You need:
printf("%d\n", *(int *) key);

A: You're typecasting a pointer to an integer. This means that you simply get the address. After all, a pointer is just an address.
You probably want to dereference the pointer instead of casting it. *(int*)key would do that.

A: You're printing the pointer, ie. the address, not the value that it's pointing to.
Use this to print the value:
void CreateObject(void *key)
{
   printf("%d\n", *(int*)key);
}


text:
Q: React + Chai + Enzyme I'm trying to run some unit test with Chai&Enzyme to my React app.
Enzyme seems to have an issue with props I passed to components. They got undefined in tests (not in app).
main file:
import React, { Component } from 'react';
import ReactDOM from 'react-dom';

import TaskList from './components/task_list';
import AddingInput from './components/input';

const titleHeader =
Simple to-do list:
;

class App extends Component {
    constructor(props) {
        super(props);

        this.state = {
            tasks: [
                {id: 0, name: 'Complete task'},
                {id: 1, name: 'Add task'},
                {id: 2, name: 'Delete task'}
            ],
            id: 3,
        };
    }

(...)

  render () {
    return (

        {titleHeader}
        <TaskList
            tasks={this.state.tasks}
            deleteMe={this.deleteMe.bind(this)} />
        <AddingInput addTodo={this.addTodo.bind(this)} />

    );
  }
}

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

Task_list - first component I want to test:
import React from 'react';
import TaskItem from './task_item';

const TaskList = (props) => {
    const taskItems = props.tasks.map((task) => {
        return (
            <TaskItem
                key={task.id}
                task={task}
                deleteMe={props.deleteMe}
                />
        );
    });

    return (

            {taskItems}

    );
};

export default TaskList;

And the second:
import React from 'react';

const TaskItem = React.createClass({
  onCompleted: function(e) {
    e.target.className += " ordered-list__item--completed"
  },
  render: function() {

    return (

{this.props.task.name}
             this.props.deleteMe(this.props.task)}
                  className='btn btn--delete'>Delete

    );
  }
});

export default TaskItem;

An here are my tests. Two of them are passed (both component exist) but in other two got undefined on props.tasks:
import React from 'react';
import { expect, assert } from 'chai';
import { shallow, mount } from 'enzyme';
import TaskList from './src/components/task_list';
import TaskItem from './src/components/task_item';

describe('TaskList', () => {
    it('should render TaskItem', () => {
        const wrapper = shallow(<TaskList />);
        expect(wrapper.containsAllMatchingElements([
            <TaskItem />,
        ])).to.equal(true);
    });
    it('should exists', () => {
        assert.isDefined(TaskList)
    })
});
describe('TaskItem', () => {
    it('should render one item of unordered list', () => {
        const item = mount(<TaskItem />);
        expect(item).to.contain('li');
    });
    it('should exists', () => {
        assert.isDefined(TaskList)
    })
});

Problems:
 1) TaskList should render TaskItem:
     TypeError: Cannot read property 'map' of undefined
 2) TaskItem should render one item of unordered list:
     TypeError: Cannot read property 'name' of undefined

A: Your App component passes a tasks prop:
<TaskList
    tasks={this.state.tasks}
    deleteMe={this.deleteMe.bind(this)} />

And TaskList expects it to be always present.  Similarly, TaskItem expects to always have certain props available (from TaskList).
If you add the necessary props in your unit tests, it should work.  For TaskList, this might look something like the following (untested):
const tasks = [
    {id: 0, name: 'Complete task'},
    {id: 1, name: 'Add task'},
    {id: 2, name: 'Delete task'}
];
const wrapper = shallow(<TaskList tasks={tasks}/>);


text:
Q: Apple's Server-Side Swift Framework Does Apple have its own Swift (or, at least, Objective-C) server-side framework with similar capabilities like Vapor or Kitura have?
I'm not interested in using third-party frameworks or Cocoapods.
Any help appreciated.

A: Vapor and Kitura are both build on Apples Swift-NIO.
So you could technicaly go with that as well but you would have to build alot of functionality by yourself that frameworks like vapor and kitura bring, to make you life easier.