text:
Q: How can I use a ComplexPanel with a GWT ActivityManager I'm trying to modify the GWT 2.1 HelloMVP example code to use a more complex UI. (I'm not allowed to provide the link due to a two link limit)
My problem is that ActivityManager.setDisplay only accepts objects that implement AcceptsOneWidget. LayoutPanel and other ComplexPanel's don't implement AcceptsOneWidget. The example code uses a SimplePanel instead. But I can't seem to nest complex Widgets within the SimplePanel (they don't display).
I've found a few discussions on this problem:
http://www.google.com/url?sa=D&q=https://stackoverflow.com/questions/5143196/is-there-a-acceptsonewidget-which-also-providesresze-other-than-scrollpanel%3Fanswertab%3Dactive%23tab-top
http://www.google.com/url?sa=D&q=http://www.tempura.org/rants/2010/10/using-layoutpanels-with-gwt-2-1s-activitymanager/
People suggest the solution is to create a subclass of the ComplexPanel I want that implements the AcceptsOneWidget interface. Like so:
public class PanelForView extends LayoutPanel implements AcceptsOneWidget {
     IsWidget myWidget = null;

    @Override
     public void setWidget(IsWidget w) {
         if (myWidget != w)  {
             if (myWidget != null) {
                 remove(myWidget);
             }

            if (w != null) {
                 add(w);
             }

            myWidget = w;
         }
     }
}

This sounds great but it doesn't seem to work for me. Perhaps because I'm using GWT 2.3 instead of 2.1 or 2.2. In my EntryPoint I expect to simply replace the SimplePanel with my new PanelForView class and have the app run as before. Like so:
public class HelloMVP implements EntryPoint {
    private Place defaultPlace = new HelloPlace("World!");
//  private SimplePanel appWidget = new SimplePanel(); // Replace this with PanelForView
    private PanelForView appWidget = new PanelForView(); // This compiles but doesn't work.
//  private SimpleLayoutPanel appWidget = new SimpleLayoutPanel(); // This doesn't work either.

    public void onModuleLoad() {
        // Create ClientFactory using deferred binding so we can replace with different
        // impls in gwt.xml
        ClientFactory clientFactory = GWT.create(ClientFactory.class);
        EventBus eventBus = clientFactory.getEventBus();
        PlaceController placeController = clientFactory.getPlaceController();

        // Start ActivityManager for the main widget with our ActivityMapper
        ActivityMapper activityMapper = new AppActivityMapper(clientFactory);
        ActivityManager activityManager = new ActivityManager(activityMapper, eventBus);
        activityManager.setDisplay(appWidget);

        // Start PlaceHistoryHandler with our PlaceHistoryMapper
        AppPlaceHistoryMapper historyMapper= GWT.create(AppPlaceHistoryMapper.class);
        PlaceHistoryHandler historyHandler = new PlaceHistoryHandler(historyMapper);
        historyHandler.register(placeController, eventBus, defaultPlace);

        RootPanel.get().add(appWidget);
        // Goes to place represented on URL or default place
        historyHandler.handleCurrentHistory();
    }
}

This compiles fine but when I run it, I see nothing but a blank screen now. Is there something extra I have to do to initialize a ComplexPanel? Am I just misunderstanding something? I've tried adding Widgets and calling setSize to no avail. This is my first GWT project.
Thanks for your time.
Corey

A: You should be able to easily use a SimplePanel (or Composite subclass the implement AcceptsOneWidget). The best way to do this is to Think about the containing widget. You can add a: HTMLPanel, FlowPanel, VerticalPanel, etc into the one widget area of SimplePanel.
However, once you do this, you are bending the intended use of ActivityMapper/AcceptsOneWidget/SimplePanel
You can either create a more complex ui by:
Adding another ActivityMapper (with a different UI region - SimplePanel - which should change from Place to Place) or Adding a Widget area (that doesn't change from Place to Place)
or*
Have your Activity control the more complex view (keep the ActivityMapper.setDisplay widget a SimplePanel - but then have the Activity set an HTMLPanel, VerticalPanel, etc)
A very popular implementation is to keep a SimplePanel as the content area for the ActivityMapper. Then use UiBinder (with HTMLPanel as the top level element)
We can call the UiBinder: "view" and it can have many regions
view.getTopArea() - SimplePanel, view.getLeft() - FlowPanel, view.getNameArea - Anchor/InlineHTML

All of these different elements are wrapped into view which can be a Composite
and then, in your
activity.start(AcceptsOneWidget panel){
 panel.setWidget(view);//insert your complex view into the SimplePanel view
  ...
}

A: Ok, so when I was having this problem I was just experimenting with the very simple UI that comes with the sample app.
I also tried keeping the SimplePanel and having the Activity return a HeaderPanel consisting of a label and an image (the second method mentioned in Ashton's Answer). I thought this didn't work. And I saw comments in blogs and forums that seemed to indicate this doesn't work. But once I started actually building up the UI  with a DockPanel and nested TabPanel, etc., all of the sudden everything started displaying properly. I don't know why. It was probably a bug in my code I suppose. But I'm on my way now. I don't care to go back and diagnose exactly what went wrong.  :)
Thanks for the advice guys!
Corey

A: Use RootLayoutPanel instead of RootPanel


text:
Q: How to check if a button was pressed My goal is to populate the client area of my window with a bunch of different child controls. Things like buttons check boxes and static text but I'm having a difficult time figuring out how to catch the button clicked message.
My Code:
#include <windows.h>
#include <CommCtrl.h>
#include "resource.h"

HMENU        BUTTON1;

LRESULT CALLBACK WndProc (HWND hwnd, UINT message, UINT wParam, LONG lParam) ;

int WINAPI WinMain (HINSTANCE hInstance, HINSTANCE hPrevInstance,
                    LPSTR lpszCmdParam, int nCmdShow)
     {
     static char szAppName[] = "Keyboarding" ;
     HWND        hwnd;
     MSG         msg;
     WNDCLASS    wndclass;
     HMENU       hMenu;

     hMenu = LoadMenu(hInstance, MAKEINTRESOURCE(IDR_MENU1));

     if (!hPrevInstance)
          {
          wndclass.style         = CS_HREDRAW | CS_VREDRAW;
          wndclass.lpfnWndProc   = WndProc;
          wndclass.cbClsExtra    = 0;
          wndclass.cbWndExtra    = 0;
          wndclass.hInstance     = hInstance ;
          wndclass.hIcon         = LoadIcon (NULL, IDI_APPLICATION) ;
          wndclass.hCursor       = LoadCursor (NULL, IDC_ARROW) ;
          wndclass.hbrBackground = static_cast<HBRUSH>(GetStockObject (WHITE_BRUSH));
          wndclass.lpszMenuName  = NULL ;
          wndclass.lpszClassName = szAppName ;

          RegisterClass (&wndclass) ;
      }

     hwnd = CreateWindow (szAppName,         // window class name
                    "Lab 6",   // window caption
                    WS_OVERLAPPEDWINDOW,     // window style
                    CW_USEDEFAULT,           // initial x position
                    CW_USEDEFAULT,           // initial y position
                    CW_USEDEFAULT,
                    CW_USEDEFAULT,                // hmmmmm???
                    NULL,                    // parent window handle
                    hMenu,                    // window menu handle
                    hInstance,               // program instance handle
                  NULL) ;              // creation parameters

     HWND button1 = CreateWindow( WC_BUTTON,
                         "Push Button",
                         WS_TABSTOP|WS_VISIBLE|WS_CHILD|BS_PUSHBUTTON,
                         50,
                         50,
                         100,
                         24,
                         hwnd,
                         BUTTON1,
                         hInstance,
                         NULL);

     HWND button2 = CreateWindow( WC_BUTTON,
                         "Auto Check Button?",
                         WS_TABSTOP|WS_VISIBLE|WS_CHILD|BS_PUSHBUTTON,
                         50,
                         50,
                         100,
                         24,
                         hwnd,
                         NULL,
                         hInstance,
                         NULL);

     HWND button3 = CreateWindow( WC_BUTTON,
                         "Push Button",
                         WS_TABSTOP|WS_VISIBLE|WS_CHILD|BS_PUSHBUTTON,
                         50,
                         50,
                         100,
                         24,
                         hwnd,
                         NULL,
                         hInstance,
                         NULL);

     HWND editControl = CreateWindow( WC_BUTTON,
                         "Push Button",
                         WS_TABSTOP|WS_VISIBLE|WS_CHILD|BS_PUSHBUTTON,
                         50,
                         50,
                         100,
                         24,
                         hwnd,
                         NULL,
                         hInstance,
                         NULL);

     HWND StaticControl = CreateWindow( WC_STATIC,
                         "Hello World",
                         WS_TABSTOP|WS_VISIBLE|WS_CHILD|BS_PUSHBUTTON,
                         50,
                         100,
                         100,
                         24,
                         hwnd,
                         NULL,
                         hInstance,
                         NULL);

     HWND ListBox = CreateWindow( WC_BUTTON,
                         "Push Button",
                         WS_TABSTOP|WS_VISIBLE|WS_CHILD|BS_PUSHBUTTON,
                         50,
                         50,
                         100,
                         24,
                         hwnd,
                         NULL,
                         hInstance,
                         NULL);

     ShowWindow (hwnd, nCmdShow) ;
     UpdateWindow (hwnd) ;

     while (GetMessage (&msg, NULL, 0, 0))
          {
            TranslateMessage (&msg) ;
            DispatchMessage (&msg) ;
          }
     return (int) msg.wParam ;
     }

LRESULT CALLBACK WndProc (HWND hwnd, UINT message, UINT wParam,
                            LONG lParam)
     {
     HDC         hdc ;
     PAINTSTRUCT ps ;
     TEXTMETRIC  tm;
     RECT        rClientRect;
     RECT        rWindowRect;
     SIZE        size;
     int        cButtons = 0;

     switch (message)
          {

     case WM_COMMAND:
         switch(LOWORD(wParam))
         {
         case BUTTON1:
             break;
         }

          case WM_PAINT:
                hdc = BeginPaint (hwnd, &ps) ;

                EndPaint (hwnd, &ps) ;
                return 0 ;

          case WM_DESTROY:
                PostQuitMessage (0) ;
                return 0 ;
          }

     return DefWindowProc (hwnd, message, wParam, lParam) ;
     }

I'm trying to catch my first button labaled button1 and has the "ID" BUTTON1. I have tried just catching them in my WM_COMMAND and it says my BUTTON1 is unidentified.

A: What you are looking for is:
case WM_COMMAND:
    switch(LOWORD(wParam)) {
         case BUTTON1: {

But before it will recognize BUTTON1 you will have to declare it in such a way that it can be recognized by the message handler: for example make it a global variable, instead of declaring it in the WinMain:
HMENU       BUTTON1;

int WINAPI WinMaietcetc..

Let me know if this works !

redpajama_set_name: RedPajamaStackExchange


text:
Q: DELETE V1/addresses/:addressId - This Rest API is not working with Customer Token delete /V1/addresses/{addressId}

This is the Delete Address REST API in Magento 2.
It works with admin tokens, but not with customer tokens.
I think it should be working with custom tokens as customers should have the right to delete their own addresses stored.
This API has access permission for Resource: Magento_Customer::manage
This resource permission should be working with customer token, isn't it?
Does anybody have the same issue?

A: Customer token CANNOT access customerAddressRepositoryV1 so your API doesn't work on customer token. This is how swagger looks after inserting a customer token:

If customer wants to modify/delete customer address, we can use PUT /V1/customer/me. Although it doesn't list on swagger(Confirmed: it's a bug), it tested and successful on my 2.1.7 EE + POSTMAN. Here is a sample JSON for using PUT /V1/customer/me:
{
  "customer": {
    "email": "your_email",
    "firstname": "your_firstname",
    "lastname": "your_lastname",
    "website_id": 1,
    "addresses": [

    ],
    ...
   }
}

Of course, you have to add token on header.


text:
Q: jQuery UI Touch Punch and dynamically loaded content jQuery UI Touch Punch works perfectly if content was loaded in DOM before loading this library.
After loading content dynamically into the DOM (like HTML-tags <select> and <input>) these tags are not responding anymore on touch-events.
(can be simulated in Chrome)
Dragging elements on touch devices is still working fine

Suggestions are very welcome. Thanks


text:
Q: Azure WebApp to WebApp call - Can we make it private? We are deploying kind of micros services developed in .Net core and will be deployed in Azure WebApp
There will be numerous communications between these WebApps.
Now as WebApp is internet facing, all calls between them will go through internet which will have impact on performance.
Apart from ASE (App Service Enviornment), is there any way we can achieve this?

A: Yes you can do that with Access Restriction:
az webapp config access-restriction add --resource-group ResourceGroup --name AppName \
   --rule-name 'IP example rule' --action Allow --ip-address 122.133.144.0/24 --priority 100

https://learn.microsoft.com/en-us/azure/app-service/app-service-ip-restrictions#adding-and-editing-access-restriction-rules-in-the-portal
ps. AKS would probably be a better option for microservices ;)

A: There are two ways to have communication over private IP between two web app.

*

*Configure regional VNET integration on either or both web app.

*Think of having Azure Application gateway before web app one and configure access restriction to allow access to only application gateway subnet.
https://learn.microsoft.com/en-us/azure/app-service/app-service-ip-restrictions#set-a-service-endpoint-based-rule
Some other use cases

*

*Use Service fabric if you don't want to expose web application to internet.

*You can also think of putting both application as backend to API management.
https://learn.microsoft.com/en-us/azure/api-management/api-management-using-with-internal-vnet?tabs=stv2#routing
whenever you have application gateway enabled that time app gateway act as interceptor and forwards the traffic hence both of your web app can communicate over a private IP.


text:
Q: Writing to a mounted Windows share I am using Ubunutu 20.04 and I am trying to write to a mounted Windows share.  This is the command I am using to mount the share:
sudo mount.cifs //192.168.1.5/tv /mnt/tv -o username=xxxxxxxxxx,password=xxxxxxxxx,file_mode=0777,dir_mode=0777
I am able to view the contents of the Windows share in Ubuntu:
darren@homeserver:~$ ls -l /mnt/tv/
total 0
drwxrwxrwx 2 root root 0 Jun 30 15:33 '$RECYCLE.BIN'
drwxrwxrwx 2 root root 0 Jan  1  2019  MSOCache
drwxrwxrwx 2 root root 0 Apr 28 00:38 'Plex dance'
drwxrwxrwx 2 root root 0 Dec 30  2019 'System Volume Information'
drwxrwxrwx 2 root root 0 Jun 24 15:37 'TV Shows'
-rwxrwxrwx 1 root root 0 Jan  1  2019  desktop.ini

But if I try to create a test file i get this error:
 [ Error writing lock file /mnt/tv/.test.swp: Permission denied ]

I have the Windows share permissions set to "Everyone":

Any thoughts?

A: Try this configuration:
-fstype=cifs,credentials=<fileWithCred>,vers=3.0,dir_mode=0777,file_mode=0777,noserverino ://<IP-Winshare>/Path


text:
Q: Is accessing mapped device memory slow (in terms of latency)? I know the question is vague.. but here is what I hope to learn: the MCU directs some part of memory address to devices on the PCI bus, hence in theory user/kernel code can directly read/write device memory as if it were  main memory. But data in and out of PCI Express devices are packaged/serialized/transmitted in lanes, which means each read/write incurs significant overhead, such as packaging (add headers) and un-packaging. So that means it is not ideal for user/kernel to read device memory a byte at a time, instead it should do some sort of bulk transfer. If so, what is the preferred mechanism and API?
BTW, I know there is DMA, but it seems to me that DMA does not require device memory to be directly mapped into main memory address space - DMA is about letting device access main memory, and my question is the other way, letting user/kernel access device memory. So I am guessing it is not related to the question above, is that correct?

A: Yes, accessing memory-mapped I/O (MMIO) is slow.
The primary reason that it is slow is that it is typically uncacheable,
so every access has to go all the way to the device.
In x86 systems, which I am most familiar with, cacheable memory is accessed in 64-byte chunks,
even though processor instructions typically access memory in 1, 2, 4, or 8 byte chunks.
If multiple processor instructions access adjacent cacheable memory locations, all but the first access are satisfied from the cache. For similar accesses to device memory, every access incurs the full latency to the device and back.
The second reason is that the path from the processors to memory are critical to performance and are highly optimized.
The path to devices has always been slow, so software is designed to compensate for that, and optimizing the performance of MMIO isn't a priority.
Another related reason is that PCI has ordering rules that require accesses to be buffered and processed in a strict order.
The memory system can handle ordering in a much more flexible way. For example, a dirty cache line may be written to memory at any convenient time. MMIO accesses must be performed precisely in the order that they are executed by the CPU.
The best way to do bulk transfer of data to a device is to have the device itself perform DMA, "pulling" the data from memory into the device, rather than "pushing" it from the CPU to the device. (This also reduces the load on the CPU, freeing it to do other useful work.)


text:
Q: Live data HTML parsing with Python/BS I have scoured these pages for days without success, so I am hoping this is not a duplicate. If so I apologize.
I have a device on a local network that provides a data read out in HTML that is updated live. So far my BeautifulSoup and URLLIB2 attempts at parsing this data has been unsuccessful.
Any help would be appreciated.
This is the source code, with the data of interested encircled:

This if the resultant output:

from bs4 import BeautifulSoup
import re
import urllib2
from urllib import urlopen
url = 'http://192.168.1.2/index.html#home-view'
#___________________________________________________________________
usock = urllib2.urlopen(url)
data = usock.read()
usock.close()
soup = BeautifulSoup(data, "html.parser")
result = soup.findAll('p', {'class':'gas-conc'})
print result

SOLVED!: Thank you for the assistance. With Selenium I was able to painfully scrape out this data. However I had to use the BS 'beautify' function on the source code and manually count out which characters to splice out.

A: I'm 90% sure that you wouldn't get these data unless you managed to render Javascript somehow.
Check out this post for more info in how to make that happens.
In a nutshell, you can use:

*

*selenium

*PyQt5

*Dryscrape


text:
Q: Python Pandas: Find the maximum for each row in a dataframe column containing a numpy array I got a Pandas DataFrame looking like the following:
      values                                      max_val_idx
0    np.array([-0.649626, -0.662434, -0.611351])            2
1    np.array([-0.994942, -0.990448, -1.01574])             1
2    np.array([-1.012, -1.01034, -1.02732])                 0

df['values'] contains numpy arrays of a fixed length of 3 elements
df['max_val_idx] contains the index of the maximum value of the corresponding array
Since the index of the maximum element for each array is already given, what is the most efficient way to extract the maximum for each entry?
I know the data is stored somewhat silly, but I didn't create it myself. And since I got a bunch of data to process (+- 50GB, as several hundreds of pickled databases stored in a similar way), I'd like to know what is the most time efficient method.
So far I tried to loop over each element of df['max_val_idx] and use it as an index for each array found in df['values']:
max_val = []
for idx, values in enumerate(df['values']):
     max_val.append(values[int(df['max_val_idx'].iloc[idx])])

Is there any faster alternative to this?

A: I would just forget the 'max_val_idx' column.  I don't think it saves time and actually is more of a pain for syntax.  Sample data:
df = pd.DataFrame({ 'x': range(3) }).applymap( lambda x: np.random.randn(3) )

                                                   x
0  [-1.17106202376, -1.61211460669, 0.0198122724315]
1    [0.806819945736, 1.49139051675, -0.21434675401]
2  [-0.427272615966, 0.0939459129359, 0.496474566...

You could extract the max like this:
df.applymap( lambda x: x.max() )

          x
0  0.019812
1  1.491391
2  0.496475

But generally speaking, life is easier if you have one number per cell.  If each cell has an array of length 3, you could rearrange like this:
for i, v in enumerate(list('abc')): df[v] = df.x.map( lambda x: x[i] )
df = df[list('abc')]

          a         b         c
0 -1.171062 -1.612115  0.019812
1  0.806820  1.491391 -0.214347
2 -0.427273  0.093946  0.496475

And then do a standard pandas operation:
df.apply( max, axis=1 )

          x
0  0.019812
1  1.491391
2  0.496475

Admittedly, this is not much easier than above, but overall the data will be much easier to work with in this form.

A: I don't know how the speed of this will compare, since I'm constructing a 2D matrix of all the rows, but here's a possible solution:
>>> np.choose(df['max_val_idx'], np.array(df['values'].tolist()).T)
0   -0.611351
1   -0.990448
2   -1.012000


text:
Q: getting the check if twitch stream is live I have been working with java to make it where i check if a certain user if live and it will say true or false if the user is streaming...im working with minimal json.
here is my code
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;

import com.eclipsesource.json.JsonObject;

public class hostbot {

public static void main(String[] args) throws Exception {

    Twitchbot bot = new Twitchbot();
    bot.setVerbose(true);
    bot.connect("irc.twitch.tv", 6667, "something");
 }
 public boolean isStreamLive()
   {
     try
         {
           URL url = new        URL("https://api.twitch.tv/kraken/streams/rexephon");
           URLConnection conn = url.openConnection();
           BufferedReader br = new BufferedReader( new InputStreamReader( conn.getInputStream() ));
           String inputLine = br.readLine();
           br.close();
           JsonObject jsonObj = JsonObject.readFrom(inputLine);
           return ( jsonObj.get("stream").isNull() )?false:true;
          }
          catch (IOException e)
          {
          e.printStackTrace();
          }
    return false;
}
}

when i return false is that suppose to print in the log the word false? or something else?


text:
Q: ruby/rails - creating an inverted tree from active record find I have been playing around with this and wanted to get a second opinion.
Here is the problem -
I want to order these results by who the person reports to (i.e. there boss)
---
- !ruby/object:History
 attributes:
  id: 1392
  job_title: Global Leader
  reports_to:
  attributes_cache: {}

- !ruby/object:History
 attributes:
  id: 1393
  job_title: Programme Organiser
  reports_to: 1392
  attributes_cache: {}

- !ruby/object:History
 attributes:
  id: 1394
  job_title: Programme Lead
  reports_to: 1393
  attributes_cache: {}

they will be outputted in json so will look like this
{id: 1394, some_attributes, children: {id: 1393, some_attributes, children: { etc }}

I wrote this function but it started to look really bad
 candidates.each do |candidate, index|
  if !candidate.reports_to.present?
    structure << candidate
    candidates.to_a.delete_if {|candidate_inst| candidate_inst == candidate}
    candidates.each do |child|
      if child.reports_to == candidate.candidate_id
        # add child to children of parent
      end
    end
 end

There must be a cleaner way of doing this ??
Thanks, Alex

A: maybe you can achieve same goal using Enumerable#group_by, see docs
candidates.group_by(&:reports_to)


text:
Q: Cascading Encryption with Multiple Keys AES is symmetric encryption, so if I encrypt using key1, I can always decrypt using key1. If I encrypt using key2, I can always decrypt using key2.
I want to apply this encryption multiple times with multiple keys to strengthen it. I want to encrypt my cipher first using key1, then encrypt the result using key2, and then the result using key3, and so on. As illustrated below:

*

*cipher -> enc with key1 -> enc with key2 -> enc with key3 -> result

In order to decrypt the result, I have to decrypt in reverse:

*

*result -> dec with key3 -> dec with key2 -> dec with key1 -> cipher

My question is, does there exist a key that represents the product of key1, key2 and key3, so that it will decrypt the result in one pass? Meaning, can an attacker simply find a key4 that would short-circuit my scheme?

*

*result -> dec with key4 -> cipher

A: Currently there is no such thing for AES, nor is it likely that there will be. This would only be possible if the AES algorithm would be seriously flawed.
This does not mean you cannot find a concrete sample where such a key might exists (still very unlikely), but there is no process to extract a combined key out of multiple others.

A: CryptoLib (https://github.com/IcyApril/CryptoLib) supports cascading (layered) encryption using different encryption ciphers; it uses 1 key, but that undergoes PBKDF2 hashing at each encryption level (with SOHA alternations between Whirlpool and SHA512). This will protect you in case one cipher is broken, the others still stand in it's place, in order to call it, you simply do this (replacing path/to with where you put CryptoLib):
<?php
  require_once('path/to/cryptolib.php');
  $encryptedString = CryptoLib::encryptData("Test string.", "password");
  $decryptedString = CryptoLib::decryptData($encryptedString, 'password');
?>

To directly answer the initial question, building on this: In order to use three separate keys (in a cascading fashion) with CryptoLib you can just call the encrypt function three times.
<?php
  require_once('path/to/cryptolib.php');
  $encryptedString = CryptoLib::encryptData("Test string.", "password1");
  $encryptedString = CryptoLib::encryptData($encryptedString, "password2");
  $encryptedString = CryptoLib::encryptData($encryptedString, "password3");
?>

And to decrypt the string, call the decrypt function 3 times in reverse:
<?php
  require_once('path/to/cryptolib.php');
  $decryptedString = CryptoLib::decryptData($encryptedString, "password3");
  $decryptedString = CryptoLib::decryptData($decryptedString, "password2");
  $decryptedString = CryptoLib::decryptData($decryptedString, "password1");
?>

CryptoLib source is on GitHub at: https://cryptolib.ju.je/ and documentation site is https://cryptolib.ju.je.

A: Due to meet-in-the-middle attack, the security of triple encryption is O(2^256) for AES-128.
This attack was found when 3-DES designed.
AES, actually, designed with different key size for future development of attacks and possible hardware improvements except Quantum Computing. AES by designs has 128, 192 and 256 bits. AES-256 will be faster than 3-AES-128 with the same security.


text:
Q: angular 4 FileReader onloadend not getting called on IE11 I am trying to read data from an excel file. The following code w stopped working on IE11, I don't know why? When I put the console logs, I see onloadend is not getting triggered. Please let me know any ways to fix this.
private myReader: FileReader = new FileReader();
changeListener($event): void {
    readThis($event.target);
  }

readThis(inputValue: any): void {
    const file: File = inputValue.files[0];
 public test: String[] = [];
if (fileType === 'xlsx') {
      console.log(this.myReader);
      this.myReader.onloadend = (e) => {
        /* read workbook */
        const bstr: string = this.myReader.result;
        const wb: XLSX.WorkBook = XLSX.read(bstr, { type: 'binary' });
        /* grab first sheet */
        const wsname: string = wb.SheetNames[0];
        const ws: XLSX.WorkSheet = wb.Sheets[wsname];
          this.data = XLSX.utils.sheet_to_json(ws, { header: 1 });
          this.data.forEach(eachline => {
             if (eachline[0] !== undefined) {
              test.push(eachline[0]) ;
            }
            }
          });
      };
      this.myReader.readAsBinaryString(file);
    }
}


text:
Q: Depending on the OS, define different methods Although Python doesn't have the C pre-processor, I wonder, what's a way to declare methods and variables depending on the OS?
Something like:
class C1:

#if defined(WINDOWS)
        self.var1 = 1

        def method1(....):
            pass

#elif defined(LINUX)
        self.var2 = 1

        def method2(....):
            pass

#endif

My question isn't how to detect the platform only. But how to define different methods and variables depending on it also.

A: You can detect the current platform as follows
import platform
platform.system()

The output for me is
'Linux'


text:
Q: lightweight publish/subscribe framework in java Is there a good lightweight framework for java that provides the publish/subscribe pattern?
Some ideal features

*

*Support for generics

*Registration of multiple subscribers to a publisher

*API primarily interfaces and some useful implementations

*purely in-memory, persistence and transaction guarantees not required.

I know about JMS but that is overkill for my need. The publish/subscribed data are the result of scans of a file system, with scan results being fed to another component for processing, which are then processed before being fed to another and so on.
EDIT:
All within the same process. PropertyChangeListener from beans doesn't quite cut it, since it's reporting changes on properties, rather than publishing specific items. I could shoehorn ProprtyChangeListener to work by having a "last published object" property, and so published objects. PropertyChangeListeners don't support generics, and are entrenched in property change semantics, rather than pure publish/subscribe. The java.util Observer/Observable pattern would be good, but Oberver is a concrete class.

A: Since you're using Spring, I don't know if you're aware that Spring has its own lightweight event framework. It's used primarily within the framework itself, but it's perfectly usable by application code.
By default, it's synchronous pub/sub, but you can make it asynchronous using an ApplicationEventMulticaster.

A: It seems this fits the requirements:
EventBus from Google Guava Library - "Publish-subscribe-style communication between components without requiring the components to explicitly register with one another". It can also be an AsyncEventBus that will dispatch events on another thread.
Some extra options to consider:

*

*If it's in same process it's possible the Observer pattern can be used. Subscribers can add listeners and receive event notifications. Observable is already part of the Java API.

*FFMQ is a full Java, light-weight, Fast JMS 1.1 Queue implementation.

A: JMS is as light or heavy as you configure it. We use for example HornetQ in one project with an in memory queue. It is easy to setup, doesn't need any JNDI based configuration and is really easy to use.
I believe that JMS as an API for Message Pub/Sub is as easy as it gets. (And not easier ;)

A: I think Camel is also a good candidate. Especially with the publish-subscribe pattern
Camel can be embedded and is lightweight. It proposes Enterprise Integration Patterns - many useful tools for integration, inside an application or even with other actors (hence 'Integration').
It compares to Spring Integration but more complete IMO.

A: If you are crossing process boundaries then some degree of "weight" is going to be incurred. Why do you say that JMS is heavyweight? The API is quite simple? There are supposedly light-weight implementations, for example link text heavier costs such a persistence and transactionality are optional.
What do you need that is lighter than this?

A: Bob Lee has a QueueFile class at http://snipt.org/GWm/ that you might find interesting. It's a simple persistent queue and could be used by multiple consumers. It sounds like you don't need persistence, but since the whole thing is so lightweight it could still be useful.


text:
Q: relationship between rows in sql table i'm wondering if there is a way to relate between rows in the same table.
for example: i want to store a keywords in the database and make every single keyword points to others which are related to it. (instead of creating a table to every single keyword and add related keywords to it)
if not, hope anyone can suggest an idea to store keyword and relate between them with minimum size.
Thanks,


text:
Q: Logging into a site that has ReCaptcha I am making an android application, trying to log in a site with POST requests. The problem is site is not mine and it has ReCaptcha on login form.
I tried implementing android SafetyNet API, made a verify request using the site's own site-key but normally, the site ReCaptcha key type is not set to 'reCaptcha Android' and thus it returns the error RECAPTCHA_INVALID_KEYTYPE so I can't verify myself using android SafetyNet API.
I was wondering if there is any other way to verify the captcha site serves.

A: I created a WebView component and loaded the page that has captcha in it. Then I get the site-key from the existing captcha, deleted all components in the page and rendered a new ReCaptcha element using javascript.
When the user verifies captcha, I log the verified token to WebView console to be used in a further login POST request in my application. I get the token by overriding the onConsoleMessage method on WebChromeClient.
    // assuming theres a webview component with id 'webview'
    final WebView webView = findViewById(R.id.webview);
    webView.getSettings().setJavaScriptEnabled(true);
    webView.setBackgroundColor(Color.TRANSPARENT);
    webView.setVisibility(View.GONE);
    webView.setWebViewClient(new WebViewClient()
    {
        @Override
        public void onPageFinished(WebView view, String url)
        {
            super.onPageFinished(view, url);

            webView.loadUrl("javascript: if($('div.g-recaptcha').length)" +
                    "{" +
                    "var sitekey = $('div.g-recaptcha').attr('data-sitekey');" + // getting the site-key from existing recaptcha element
                    "$('body > *').remove(); " + // deleting all content of the page
                    "$('body').append('

'); " + // a div to draw new recaptcha
                    "grecaptcha.render('captcha', {\n" + // render the new recaptcha element in 'captcha' div
                    "    'sitekey' : sitekey,\n" +
                    "    'callback' : function(response){console.log('captchatoken:'+response)},\n" + // log the token on callback
                    "});" +
                    "$('body').css('background-color','transparent');" + // for aesthetic purposes
                    "}");
            webView.setVisibility(View.VISIBLE); // show the webview now since captcha is ready
        }
    });
    webView.setWebChromeClient(new WebChromeClient()
    {
        @Override
        public boolean onConsoleMessage(ConsoleMessage consoleMessage)
        {
            String message = consoleMessage.message();
            if (message.startsWith("captchatoken:"))
            {
                String token = message.substring(13); // removing 'captchatoken:' part from console message
                // now this token can be used in a POST request for logging in
            }
            return super.onConsoleMessage(consoleMessage);
        }
    });
    webView.loadUrl(url_that_has_captcha);
}

Here's how it looks like in action:

A: The whole reason reCaptcha exists is to prevent automated systems from crawling or interacting with systems. So in this case, unfortunately for you, it is succeeding by stopping you from logging in to the website using an android app.
You should not try to bypass this because it could be against the website's TOS, and could get you into some legal trouble. Instead, seek a public API that the website provides to do whatever you need to do.
Also, making a verify request using the site's own site key will generally not work because reCaptcha only accepts requests for your key on specific domains.
As far as I know, there is no reliable way of bypassing the captcha. That is why the captcha is widely trusted and used by many big corporations.


text:
Q: Issue with jquery tablesorter and {sorter: false} Seem to be having an issue with the tablesorter plugin and excluding columns for sorting. In the documentation: http://tablesorter.com/docs/example-meta-headers.html you can add a class to the th (class="{sorter: false}") so sorting is disabled on that column. This does not seem to work and also his example on that page does not work. If you inspect the source you can see that the class is specified on 2 columns but they are still sortable.
I know this used to work as I have a project which uses it and it works. I am however using an older version of jquery in that project so that is probably the issue. Maybe the meta-data is not compatible with the latest version of jquery?
Is anyone else having this issue?
Thanks.

A: Hmm, I'm not sure why the metadata isn't registering - I have a working demo here
But I wanted to add that I ended up adding a fork of the tablesorter plugin on github. I've also made it so you can just use a class name instead of relying on metadata, like this class="sorter-false" - here is the demo.

A: The issue is that there is a 404 error for file "http://tablesorter.com/jquery.metadata.js"
just fix this and it will work.


text:
Q: Installing and maintaining email server Until now, I've been using managed shared hosting, but recently I've been seriously considering moving everything to a VPS, such as Linode. The one thing that has me really hesitating is that I  must have a externally accessible email service as well. I've done a bit of research and I have no problem installing Postfix/Dovecot/Exim (plus clamav and spamassassin). But it worries me that it may be a lot more difficult to install and maintain than I expected. The only thing that seems to make this difficult is that I have four or five domains, each with their own email addresses that I want to carry over to the new setup, and I want all client traffic to be encrypted.
So how difficult is it to get an email server up and running, that's accessible via external email clients (SMTP and POP3 -- no IMAP), works with SSL/TLS, and supports multiple domains?


text:
Q: What are the default precision and scale for floating point types in EF core 6? I am receiving the following warning:

No store type was specified for the decimal property 'PurchasePrice' on entity type 'ProductStatisticsKeylessEntity'. This will cause values to be silently truncated if they do not fit in the default precision and scale. Explicitly specify the SQL server column type that can accommodate all the values in 'OnModelCreating' using 'HasColumnType', specify precision and scale using 'HasPrecision', or configure a value converter using 'HasConversion'.

(emphasis mine)
I know how to set a precision and scale, but I want to know the EF default values - what exactly are the default precision and scale for decimal, float or double?
Perhaps the default values are good enough and i can set the precision/scale to the same values to hide the errors.

A: I'm not aware of any official documentation on default precision and scale mappings of C# decimal to SQL Server decimal. The quickest way is just to try.
The source code (see the initialization of the _clrTypeMappings field) reveals that decimals are mapped by default to decimal(18,2), as they have always been in Entity Framework.
Both float and double only have precision (and exponent, but no scale), so the question doesn't really apply here. But for these types it matters to which SQL Serer types they are mapped, because the definitions on both sides differ confusingly.
If we let EF generate a table from this class...
public class Num
{
    public int Id { get; set; }
    public decimal Dec { get; set; }
    public float Float { get; set; }
    public double Double { get; set; }
}

... we get this:
CREATE TABLE [dbo].[Nums](
    [Id] [int] IDENTITY(1,1) NOT NULL,
    [Dec] [decimal](18, 2) NOT NULL,
    [Float] [real] NOT NULL,
    [Double] [float] NOT NULL,
 CONSTRAINT [PK_Nums] PRIMARY KEY CLUSTERED ([Id]))

So the default mappings from CLR to SQL Server types are:

*

*decimal to decimal(18,2)

*float to real

*double to float
Note that for float (CLR) this isn't really a default, it is the only mapping that makes sense. For double it is a default because the precision of double can be cut down by mapping instructions like:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<Num>().Property(e => e.Double).HasPrecision(24);
}

In this case the Double property will mapped to a real in SQL Server because it has the storage size of a real.

A: Please take a look, here are new changes in .NET 6.
https://learn.microsoft.com/en-us/ef/core/modeling/entity-properties?tabs=data-annotations%2Cwithout-nrt

The Data Annotation for configuring precision and scale was introduced in EF Core 6.0.

You can set like this:
[Precision(14, 2)]
public decimal Score { get; set; }


text:
Q: Kotlin - Validating URL with custom URL scheme In my app, I can have web URL starting with "https://" or "http://" or URL with custom scheme starting with "custom://" or "testing://".
I tried using URLUtil.isValidUrl(), but this returns true only if URL starts with http or https.
How can I validate the URL with custom scheme in android?

A: If i understand right, you just need to validate if the syntaxe is right, right ?
I did an sample here to validate URLs using Regex
val regex = "([A-Za-z]*:\\/\\/)?\\S*".toRegex()

fun isValidUrl(url: String): Boolean {
    return regex.containsMatchIn(url)
}


text:
Q: Is saying each pt of a topo. manifold has nbhd homeomorphic to R^n the same thing as saying there is a local coordinate system at each point? Is saying each point of a topological manifold has a neighborhood homeomorphic to $\Bbb{R}^{n}$ the same thing as saying there is a local coordinate system at each point?
I'm not really sure what I mean by coordinate system. It's just a term I have heard used. If someone could define that at the same time that would be awesome.

A: Yes. This is true by definition:
A topological space $M$ is said to be locally Euclidean of dimension $n$ if each point $x \in M$ has a neighbourhood $U$ homeomorphic to an open subset $V$ of $\mathbb{R}^n$. A homeomorphism of this sort is by definition a coordinate chart.

A: I believe you mean that each point has a neighborhood homeomorphic to $\mathbb{R}^n$.  A local coordinate system about a point is basically a choice of homeomorphism from a neighborhood of that point to $\mathbb{R}^n$.

A: generally when imposing coordinate systems there is the additional condition that they are compatible. Thus if two neighbourhood's intersect then the intersection the associated two homeomorphisms yield a map between two subsets of $R^n.$ This map must also be a homeomorphism for a coordinate system.


text:
Q: why are system calls handled using interrupts? I have a basic question about the linux system call.
Why are the  system calls not handled just like normal function calls and why is handled via software interrupts?
Is it because, there is no linking process performed for user space application with kernel during the build process of user application?

A: Linking between separately compiled pieces of code is a minor problem. Shared libraries have had a workaround for it for quite some time (relocatable code, export tables, etc). You pay the cost typically just once, when you load the library in the program.
The bigger problem is that you need to switch the CPU from the unprivileged, user mode into the privileged, kernel mode and you need to do it in a controllable way, without letting user code escape and wreck a havoc on the kernel. And that's typically done with special or designated instructions. You may also benefit from automatic interrupt disabling when transitioning into the kernel, which the x86 int instruction can do for you. Most CPUs have something like this instruction and it's a common way of implementing the system call interface, although not the only one.
If you asked about MS-DOS or the original MINIX, both of which ran on the i8086 in the real address mode, where the kernel couldn't protect itself or other programs from anything because all the memory and system resources were accessible to all code, then there would be less reason in using a special instruction like int, there were no two modes, only one, and in that respect int would be largely equivalent to a simple call (far).
Also noteworthy is the fact that CPUs often handle the following 3 types of events in a very similar fashion:

*

*hardware interrupts from I/O devices

*exceptions, errors from code execution (e.g. division by 0, page faults, etc)

*system calls

That makes using something like the int instruction a natural choice as your entry and exit points in all of the above handlers would be if not fully then largely identical.


text:
Q: multiple tables need one to many relationship I have a SQL database with multiple tables: A, B, C, D. Entities in those tables are quite different things, with different columns, and different kind of relations between them.
However, they all share one little thing: the need for a comment system which, in this case, would have an identical structure: author_id, date, content, etc.
I wonder which strategy would be the best for this schema to have A,..D tables use a comment system. In a classical 'blog' web site I would use a one-to-many relationship with a post_id inside the 'comments' table.
Here it looks like I need an A_comments, B_comments, etc tables to handle this problem, which looks a little bit weird.
Is there a better way?

A: I had a similar "problem" with comments for more different object types (e.g. articles and shops in my case, each type has it's own table).
What I did: in my comments table I have two columns that manage the linking:

*

*object_type (ENUM type) that determines the object/table we are linking to, and

*object_id (unsigned integer type that matches the primary key of your other tables (or the biggest of them)) that point to the exact row in the particular table.

The column structure is then: id, object_type, object_id, author_id, date, content, etc.
Important thing here is to have an index on both of the columns, (object_type, object_id), to make indexing fast.

A: I presume that you are talking of a single comments table with a foreign key to "exactly one of" A, B, C or D.
The fact that SQL cannot handle this is one of its fundamental weaknesses.  The question gets asked over and over and over again.
See, e.g.
What is the best way to enforce a 'subset' relationship with integrity constraints
Your constraint is a "foreign key" from your "single comments" table into a view, which is the union of the identifiers in A, B, C and D.  SQL supports only foreign keys into base tables.
Observe that SQL as a language does have support for your situation, in the form of CREATE ASSERTION.  I know of no SQL products that support that statement, however.
EDIT
You should also keep in mind that with a 'single' comments table, you might need to enforce disjointness between the keys in A,B,C and D, for otherwise it might happen some time that a comment automatically gets "shared" between entity occurrences from different tables, which might not be desirable.

A: Create a comment table with a comment_id primary key and the various attributes of a comment.
Additionally, create A_comment thus:
CREATE TABLE A_comment (
    comment_id PRIMARY KEY REFERENCES comment(comment_id),
    A_id REFERENCES A(A_id)
)

Do likewise for B, C and D. This ensures referential integrity between comment and all the other tables, which you can't do if you store the ids to A, B, C and D directly in comment.
Declaring A_comment.comment_id as the primary key ensures that a comment can only belong to one entry in A. It doesn't prevent a comment from belonging to an entry in A and an entry in B, but there's only so much you can achieve with foreign keys; this would require database-level constraints, which no database I know of supports.
This design also doesn't prevent orphaned comments, but I can't think of any way to prevent this in SQL, except, of course, to do the very thing you wanted to avoid: create multiple comment tables.

A: You could have a single comments table and within that table have a column that contains a value differentiating which table the comment belongs to - ie a 1 in that column means it's a comment for table A, 2 for table B, and so on.  If you didn't want to have "magic numbers" in the comments table, you could have another table that has just two columns: one with the number and another detailing which table the number represents.

A: You don't need a separate comment table for every other, one is enough. Every comment will have a unique ID, so you don't have to worry about conflicts.


text: Q: When can the commutator of two matrices be neglected in series expansions? Under what conditions can the higher order commutators in the Baker–Campbell–Hausdorff formula be neglected when the commutators does not vanish exactly and there is no small parameter in the matrices? Is it when the determinant of the commutator is negligible for example?


text:
Q: problema con alcance d e variables estoy haciendo un programa con tkinter  y python , la cual el usuario ingrese sus datos y  guarde sus datos para posterior mente ser guardados en una lista , despues a la base  datos que todavía no esta activa  y no tiene nada que ver  por el momento con este codigo .
el codigo es el siguiente .
from tkinter import*
import sqlite3

ventana=Tk()
conexion = sqlite3.connect("base_registro")
cursor=conexion.cursor()

#-----------------FUNCIONES----------------------
usuario =[]
def crear():
    global nombre_usuario
    nombre_usuario = entrada_nombre.get()
    global apellido_usuario
    apellido_usuario= entrada_apellido.get()
    global direccion_usuario
    direccion_usuario = entrada_direccion.get()
    global contraseña_usuario
    contraseña_usuario = entrada_contraseña.get()
 #usuario.extend([direccion_usuario,contraseña_usuario])
print(nombre_usuario)
def actualizar():
    pass

def  leer(self):
    pass

def eliminar():
    pass

def enviar():
    pass

#--------------------------------------------------
nombre=Label(ventana,text="NOMBRE")
nombre.grid(row=1,column=0 )

entrada_nombre=Entry(ventana)
entrada_nombre.grid(row=1,column=1 )
#--------------------------------------------------
apellido=Label(ventana,text="APELLIDO")
apellido.grid(row=2,column=0 )

entrada_apellido=Entry(ventana)
entrada_apellido.grid(row=2,column=1 )
#--------------------------------------------------
direccion=Label(ventana,text="DIRECCION ")
direccion.grid(row=3,column=0 )

entrada_direccion=Entry(ventana)
entrada_direccion.grid(row=3,column=1 )

#--------------------------------------------------
contraseña=Label(ventana,text="CONTRASEÑA")
contraseña.grid(row=4,column=0 )

entrada_contraseña=Entry(ventana)
entrada_contraseña.grid(row=4,column=1 )

#----------------BOTONES--------------
crear=Button(ventana,text="crear", command=crear)
crear.grid(row=5,column=0)

#--------------------------------
leer=Button(ventana,text="leer")
leer.grid(row=5,column=1)

#--------------------------------
actualizar=Button(ventana,text="actualizar")
actualizar.grid(row=5,column=2,pady=2, padx=1)

#--------------------------------
eliminar=Button(ventana,text="eliminar")
eliminar.grid(row=5,column=3)

#--------------------CODIGO SQL -------------------

"""
usuario =[nombre,apellido,direccion,contraseña,correo]

cursor.executemany("INSERT INTO PRODUCTOS VALUES(?,?,?,?) ",usuario)

"""
#----------------------PRUEBAS-------------------

enviar=Button(ventana,text="enviar",command=enviar)
enviar.grid(row=6)
conexion.close()
ventana.mainloop()

pero al momento de guardar la información de en una lista:
usuario =[]
def crear():
    global nombre_usuario
    nombre_usuario = entrada_nombre.get()
    global apellido_usuario
    apellido_usuario= entrada_apellido.get()
    global direccion_usuario
    direccion_usuario = entrada_direccion.get()
    global contraseña_usuario
    contraseña_usuario = entrada_contraseña.get()
usuario.extend([direccion_usuario,contraseña_usuario])

me da el siguiente error:
usuario.extend([direccion_usuario,contraseña_usuario])
NameError: name 'direccion_usuario' is not defined
[Finished in 1.3s]

cuando ya le indique al programa que las variables son globales y las llame en el buton en la parte de tkinter  , por otro lado el get es la forma d eobtencion de datos a penas el usuario pulse el boton crear se activara la funcion y capturar alos datos

A: el problema fue solucionado pero no borro la pregunta para enseñar a otra personas que les pase lo mismo
la solucion fue la siguiente:
el problema era  que el orden de orden de ejecución ya que al tener la lista dentro de la ventana de tkinter funcionaba como un scope local pero si se hacia fuera de `ventana.mainloop() se convertia en una variable global
INCORRECTO
print(usuario)
ventana.mainloop()

NameError: name 'nombre_usuario' is not defined

correcto
ventana.mainloop()
print(usuario)
[Finished in 6.9s]

`


text:
Q: Jsoup getting background image path from css I am looking for all of the images on a given website.
For this purpose i need to find the ones that are within the css for example:
   .gk-crop {
    background-image: url("../images/style1/g_rss-2.png");
}

Now my question is how can i get all of these urls with JSoup?
so far ive tried the following:
    Document doc = Jsoup.connect(url).get();
    Elements imagePath = doc.select("[src]");
    imagePath.select("*[style*='background-image']");

but so far no luck.
Does anyone know how i can acheive it?

A: Jsoup  doesn't parse css files.
Have a look at this to know what Jsoup is responsible for.
You need a separate css parser to extract url from css files. Have a look at this

A: Just like Niranjan mentioned, Jsoup is not for parsing CSS but XML. If you really need to extract some images from CSS, you will need to use some some 3rd party library for that purpose OR write simple regex for grabbing URLs from CSS file - its still plain text isn't it? This is not flexible resolution to your problem, but it would be the fastest one:)

A: If you want to select the URL's of all the images on a website you can select all the image tags and then get the absolute URL's.
Example:
String html = "http://www.bbc.co.uk";
Document doc = Jsoup.connect(html).get();

Elements titles = doc.select("img");

for (Element e : titles) {
    System.out.println(e.absUrl("src"));
}

which will grab all the <img> elements and present it, such as
http://sa.bbc.co.uk/bbc/bbc/s?name=SET-COUNTER&pal_route=index&ml_name=barlesque&app_type=web&language=en-GB&ml_version=0.16.1&pal_webapp=wwhp&blq_s=3.5&blq_r=3.5&blq_v=default-worldwide
http://static.bbci.co.uk/frameworks/barlesque/2.50.2/desktop/3.5/img/blq-blocks_grey_alpha.png
http://static.bbci.co.uk/frameworks/barlesque/2.50.2/desktop/3.5/img/blq-search_grey_alpha.png
http://news.bbcimg.co.uk/media/images/69139000/jpg/_69139104_69139103.jpg
http://news.bbcimg.co.uk/media/images/69134000/jpg/_69134575_waynerooney1.jpg

If you only want the .JPG files, tell the selector that by including
Elements titles = doc.select("img[src$=.jpg]");

which result in only parsing the .JPG-urls.


text:
Q: Why Scoped service in Blazor server App will not create new instance to each device? I use core 6 and initiate a class named DAL as a scoped service in blazor server app.
Instead of creating new DAL instance to each connected device it uses the same instance to all of the devices.
I tested it in debug mode and it actually hit the services.AddScoped<DAL>(); line only once.
Any ideas ?
Thanks
Startup.cs
 [Obsolete]
public void ConfigureServices(IServiceCollection services)
{
    //This command is for API route
    services.AddMvc(setupAction: Options => Options.EnableEndpointRouting = false).SetCompatibilityVersion(CompatibilityVersion.Version_3_0);
    services.AddRazorPages();
    services.AddServerSideBlazor();
    services.AddSingleton<WeatherForecastService>();
    services.AddSingleton<HttpClient>();
    services.AddScoped<DAL>();
    services.AddBlazoredSessionStorage();

}

_Host.cshtml
 <app>
    <component type="typeof(App)" render-mode="Server" />
</app>

A: As per @enet's comments - I don't believe this.
The simplest way of testing this is is to assign a GUID to each instance of DAL.
Here's my Blazor Server version.
using System.Diagnostics;

public class DAL
{
    public Guid Id { get; } = Guid.NewGuid();

    //....

    public DAL()
    {
        Debug.WriteLine($"DAL Service Id created {Id.ToString()}");
    }
}

As expected I get a new Id for each browser window opened, which is the same as each device!

A: Thanks guys, I found the problem.
It was related to my DAL class architecture and how I used it in my razor pages.


text:
Q: HealtKit: how to determine original unit HKQuantitySample was stored in? If I am accessing a user's weight (or any other HKQuantitySample), how can I determine what unit the user originally stored the weight in?

A: HealthKit does not expose the original unit that was used when the sample was saved.  However, if you'd like to display the quantity in the unit that the user prefers for samples of that type I'd recommend checking out the documentation for the preferredUnitsForQuantityTypes:completion: method on HKHealthStore.


text:
Q: Show that $f(x+t)= f(x)$ Let $a, b \in R$ ($a<b$) and let $f: [a,b] \longrightarrow R$
a continuous function s.t. $f(a) = f(b)$.
I need to show that there exist $\delta > 0 \in R$ s.t.
$\forall t \in [0, \delta]    \exists x \in [a,b-t]$ that $f(x+t)= f(x)$
What I've done:  $f$ is continuous in the closed and bounded interval $[a,b]$, then $f$ must attain a maximum and a minimum so if the maximum is in the edges then we're done because $ f(a) = f(b)$. Otherwise it has to be within the interval. I want to take a $ \delta$ around the maximum and show that $f(x+t)= f(x)$ using the Intermediate value theorem.
Can you help me formalize it?
Thanks in advance!

A: Let's suppose that $f$ is not constant so that it attains a global min or max in the interior (the result is trivial for constant $f$). Let us assume without loss of generality that there is a global maximum $f(x_0)=M$.
I claim that $\delta = \min\{x_0-a,b-x_0\}$. For fixed $0 \le t \le \delta$, let us define the function
$$g(s) = f(x_0+s) - f(x_0-t+s),$$
for $0 \le s \le t$. Notice that $g$ is well defined since
$$a \le x_0 + s \le x_0 + t \le x_0 + \delta \le b,$$
and likewise
$$a \le x_0 - \delta \le x_0 - t \le x_0-t+s \le x_0 \le b.$$
When $s=0$, we have
$$g(0) = f(x_0) - f(x_0 - t) \ge 0,$$
since $f(x_0) = M$ is the global maximum. Likewise, when $s=t$, we have
$$g(t) = f(x_0+t) - f(x_0) \le 0.$$
If ether inequality is an equality, then we have found a point $x_t$ such that $f(x_t) = f(x_t+t)$, namely $x_t=x_0$ or $x_t=x_0-t$.
So suppose both inequalities are strict. Then by the intermediate value theorem, there must exist some $s_0$ for which $g(s_0) = 0$. Then our required point is $x_t=x_0+s_0-t$, for which
$$g(s_0) = f(x_0+s_0) - f(x_0-t+s_0) = f(x_t + t) - f(x_t) = 0.$$
In either case, we have found our required $x_t$. Since we have done for this every $t\in [0,\delta]$, this completes the required proof.


text:
Q: Binance search API returns 403 when using with google scripts I'm using the binance API to get the prices of usdt. The API works on postman but it doesn't work on google script.
function fetchCryptoPricesFromApi() {
  const data = {
    "page": 1,
    "rows": 10,
    "payTypes": [],
    "asset": "USDT",
    "tradeType": "SELL",
    "fiat": "LKR",
    "publisherType": null,
    "transAmount": "2600"
  }

  const payload = JSON.stringify(data)

  const options = {
    "method" : "POST",
    "contentType" : "application/json",
    "payload" : payload
  }

  let response;

  try {
    response = UrlFetchApp.fetch('https://p2p.binance.com/bapi/c2c/v2/friendly/c2c/adv/search', options);
  } catch (error) {
    console.log('Oops Error, ', error);
    return
  }

  const prices = JSON.parse(response)['data'];
  console.log(prices)
}

I get the following error when executing this,
Oops Error,  { [Exception: Request failed for https://p2p.binance.com returned code 403. Truncated server response: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<HTML><HEAD><META HTTP-EQUIV="Content-Type" ... (use muteHttpExceptions option to examine full response)] name: 'Exception' }

I tried waiting some time as well.

A: From your showing error message, I confirmed the status code 403. Ref In this case, it is considered that the site cannot be directly accessed from the Google side. I think that the reason for your issue is due to this.
In this case, as a workaround, I would like to propose access to the URL without directly running the script with the script editor. When I tested this workaround, I confirmed that the value could be returned.
In this workaround, the following flow is used.

*

*Put the custom function of =fetchCryptoPricesFromApi() to a cell.

*Retrieve the values from the API.

*Retrieve the values from the cell.

*Parse the value as JSON data.

The sample script of this workaround is as follows.
Sample script:
In this workaround, I use Google Spreadsheet. So please create a new Google Spreadsheet and open the script editor of Google Spreadsheet. And, copy and paste the following script. And, run main() function with the script editor.
function fetchCryptoPricesFromApi() {
  const data = {
    "page": 1,
    "rows": 10,
    "payTypes": [],
    "asset": "USDT",
    "tradeType": "SELL",
    "fiat": "LKR",
    "publisherType": null,
    "transAmount": "2600"
  }
  const payload = JSON.stringify(data)
  const options = {
    "method": "POST",
    "contentType": "application/json",
    "payload": payload
  }
  const response = UrlFetchApp.fetch('https://p2p.binance.com/bapi/c2c/v2/friendly/c2c/adv/search', options);
  return response.getContentText();
}

// Please run this function.
function main() {
  const sheet = SpreadsheetApp.getActiveSheet();
  const range = sheet.getRange("A1");
  range.setFormula("=fetchCryptoPricesFromApi()");
  SpreadsheetApp.flush();
  const value = range.getValue();
  range.clearContent();
  const prices = JSON.parse(value)['data'];
  console.log(prices)
}


text:
Q: Proper way around lengthy onPaint event in C# winforms? I am currently working on a C# winforms graphing application. To get right to the point, the Paint event handler for my graphing control has to plot thousands of points which can take several seconds. During this time the application is frozen. My goal is the following: if the user changed what data to be plotted while the older data is being plotted then it would stop in the middle of drawing the older data and start drawing the new the data. What is the proper way to do this or is this something else I am total missing? I tried to make my question as clear as possible.

A: The answer to you question lies in double buffering. You don't need to know all the details about double buffering to use it. Simply set the property to true like below to enable it within a control.
 MyGraphPanelControl.DoubleBuffered = true;

The obvious draw back is memory usage but it will greatly increase the "speed" of things drawn on the panel. Like a lot of things in Computer Science, you trade memory for speed and visa versa.
Also, reading this from Microsoft will give you more insight in how to use Double Buffering.


text:
Q: .Net Core Web Application remote shared Layout or partial view I'm making an Intranet application which will have multiple web apps managed in separate projects. There will however be common layout code such as the Intranet header/menu/footer etc.
In a single application this is done easily with the Layout page but how do I manage that in multiple applications?
I've considered pointing the _ViewStart at a remote location but that appears to only search paths local to the project.
Partial views again want local paths.
Previously I've seen this completed using a web service injecting html into the page which could possibly done using the middleware.
Am I going about this the right way or is there another solution?


text:
Q: Deleted "Resources" Column and now site gives error I've deleted the Resource column in my calendar list and now, when I have Use this calendar to share member's schedule checked YES, I get an error:

Unable to retrieve 'Resource' field from the current list (Events)

I want to share this calendar, so I need to have that option checked YES, but I'm not sure how to bring back the Resource column. I should have hide it, but I didn't think my page would have blown up like this.
Does anyone know why this happens?
More importantly, is there a way to fix this without wiping out my list?

A: Add the Reservations content type by clicking Add from existing site content types. Then you should be able to click Use this calendar to share member's schedule?


text:
Q: NodeJS Redis Client Returning Wrong Value I'm using the NodeJS Redis client (Node Redis) and calling the SISMEMBER Redis command. However, when I call the command it always returns true, no matter whether or not the value is a member of the set.
I am using this in conjunction with the Node IRC module. I am at a loss for why the Redis call is returning the wrong value. I have tried isolating just the Redis code (without the surrounding code) and it works fine. Code follows, thank you for the help.
This does not work
var redis = require("redis");
var redisClient = redis.createClient();

ircClient.addListener('join', function(channel, who) {
    console.log(redisClient.sismember('visitedUsers', 'awdwf'));
    console.log(who + ' connected');
});

This works, however
var redis = require("redis");
var redisClient = redis.createClient();

console.log(redisClient.sismember('visitedUsers', 'awdwf'));

A: redis methods are all asynchronous. The return values are just booleans indicating whether any more commands should be issued for the time being (depending on if the command queue size exceeds the high water mark -- this is similar to node's stream.write() returning false).
Try something like this:
client.sismember('visitedUsers', 'awdwf', function(err, reply) {
  if (err) throw err;
  console.log(reply);
});


text:
Q: Php Cannot Read Node Value in Xml I cannot able to read  node.I want to read the USER_ID node value.When i am trying to read with simplexml_load_string.
I am unable to read the node value.
This is my xml code :
<?xml version="1.0" encoding="utf-16" standalone="yes"?>
<RESULT>
<SUCCESS>1</SUCCESS>
<ERRMESSAGE />
<REMARKS />
<DATA>
  <data>
    <USERS>
      <U>
        <USER_ID>1</USER_ID>
      </U>
  </data>
</DATA>
</RESULT>

A: Your xml file is not valid. Change encoding of xml document to utf-8.
Then just access like normal object:
$xmlfile = file_get_contents('test.xml');
$array = simplexml_load_string($xmlfile);

echo "<pre>";
print_r($arr->DATA->data->USERS->U->USER_ID);
echo "</pre>";


text:
Q: IOS: problem with a label I want to create a label with "ComicSans" font but it don't work, why?
I write my label and when I go to change its font, it don't change...

A: These are the fonts that are supported on iPad & iPhone. "ComicSans" is not a part of it. Maybe you need to select something else...

A: First of all you will need .ttf files of all fonts.
Search for fontlabel... link


text:
Q: Call MVC method from Controller Full Path I have an issue because I do not know how to call a specific method inside a Controller that is far away on the foler structure. I try to call it this way from my View
@Html.Action("Method", "DesiredControllerName", parameter)
I am pretty sure this works, because I am calling other methods from controllers this way. The only problem is that this time I need to reach a controller that is way up in a different folder, i.e.
The controller is in:
MySolution/Areas/Area1/Controllers/DesiredControllerName
Whereas the CurrentView Im making the call is in:
MySolution/Areas/Area2/Views/Client/CurrentView
How can I make the call work?
Thanks!
EDIT:
I found it,
As the controller is in another Area I just had to add it as a parameter
The controller for path was not found or does not implement IController

A: looks like you maybe got it, where your example code line:
@Html.Action("Method", "DesiredControllerName", parameter)

has the 'parameter' parameter, try using an array of anonymously typed routevalues and include an area and controller, something like this:
@Html.Action("Method", new { Area = "Area1", Controller =
    "DesiredControllerName", })

I am used to using this style of providing mvc routing info using Html.ActionLink, but the Html.Action should be similar-ish.  here is the msdn page for the Action method, hope that helps

A: @Html.Action("Method", "DesiredControllerName", new { Area = "Area1" })

This will works


text:
Q: Monitor and scale Docker-based Celery workers cluster on AWS so I have a docker image that runs a celery worker via supervisor and works just fine on single-docker Elastic Beanstalk (pretty long tasks, so acks late = true, concurrency = 1 and prefetch multiplier = 1).
The trouble is I would like to scale instances depending on the effective task load of the workers, while EB only allows overall network and CPU load.
Adding a rule to scale up on CPU load works ok, but I have no guarantee that EB wouldn't decide to scale down whilst in the middle of a task. That would trigger a docker stop and effectively kill any running celery that is not able to complete quite shortly (10s if I'm not mistaken).
Ideally I would need a monitor based on both CPU activity and tasks in the queue, in pseudo code something like:
while check interval has passed
  if task queue is empty (or workers are not busy)
    if running instances is greater than 1
      scale down 1 instance
  else
    if CPU load is higher than threshold
      scale up 1 instance

now the problem is that this level of logic doesn't seem achievable in EB, more likely to run on ECS but I am not sure of the following:

*

*what kind of celery monitor should we implement and where should the code run? e.g. the usual celery worker monitor commands don't seem to be a good solution to monitor how busy a worker is and we need to handle the additional complexity of running a worker in docker

*where should the cluster scaling function run? after a chat with an AWS engineer, seems that AWS Lambda could be a potential solution but hooking cluster instances load reports to lambda snippets seems quite complicated and hard to maintain

*as a bonus question, in case we need to migrate to ECS, we will also need to rewrite our deploy scripts to manually trigger a version swap, as this is currently managed by EB. what would be the best way to do so?

any help appreciated, thanks!

A: You can take advantage of AWS elastic beanstalk service where you just need to provide docker image. It also comes with the dashboard where you can provide your environment variable or scale your application/worker based on CPU/requests/memory etc.
You already made docker image of your celery worker. So, instead of scaling on CPU or memory. You can scale your instance based on a number of tasks in the queue. You can put scaling constraint yourself.
following are different ways you can count celery tasks inside the queue.
Pick up your option to put a watch on the task queue.
Using pika:
import pika

pika_conn_params = pika.ConnectionParameters(
    host='localhost', port=5672,
    credentials=pika.credentials.PlainCredentials('guest', 'guest'),
)
connection = pika.BlockingConnection(pika_conn_params)
channel = connection.channel()
queue = channel.queue_declare(
    queue="your_queue", durable=True,
    exclusive=False, auto_delete=False
)

print(queue.method.message_count)

Using PyRabbit:
from pyrabbit.api import Client
cl = Client('localhost:55672', 'guest', 'guest')
cl.get_messages('example_vhost', 'example_queue')[0]['message_count']

Using HTTP
Syntax:
curl -i -u user:password http://localhost:15672/api/queues/vhost/queue

Example:
curl -i -u guest:guest http://localhost:15672/api/queues/%2f/celery

Note: Default vhost is / which needs to be escaped as %2f
Using CLI:
$ sudo rabbitmqctl list_queues | grep 'my_queue'

Now, Based on the option you choose(CLI or Python), you can apply following solution to scale your celery worker. The common thing between the two logic is both need to run continuously.
If you choose CLI. You can create a script which will monitor the number of tasks continuously and apply scaling logic if it is more than the provided limit. If you are using the kubernetes that it would be very easy to scale your Deployments. Otherwise, You will need to follow approach your system required.
With python, You can follow the same path but the only advantage is it can work as service in future if logic gets too complicated in future.


text:
Q: Difficulty understanding recursion puzzle I am trying to print the steps leading to the answer but not getting anywhere. Please refer to this image:

I am able to check if the given problem is solvable or not:
bool Solvable(int a[], int index, int target, int sz, int b[]) {
    static int b_ind = 0;
    if (target == 0 && index == sz-1)
        return true;
    if (index >= sz || index < 0)
        return false;
    int u_ind = index+a[index];
    int d_ind = index-a[index];
    bool u_y = Solvable(a,u_ind,a[u_ind],sz,b);
    if (u_y) {
        b[b_ind++] = u_ind;
        return u_y; }
    else {
        bool d_y = Solvable(a,d_ind,a[d_ind],sz,b);
        if (d_y) {
            b[b_ind++] = d_ind;
            return d_y; }
    }
}

but am not able to print the sequence of indexes visited for a correct solution.

A: 2 things to do :

*

*When your criterion is reached eg if (target == 0 && index == sz-1), display the b variable. b  is where your store the explored path right ?

*when Solvable(...) returns false you must decrement b_ind
NB: your code is a bit suspicious since the last if does not have any else ; this is missing :
        if (d_y) {
            b[b_ind++] = d_ind;
            return d_y;
        } /* the following block is missing */
        else
        {
            b_ind--;
            return false;
        }

A: You cannot print the indices on your way because you don't know in advance whether you will find a solution or not. So what you have to do is, in your recursive calls, pass on a list (the "path") of positions visited. Make sure you don't change existing paths but you actually create copies.
Also, you might want to go on searching after having found a first solution, sometimes there's more than one.
A catch is that you might loop forever depending on the input puzzle. That's why it's actually beneficial to have the path because it allows you to detect loops.
In executable pseudo-code (they call it Python) it's something like:
def puzzle(lst):
    def solve(pos, path):
        if 0 <= pos < length:   # position is inside puzzle
            if pos not in path: # we've already been here; prevent looping
                val = lst[pos]
                newpath = path + [pos] # newpath is a *copy* of path with pos appended
                if val == 0:    # we've found one solution
                    print(newpath)
                else:
                    solve(pos-val, newpath)
                    solve(pos+val, newpath)
    length = len(lst)
    solve(0, [])

puzzle([3, 6, 4, 1, 3, 4, 2, 5, 3, 0])

For your example this yields:
[0, 3, 2, 6, 8, 5, 9]
[0, 3, 4, 1, 7, 2, 6, 8, 5, 9]
[0, 3, 4, 7, 2, 6, 8, 5, 9]


text:
Q: Elements in View Controller Disappear When Clicking or Tapping Them I am developing an app on XCode using Swift 2 and have run into an error with my UI. I have placed a UILabel, UITextView, and UITextField on the View Controller of interest.
Before inputting the UITextField, everything worked fine. I inserted the text field and assigned the proper constraints and when simulating the app, clicking on the text field will cause all of the UI elements to disappear or the alpha to go instantaneously to zero (I'm not sure which of the two is actually happening).
I'm not receiving any feedback via the console and the app itself does not crash.
Here is my code:
//Declare the following UI objects to be manipulated
@IBOutlet weak var labelOneTitle: UILabel!
@IBOutlet weak var textDescription: UITextView!

@IBOutlet weak var fieldInput: UITextField!

override func viewDidLayoutSubviews() {

    //Set UI object alphas to zero prior to loading the view
    labelOneTitle.alpha = 0
    textDescription.alpha = 0
    fieldInput.alpha = 0

}
override func viewDidLoad() {
    super.viewDidLoad()

    // Do any additional setup after loading the view.
}

override func viewDidAppear(animated: Bool) {

    UIView.animateWithDuration(2) { () -> Void in
        self.labelOneTitle.alpha = 1
    }
    UIView.animateWithDuration(3) { () -> Void in
        self.textDescription.alpha = 1
    }
    UIView.animateWithDuration(3) { () -> Void in
        self.fieldInput.alpha = 1
    }

}

A: It might be the UIViewController.viewDidLayoutSubviews rechecking all the constraints and reconfiguring the view as per the the class reference:

When the bounds change for a view controller's view, the view adjusts the positions of its subviews and then the system calls this method. However, this method being called does not indicate that the individual layouts of the view's subviews have been adjusted. Each subview is responsible for adjusting its own layout.
Your view controller can override this method to make changes after
  the view lays out its subviews. The default implementation of this
  method does nothing.

When you click on the UITextField the keyboard appears (Probably) and thus recalling the method to set the alpha of all your UI Elements to 0.
If you'd move setting the alpha's to 0 to the viewDidLoad() than the problem might go away.


text:
Q: Problems building OpenSSL 1.1.0c for Android against NDK 15.2 When running build-openssl-libraries.sh, I come across following problems:
Warning when it runs ./Configure dist at line 48:
The library could not be configured for supporting multi-threaded
applications as the compiler options required on this system are not known.
See file INSTALL for details if you need multi-threading.

The options 'shared', 'pic' and 'dynamic-engine' aren't supported on this
platform, so we will pretend you gave the option 'no-pic', which also disables
'shared' and 'dynamic-engine'.  If you know how to implement shared libraries
or position independent code, please let us know (but please first make sure
you have tried with a current version of OpenSSL).

Error when it runs build/tools/make-standalone-toolchain.sh @line 75:
HOST_OS=darwin
HOST_EXE=
HOST_ARCH=x86_64
HOST_TAG=darwin-x86_64
HOST_NUM_CPUS=4
BUILD_NUM_CPUS=8
ERROR: Failed to create toolchain.

Because of this error subsequent compile of .c files fail saying stdlib.h not found.
Please help me to find out how I can build it successfully... On Android I would need multi-threaded support.

*

*What are the implications of ignoring the two ./Configure warnings

*How to get Make toolchain succeed?

I am running on macOS Sierra 10.12.6. This is part of building SQLCipher.

A: I have updated the build script for building OpenSSL using the Android NDK r15c for SQLCipher for Android here currently. Would you give that a try?

A: The two warnings disappeared when I changed the line "./Configure dist" to "./Configure android".
The make toolchain problem was because the parameters were passing android-9 while the NDK15 supports only from android-14. As someone has suggested, this was discovered by enabling --verbose for make-toolchain command.
Now the script compiles all .c files but facing problems during link (apps/openssl.o:openssl.c:function main: error: undefined reference to 'stpcpy'). Looks like again some problem with Configure or NDK config..
Writing as answer for anyone who may face the same issue..


text:
Q: How to insert two tables having same primary key? I have two tables say Table A and Table B. Both have same columns and column  'cid' has primary Key and it's auto_incremented.
Now i have to insert Table A into Table B but i need data of both tables into Table B.
How can i insert Table A into Table B ??

A: INSERT INTO TableB ("Column 1 of Table B", "column 2 of Table B", , ,etc) (SELECT "Column 1 of Table A", "column 2 of Table A", , ,etc FROM TableA)
The above query will insert the Values of Table A into Table B. Do not include the column cid in the column list(since it is auto-incremented).

A: I have resolved the issue by doing following thing, hope it may be useful to anyone too.
The cause of the problem is that the parent table and its corresponding backup table have same schema so whenever Restore process is took place it just encounter a problem due to same primary key on both tables.
Hence to overcome it, backup table has to be modified by using ALTER query. And in modification a  new column 'ID' is added to all backup tables using :
ALTER TABLE $backup_tbl_name ADD `id` BIGINT unsigned NOT NULL   AUTO_INCREMENT COMMENT 'Auto increment field for backup table.' PRIMARY KEY

and making this newly added column Primary key of backup table.
And at last INSERT query has to be modified as well as during insertion newly added column also has to be pass. And it modified as:
INSERT INTO $backup_tbl_name SELECT * , NULL FROM $tbl;


text:
Q: Is separate QA team, redundant in development life cycle? Background:

Developer is the best person to know/understand the dark corners after any development/enhancement of enterprise software, compared to QA technician.
Developer can assess the depth/breadth of production problems that can arise from such dark corners.

FOR Quality reasons(only) but not for cost cutting, my new employer does not maintain separate QA team and shifts the responsibility to developer(as better owner) to write/append/automate/validate test cases. So, all new test cases are append to existing test suite, as part of process.
My employer, manufacture network switches with their customised Linux based OS on switch.
At my workplace, the first rule that is followed in regression testing is to avoid regression testing. We avoid regression testing by testing any new testcase written for every feature, on every platform, for every release. If the test fails, then matches the log with database of known failures and points out some fingerprints.

Question:
1) Does separate QA team add any value in a software development life cycle?
2) Does it add value for a Quality product delivery, if QA team is formed that has ethical hacking skills? For software products that run on network

A: FrustratedWithFormsDesigner brings up one case where separate QA is useful - a complex system.
There is another case where separate QA may not only be useful, but mandatory - regulated environments. There is a notion of independent verification and validation. Independent means that it's done by a person or group of people who did not write the production code. In some environments (I have experience in aerospace and healthcare) and under some conditions, it is mandated that there is some level of independent verification and/or validation. In all of my experiences, the development team is responsible for some level of testing to ensure that garbage isn't turned over to the independent QA testers. In addition, the independent testing may be manual testing, automated testing, or a combination of both.
There's also the question as to what "separate QA" really means. Does it mean embedding QA staff onto each development team or does it mean having a handoff from a development team to a QA team. Independence can be achieved in both models.

A: I definitely like the points discussed by @FrustratedWithFormsDesigner, but I think it is useful to consider the larger universe of testing types when it comes to a complete software system. I am sure there will be differences of opinion on who should do what -- and I welcome discussion :-) -- but the figure below is a quick sketch representing my experience and opinions.
As you will observer, there is a lot of overlap as to who should test what. Developers should be responsible for delivering to QA a complete and correct product (or feature) by means not just of unit testing, but some measure of the other categories of testing noted. Those that I have marked as "secondary" should be considered by developers, but not as their primary responsibility. That's why you need dedicated QA people, people with expertise in those areas.
The business stakeholders add another level of validation, and though their participation in testing will vary widely from company to company, it is, after all, they who deliver an acceptable or unacceptable product to the customer.
A couple key takeaways from my chart:

*

*Unit testing is the sole domain of developers. QA folks with expertise in coding might want to peek at some of the internals but to help them with developing functional and other tests, not for unit testing.

*QA is responsible for the whole system synergy, already discussed by @FrustratedWithFormsDesigner.

*Security is everybody's business!

A: I would say that it depends on the system being developed and tested.
The developer might have the best understanding of the code, but that doesn't mean they fully understand all the business cases that the code is used for.
For example, consider a web application used by insurance brokers to manage and process policies and claims. There are many many rules and business cases that go into such a system. It's highly unlikely that any one developer will be able to know all of it in great depth. Heck, most business users probably won't know the whole system (although they will have a better business-level understanding of more of it than developers).
In this case, a separate QA team will have received special training on the business flows within the application. Chances are, they might not even be developers, they might be Business Analysts who have transitioned into QA due to their extensive experience. Or they might be developers who are more interested in the non-code-related facets of the system. They won't understand all of the technical details, and they won't need to. They will execute business cases that probably go beyond what the developers know or even need to know. Developer testing (usually done by developers locally on their own workstation, to ensure that their code works at more than just a basic level) and QA testing (done by QA teams to ensure larger sets of business cases are satisfied) are two distinct phases with different kinds of tests and expectations.
What value does this add? You have seasoned, experienced QA testers who have a very good high-level understanding of the system as a whole. They know how to test the system to ensure that all parts are properly covered, based on the changes made by the developer. And it frees up developer time from something that really is a full-time job and requires extensive business training. All of this can lead to fewer bugs making it to production and higher over-all quality, and happier customers (and that's the whole point, isn't it?).
In my experience, the larger/more complex the project is, the greater the value added by having a full QA team. On smaller systems with a single (or small handful of) developer and simpler use cases, the value added is not so great, and in some cases, having a separate QA team could be redundant (and costly) if the testing is simple enough for the developers to manage on their own.

A: Of course you have thoroughly tested yourself before handing over to QA. But the very fact that the developer is the most familiar with the application is the best reason to have someone ELSE test it.
The developer knows what the software is supposed to do, the way in which it is supposed to be used, etc., and it will be exceptional if he or she attempts to use it in the way a naïve user might, thus breaking it in unexpected ways. It will never be a black box to the one with the x-ray vision. Too often the developer is the the one the most removed from the real world use of all persons involved in the project.


text:
Q: R: Send text messages without the use of 3rd parties (or do it WITH your own number) I'm trying to use R to send text messages - without using platforms like Twilio or Plivo. Is there an easy way to do this in R?
The platforms mentioned above make it easy to send text messages, but you have to get verification of the phone numbers / pay for a new number / jump through several hoops. I don't mind paying a small amount, either, but I do want to use my own number. Here's the set up for Twilio:
Sys.setenv(TWILIO_SID = "xxxxxxx...")
Sys.setenv(TWILIO_TOKEN = "xxxxxxx...")

my_phone <- "xxxxxxxxxx" # personal phone number / or number you want to send messages to
twilios_phone <- "xxxxxxxxxx" # the number they give you

tw_send_message(from = twilios_phone, to = my_phone,
                body = "We the People of the United States, in Order to form a more perfect Union")

I can send messages to my own phone number, but I cannot send anything from my own number, which is the point of me asking this question.
The Plivo setup:
AUTH_ID = "xxxxx..."
AUTH_TOKEN = "xxxxxx......."

message <- "We the People of the United States, in Order to form a more perfect Union"

url = "https://api.plivo.com/v1/Account/xxxxxxx..../Message/"

POST(url, authenticate(AUTH_ID, AUTH_TOKEN),
     body = list(src = "xxxx..", dst = "xx....",
                 text = message))

Both super simple setups, but how can I send messages (free or not) from MY own number, and do it easily? (And yes, I'm doing this to learn/ spam my friends with the Constitution once a month - a worthy cause, I know).


text:
Q: Python: Ssl Certificate verify failed I have installed dvc on my ubuntu-18.04-LTS system and while trying to download the data files from github using dvc, it fails with below error.
$ dvc get https://github.com/iterative/dataset-registry get-started/data.xml -o data/data.xml -v

2022-07-22 12:55:22,260 DEBUG: Creating external repo https://github.com/iterative/dataset-registry@None
2022-07-22 12:55:22,260 DEBUG: erepo: git clone 'https://github.com/iterative/dataset-registry' to a temporary dir
2022-07-22 12:55:23,683 DEBUG: Removing '/dvc/dvc_test/data/.UEeAzwmJCY3q85YQuCeahx'
2022-07-22 12:55:23,684 ERROR: failed to get 'get-started/data.xml' from 'https://github.com/iterative/dataset-registry' - Failed to clone repo 'https://github.com/iterative/dataset-registry' to '/tmp/tmpvmrmu9qsdvc-clone'
------------------------------------------------------------
Traceback (most recent call last):
  File "urllib3/connectionpool.py", line 703, in urlopen
  File "urllib3/connectionpool.py", line 386, in _make_request
  File "urllib3/connectionpool.py", line 1042, in _validate_conn
  File "urllib3/connection.py", line 414, in connect
  File "urllib3/util/ssl_.py", line 449, in ssl_wrap_socket
  File "urllib3/util/ssl_.py", line 493, in _ssl_wrap_socket_impl
  File "ssl.py", line 500, in wrap_socket
  File "ssl.py", line 1040, in _create
  File "ssl.py", line 1309, in do_handshake
ssl.SSLCertVerificationError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1108)

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "dvc/scm.py", line 145, in clone
  File "scmrepo/git/__init__.py", line 143, in clone
  File "scmrepo/git/backend/dulwich/__init__.py", line 199, in clone
scmrepo.exceptions.CloneError: Failed to clone repo 'https://github.com/iterative/dataset-registry' to '/tmp/tmpvmrmu9qsdvc-clone'

Already our corporate proxy certificate has been installed and traffic to github.com allowed I'm able to clone above repository separately on CLI. But with dvcthe above errors are occurring, Even the below couldn't solve the issue.
$ python -c "import ssl; print(ssl.get_default_verify_paths())"

DefaultVerifyPaths(cafile=None, capath='/usr/lib/ssl/certs', openssl_cafile_env='SSL_CERT_FILE', openssl_cafile='/usr/lib/ssl/cert.pem', openssl_capath_env='SSL_CERT_DIR', openssl_capath='/usr/lib/ssl/certs')

export SSL_CERT_DIR=/etc/ssl/certs/
export REQUESTS_CA_BUNDLE=/usr/local/lib/python2.7/dist-packages/certifi/cacert.pem
pip install --upgrade certifi
export PYTHONHTTPSVERIFY=0

sudo apt install ca-certificates
sudo update-ca-certificates --fresh

$ python --version
Python 2.7.17

$ dvc doctor
DVC version: 2.13.0 (deb)
---------------------------------
Platform: Python 3.8.3 on Linux-5.4.0-92-generic-x86_64-with-glibc2.14
Supports:
        azure (adlfs = 2022.7.0, knack = 0.9.0, azure-identity = 1.10.0),
        gdrive (pydrive2 = 1.10.1),
        gs (gcsfs = 2022.5.0),
        hdfs (fsspec = 2022.5.0, pyarrow = 8.0.0),
        webhdfs (fsspec = 2022.5.0),
        http (aiohttp = 3.8.1, aiohttp-retry = 2.5.1),
        https (aiohttp = 3.8.1, aiohttp-retry = 2.5.1),
        s3 (s3fs = 2022.5.0, boto3 = 1.21.21),
        ssh (sshfs = 2022.6.0),
        oss (ossfs = 2021.8.0),
        webdav (webdav4 = 0.9.7),
        webdavs (webdav4 = 0.9.7)

Tp bypass the ssl validation in git we have git config http.sslVerify "false" Similarly do we have option in dvc?
Further what should i update to resolve this issue?

A: The Python environment you're applying fixes to is not the one DVC is using. Your Python version is 2.7.17, while DVC is using Python 3.8.3.
It looks like you installed the Debian Linux package; Please figure out what python binary that is using and fix the certs for that env.


text:
Q: Raspberry Pi 4: upgraded kernel is not selected in the next boot (Cross-posted from Raspberry Pi StackExchange)
My Raspberry Pi 4 was originally loaded with Ubuntu 21.04, but after yesterday's release of 21.10, I upgraded using the do-release-upgrade command.
Among the other upgraded packages, there was a new Linux kernel: prior to the upgrade, the kernel version was 5.11.0-1019-raspi, while a new version 5.13.0-1008-raspi was installed in the course of the upgrade.
After the requested reboot at the end of the upgrade process, I found out that kernel version 5.11.0-1019-raspi was still in use. I have attempted to reinstall modules such as linux-image-5.13.0-1008-raspi, linux-image-raspi linux-modules-5.13.0-1008-raspi and linux-raspi, as well as removing the old kernel version. I have confirmed that /boot/vmlinuz and /boot/firmware/vmlinuz point to the same file, and it is the one for version 5.13.0-1008-raspi. Furthermore, after removing the old version, even vmlinuz.old points to the new version, so I have no idea where the system is fetching the old version from. Note that there have been quite a few reboots in the process, even a physical one by removing the power cable.
Regardless of everything done above, the system still boots to 5.11.0-1019-raspi. I suspect there's a missing installation step that updates some kind of onboard memory on the Raspberry Pi.
Note that, ever since installing Ubuntu 21.04 in this board a few months ago, I've seen apt upgrade install new kernel versions -- I am made aware of this due to the need to recompile a custom kernel module. Thus, the upgrade has worked automatically in the past. I'm not sure why it's not working this time.
My question is: what do I need to do make the Raspberry Pi boot the new version of the kernel?
EDIT: as requested, these are the contents of /etc/default/grub:
# If you change this file, run 'update-grub' afterwards to update
# /boot/grub/grub.cfg.
# For full documentation of the options in this file, see:
#   info -f grub -n 'Simple configuration'

GRUB_DEFAULT=0
GRUB_TIMEOUT_STYLE=hidden
GRUB_TIMEOUT=0
GRUB_DISTRIBUTOR=`lsb_release -i -s 2> /dev/null || echo Debian`
GRUB_CMDLINE_LINUX_DEFAULT="quiet splash"
GRUB_CMDLINE_LINUX=""

# Uncomment to enable BadRAM filtering, modify to suit your needs
# This works with Linux (no patch required) and with any kernel that obtains
# the memory map information from GRUB (GNU Mach, kernel of FreeBSD ...)
#GRUB_BADRAM="0x01234567,0xfefefefe,0x89abcdef,0xefefefef"

# Uncomment to disable graphical terminal (grub-pc only)
#GRUB_TERMINAL=console

# The resolution used on graphical terminal
# note that you can use only modes which your graphic card supports via VBE
# you can see them in real GRUB with the command `vbeinfo'
#GRUB_GFXMODE=640x480

# Uncomment if you don't want GRUB to pass "root=UUID=xxx" parameter to Linux
#GRUB_DISABLE_LINUX_UUID=true

# Uncomment to disable generation of recovery mode menu entries
#GRUB_DISABLE_RECOVERY="true"

# Uncomment to get a beep at grub start
#GRUB_INIT_TUNE="480 440 1"

As for grub-editenv, which didn't even exist (I had to install the grub-common apt package), its output is empty. I may be wrong, but doesn't Raspberry Pi use its own boot system which sidesteps grub?

A: This command fixed it:
sudo flash-kernel 5.13.0-1008-raspi

I'm pretty sure I saw the same output in the course of my attempts described in the question, but anyway, it's fixed now.