text:
Q: Showing the MCBrowserViewController in swift 4 So, I've been trying to get the MCBrowserViewController to appear, but I've had no luck. I'm trying to create this in an appp I'm developing for iOS. Can anyone help? Here is my code:
import UIKit
import PlaygroundSupport
import MultipeerConnectivity

var peerID: MCPeerID!
var mcSession: MCSession!
var mcAdvertiserAssistant: MCAdvertiserAssistant!
var foundPeers = [MCPeerID]()

PlaygroundPage.current.needsIndefiniteExecution = true

class viewcontroller: UIViewController {
override func viewDidLoad() {
var serviceBrowser : MCBrowserViewController!
func startBrowsingForPeer()  {
    serviceBrowser = MCBrowserViewController(serviceType: "hws-ridleyn", session: mcSession)

    serviceBrowser.delegate.self

}

peerID = MCPeerID(displayName: UIDevice.current.name)
mcSession = MCSession(peer: peerID, securityIdentity: nil, encryptionPreference: .none)
mcSession.delegate.self

class ViewController: UIViewController, MCSessionDelegate, MCBrowserViewControllerDelegate {

let session = MCSession(peer: peerID,
                        securityIdentity: nil,
                        encryptionPreference: .none)

func session(_ session: MCSession, peer peerID: MCPeerID, didChange state: MCSessionState) {
    switch state {
    case MCSessionState.connected:
        print("Connected: \(peerID.displayName)")
    case MCSessionState.connecting:
        print("Connecting: \(peerID.displayName)")
    case MCSessionState.notConnected:
        print("Not Connected: \(peerID.displayName)")
    }
}

func browser(browser: MCNearbyServiceBrowser!, foundPeer peerID: MCPeerID!, withDiscoveryInfo info: [NSObject : AnyObject]!) {
    foundPeers.append(peerID)

    print(browser)
    browser.startBrowsingForPeers()

}

func session(_ session: MCSession, didReceive data: Data, fromPeer peerID: MCPeerID) {
    if let image = UIImage(data: data) {
        DispatchQueue.main.async { [unowned self] in
            print("image recieved")
        }
    }
}
func sendImage(img: UIImage) {
    if mcSession.connectedPeers.count > 0 {
        if let imageData = UIImagePNGRepresentation(img) {
            do {
                try mcSession.send(imageData, toPeers: mcSession.connectedPeers, with: .reliable)
            } catch let error as NSError {
                let ac = UIAlertController(title: "Send error", message: error.localizedDescription, preferredStyle: .alert)
                ac.addAction(UIAlertAction(title: "OK", style: .default))
                present(ac, animated: true)
            }
        }
    }
}

func session(_ session: MCSession, didReceive stream: InputStream, withName streamName: String, fromPeer peerID: MCPeerID) {
}
func session(_ session: MCSession, didStartReceivingResourceWithName resourceName: String, fromPeer peerID: MCPeerID, with progress: Progress) {
}
    func session(_ session: MCSession, didFinishReceivingResourceWithName resourceName: String, fromPeer peerID: MCPeerID, at localURL: URL?, withError error: Error?) {
    }
func browserViewControllerDidFinish(_ browserViewController: MCBrowserViewController) {
            dismiss(animated: true)
        }
func browserViewControllerWasCancelled(_ browserViewController: MCBrowserViewController) {
    dismiss(animated: true)
}

func startHosting(action: UIAlertAction!) {
    mcAdvertiserAssistant = MCAdvertiserAssistant(serviceType: "hws-ridleyn", discoveryInfo: nil, session: mcSession)
    mcAdvertiserAssistant.start()
}
func joinSession(action: UIAlertAction!) {
    let mcBrowser = MCBrowserViewController(serviceType: "hws-ridleyn", session: mcSession)
    mcBrowser.delegate = self
    present(mcBrowser, animated: true)
}

let vc = UIToolbar(frame: CGRect(x: 100, y: 100, width: 200, height: 200))

// your view controller here
}

let vcc = ViewController()
vcc.startHosting(action: nil)
ViewController.startHosting(vcc)

   }
}
extension viewcontroller : MCBrowserViewControllerDelegate {
func browserViewControllerDidFinish(_ browserViewController: MCBrowserViewController) {
    dismiss(animated: true, completion: nil)
}

func browserViewControllerWasCancelled(_ browserViewController: MCBrowserViewController) {
    dismiss(animated: true, completion: nil)

   }

}

PlaygroundPage.current

If you're wondering, I've done lots of research, but I'm not really understanding this, I've also looked at apple's documentation, but that doesn't give me a suitable example. I asked a question like this before but I didn't get an answer that i could use for reference. So if you can, can you post your answer but with my current code attached to it, please?

A: Your playground code is a little bit of a mess, but here's a clearer example of how to set up classes of this type:
import UIKit
import MultipeerConnectivity

class MPCPeripheralViewController: UIViewController {

    private let peerID = MCPeerID(displayName: UIDevice.current.name)
    private var mcBrowser: MCBrowserViewController?
    private var mcSession: MCSession!
    private var outputStream: OutputStream?

    // MARK: Class methods
    override func viewDidLoad() {
        super.viewDidLoad()

        // Create a session - Using the arguments you require
        mcSession = MCSession(peer: peerID, securityIdentity: nil, encryptionPreference: .required)
        mcSession.delegate = self
    }

    // Hook this up to a button - use it to show the browser
    @IBAction func connectButtonPressed(_ sender: UIBarButtonItem) {
        // The MCBrowserView is nicely set up for us in situation - so we don't need any custom views
        mcBrowser = MCBrowserViewController(serviceType: "StackOverflow", session: mcSession)

        guard let mcBrowser = mcBrowser else {
            print("Couldn't create mcBrowser!")
            return
        }

        mcBrowser.delegate = self
        present(mcBrowser, animated: true)
    }

    func joinSession() {
        guard mcSession.connectedPeers.count > 0 else {
            print("No connected peers")
            return
        }

        outputStream = try? mcSession.startStream(withName: "control", toPeer: mcSession.connectedPeers.first!)

        guard let outputStream = outputStream else {
            print("Output stream is nil")
            return
        }

        outputStream.delegate = self
        outputStream.schedule(in: RunLoop.main, forMode:RunLoopMode.commonModes)
        outputStream.open()

        // From now on you can write to the stream!
    }
}

// MARK: MCBrowserViewControllerDelegate
extension MPCPeripheralViewController: MCBrowserViewControllerDelegate {

    func browserViewControllerDidFinish(_ browserViewController: MCBrowserViewController) {
        dismiss(animated: true)
        joinSession()
    }

    func browserViewControllerWasCancelled(_ browserViewController: MCBrowserViewController) {
        dismiss(animated: true)
    }
}

extension MPCPeripheralViewController: MCSessionDelegate {
    func session(_ session: MCSession, peer peerID: MCPeerID, didChange state: MCSessionState) {
        switch state {
        case .connected:
            print("Connected: \(peerID.displayName)")
        case .connecting:
            print("Connecting: \(peerID.displayName)")
        case .notConnected:
            print("Not Connected: \(peerID.displayName)")
        }
    }

    // You probably aren't going to receive data on a peripheral connection!
    func session(_ session: MCSession, didReceive data: Data, fromPeer peerID: MCPeerID) {}

    func session(_ session: MCSession, didReceive stream: InputStream, withName streamName: String, fromPeer peerID: MCPeerID) {}

    func session(_ session: MCSession, didStartReceivingResourceWithName resourceName: String, fromPeer peerID: MCPeerID, with progress: Progress) {}

    func session(_ session: MCSession, didFinishReceivingResourceWithName resourceName: String, fromPeer peerID: MCPeerID, at localURL: URL?, withError error: Error?) {}
}

extension MPCPeripheralViewController: StreamDelegate {
}

// The Central device!

import UIKit
import MultipeerConnectivity

class MPCCentralViewController: UIViewController {

    // MARK: Properties
    var mcAdvertiserAssistant: MCAdvertiserAssistant!
    var peerID: MCPeerID = MCPeerID(displayName: UIDevice.current.name)
    var mcSession: MCSession!
    var stream: InputStream?

    override func viewDidLoad() {
        super.viewDidLoad()

        mcSession = MCSession(peer: peerID, securityIdentity: nil, encryptionPreference: .required)
        mcSession.delegate = self
    }

    // Hook this up!
    @IBAction func findDeviceButtonPressed(_ sender: Any) {
        startHosting()
    }

    func startHosting() {
        mcAdvertiserAssistant = MCAdvertiserAssistant(serviceType: "StackOverflow", discoveryInfo: nil, session: mcSession)
        mcAdvertiserAssistant.delegate = self
        mcAdvertiserAssistant.start()
    }
}

// MARK: MCSessionDelegate
extension MPCCentralViewController: MCSessionDelegate {
    func session(_ session: MCSession, peer peerID: MCPeerID, didChange state: MCSessionState) {
        // Utility debug method - check how our session is doing
        switch state {
        case .connected:
            print("Connected: \(peerID.displayName)")
        case .connecting:
            print("Connecting: \(peerID.displayName)")
        case .notConnected:
            print("Not Connected: \(peerID.displayName)")
        }
    }

    func session(_ session: MCSession, didReceive data: Data, fromPeer peerID: MCPeerID) {
        print("Received some data")
    }

    func session(_ session: MCSession, didReceive stream: InputStream, withName streamName: String, fromPeer peerID: MCPeerID) {
        // Stop advertising once we're receiving a stream
        mcAdvertiserAssistant.stop()

        print("Received stream!")
        stream.delegate = self
        stream.schedule(in: RunLoop.main, forMode:RunLoopMode.commonModes)
        stream.open()
    }

    func session(_ session: MCSession, didStartReceivingResourceWithName resourceName: String, fromPeer peerID: MCPeerID, with progress: Progress) {}

    func session(_ session: MCSession, didFinishReceivingResourceWithName resourceName: String, fromPeer peerID: MCPeerID, at localURL: URL?, withError error: Error?) {}
}

// MARK: MCAdvertiserAssistantDelegate
extension MPCCentralViewController: MCAdvertiserAssistantDelegate {}

// MARK: StreamDelegate
extension MPCCentralViewController: StreamDelegate {

    func stream(_ aStream: Stream, handle eventCode: Stream.Event) {
        // Deal with your snazzy new stream here!
    }
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Choosing the clock for STM32 I'm building a custom board using a STM32F303K8T6. This custom board will be connected to 4 other custom boards via CAN bus protocol. The task of the following board is to drive high switches if there is an incoming CAN bus command.
In addition to this I will mount a temperature sensor (perhaps I2C I still have to evaluate) and the value will always be transmitted via CAN bus.
The high switch activation data and the current read by these travel via the CAN bus.
I'm starting to create the schematic but I have a couple of doubts about using or not the external clock. In your opinion, for what I have to do, can I use the internal clock of the STM32 (on the datasheet it says that it is 1% accurate at about 25 degrees)?
Furthermore, the typical value written on the datasheet is 8 MHz but the Nucleo board mounts a 32 MHz one.
I specify that I come from the Arduino / ESP world and I decided to take the path towards STM32. I've never understood how to choose the clock. How do I go about that?

A: No you can't use the STM32F onboard clock to do this in any reliable way. The base tolerance is already +/-1%, which means that across two nodes you could have more than 2% relative error straight out of the box. This will cause problems with CAN communications. Further, the temperature stability is poor and this can push the relative error out by at least another 1%.
For reliable CAN communications your best bet is to just use a ceramic resonator. These are dirt cheap, low power and simple to use. Something with a +/-0.5% tolerance will be adequate as the CAN specification allows for up to 1.58% of relative timing error between nodes, but check the situation at whatever temperature extremes you want to operate at as well.
Also note that the limit on CAN timing tolerance is to allow a node to distinguish between a local and bus-wide error condition. But this only comes into play when an error occurs, so the bus will happily receive messages at higher timing error levels. But you'll now have created a 'hidden' problem on the bus that might result in random weird node drop outs that take ages to debug. This is why it's best to just be very conservative with CAN implementations - they are very fault tolerant, but don't allow this to lull you into a sloppy implementation.
Also note that the new STM32G devices have a more accurate clock that is theoretically able to meet the CAN requirements across a limited temperature range (roughly commercial grade if I recall correctly). These could work but you'd be putting a lot of faith in ST's quality control. I'd still opt for an external resonator unless you're seriously trying to squeeze cost (and can do your own oscillator characterisation testing).

A: The absolute minimum accuracy required for CAN is 1.58%. However, I strongly recommend to keep it below 1%. It depends on what baudrate you intend to use, the higher the baudrate, the more accurate the clock needs to be.
Furthermore you need to provide the CAN peripheral with a clock that is suitable for prescaling, so that it can configure the location of the sample point accurately.
See What are the most common causes of CAN bus communication errors? The recommendation to avoid RC oscillators or ceramic resonators when doing 250kbps or faster is from the CAN standard. The best option is very likely to use external quartz and then follow ST's recommendations regarding layout and component values.
Unrelated to CAN, you should check if flash wait states are required when passing a certain system clock. If so you need to configure some flash register before enabling a fast running oscillator.

A: As others have mentioned, always compare the precision of available clock sources to the precision you need. These are usually mentioned in MCU documentation as well, but as you use CAN the precision requirement or tolerance for the bit rate will be in CAN specs. Also take the tolerance into account within the temperature and supply voltage range you intend to use the MCU. The tolerance of internal oscillators might be adverized to be 1% but it is 1% only at certain temperature and supply. For the STM32F303, tolerance goes up to 2% between range of 0 to 55 degrees C, and since your product is used in a car, expect temperature changes beyond that.
The optimal crystal frequency is much more complex question, as it might always be a compromise. These are always mentioned in data sheets, reference manuals, and application notes.
Your MCU supports crystals in the range of 4 to 32 MHz and external oscillators in the 1 to 32 MHz range, with typical of 8 MHz. That's a good reason to just pick 8 MHz as that is typical and same as the internal oscillator frequency.
Frequency-wise, the frequency does not matter much, as the MCU can run directly at the input frequency, or up to 72 MHz, which can be achieved with the internal PLL. From the input frequency, higher and lower frequencies can be generated with the PLL.
So for the PLL, the PLL can accept frequencies between 1 and 24 MHz, and the PLL can output between 16 and 72 MHz. It can have a pre-divider, a multiplier, and a post-divider. All limits for the frequencies at each stage must be obeyed, but fortunately these calculations can simply be left for manufacturer tools to configure as they see fit. The data sheet and reference manual has details on this.
For the oscillator and crystal, the higher frequency you use, the stricter are the crystal parameters that lead to reliable operation. There is also an app note on crystal selection. The basic idea is, to have the same margin of reliability in all conditions, higher frequencies require lower ESR and lower load capacitance, and this again makes the changes in stray capacitances affect the oscillating frequency more that at higher load capacitances. It is also harder and more expensive to find a suitable high frequency crystal, but on the other hand, higher frequency can be available in smaller packages.
If going for lower frequency crystals, they have more margin for stable operation, they are easier to find and allow for more load capacitance and changes in load capacitance due to stray capacitances has less effect on frequency. They also come in larger packages physically. But of course too low frequencies can't be used with the built-in oscillator, and there is always a sweet spot for the PLL input, which for some other STM32 chips is as low as between 1 and 2 MHz.
So the typical 8 MHz is a good compromise for all aspects, not too high, not too low. It is also a common multiple for generating the maximum frequency and 48 MHz for USB if needed. It is also listed as supported frequency for the system boot loader as it does not support any arbitrary frequencies. Some system boot loaders have some limitations and work better at lower than high frequencies. See the appnote for system boot modes for more info.
If smaller, cheaper, and slightly less precise option is tolerated for low speed CAN, there are ceramic resonators that can be used instead of crystals, but high speed CAN requires a crystal, even according to specs.


text:
Q: Spliting strings values of a column out of index and fill with NaN in a Pandas DataFrame I've a DataFrame like this :
ROW_A    ROW_B
1        tata+toto
2        tata+toto
3        tata+toto
4        ti+tu+te
5        ti+tu+te
6        ti+tu+te
7        ti+tu+te

I want to split ROW_B values in a new row. I know that the length of values does not match length of index but I just want to split the values and fill last values with NaN like this :
ROW_A    ROW_B       ROW_C
1        tata+toto   tata
2        tata+toto   toto
3        tata+toto   NaN
4        ti+tu+te    ti
5        ti+tu+te    tu
6        ti+tu+te    te
7        ti+tu+te    NaN

I tried this code :
df_columns = df.columns
row_b = df_columns[1]

df['ROW_C'] = df.groupby('ROW_A')[row_b].transform(lambda x:x.head(1).str.split('+').explode().values)).fillna

Here is the error message :
ValueError: Length of values (2) does not match length of index (3)

A: One option is to drop_duplicates + str.split + explode to create a temporary Series. Then reindex this with df.index to get the NaNs:
tmp = df['ROW_B'].drop_duplicates().str.split('+').explode()
df['ROW_C'] = tmp.set_axis(tmp.groupby(level=0).cumcount().pipe(lambda x: x+x.index), axis=0).reindex(df.index)

Another option is to use groupby + cumcount to create group numbers, then index the list in each row using the group number. Since the group number exceeds the list length, wrap it in try-except:
out = []
for i, lst in zip(df.groupby('ROW_B').cumcount(), df['ROW_B'].str.split('+')):
    try:
        out.append(lst[i])
    except IndexError:
        out.append(float('nan'))

Output:
   ROW_A      ROW_B ROW_C
0      1  tata+toto  tata
1      2  tata+toto  toto
2      3  tata+toto   NaN
3      4   ti+tu+te    ti
4      5   ti+tu+te    tu
5      6   ti+tu+te    te
6      7   ti+tu+te   NaN

A: You could group by column ROW_B and then create a new column on each of the groups -
from itertools import zip_longest

recons_df = []
for k, g in df.groupby('ROW_B'):
    g.loc[:, 'ROW_C'] = list(x if x else y for (x, y) in zip_longest(k.split('+'), [np.nan]*g.index.size))
    recons_df.append(g)

recons_df = pd.concat(recons_df)
print(recons_df)
#   ROW_A      ROW_B ROW_C
#0      1  tata+toto  tata
#1      2  tata+toto  toto
#2      3  tata+toto   NaN
#3      4   ti+tu+te    ti
#4      5   ti+tu+te    tu
#5      6   ti+tu+te    te
#6      7   ti+tu+te   NaN

A: In case you don't care about the NaN for every missing split, use -
df.merge(df['ROW_B'].str.split('+', expand=True).stack().reset_index(), left_on=[df.index], right_on=['level_0']).drop(['level_0', 'level_1'], axis=1).rename({0: 'ROW_C'}, axis=1)

Output
    ROW_A      ROW_B ROW_C
0       1  tata+toto  tata
1       1  tata+toto  toto
2       2  tata+toto  tata
3       2  tata+toto  toto
4       3  tata+toto  tata
5       3  tata+toto  toto
6       4   ti+tu+te    ti
7       4   ti+tu+te    tu
8       4   ti+tu+te    te
9       5   ti+tu+te    ti
10      5   ti+tu+te    tu
11      5   ti+tu+te    te
12      6   ti+tu+te    ti
13      6   ti+tu+te    tu
14      6   ti+tu+te    te
15      7   ti+tu+te    ti
16      7   ti+tu+te    tu
17      7   ti+tu+te    te


text:
Q: Webview randomly does not readjust after orientation change on iOS When change orientation of iOS device the contents of Webview don't always adjust to new orientation. It cuts off to what seems to be width of the space that it occupied in previous orientation. Screenshot below

On orientation change I call orientationchange event
evalJavascript("var e= document.createEvent('Events');" +
    "e.initEvent('orientationchange',true, false); document.dispatchEvent(e)");

In HTML I have viewport meta tag
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=5.0, user-scalable=1" />

What's interesting is that this does not happen to other pages like New York Times home page, which I load locally. Any ideas what could be the issue?

A: Put this HTML code into your website header:
<meta name="viewport" content="initial-scale=1, maximum-scale=1, width=device- width, height=device-height">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">

This should ensure that your website is app/mobile accessible.


text:
Q: Generated UUIDs behavior in postgres INSERT rule compared to the UPDATE rule I have a postgres database with a single table. The primary key of this table is a generated UUID. I am trying to add a logging table to this database such that whenever a row is added or deleted, the logging table gets an entry. My table has the following structure
CREATE TABLE configuration (
     id    uuid NOT NULL DEFAULT uuid_generate_v4(),
     name  text,
     data  json
);

My logging table has the following structure
CREATE TABLE configuration_log (
    configuration_id         uuid,
    new_configuration_data   json,
    old_configuration_data   json,
    "user"                   text,
    time                     timestamp
);

I have added the following rules:
CREATE OR REPLACE RULE log_configuration_insert AS ON INSERT TO "configuration"
       DO INSERT INTO configuration_log VALUES (
          NEW.id,
          NEW.data,
          '{}',
          current_user,
          current_timestamp
       );

CREATE OR REPLACE RULE log_configuration_update AS ON UPDATE TO "configuration"
      WHERE NEW.data::json::text != OLD.data::json::text
      DO INSERT INTO configuration_log VALUES (
          NEW.id,
          NEW.data,
          OLD.data,
          current_user,
          current_timestamp
      );

Now, if I insert a value in the configuration table, the UUID in the configuration table and the configuration_log table are different. For example, the insert query
INSERT INTO configuration (name, data)
       VALUES ('test', '{"property1":"value1"}')

The result is this... the UUID is c2b6ca9b-1771-404d-baae-ae2ec69785ac in the configuration table whereas in the configuration_log table the result is this... the UUID id 16109caa-dddc-4959-8054-0b9df6417406
However, the update rule works as expected. So if I write an update query as
UPDATE "configuration"
    SET "data" = '{"property1":"abcd"}'
    WHERE "id" = 'c2b6ca9b-1771-404d-baae-ae2ec69785ac';

The configuration_log table gets the correct UUID as seen here i.e. c2b6ca9b-1771-404d-baae-ae2ec69785ac
I am using NEW.id in both the rules so I was expecting the same behavior. Can anyone point out what I might be doing wrong here?
Thanks

A: This is another good example why rules should be avoided
Quote from the manual:

For any reference to NEW, the target list of the original query is searched for a corresponding entry. If found, that entry's expression replaces the reference.

So NEW.id is replaced with uuid_generate_v4() which explains why you are seeing a different value.
You should rewrite this to a trigger.

Btw: using jsonb is preferred over json, then you can also get rid of the (essentially incorrect) cast of the json column to text to compare the content.


text:
Q: Cannot boot into windows after installing Fedora I had a PC with a Windows and Ubuntu dual boot. Same disk with 2 paritions of 500GB each.
I decided to install Fedora instead of Ubuntu. So I downloaded project Nobara and installed it. During the installation, I remember that I reclaimed the ubuntu partition and /boot/efi partition. Now when I reboot I don't see windows as an option in Grub.
How can I boot into Windows if I want to.

A: It sounds like reclaim in this case could have meant "reformat", which means that other installed boot loader disappear.

*

*Put back `\EFI\Microsoft\Boot\bootmgfw.efi' into the EFI-partition (copy from some other windows-install of the same version)
Copy other "Microsoft"y-looking folders/folders you find too

*Edit EFI config with efibootmgr:
efibootmgr -c  -L "Windows Boot Manager" -l "\EFI\Microsoft\Boot\bootmgfw.efi" -d /dev/sdb -p 2
(Adapt sdb2 to wherever your EFI partition is)

*update/reinstall grub to (re)detect the foreign OSs
I had to look up "Nobara", it seems like a newish fedora-offshoot. Perhaps also consider using one of the more mainstream distros which are less likely to break boot behavior of existing systems without severe warnings.


text:
Q: Android Volley ListView Blinking and Items Remaining I have a ListView with a CustomAdapter set to it which displays an array of json objects that I call with a volley request:
final ListView listView = (ListView) findViewById(R.id.list);

adapter = new CustomListAdapter(this,personList);
listView.setAdapter(adapter);

// Creating volley request obj
     final JsonArrayRequest personReq = new JsonArrayRequest(url,
        new Response.Listener<JSONArray>() {
            @Override
            public void onResponse(JSONArray response) {
                Log.d(TAG, response.toString());

                // Parsing json
                for (int i = 0; i < response.length(); i++) {
                    try {

                        JSONObject obj = response.getJSONObject(i);
                        person.setfirstName(obj.getString("first_name"));
                        person.setlastName(obj.getString("last_name"));

                        //Add person to list
                        personList.add(person);
                        adapter.notifyDataSetChanged();

                    } catch (JSONException e) {
                        e.printStackTrace();
                    }

                }

                Log.i(TAG, "personList items: " + personList.size());

            }
        }, new Response.ErrorListener() {
    @Override
    public void onErrorResponse(VolleyError error) {
        VolleyLog.d(TAG, "Error: " + error.getMessage());
        hidePDialog();

    }
});

    // Adding request to request queue
    AppController.getInstance().addToRequestQueue(personReq);

Using a runnable and handler, I make this request every 5 seconds:
    //Run volley request every 5 seconds
    Runnable runnable = new Runnable() {
        @Override
        public void run() {

            if (orderList != null) {
                orderList.clear();
            }

            //Placing here TOO removes the last item but causes blinking
            //adapter.notifyDataSetChanged();

            AppController.getInstance().addToRequestQueue(personReq);

            handler.postDelayed(this, 5000);

        }
    };

    handler.postDelayed(runnable, 5000);

The problem is that one item always remains, even though it should not be there (due to removing it via a separate volley request). Tapping the item causes the app to crash with the following from the logcat:
java.lang.IllegalStateException: The content of the adapter has changed but ListView did not receive a notification. Make sure the content of your adapter is not modified from a background thread, but only from the UI thread. Make sure your adapter calls notifyDataSetChanged() when its content changes.

As you can see, I am calling adapter.notifyDataSetChanged(); directly after adding a person object. It works fine until the last item on the list is gone (but still being seen).
Adding adapter.notifyDataSetChanged(); inside the Runnable does clear the last item but causes the whole view to blink every 5 seconds.
Is it even possible to prevent this blinking?

A: Try this.
In your Adapter.
public void addAll(List<T> datas) {
    if (datas != null) {
        mData.addAll(datas);
        notifyDataSetChanged();
    }
}

Then in your Activity.
personList.add(person);
adapter.addAll(personList);
adapter.notifyDataSetChanged();

Make sure your adapter calls notifyDataSetChanged() when its content changes

A:
As you can see, I am calling adapter.notifyDataSetChanged(); directly
  after adding a person object.

That's a waste. Call notifyDataSetChanged once, after the list is in the final state you want to display.

Adding adapter.notifyDataSetChanged(); inside the Runnable does clear
  the last item but causes the whole view to blink every 5 seconds.
Is it even possible to prevent this blinking?

I can only guess that this "blinking" is because you are clearing the list and refreshing the adapter (thus making the ListView empty) before making your network request, which of course will have a delay based on the network condition.
Instead of clearing your list before making your network request, why don't you clear it after the response comes back?
public void onResponse(JSONArray response) {
    Log.d(TAG, response.toString());

    personList.clear(); // Wipe the list before adding new data

    // Parsing json
    // The rest of your parsing code here...

    // Now that the list is fully updated to the new state, call this ONCE
    adapter.notifyDataSetChanged();
}

A: OK I figured out a way to stop the blinking and clearing the last remaining item.
In addition to the onResponse method, adapter.notifyDataSetChanged(); must also be present in the onErrorResponse method.


text:
Q: An analogue to OEIS for graphs and ordered pairs? Does anyone know if such a thing exists already? I was able to find a number of seemingly very comprehensive encyclopedia-like reference pages on many species of graphs, but it seemed that the use case and spirit behind these pages differed from the the more Wiki-like OEIS.
If such a resource exists, please point me at it. Ideally, a database that is searchable by graph or subgraph along the same lines as OEIS with its subsequences (a simple list of ordered pairs should suffice for many queries), and then allows for accumulated community comments for that graph, though I realize this differs in that it may only be computationally tractable for relatively small structures.
If it does not, I am seriously considering trying to establish one myself, iff this is the sort of thing that people like you would be interested in using. I realize this is a questionable post for this forum; that said, I am trying to gauge the interest in a potentially useful free mathematical public good, which seems like a reasonable cause to post, and I can think of absolutely no more relevant target audience to query on this. Even the probable need to handle some method of graph canonization seems involved at the very least. I'm still unsure as to whether this is a great or terrible idea (or if there is interest), so a little bit of feedback either way would be tremendously helpful.

A: The House of Graphs is the analogue you're looking for, at least in spirit.
It does not allow searches by subgraphs, but it does allow searches by various graph properties - in my experience, if you have a graph, and you want to see if it has an entry in the House of Graphs database, it is pretty straightforward to narrow things down enough. (You can also draw the graph or paste a graph6 string, if you're looking for a specific graph.)
More usefully, it can often tell you if a graph exists with the properties you want. For example, this question, this question, and this question are all MSE questions I answered just by searching the House of Graphs database.
Anyone can add graphs or comments to them after creating an account, though currently not many of the graphs have detailed comments.

A: Second the reference to House of Graphs, as that's the closest that I know of for what you are looking for.
However, the analogous service would be searchable chemical databases. For example, chemspider:
http://www.chemspider.com/
which allows for exact structure searches, as well as substructure search.
The equivalent for graphs seems a little strange - how many subgraph searches would be useful? You would have to find a subgraph isomorphism to the graphs in the database.
For exact matches, canonicalising the input would be necessary for fast searching against the database. You could also store invariants for the graphs and use those to speed up the search. This is the concept of 'fingerprints' in computational chemistry.


text:
Q: Zoom in on subplot (with inset_axes plot) on click So I have followed the approach from this thread:
How can I plot the same figure standalone and in a subplot in Matplotlib?
And it actually works quite well, as seen in his example. However, one issue is that I have inset_axes plots in my plots. So when it zooms, all the inset plots remains, and actually overlaps the enlarged plot.
I am however not sure how to remove them, and maybe even also zoom in on the inset plot that are together with the subplot being clicked.
So from the thread I have just used this class for the zoom approach:
class ZoomingSubplots(object):
    def __init__(self, *args, **kwargs):
        """All parameters passed on to 'subplots`."""
        self.fig, self.axes = plt.subplots(*args, **kwargs)
        self._zoomed = False
        self.fig.canvas.mpl_connect('button_press_event', self.on_click)
        self.fig.subplots_adjust(hspace=0.3)

    def zoom(self, selected_ax):
        for ax in self.axes.flat:
            ax.set_visible(False)
        self._original_size = selected_ax.get_position()
        selected_ax.set_position([0.125, 0.1, 0.775, 0.8])
        selected_ax.set_visible(True)
        self._zoomed = True

    def unzoom(self, selected_ax):
        selected_ax.set_position(self._original_size)
        for ax in self.axes.flat:
            ax.set_visible(True)
        self._zoomed = False

    def on_click(self, event):
        if event.inaxes is None:
            return
        if self._zoomed:
            self.unzoom(event.inaxes)
        else:
            self.zoom(event.inaxes)
        self.fig.canvas.draw()

And then when I plot I use this:
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1.inset_locator import inset_axes

__name__ = '__main__':
    subplots = ZoomingSubplots(2, 2)

    for ax in subplots.axes.flat:
        ax.plot(x, y)
        axins = inset_axes(ax, width=1.3, height=0.9, loc=2)
        axins.plot(x2, y2)

    plt.show()

But as stated, with this the inset plot for all subplots will remain in their position and overlap with the enlarged plot. How can I change this, so that they don't intervene, and maybe even the inset_plot for the subplot remains and is also enlarged ?

A: I couldn't find a way to change the position of the inset_axes, probably because their position and size are locked-in to their parent axes.
In the meantime, here is a new class that creates the inset_axes automatically, and hides/shows the relevant inset_axes when clicking on one of the base axes.
class ZoomingSubplotsWithInset(ZoomingSubplots):
    def __init__(self, *args, inset_width=1.3, inset_height=0.9, inset_loc=2, **kwargs):
        super(ZoomingSubplotsWithInset, self).__init__(*args, **kwargs)
        self.inset_axes = []
        for ax in self.axes.flat:
            axins = inset_axes(ax, width=inset_width, height=inset_height, loc=inset_loc)
            self.inset_axes.append(axins)
        self.inset_axes = np.array(self.inset_axes)

    def on_click(self, event):
        if event.inaxes in self.axes.flat:
            super(ZoomingSubplotsWithInset, self).on_click(event)

    def zoom(self, selected_ax):
        for ax in self.inset_axes.flat:
            ax.set_visible(False)
        super(ZoomingSubplotsWithInset, self).zoom(selected_ax)
        # restore visibility of the inset_axes corresponding to the zoomed axes
        _, _, i = selected_ax.get_geometry()
        self.inset_axes[i-1].set_visible(True)

    def unzoom(self, selected_ax):
        for ax in self.inset_axes.flat:
            ax.set_visible(True)
        super(ZoomingSubplotsWithInset, self).unzoom(selected_ax)

if __name__ == '__main__':
    N = 10

    subplots = ZoomingSubplotsWithInset(2, 2)

    for ax, axins in zip(subplots.axes.flat, subplots.inset_axes.flat):
        x, y = np.random.random(size=(2, N))
        x2, y2 = np.random.random(size=(2, N))
        ax.plot(x, y)
        axins.plot(x2, y2)

    plt.show()


text:
Q: How do I remove a UIViewController from the view while adding a different one? On one view controller lets say UIViewController1, I have a UIButton instance that when clicked I want it to remove the current controller (self) from the stack and add on a different one, we will call it UIViewController2.
-(IBAction) pressedButton: (id) sender {
    [self.view removeFromSuperview];
    AppDelegate.rootViewController = [[UIViewController2 alloc] init];
}

I know this way doesn't work, but what is a good way to implement this? Or am I looking at the whole concept incorrectly?

A: You can use the following two methods to present and dismiss view controllers.
Present:
- (void)presentViewController:(UIViewController *)viewControllerToPresent animated:(BOOL)flag completion:(void (^)(void))completion

Dismiss:
- (void)dismissViewControllerAnimated:(BOOL)flag completion:(void (^)(void))completion

You just have to set the animated property to YES on the dismiss and to NO on the present to achieve what you want to do. You can also use the completion block to chain view controllers.


text:
Q: Event listener not working on Hibernate? I have implemented an event listener for auditing operations over my entities. For example, I made one for PreInsertEventListener called HibernatePreInsert. Also, by reading here on stackoverflow I configured an Integrator called HibernateIntegrator. Since I'm using Hibernate 4 and spring 4, I created a file under META-INF/services named com.dacasals.raspertwo.interceptors.HibernateInterceptor and there I added the integrator class, as recommended over the web and also here. But when I run my application and insert a new element, nothing happens, not even the messages of my HibernatePrePersist are displayed. This is the first time I try Hibernate EventListeners and I don't know what could be wrong.
Here is and example of the classes involved in my problem, also the file structure:
The listener:
public class HibernatePreInsert implements PreInsertEventListener{
    private static final long serialVersionUID = 1L;
    static final Logger logger = LoggerFactory.getLogger(HibernatePreInsert.class);

    @Override
    public boolean onPreInsert(PreInsertEvent event) {
        if(event.getEntity() instanceof Person){
            //display a message to know if this works or not
            logger.info("It works");
        }
        return false;
    }
}

The Integrator:
public class HibernateIntegrator implements Integrator{

    public void integrate(Configuration configuration, SessionFactoryImplementor sessionFactory, SessionFactoryServiceRegistry serviceRegistry){
        final EventListenerRegistry registry = serviceRegistry.getService(EventListenerRegistry.class);

        HibernatePreInsert listener = new HibernatePreInsert();

        registry.prependListeners(EventType.PRE_INSERT, listener);
    }

    @Override
    public void integrate(Metadata metadata, SessionFactoryImplementor sessionFactory,
            SessionFactoryServiceRegistry serviceRegistry) {
        // TODO Auto-generated method stub

    }

    @Override
    public void disintegrate(SessionFactoryImplementor sessionFactory, SessionFactoryServiceRegistry serviceRegistry) {
        // TODO Auto-generated method stub

    }

}

The file com.dacasals.raspertwo.interceptors.HibernateInterceptor:
com.dacasals.raspertwo.interceptors.HibernateInterceptor

Thanks in advance.
EDITED:
I made a mistake while writing. I'm using Hibernate 5, not 4.

A: I got my listeners to work without using the method I found before. Instead of defining a file with the service, I created a new class where I register my implemented Event Listeners like this:
@Component
public class EscuchadorGeneral {

    @PersistenceUnit
    private EntityManagerFactory emf;

    @Inject
    private InsertEvent insert;

    @Inject
    private UpdateEvent update;

    @Inject
    private DeleteEvent delete;

    @PostConstruct
    protected void init(){
        SessionFactoryImpl sF = emf.unwrap(SessionFactoryImpl.class);
        EventListenerRegistry registry = sF.getServiceRegistry().getService(EventListenerRegistry.class);
        registry.getEventListenerGroup(EventType.POST_INSERT).appendListener(insert);
        registry.getEventListenerGroup(EventType.POST_UPDATE).appendListener(update);
        registry.getEventListenerGroup(EventType.PRE_DELETE).appendListener(delete);
    }

}

And now I can listen when any of my entities is inserted, updated or deleted. I hope this solution works for other developers too.

A: Since all you're wanting to do is to manipulate the entity associated to the event, I would advocate the usage of @PrePersist here.
You can fool Hibernate to still fire the JPA integrator callbacks even when the application doesn't use any JPA features and continues to use the native SessionFactory configuration.
For Hibernate prior to 5.2, you would need to make sure that you also include the appropriate versioned hibernate-entitymanager on your dependency classpath that matches the same version of your hibernate-core dependency.  For Hibernate 5.2 and beyond, all you need to include is hibernate-core, which you obviously already use.
Next is to setup META-INF/services/org.hibernate.integrator.spi.Integrator.
For Hibernate prior to 4.2 you need to add:

org.hibernate.ejb.event.JpaIntegrator

For Hibernate 4.3 and 5.x, you need to add:

org.hibernate.jpa.event.spi.JpaIntegrator

You should now be able to use the @PrePersist callback even when your configuration does not bootstrap a JPA EntityManager.
Then as you port your application to using JPA specifically, you can eventually remove this integrator configuration as a JPA built EntityManager will automatically register and execute these callbacks.
UPDATE
Should you decide you want to use a Hibernate EventListener, I would make sure both integrate methods register that listener.  I think the one you've implemented was left for legacy contracts but I believe the later versions of Hibernate use the other signature specifically that you haven't yet implemented.  That could be why your listener doesn't fire.


text:
Q: Two dimensional matrix in Perl Newbie's question: What does $matrix[$row][4]=1; mean in a code? The row and column are known to me. Why is it made equal to 1?

A: The command will set the cell at position $row,4 with the value 1

A: = is the assignment operator in Perl. It assigns the value 1 to the cell at the coordinates $row, 4.
The comparison operators for equiality are eq for strings and == for numbers.


text:
Q: Spring security + spring social without xml I'm trying to create a login interface only with a Facebook login. And I would like that once logged in the user stay logged and disconnect if he wants.
I don't want the user to register via login/pass, only facebook so once he's logged I only keep information facebook gave me(mail,name etc.).
I followed the tutorial here : http://docs.spring.io/spring-security/site/docs/3.2.x/reference/htmlsingle/#jc-form
And tried to figure it out with this : https://github.com/spring-projects/spring-social-samples/blob/master/spring-social-showcase-boot/src/main/java/org/springframework/social/showcase/config/SecurityConfig.java
But I can't make it work, it always say :

org.springframework.security.ldap.DefaultSpringSecurityContextSource
  not found

i use maven and not graddle, here is my pom.xml :
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>org.springframework</groupId>
<artifactId>cinemagik</artifactId>
<version>0.1.0</version>

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.1.8.RELEASE</version>
</parent>

<dependencies>
    <dependency>
        <groupId>junit</groupId>
        <artifactId>junit-dep</artifactId>
        <version>4.11</version>
    </dependency>
    <dependency>
        <groupId>com.google.sitebricks</groupId>
        <artifactId>slf4j</artifactId>
        <version>0.8.3</version>
    </dependency>
    <dependency>
        <groupId>ch.qos.logback</groupId>
        <artifactId>logback-classic</artifactId>
        <version>1.0.13</version>
        <scope>runtime</scope>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-thymeleaf</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>
    <dependency>
        <groupId>org.postgresql</groupId>
        <artifactId>postgresql</artifactId>
        <version>9.3-1102-jdbc41</version>
    </dependency>
    <dependency>
        <groupId>org.mongodb</groupId>
        <artifactId>mongo-java-driver</artifactId>
        <version>2.13.0-rc0</version>
    </dependency>
    <dependency>
        <groupId>org.eclipse.persistence</groupId>
        <artifactId>eclipselink</artifactId>
        <version>2.5.2</version>
    </dependency>
    <dependency>
        <groupId>org.eclipse.persistence</groupId>
        <artifactId>org.eclipse.persistence.jpa.modelgen.processor</artifactId>
        <version>2.5.2</version>
        <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>nz.net.ultraq.thymeleaf</groupId>
        <artifactId>thymeleaf-layout-dialect</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.social</groupId>
        <artifactId>spring-social-facebook</artifactId>
        <version>1.1.1.RELEASE</version>
        <type>jar</type>
    </dependency>
    <dependency>
        <groupId>org.springframework.social</groupId>
        <artifactId>spring-social-twitter</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-core</artifactId>
        <version>4.0.0.M2</version>
        <type>jar</type>
    </dependency>
    <dependency>
        <groupId>org.springframework.security</groupId>
        <artifactId>spring-security-config</artifactId>
        <version>4.0.0.M2</version>
        <type>jar</type>
    </dependency>
    <dependency>
        <groupId>org.springframework.social</groupId>
        <artifactId>spring-social-security</artifactId>
        <version>1.1.0.RELEASE</version>
        <type>jar</type>
    </dependency>
    <dependency>
        <groupId>org.springframework.ldap</groupId>
        <artifactId>spring-ldap-core</artifactId>
        <version>1.3.1.RELEASE</version>
    </dependency>
</dependencies>

<properties>
    <start-class>app.Application</start-class>
</properties>

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>

<repositories>
    <repository>
        <id>spring-milestone</id>
        <url>http://repo.spring.io/libs-release</url>
    </repository>
    <repository>
        <id>unknown-jars-temp-repo</id>
        <name>A temporary repository created by NetBeans for libraries and jars it could not identify. Please replace the dependencies in this repository with correct ones and delete this repository.</name>
        <url>file:${project.basedir}/lib</url>
    </repository>
</repositories>

<pluginRepositories>
    <pluginRepository>
        <id>spring-milestone</id>
        <url>http://repo.spring.io/libs-release</url>
    </pluginRepository>
</pluginRepositories>
<name>cinemagik</name>

I tried multiple version of spring-ldap from the last release to the 1.3.1.
Here is my code :
WebAppConfiguration
package app.configuration;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

@Configuration
@EnableWebMvc
@ComponentScan(basePackages = {"app"})
public class WebAppConfiguration extends WebMvcConfigurerAdapter {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/js/**").addResourceLocations("classpath:/static/js/");
        registry.addResourceHandler("/css/**").addResourceLocations("classpath:/static/css/");
        registry.addResourceHandler("/images/**").addResourceLocations("classpath:/static/images/");
    }

    @Override
    public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) {
        configurer.enable();
    }
}

SecurityConfig :
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package app.configuration;

/**
 *
 * @author Antoine
 */
import javax.inject.Inject;
import javax.sql.DataSource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.builders.WebSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.encrypt.Encryptors;
import org.springframework.security.crypto.encrypt.TextEncryptor;
import org.springframework.security.crypto.password.NoOpPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

/**
 * Security Configuration.
 *
 * @author Craig Walls
 */
@Configuration
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private ApplicationContext context;

    @Inject
    private DataSource dataSource;

    @Autowired
    public void registerAuthentication(AuthenticationManagerBuilder auth) throws Exception {
        auth.jdbcAuthentication()
                .dataSource(dataSource)
                .usersByUsernameQuery("select username, password, true from Account where username = ?")
                .authoritiesByUsernameQuery("select username, 'ROLE_USER' from Account where username = ?")
                .passwordEncoder(passwordEncoder());
    }

    @Override
    public void configure(WebSecurity web) throws Exception {
        web
                .ignoring()
                .antMatchers("/**/*.css", "/**/*.png", "/**/*.gif", "/**/*.jpg");
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http
                .formLogin()
                .loginPage("/signin")
                .loginProcessingUrl("/signin/authenticate")
                .failureUrl("/signin?param.error=bad_credentials")
                .and()
                .logout()
                .logoutUrl("/signout")
                .deleteCookies("JSESSIONID")
                .and()
                .authorizeRequests()
                .antMatchers("/admin/**", "/favicon.ico", "/resources/**", "/auth/**", "/signin/**", "/signup/**", "/disconnect/facebook").permitAll()
                .antMatchers("/**").authenticated()
                .and()
                .rememberMe();
    }

    @Bean
    public PasswordEncoder passwordEncoder() {
        return NoOpPasswordEncoder.getInstance();
    }

    @Bean
    public TextEncryptor textEncryptor() {
        return Encryptors.noOpText();
    }

}

Thanks for any help :o


text:
Q: How can I install CUDA 9.0 for Ubuntu 17.10 without changing the current nvidia drivers? I have downloaded and installed CUDA several times, and every time it fails to pass the test samples deviceQuery and checkBandwidth. Also tensorflow is never listing the GPU between accessible devices, only the CPU.
My current nvidia driver is 384.111, where as the upgraded version 384.130 always generates a library mismatch on nvidia-smi and makes ubuntu unbootable.
Every time I try to install CUDA 9.0 with the .run file, which is the only way to install it without upgrading the nvidia drivers, it finishes with an "incomplete install message.". Runs on the tests are always negative, with the following output:

Installing CUDA 9.0 .deb with dpkg from the nvidia website https://developer.nvidia.com/cuda-downloads?target_os=Linux&target_arch=x86_64&target_distro=Ubuntu&target_version=1710&target_type=deblocal it also upgrades the nvidia driver.
How can I install CUDA 9.0 for Ubuntu 17.10, with nvidia 384.111 without upgrading to 384.130, so that it correctly performs on the sample tests and allows tensorflow-gpu to access the graphic-card?
PS: Whenever I say "it fails", the error message is always "UNKNOWN ERROR"
The graphics card in my system is a NVIDIA GeForce GTX 1080

A: I too have gone thru similar struggles. After trying to install CUDA 9.0, 9.1, 9.2 I found each toolkit requires a specific Nvidia driver version.
The official Nvidia CUDA installation guide calls for you to uninstall your Nvidia drivers. I think it's unavoidable if you want to do a local machine install unless you use Docker + Nvidia Docker.
This will allow your local machine to keep the same Nvidia drivers, and you install your specific CUDA toolkit in different container images.
This is the approach I went with.


text:
Q: Best way to broadcast camera in real-time I am trying to find the best way to broadcast a camara and send the stream to 200 connections.
If I use web-rtc, I am limited with the CPU power. I've tried to use a server as a gateway, but the number connection maximum I can perform is 60. And 120 with 2 servers.
I can't use web socket to send stream because, the TCP protocol create latency.
Last solution : use RTMP protocol, but there is 5s-10s of latency.
My question: Is there a solution to stream a camera to many clients (200/300)  in real-time  ?

A: Just using webrtc would not work as I assume the device the the camera will need a huge bandwidth. The best way is to use an SFU. This will send the video to to the server to then broadcast it to every peer. It is normally able to handle 200 connections if only video is used.
I've implemented such a server using mediasoup. It also allows you to balance the load over several cpu's and multiple servers.
Here is a simple project where this library is used.
There are also other solutions like Janus gateway or kurento server. Although I haven't used them.
SECOND SOLUTION
I found This github repository which allows video forwarding peer to peer even for large audiences. Basically forwarding the stream to other peers which will also forward their received stream. I assume that there will be a little more latency as the video could be relayed through many peers.


text:
Q: Using beamer document class I'm using \documentclass[11pt]{beamer} with the package Tikzcd but it doesn't work properly with the frames. It gives me the error:

Package pgf Error: Single ampersand used with wrong catcode. \end{frame}

A: As noted in section 3.4 of the tikz-cd manual, you can use the ampersand replacement key to solve this:
\documentclass[]{beamer}

\usepackage{tikz-cd}

\begin{document}
\begin{frame}{}{}
  \begin{tikzcd}[ampersand replacement=\&]
    A \ar[r]\& B
  \end{tikzcd}
\end{frame}

\end{document}


text:
Q: Undefined MethodError for 'location' for nil:NilClass in rails during Rake Command I am trying to run this rake task and I am getting the undefined method error for 'location' I am not sure what is causing this error to arise.
my code as follows
task :set_location_id => :environment do
  ConfiguredDevice.all.each do | configured_device |
    location = configured_device.user.location
    configured_device.update_columns(location_id: location.id)
  end
end

A: Apparently, you have a configured_device that doesn't have a user. So, when you try to call configured_device.user.location, configured_device.user returns nil and nil doesn't respond to location (as the error states).

how would i go about fixing that?

That depends. If it is expected that in some instances a configured_device won't have a user, then you could use ruby's safe operator. Something like:
task :set_location_id => :environment do
  ConfiguredDevice.all.each do | configured_device |
    if location = configured_device.user&.location
      configured_device.update_columns(location_id: location.id)
    end
  end
end

Some people don't like use of the safe operator (or the .try() method), so you could also do:
task :set_location_id => :environment do
  ConfiguredDevice.all.each do | configured_device |
    if user = configured_device.user
      configured_device.update_columns(location_id: user.location.id)
    end
  end
end

In this case, I suppose it might be possible that a user doesn't have a location. In which case user.location.id will throw a Undefined MethodError again. So, you could do:
task :set_location_id => :environment do
  ConfiguredDevice.all.each do | configured_device |
    if user = configured_device.user
      if location = user.location
        configured_device.update_columns(location_id: location.id)
      end
    end
  end
end

Which I think ought to get you where you want to go.
BTW, assuming that ConfiguredDevice belongs_to :location, you should be able to do:
configured_device.update(location: location)

Saves you a few keystrokes.


text:
Q: How i can work on same branch but exclude few files in mercurial I have one branch named john which i am working in my office.
Now i want to work from home so i have cloned therepo. Now as my home computer has different settings so there are files like
settings,test1, test2 , test3 etc which i don't to track on my home computer. I want to work on same branch as john and i want to commit to same branch as well.
How can i choose which branch i have to work.  and how to ignore those files

A: *

*Enable MQ extension

*Store skeleton files in repository

*Add location-specific edits to files as MQ-patches in repositories

A: I tend to keep default files in the repo, ones which don't actually work but don't interfere with the code that's in use. e.g. instead of having a file called settings in your repo, I'd have one called settings.default
This can be kept safely in your repos and be populated with example data. Then when you clone a repo to a new location or machine you just copy the settings.default file to settings and add your location specific data.
You would ignore the plain settings file in .hgignore so it never gets pushed between repos.


text:
Q: How do people understand astromech droids? In all the Star Wars movies, R2D2 just boops and beeps his way around. And everyone understands him perfectly, though he is obviously not speaking Basic.
How do people understand him - is there like an astromech language? If so, then would one have to learn it, or is it comprised of feelings and emotions (expressed in beeps), essentially making a tonal language?
If I may be permitted to use an example from the prequels without too many lynch mobs forming, Anakin Skywalker converses frequently with Artoo while in the Naboo fighter, but he couldn't have had much schooling at the age of eleven, especially because he was a slave.
So how would people, Anakin especially, be able to understand astromechs?

A: Luke can understand R2D2 on Dagobah just before he's swallowed by the creature. He doesn't use a readout and he doesn't have C3PO with him. It must be familiarity, as Anakin also does this in the prequels.

A: All droids speak and understand Binary - the language R2 uses.
In general, the tones used can convey much of the meaning.  Translators like C-3P0 have to translate for most people, though people who have spent a lot of time around droids can learn at least a little of what different sounds/phrases mean - just watching the trilogy, most people can figure out 'yes' and 'no'.
Luke especially spends a lot of time with R2, and has his X-Wing's computer terminal for R2 to 'speak' through - accompanied by the verbalizations he would make.  Luke certainly has at least a basic understanding of the language.
The rest of what Luke displays can be attributed to his knowing R2 so well - He can guess how R2 will respond, get a basic idea of the question from what he knows, and fill in the blanks intuitively.
Interestingly, the Galaxy of Fear young adult series featured an R2 unit with a speech module - an optional component which allowed them to speak in Basic.

A: I'm not a Star Wars expert, but it certainly seems to me that people don't generally understand the astromechs. Generally, C3PO has to translate for R2D2 - the only time in the original films that Luke understands R2 without his help is when he's in his X-Wing, and it's clearly shown that R2's beeps are being translated on the screen of Luke's ship.

A: As you can see from the first deleted scene from Star Wars: Revenge of the Sith, the simple answer is that humans don't generally understand Artoo although they may have a basic understanding of "spoken Droid". Note that while Anakin is able to reproduce the sounds perfectly, his comprehension is limited and he is relying on the communicator to provide a textual translation.

Anakin: Artoo, where are they holding the Chancellor?
Artoo: [Beeps]
Anakin: No text
[Anakin hits the communicator]
[Artoo beeps]
Anakin: It's broken. Can you understand what he's saying?
Obi-Wan: I'm not a protocol droid
Anakin: I'm pretty sure that beep [he perfectly reproduces Artoo's "speech"] is down.

You will also wish to note that this is exactly the same way that Luke communicates with Artoo in the cockpit of their X-Wing, via a speech-to-text app.

"Most people" don't speak droidspeak. Only those that work around droids bother to learn it, and even then inexpertly.
Notable characters who can understand droid (without a translator device) are;
Luke (in his later years)

"Artoo?" he asked, brightening, and a moment later the blue-and-white
astromech rolled into view, chirping and whistling at length.
"Yes," Luke said. Decades of missions with R2-D2 had left him
reasonably fluent in droidspeak, but the astromech's list of
accusations was both lengthy and highly specific. "No, I—yeah, it's
true."
R2-D2 squawked derisively.
"Hey, sacred island," Luke said. "Watch the language."
The Last Jedi: Official Novelisation

Rey

To most people, the beeping would have sounded like mechanical
gibberish. But Rey was good with technology and had studied the
communication patterns of droids. And that droid was especially
eloquent—particularly in his choice of insults toward the Teedo.
The Force Awakens - Rey's Story

Poe

BB-8, secure in the astromech socket behind the cockpit of Poe's X-wing, burbled a question. Plugged into the fighter, the droid's binary-speak was automatically decoded and displayed on the console, but Poe didn't actually need to read the translation to understand what the droid was asking.
Star Wars: Before the Awakening

A: For a direct answer as to how Anakin could understand, he worked as a mechanic for almost all of his slave life.  Of the few things he did learn, he probably learned everything there is to know about piloting and robots.  This experience would put him in the position to interact with many different droids, and the amount of exposure he had to them probably helped him learn the language (without ever really thinking that he is learning it too). Considering how a child develops language, and Anakin can clearly speak multiple languages (Basic, and Huttese which Watto speaks), it would make sense that he would learn the droid language also.

A: I think its both; you can communicate with them via text and communicators and or communicate with them through there binary language each string of beeps stands for a different word or letter.
Think of it like people who can decode Morse code they hear beeping as letters and can understand whats being said while the rest of us just hear beep beep beep beep.
So anyone who takes the time to learn binary can talk to droids.
e.g: If uncle Owen had learned binary he wouldn't have needed to buy C3PO because he'd be able to talk to his moisture evaporators.
e.g 2: In the force awakens Rey can talk to BB-8 because she has/had to learn speaking binary to make her way on Jakku.
Ok so after typing all that out I decided to check wookieepedia,  just to make sure (check it out look for binary or droidspeak) and I'm kinda right .


text:
Q: Adding a node to to another in XSLT I have xml like this:
  <configurationData>
    <path name='b'>
      <path name='a'>
        <setting name='s1'>
        ![CDATA[XXXX]]
        </setting>
        <setting name='s2'>
          XXXX
        </setting>
      </path>
    </path>
  </configurationData>

where configurationData is the root node, and there can be may nested paths followed by one or more setting nodes. I want to convert the setting node to put the contents of the setting node into a child node called value
  <configurationData>
    <path name='b'>
      <path name='a'>
        <setting name='s1'>
          <value>![CDATA[XXXX]]</value>
        </setting>
        <setting name='s2'>
          <value>XXXX</value>
        </setting>
      </path>
    </path>
  </configurationData>

I must admit I find XML a mental road block and I cannot see what XSLT to use:
This is my attempt:
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

  <xsl:output encoding ="utf-8" indent="yes" method="xml" version="1.0"/>

  <xsl:template match='/setting'>
    <xsl:apply-templates select='setting' />
  </xsl:template>

  <xsl:template match='setting'>
    <value>
      <xsl:value-of select='.'/>
    </value>
  </xsl:template>
</xsl:stylesheet>

A: You are 90% of the way there.  What you need is the "identity template"
<xsl:stylesheet version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">

    <xsl:output encoding ="utf-8" indent="yes" method="xml" version="1.0"/>

    <xsl:template match="@*|node()">
        <xsl:copy>
            <xsl:apply-templates select="@*|node()"/>
        </xsl:copy>
    </xsl:template>

    <xsl:template match='setting'>
        <xsl:copy>
            <xsl:apply-templates select="@*"/>
            <value>
                <xsl:value-of select='.'/>
            </value>
        </xsl:copy>
    </xsl:template>

</xsl:stylesheet>

The first template processes all nodes, copying them to the output.  However, the 'setting' template, being more specific, gets invoked for 'setting' nodes, That template copies the node itself and its attributes, then wraps the value in a 'value' tag.
The most non-intiutive thing about XSLT is that the stylesheet is not a program which drives the process.  Instead, it is the input XML document that controls, with the stylesheet providing instructions that get selected and executed according to what's in the input.  This is called "push" processing.  The XSL processor pushes data to your stylesheet.  XSLT does have some procedural capabilities, and you can write a stylesheet in "pull" style, where the stylesheet attempts to drive the process, but this is harder and leads to hard-to-maintain stylesheets.
Edit:
To enable CDATA sections replace:
<xsl:value-of select='.' />

with
![CDATA[<xsl:value-of select='.' disable-output-escaping="yes"/>]]

(though not the best solution as it always puts CDATA in)

A: My suggestion, based on Jim Garrison answer:
<xsl:stylesheet
  version="1.0"
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
>
  <xsl:output method="xml" encoding="utf-8" cdata-section-elements="value" />

  <xsl:template match="node() | @*">
    <xsl:copy>
      <xsl:apply-templates select="node() | @*" />
    </xsl:copy>
  </xsl:template>

  <xsl:template match="setting/text()">
    <value>
      <xsl:value-of select="." />
    </value>
  </xsl:template>

</xsl:stylesheet>


text:
Q: Gnome gestures are not working in ubuntu 21.10 I just installed ubuntu 21.10 and but the touchpad gestures of gnome 40 are not not working for me.

A: Some information to note
Gnome 40 has been released with some new features and gestures. Though Gnome 40 has gestures, it doesn't always work! This is because gnome gestures aren't sensitive, they are still not fully made right now in gnome40 (IDK but people say that it is successful in gnome 41).
Make sure, you are using gestures correctly.
According to OMG ubuntu

A three-finger swipe left or right moves between workspaces, while a three-finger push up enters the Overview and, if you keep pushing, extends the app launcher. A three-finger drag in the posit direction will return you to your selected workspace.

Some more information
Gnome 40 gestures, cannot be easily modified, disabled or enabled. Generally, by default the gestures are on, however sometimes maybe the gestures aren't on by default, in that case, you can boot into a live USB and check if gestures work there or not. If they are working there then it is recommended to backup /home/$USER and reinstall.
Possible way to use gestures
There is no possible way to use gestures except using the gestures with a lot of pressure but generally, when you put pressure on the touchpad it will more likely misbehave afterwards, so it is not recommended.
Why doesn't this works
Well... I could not provide any possible reasons for this (ask the developers of gnome) make sure that Your touchpad supports gestures as many old touchpads aren't so sensitive to identify gestures. You can also buy a gesture pad if you are using an external mouse.
When it should work?
It will work if/on :

*

*Mac hardware supports these gestures

*If you are having a sensitive touchpad

*If you are not having any problems with config files

*If the settings are not modified yet.
If you have all of these things checked then go to the next section
If you are sure that you are incorrect hardware with correct settings
I would rather recommend you to:

*

*Downgrade to 20.04 with gnome 3 and use this extension

*Upgrade to gnome 41 beta using fedora 35 or using Open suse
Conclusion
IMHO these gestures aren't going to work on gnome 40 at any cost (unless or until there is an extension update) I would highly recommend upgrading to gnome 41
Also, I think so that gnome tweaks can help in tweaking the gestures settings, but IDK.


text:
Q: Iproblem with reading excel formula using poi While parsing an excel file for the values in the column with the formula format  I receive null. Here is my code:
  Cell cell = row.getCell(i);
          CellValue cellValue = evaluator.evaluate(cell);
          switch(cell.getCellType())
          {
            case Cell.CELL_TYPE_NUMERIC:
                returnedMap.put(arrayForMappingNames[index], ""+cell.getNumericCellValue());
                break;
            case Cell.CELL_TYPE_STRING:
                returnedMap.put(arrayForMappingNames[index], cell.getStringCellValue());
                break;
            case Cell.CELL_TYPE_FORMULA :
                returnedMap.put(arrayForMappingNames[index], cellValue.getStringValue());
                break;
            default :
                returnedMap.put(arrayForMappingNames[index], ExcellUtil.DEFAULT_VALUE);
          }

A: Thanks to Alex Richter, my problem is solved now.
          Cell cell = row.getCell(i);
          CellValue cellValue = evaluator.evaluate(cell);
          String columnValue = formatter.formatCellValue(cell, evaluator);
          returnedMap.put(arrayForMappingNames[index], columnValue);


text:
Q: Fragment Tabs using Images I am using Tabs in my Apps, but now its Deprecated, So now we are recommended to use FragmentTabs, and I found this example to get started:
  // Tab titles

  private String[] tabs = { "Top Rated", "Games", "Movies" };

But my question is how can i use Images in place of Text in Fragment Tabs?

A: use SetIcon(R.drawable.icon) to show Icon in place of Text in Fragment Tabs,
see this example
Like:
  // Create Tab1 with a custom image in res folder
    mTabHost.addTab(mTabHost.newTabSpec("tab1").setIndicator("", getResources().getDrawable(R.drawable.tab1)),
            FragmentTab1.class, null);


text:
Q: Size of split views in UISplitViewController? No hard-coded values please I'm building view hierarchies programmatically, without using a nib, for the master and the detail views in the UISplitViewController. My problem is that I do not know how large those views are. Well, of course, I know their hard-coded values... But I want to be a good citizen and not use hard-coded values and instead query them. Problem is that I have no idea how... Do you?
Thanks in advance,
/Steve

A: You can do that by accessing the viewControllers property of split view and it's the 2nd view's frame in the array that is returned.
What is the hard coded value?


text:
Q: Dimple.js Stacked Bar Graph I have data for the different phases of a series of map reduce jobs in the following format:
{"GC Time":"[0.0,0.0,0.0,0.0]",
 "Result Serialization Time":"[3.0,3.0,3.0,2.0]",
 "Getting Result Time":"[0.0,0.0,0.0,0.0]",
 "Task Deserialization Time":"[17.0,16.0,16.0,16.0]",
 "Scheduler Delay":"[55.0,46.0,47.0,46.0]"}

Essentially, the array for each phase contains the times taken for that phase in increasing task number order.
I want to plot a stacked bar graph like the following using dimple.js/d3.js:
http://ibin.co/1yH9raFgUtPs
I'm not being able to figure out how to do this (should be pretty simple for someone who's good with dimple.js), so any help is greatly appreciated.

A: I think it would be much easier to help you if you could show what you have done so far.
Nevertheless, I think the way you have defined your data is wrong.
Try defining your array something like this:
var xpoints=["a","b","c"];
var ypoints=[1,2,3];
var x2points=[5,6,7];
var dataset=[];
for(var i=0;i<xpoints.length;i++){
dataset.push({
                    x : xpoints[i],
                    y : parseFloat(ypoints[i]),
                    z : x2points[i]

                    });
        }

console.log(dataset);

/*Output:

[[object Object] {
  x: "a",
  y: 1,
  z: 5
}, [object Object] {
  x: "b",
  y: 2,
  z: 6
}, [object Object] {
  x: "c",
  y: 3,
  z: 7
}]

*/

Hope it helps!


text:
Q: Passing Values from table to CTE I have a table of slot numbers, i.e. warehouse slot numbers.
0110H
0310H
0311H
0312H
0313H
0314H

The table is called WarehouseLocationLimits and the column name is "F1." The 3rd and 4th digits of the of the above slot numbers represent a maximum number of bays in an aisle of the warehouse.
I have the following code
DECLARE @I INT
SET @I = 1;
WITH CTS(BAY) AS (

    SELECT @I
    UNION ALL
    SELECT BAY + 1 FROM CTS
    WHERE BAY < 5
)
    SELECT F1, LEFT(F1, 2) AISLE,  CAST(SUBSTRING(F1, 3, 2) AS INTEGER) BAYMAX, SUBSTRING(F1, 5, 1) LEVEL, BAY
    FROM WarehouseLocationLimits WL, CTS
    Where F1 IS NOT NULL
    order by F1, BAY

Which generates something like the following:
0110H   01  10  H   1
0110H   01  10  H   2
0110H   01  10  H   3
0110H   01  10  H   4
0110H   01  10  H   5
0310H   03  10  H   1
0310H   03  10  H   2
0310H   03  10  H   3
0310H   03  10  H   4
0310H   03  10  H   5

Note: for each "slot" the CTE is generating 5 lines because of the literal '5' in the WHERE clause of the CTE. I need to pass the value CAST(SUBSTRING(F1, 3, 2) AS INTEGER) of each slot to the CTE. How can I do that?
Thanks in advance for your help
Clyde

A: Ok. I got it. The solution is the following:
WITH CTS(SLOTNO, AISLE, BAY, LEVEL)
    AS (
        SELECT F1, LEFT(F1, 2),  SUBSTRING(F1, 3, 2), ASCII(SUBSTRING(F1, 5, 1))
        FROM WarehouseLocationLimits WL1
        WHERE F1 IS NOT NULL
        UNION ALL
        SELECT WL2.F1, LEFT(WL2.F1, 2),  BAY, LEVEL - 1
        FROM WarehouseLocationLimits WL2, CTS
        WHERE WL2.F1 = CTS.SLOTNO AND LEVEL > ASCII('A')
        )
    SELECT *, CHAR(LEVEL)
    FROM CTS
    order by SLOTNO, LEVEL DESC

I didn't understand that the first query (i.e., that one atop the "UNION ALL" is a "seed" query and runs only once for each row of the table. Having understood that, it all fell into place for me.


text:
Q: Can you force a hyperlink click event on page load I've implemented a menu for my asp.net page containing some hyperlinks and loading different contents on their clicks, it's using jquery on behind for it's style mostly and it is working fine. But the problem is, what if a refer to this menu from the outside, i can refer to each of the menu items, i pass parameters on querystring, now i can find which item is clicked but how  can i force that hyperlink menu item to be clicked on page load. I'm specifing just their navigation urls, how can i specify that if something is passed in querystring than that specific menu item should be forced clicked on pageload.
Any ideas? Thanks in advance.
The real question lies can you cuase a hyperlink click event?
Now I'm using
Page.ClientScript.RegisterStartupScript(typeof(Page),"test1", ""); but still nothing desirable happens, seems that this row has no effect at all.

A: Whether the functionality being executed is client side or server side, it might be a good idea to create a function that will accept the id or something of the menu item being clicked and then handle it appropriately.
Thus all the menu items will call the same function.  And since you have the parameters in the query string just pass them through to the function which will handle it accordingly and display the correct content?

A: You need a bit of separation...
Whatever your click does can be moved into a function, then you can call the function on the click of the menu - but you can also call the function at other times as well.
Before:
Click Me

After:
Click Me
...
var fnSayHello = function() { alert('hello'); };
fnSayHello();


text:
Q: usb debugging code I want to interface my HUAWEI U8150 which is an Android 2.2 version with an external device via a USB Interface. Could there be any links or anything to guide me onto assessing the USB code to enhance that communication?

A: Is the external USB device a USB host, or USB OTG host?
AFAIK Android 2.3.4 does not support being a USB host. In which case the complexity is in the host, because the Android device does not change, it is still a USB device, and the host needs to figure out how to talk to it.
Look at http://developer.android.com/guide/topics/usb/adk.html for details if making a USB host


text:
Q: Rails Strong Parameters either in root or nested object I want to be able to support a set of parameters in either the root params object:
?foo=a
params.permit(:foo)

Or in a nested object:
?bar[foo]=a
params.require(:bar).permit(:foo)

I'm passing parameters into that controller from a form object, so the nested object happens naturally, but I'd like to also be able to pass the params in the root object in the query string and support both.
Is there an elegant, non-hacky way to accomplish this?

A: require is like [] with an exception when the value is missing (much like Hash#fetch). You can instead just use [] directly to get the nested structure if it's there, and fall back to the root params otherwise:
(params[:bar] || params).permit(:foo)

A: remember that require is different as permit.
The require method ensures that a specific parameter is present. is not necessary to use on nested ones, it makes sure that the required one come in the params or it will throw an error.
you can work with nested attributes like this
params = ActionController::Parameters.new({
  person: {
    name: "Francesco",
    age:  22,
    pets: [{
      name: "Purplish",
      category: "dogs"
    }]
  }
})

permitted = params.permit(person: [ :name, { pets: :name } ])
permitted.permitted?                    # => true
permitted[:person][:name]               # => "Francesco"
permitted[:person][:age]                # => nil
permitted[:person][:pets][0][:name]     # => "Purplish"
permitted[:person][:pets][0][:category] # => nil

you can check the documentation on this here


text:
Q: Rails Render Layout Using File Not In Views/Layout to Support a Theme Is it possible to use a layout file that is not in views/layout?
I would like users to be able to upload a theme which has a layout file and be able to use the uploaded and parsed file as their layout.
Is that possible?

A: Don't do it!
You will open a big security hole, including XSS, arbitrary code execution & private information disclosure.