text:
Q: How scrape multiple pages and differents items for each page? I'm beginner in python, just some weeks trying to do my webscrape.
I need to scrape multiple pages of one restaurant on tripadvisor, using beautifulsoup on windows32. In each page, I need to take restaurants name, socialclass and cuisines/dishes, client's name, date's review, titre's review and review.
I tryed  this code in a python console:
from urllib.request import urlopen as uReq
from bs4 import BeautifulSoup as soup

for i in range(260,1231):
    my_url = "https://www.tripadvisor.fr/Restaurant_Review-g187147-d6575305-Reviews-or260-Il_Etait_Un_Square-Paris_Ile_de_France.html".format(i)
    Inf_avis = uReq(my_url)
    page_html = Inf_avis.read()
    Inf_avis.close()
    page_soup = soup (page_html, "html.parser")
    restaurant = page_soup.findAll("div", {"id":"atf_header"})

and here Python doesn't paste (It seems blocked?...)the other code to take information about restaurant.
for rest_info in restaurant:
try:
    rest_name = restaurant.findAll("h1", {"class":"ui_header h1"})
    inf_rest_name = rest_name[0].text
    econ_class_food= restaurant.findAll("div, {"class":"header_links"})
    rest_eclf = econ_class_food[0].text
    print(inf_rest_name, rest_eclf)

What can I do?? can you help please??
I will appreciate all information you can give me.

A: I will give you some cheat sheet that will help you.

*

*I would propose to use some ready solution like Scrapy

*Try to avoid using synchronous http client like urllib or requests

*Check if the page that you try to load isn't required Js rendering, for example, it can be SPA or data store in <script> tag, or even Js makes AJAX requests, etc

*If the site does not work without Js - go to the developer console -> network -> XHR and reload your page. There you will see all AJAX request.
In your case, it's not needed, because of tripadvisor store all data in html. Here is the code that will give you the info. findAll is an old version,
find_all is a replacement for it. For avoiding this rest_name[0].text you can use just find() function of your soup object. But I really recommended you to use an easier solution for this, because a lot of work has to be done before you will finish your crawler. If you have any question - feel free
r = page_soup.select_one('div#atf_header')
rest_name = r.select_one('div.restaurantName h1').text
econ_class_food = [i.text for i in r.select('div.header_links a')]

UPD 1: This part is useless my_url = "https://www.tripadvisor.fr/Restaurant_Review-g187147-d6575305-Reviews-or260-Il_Etait_Un_Square-Paris_Ile_de_France.html".format(i) in url string you don't have {} for formating. You will make a lot of requests to the same page


text:
Q: understanding "Layout run failure" error logging I am doing some charting work and got a single line message "Layout run failure" when nothing was being created on the chart. Looking into this I found that I have to add some additional script files to generate the log files as covered here:

Layout Failures
As result of the design for the layout engine in 4.1, it is possible
  for improper configuration (or a bug) to cause a layout run to fail to
  complete all of its calculations. When this occurs, the layout simply
  stops and the partial results that have been flushed to the DOM are
  all that is visible. In some cases, the layout may be 99% complete and
  the failure may go undetected or appear as a minor visual anomaly. In
  other cases, the layout may fail early and leave the UI in a clearly
  broken state (much like a JS error during layout would do in previous
  versions).
Diagnostics
The first step if you suspect you are seeing a layout failure is to
  enable the layout diagnostics. This is done by replacing the normal
  "ext-all.js" file with "ext-all-dev.js" and adding a couple additional
  scripts.

I added the required scripts:
<script type="text/javascript" src="extjs/src/diag/layout/Context.js"></script>
<script type="text/javascript" src="extjs/src/diag/layout/ContextItem.js"></script>

And now I get diagnostic data that I can't make any sense of - it doesn't seem to diagnose an error:
++printer<autocontainer> - size: configured/shrinkWrap
    --statprint-1472<autocontainer> - size: configured/configured
        triggeredBy: count=1
            statprint-1472.containerChildrenDone:dom () dirty: false, setBy: ?
        --chart-1473<draw> - size: shrinkWrap/shrinkWrap
            triggeredBy: count=1
                chart-1473.containerChildrenDone:dom (true) dirty: false, setBy: ?
    ++panel-1474<dock> - boxParent: printer - size: natural/configured
    ++panel-1474<autocontainer> - boxParent: printer - size: natural/configured
    ++statprint-1472<dock> - size: configured/configured
        ++statprint-1472_header<body> [isBoxParent] - size: calculated/shrinkWrap
        ++statprint-1472_header<hbox> [isBoxParent] - size: calculated/shrinkWrap
            ++statprint-1472_header_hd<autocomponent> [isBoxParent] - size: calculated/shrinkWrap
            ++tool-1475<autocomponent> [isBoxParent] - size: configured/configured

Does any one know where the diagnostic information is explained?

A: I was receiving 'Layout run failure' messages in my app and discovered the problem was caused by forgetting to set the layout property inside of my Viewport.js file.  Once I defined a layout there, everything worked magnificently well. :)
Example:
Ext.define('MyApp.view.Viewport',{
   extend    : 'Ext.container.Viewport',

   layout  : 'fit',

});

A: Some of the causes can be attributed as -

*

*Overnesting (look for layouts inside layout. Some layout nested combinations will give this error)

*A container is missing a layout.

*A container or its children are missing sizing information. For
example height/width or flex.

*Using ui config on a component that is not defined in the sass.

To debug, we should investigate the layouts in the views where the exception is thrown.
Unfortunately, there is no documentation available.
source: Sencha support

A: I find these types of errors are often solved the quickest with a comment-out-till-it-goes-away approach to isolating which component config is causing the layout failure. Comment out child components from the inside out, replacing them with a filler html config, until you zero-in on which component was causing the failure, then see how much you can put back until the error comes back and you should be looking at only a few remaining lines of configuration that you can eyeball against the docs/samples.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Import data from PDF to SQL Server I am having a PDF which has rows in below format :
Category : Demo

Name : abc

Occupation :xyz

Address : abc ,xyz

Category : Demo

Name : 123

Occupation :456

Address : abcd

and this data is repeated in two column format.
Is there any way to import PDF data to SQL Server ?
I have converted PDF to Excel but it does not gives proper column structure.
How can I import data from PDF to SQL Server ? Or How can I do it in C#.Net ?

A: There is not a proper way to do this. You must develop your own solution for the pdf file and its layout/format. There are several APIs to read PDF content, but I suggest you to use PDFlib TET because it can extract table layout from pdf. If the extracted table does not fit your needs, you can do it yourself while using coordinate based extraction.

A: best way for that is exporting pdf file to excel, then use lots of different application that let you import excel file into sql.
as i'm using mac RAZOR SQL is a nice application for that.


text:
Q: TYPO3 extension: attaching an object to an objectstorage throws a MySQL database error One of my TYPO3 extension classes uses a property (checklist) that is an object storage.
class Kaufmnnisch extends \TYPO3\CMS\Extbase\DomainObject\AbstractEntity
{

    public function __construct(){

        $this->checklist = new \TYPO3\CMS\Extbase\Persistence\ObjectStorage();

    }

    /**
     * checklist
     *
     * @var Tx_Extbase_Persistence_ObjectStorage
     * @lazy
     */
    protected $checklist;

 /**
     * Returns the checklist
     *
     * @return Tx_Extbase_Persistence_ObjectStorage $checklist
     */
    public function getChecklist()
    {
        return $this->checklist;
    }

    /**
     * Sets the checklist
     *
     * @param Tx_Extbase_Persistence_ObjectStorage $checklist
     * @return void
     */
    public function setChecklist($checklist)
    {
        $this->checklist = $checklist;
    }

    /**
     * Returns the boolean state of checklist
     *
     * @return bool
     */
    public function isChecklist()
    {
        return $this->checklist;
    }

To that object storage i want to be able to add objects of the class 'Checkobject' which has just two propeties: 'name' and 'checked'...
Within the controller of the class i have following code in the createAction:
$Kundenauftragliegtvor = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('...\Kundentermine\Domain\Model\Checkobject');
        $Kundenauftragliegtvor->setName('Kundenauftrag liegt vor');
        $Kaufmnnisch->getChecklist()->attach($Kundenauftragliegtvor);

So basically when creating an object of that class i want to initially create the object $Kundenauftragliegtvor (of course later i want to add additional objects of that class, but thats another story)... BUT: When creating an object of the class Kaufmnnisch I get the following error:
Incorrect integer value: '' for column 'checklist' at row 1

It seems that attaching the object to the objectstorage 'checklist' seems to create the error in my MySQL database. I suspect that my TCA (specifically the part for the objectstorage) isn't correct:
 'checklist' => [
            'exclude' => true,
            'label' => 'LLL:EXT:kundentermine/Resources/Private/Language/locallang_db.xlf:tx_kundentermine_domain_model_kaufmnnisch.checklist',
            'config' => [
                'type' => 'passthrough',
                'items' => [
                    '1' => [
                        '0' => 'LLL:EXT:lang/locallang_core.xlf:labels.enabled'
                    ]
                ],
                'default' => 0,
            ]
        ],

Edit: in my ext_tables.sql file the datatype for 'checklist' is:
checklist smallint(5) unsigned DEFAULT '0' NOT NULL,

I guess the error has something to do with this... But what datatype should i specify for an objectstorage?

A: If you have a Checkobject, you should use a CheckobjectRepository and add the Checkobject first.
Try:
$Kundenauftragliegtvor = \TYPO3\CMS\Core\Utility\GeneralUtility::makeInstance('...\Kundentermine\Domain\Model\Checkobject');
$checkobjectRepository = $this-objectManager->get('...\Kundentermine\Domain\Repository\CheckobjectRepository');
$checkobjectRepository->add($Kundenauftragliegtvor);

$Kundenauftragliegtvor->setName('Kundenauftrag liegt vor');
$Kaufmnnisch->getChecklist()->attach($Kundenauftragliegtvor);

Note: You can inject the repository inside your controller too.
**
* checkobjectRepository
*
* @var ...\Kundentermine\Domain\Repository\CheckobjectRepository
*/
$protected $checkobjectRepository = null;

public function injectCheckobjectRepository(...\Kundentermine\Domain\Repository\CheckobjectRepository $checkobjectRepository) {
            $this->checkobjectRepository = $checkobjectRepository;
        }

If you do this change pls don't forget to clear all caches including Optcode cache.
You TCA should be configured correctly:
  'checklist' => [
            'exclude' => true,
            'label' => 'LLL:EXT:kundentermine/Resources/Private/Language/locallang_db.xlf:tx_kundentermine_domain_model_kaufmnnisch.checklist',
            'config' => array(
                     'type' => 'select',
                     'foreign_table' => 'tx_kundentermine_domain_model_checkobject',
                     'foreign_table_where' => ' AND tx_kundentermine_domain_model_checkobject.sys_language_uid IN (-1,0) ORDER BY tx_kundentermine_domain_model_checkobject.title',
        ],

A: Your TCA lacks information in the items. Inside the '1' array you need to add one key/value pair for the value (you only defined the label). In case you need an integer, you need to add e.g. 1 => 0 to define the zero to the label "enabled".
See: https://docs.typo3.org/typo3cms/TCAReference/ColumnsConfig/Type/Select.html#items
PS: Please use english variables and declare integers as integers, not as string.


text:
Q: Problem Installing Expo-cli in Ubuntu using npm I am having an issue when I run npm install expo-cli --global I get an error saying response timeout while trying to fetch https://registry.npmjs.org/@expo
npm install command shows me the error
I've tried npm cache clear --force and tried npm install expo-cli --global but still, I got the error

A: It sounds like your computer does not have internet, can you please check well?
If you are connected to the internet, there could be a problem with proxy blocking traffic to https://registry.npmjs.org, this answer might help you

A: The ping is of 30,000 ms which is very high, you might have low internet speed or request is blocked by network.  Please Check your internet connection.


text:
Q: How to remove the blank page from end of the word document I am not able to remove the blank page from end of the word document. I tried the following ways but i couldn't. Can any one help me on this..
First way :

        <apex:outputPanel rendered="{!historyList.SIZE > 0}">
            <apex:variable var="cnt" value="{!0}" />

 Version History

                            Version #

                            Created Date

                            Reason For Change

                    <apex:repeat var="history" value="{!historyList}">

                                {!history.verNo}

                                {!history.createdDate}

                                {!history.reasonForChange}

                    </apex:repeat>

        </apex:outputPanel>

Second Way:
<apex:outputPanel rendered="{!historyList.SIZE > 0}">
            <apex:variable var="cnt" value="{!0}" />

 Version History

                            Version #

                            Created Date

                            Reason For Change

                    <apex:repeat var="history" value="{!historyList}">
                        <div style="{!if(cnt < 1, 'page-break-before:avoid;','page-break-before:always;')}">
                        <apex:variable var="cnt" value="{!cnt+1}"/>

                                {!history.verNo}

                                {!history.createdDate}

                                {!history.reasonForChange}

                    </apex:repeat>

        </apex:outputPanel>

A: Printing Word documents would be similar to printing PDFs in that you'll first want to add contentType="application/msword" to the <Apex:page> line in your code. Then, you'll want to use CSS that includes @media tags for print and for screen. I recommend you try something along the lines of the following:
@media print
{
   size: 8.5in 11in;/* width height */
   table { page-break-inside:auto }
   tr { page-break-inside:avoid; page-break-after:auto;}
   thead { display:table-header-group }
}

See this W3C reference for more on the @media tag and paged media.
<#div style="page-break-inside:avoid;">
The stuff inside this div will move to a fresh page if it's too long to fit on the remainder of the current page.
<#/div>

@page {
  size: 8.5in 11in;/* width height */
}

Add a new attribute to the page tag: "ContentType":

*

*For Word: contentType="application/msword"


text:
Q: Forked process goes in wrong path I have an assignment in C Language; the requirement is that I am given number of students, everyone has 2 grades midterm grade and final grade my task is to calculate the number of students who passed. But I will use forking; we will fork Teaching Assistants to separately choose whether a student should pass or not and the number of Teaching Assistants will be passed on terminal.
Everything is fine. I wrote the code, but I noticed something very weird, I got a segmentation fault which is so weird because I am sure I am not accessing wrong memory. I tried to print something (line 53) and I found that this line is printed 4 times actually, which is equal to number of children + parent, although this line above the fork(). My code creates more than one process (TA) and every TA takes a partition and calculate number of passed students and exit with this code and on parent I make for loop and wait until any child dies so I print its exit code.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/wait.h>
#include <unistd.h>

void main(int argc, char **argv)
{
    int Number_of_TAs = atoi(argv[1]);
    int leastgrade = atoi(argv[2]);
    int size_of_array = 0;
    int flag = 0;
    int last_visited = 0;
    int ind = 0;

    FILE* ptr;
    char ch;

    // Opening file in reading mode
    ptr = fopen("students.txt", "r");

    if (NULL == ptr) {
        printf("file can't be opened \n");
    }

    do {
        ch = fgetc(ptr);
        size_of_array = 2 * ((int)ch - 48);
        break;

    } while (ch != EOF);

    fclose(ptr);
    int arr_of_grades[size_of_array];
    int arr_of_grades2[size_of_array/2];

   FILE *myFile;
   myFile = fopen("students.txt", "r");

    int *dummy;
    fscanf(myFile, "%d", &dummy);
    for (int i = 0; i < size_of_array; i++)
        fscanf(myFile, "%d", &arr_of_grades[i]);

    int index2 = 0;
    printf("%d", size_of_array);
    printf(" ");
    for (int i = 0; i< size_of_array; i=i+2)
    {
        arr_of_grades2[index2] = arr_of_grades[i] + arr_of_grades[i+1];
        index2 = index2 + 1;

    }

    fclose(myFile);

    int pid, stat_loc;
    int passed_students = 0;
    int partion = size_of_array / (2 * Number_of_TAs );
    for (int i=0; i< Number_of_TAs; i++)
    {
        pid = fork();
        ind = ind + partion;
    }

    if (pid == 0)
    {

        for (int i = ind; i< ind + partion; i++)
           {
            if (arr_of_grades2[i]>=leastgrade )
                passed_students = passed_students + 1;
           }
    exit(passed_students);
    }

    else
    {
        int sid;
        for (int i = 0; i<Number_of_TAs; i++)
        {
            sid = wait(&stat_loc);
            if(!(stat_loc & 0x00FF))
            printf(stat_loc>>8);
            printf(" ");
        }
    }

    return 0;
}

I am a newbie in C so I didn't try many things

A: The segmentation fault issue may happen at any array access with the wrong index.
In your case, it may happen at the first 2 lines:
int Number_of_TAs = atoi(argv[1]);
int leastgrade = atoi(argv[2]);

if you execute the program without the 2 parameters.
Another issue of your program is that you should move the if-else statement where you check the pid inside the for loop where you create the processes with the fork() otherwise it creates more processes than expected.


text:
Q: numpy.ndarray lambda is not callable within loop when using scipy.minimize_scalar, works fine single-run I'm working on a piece of code that calculates surface wave velocities. When I run this as a single-shot in my Jupyter notebook it works fine, however when I try to start looping over the phi1 angle, I end up with the 'numpy.ndarray is not callable error' after the zero iteration of the loop.
It seems to be focused on the lambda (g) I am using, but I am not sure the best way to go about debugging it. Any help/review would be greatly appreciated as Google searches aren't helping too much.
I do apologize for the novel of code, but this is trimmed down to where it should be easily reproducible.
## This code is an implementation of the framework described by M. Cherry et al. in
## Cherry, Matthew R., Shamachary Sathish, and Ramana Grandhi. "A numerical method for predicting Rayleigh surface wave
## velocity in anisotropic crystals." Journal of Computational Physics 351 (2017): 108-120.
## The logic of this code is as follows.
##    (1) It then calculates R, T, and Qv (which is the velocity independent Q, needed to determine the velocity range
##    over which to search.
##    (2)  It then iterates to determine the velocity range by changing a variable called 'angle'.
##    (3)  It then finds a minimum vL, and solves for Q (with velocity as a term), N, A, B, and Z matrices.
##    (4)  It stores the three Euler angles (p1, P, p2) and RSW_vel
##    This does not deal with pseudowaves yet.

import matplotlib.pyplot as plt
import numpy as np
import scipy as sp
import scipy.optimize as spo
import scipy.linalg as la
from scipy.linalg import eig, eigvals
import math
from decimal import *
import time

ts1 = time.time()
# Setup material properties
# Setup the Cij matrix of Ni (units in Pa)
C11 = C22 = C33 = 2.41e11
C12 = C13 = C23 = C21 = C31 = C32 = 1.47e11
C14 = C15 = C16 = C24 = C25 = C26 = C34 = C35 = C36 = C41 = C42 = C43 = C51 = C52 = C53 = C61 = C62 = C63 = 0
C44 = C55 = C66 = 1.26e11
C45 = C46 = C56 = C54 = C64 = C65 = 0
Cij_list = np.array([C11,C12,C13,C14,C15,C16,C21,C22,C23,C24,C25,C26,C31,C32,C33,C34,C35,C36,C41,C42,C43,C44,C45,C46,C51,C52,C53,C54,C55,C56,C61,C62,C63,C64,C65,C66])
Cij=Cij_list.reshape(6,6)
print('Cij =')
print(Cij)
# Setup density of Ni (units are in kg/m3)
rho = 8910
RSW_matrix = np.array([0,0,0,0])

## This is where the setting up of the loop for p1, P, and p2 should be.
# Setup Euler Angles in Bunge's active notation (one time only - demo, will need to be iterated over), angles in degrees. p1 = phi1, P = Phi, p2 = phi2
#p1 = 15
P = 45
p2 = 8

for rotation in range(0, 180):
    ## Below this point, everything must be done for every Euler calculation.
    p1_rad = np.radians(rotation)
    P_rad = np.radians(P)
    p2_rad = np.radians(p2)
    Eul_Ang_deg = np.array([p1,P,p2])
    Eul_Ang_rad = np.array([p1_rad,P_rad,p2_rad])
    c1 = np.cos(p1_rad)
    c2 = np.cos(P_rad)
    c3 = np.cos(p2_rad)
    s1 = np.sin(p1_rad)
    s2 = np.sin(P_rad)
    s3 = np.sin(p2_rad)

    # Solve Rotation Matrix from Bunge's active notation, and m and n (m is wave propagation vector, n is plane normal)
    Rot_mat = np.array([[c1*c3-c2*s1*s3,-c1*s3-c2*c3*s1,s1*s2],
                        [c3*s1+c1*c2*s3,c1*c2*c3-s1*s3,-c1*s2],
                        [s2*s3,c3*s2,c2]])    #- could fill in the rest here and just extract col 1 and col 3

    print('Rotation Matrix =')
    print(Rot_mat)

    m_vec = Rot_mat[[0],:]
    m1 = Rot_mat[[0],[0]]
    m2 = Rot_mat[[0],[1]]
    m3 = Rot_mat[[0],[2]]
    n_vec = Rot_mat[[2],:]
    n1 = Rot_mat[[2],[0]]
    n2 = Rot_mat[[2],[1]]
    n3 = Rot_mat[[2],[2]]

    # Below, we calculate R, T and Q matrices
    # CORRECT R matrix calculations
    Rij = np.ndarray(shape=(3,3))
    Rij[0,0] = C11*m1*n1 + C61*m2*n1 + C51*m3*n1 + C16*m1*n2 + C66*m2*n2 + C56*m3*n2 + C15*m1*n3 + C65*m2*n3 + C55*m3*n3
    Rij[0,1] = C16*m1*n1 + C66*m2*n1 + C56*m3*n1 + C12*m1*n2 + C62*m2*n2 + C52*m3*n2 + C14*m1*n3 + C64*m2*n3 + C54*m3*n3
    Rij[0,2] = C15*m1*n1 + C65*m2*n1 + C55*m3*n1 + C14*m1*n2 + C64*m2*n2 + C54*m3*n2 + C13*m1*n3 + C63*m2*n3 + C53*m3*n3
    Rij[1,0] = C61*m1*n1 + C21*m2*n1 + C41*m3*n1 + C66*m1*n2 + C26*m2*n2 + C46*m3*n2 + C65*m1*n3 + C25*m2*n3 + C45*m3*n3
    Rij[1,1] = C66*m1*n1 + C26*m2*n1 + C46*m3*n1 + C62*m1*n2 + C22*m2*n2 + C42*m3*n2 + C64*m1*n3 + C24*m2*n3 + C44*m3*n3
    Rij[1,2] = C65*m1*n1 + C25*m2*n1 + C45*m3*n1 + C64*m1*n2 + C24*m2*n2 + C44*m3*n2 + C63*m1*n3 + C23*m2*n3 + C43*m3*n3
    Rij[2,0] = C51*m1*n1 + C41*m2*n1 + C31*m3*n1 + C56*m1*n2 + C46*m2*n2 + C36*m3*n2 + C55*m1*n3 + C45*m2*n3 + C35*m3*n3
    Rij[2,1] = C56*m1*n1 + C46*m2*n1 + C36*m3*n1 + C52*m1*n2 + C42*m2*n2 + C32*m3*n2 + C54*m1*n3 + C44*m2*n3 + C34*m3*n3
    Rij[2,2] = C55*m1*n1 + C45*m2*n1 + C35*m3*n1 + C54*m1*n2 + C44*m2*n2 + C34*m3*n2 + C53*m1*n3 + C43*m2*n3 + C33*m3*n3
    Rij_trans = np.transpose(Rij)
    Rij_inv = np.linalg.inv(Rij)

    # CORRECT T matrix calculations
    Tij = np.ndarray(shape=(3,3))
    Tij[0,0] = C11*n1*n1 + C16*n2*n1 + C51*n3*n1 + C16*n1*n2 + C66*n2*n2 + C56*n3*n2 + C15*n1*n3 + C65*n2*n3 + C55*n3*n3
    Tij[0,1] = C16*n1*n1 + C66*n2*n1 + C56*n3*n1 + C12*n1*n2 + C62*n2*n2 + C52*n3*n2 + C14*n1*n3 + C64*n2*n3 + C54*n3*n3
    Tij[0,2] = C15*n1*n1 + C65*n2*n1 + C55*n3*n1 + C14*n1*n2 + C64*n2*n2 + C54*n3*n2 + C13*n1*n3 + C63*n2*n3 + C53*n3*n3
    Tij[1,0] = C61*n1*n1 + C21*n2*n1 + C41*n3*n1 + C66*n1*n2 + C26*n2*n2 + C46*n3*n2 + C65*n1*n3 + C25*n2*n3 + C45*n3*n3
    Tij[1,1] = C66*n1*n1 + C26*n2*n1 + C46*n3*n1 + C62*n1*n2 + C22*n2*n2 + C42*n3*n2 + C64*n1*n3 + C24*n2*n3 + C44*n3*n3
    Tij[1,2] = C65*n1*n1 + C25*n2*n1 + C45*n3*n1 + C64*n1*n2 + C24*n2*n2 + C44*n3*n2 + C63*n1*n3 + C23*n2*n3 + C43*n3*n3
    Tij[2,0] = C51*n1*n1 + C41*n2*n1 + C31*n3*n1 + C56*n1*n2 + C46*n2*n2 + C36*n3*n2 + C55*n1*n3 + C45*n2*n3 + C35*n3*n3
    Tij[2,1] = C56*n1*n1 + C46*n2*n1 + C36*n3*n1 + C52*n1*n2 + C42*n2*n2 + C32*n3*n2 + C54*n1*n3 + C44*n2*n3 + C34*n3*n3
    Tij[2,2] = C55*n1*n1 + C45*n2*n1 + C35*n3*n1 + C54*n1*n2 + C44*n2*n2 + C34*n3*n2 + C53*n1*n3 + C43*n2*n3 + C33*n3*n3
    Tij_trans = np.transpose(Tij)
    Tij_inv = np.linalg.inv(Tij)
    ## R and T defined as above.  Q needs to be new - and not remove the rv2. Thus, we introduce Qv for "Q to determine
    ## critical velocity"
    Qv = np.ndarray(shape=(3,3))
    Qv[0,0] = C11*m1*m1 + C61*m2*m1 + C51*m3*m1 + C16*m1*m2 + C66*m2*m2 + C56*m3*m2 + C15*m1*m3 + C65*m2*m3 + C55*m3*m3
    Qv[0,1] = C16*m1*m1 + C66*m2*m1 + C56*m3*m1 + C12*m1*m2 + C62*m2*m2 + C52*m3*m2 + C14*m1*m3 + C64*m2*m3 + C54*m3*m3
    Qv[0,2] = C15*m1*m1 + C65*m2*m1 + C55*m3*m1 + C14*m1*m2 + C64*m2*m2 + C54*m3*m2 + C13*m1*m3 + C63*m2*m3 + C53*m3*m3
    Qv[1,0] = C61*m1*m1 + C21*m2*m1 + C41*m3*m1 + C66*m1*m2 + C26*m2*m2 + C46*m3*m2 + C65*m1*m3 + C25*m2*m3 + C45*m3*m3
    Qv[1,1] = C66*m1*m1 + C26*m2*m1 + C46*m3*m1 + C62*m1*m2 + C22*m2*m2 + C42*m3*m2 + C64*m1*m3 + C24*m2*m3 + C44*m3*m3
    Qv[1,2] = C65*m1*m1 + C25*m2*m1 + C45*m3*m1 + C64*m1*m2 + C24*m2*m2 + C44*m3*m2 + C63*m1*m3 + C23*m2*m3 + C43*m3*m3
    Qv[2,0] = C51*m1*m1 + C41*m2*m1 + C31*m3*m1 + C56*m1*m2 + C46*m2*m2 + C36*m3*m2 + C55*m1*m3 + C45*m2*m3 + C35*m3*m3
    Qv[2,1] = C56*m1*m1 + C46*m2*m1 + C36*m3*m1 + C52*m1*m2 + C42*m2*m2 + C32*m3*m2 + C54*m1*m3 + C44*m2*m3 + C34*m3*m3
    Qv[2,2] = C55*m1*m1 + C45*m2*m1 + C35*m3*m1 + C54*m1*m2 + C44*m2*m2 + C34*m3*m2 + C53*m1*m3 + C43*m2*m3 + C33*m3*m3
    res = []
    res = spo.minimize_scalar(lambda x: ((min(eigvals(Qv * np.cos(np.radians(x)) * np.cos(np.radians(x)) + (Rij + Rij_trans) * np.cos(np.radians(x)) * np.sin(np.radians(x)) + Tij * np.sin(np.radians(x)) * np.sin(np.radians(x)))) / rho)**(0.5))*(1/(np.abs(np.cos(np.radians(x))))), bracket=(-90,0,90), method='Golden')
    vel_L = res.fun.real
    vel_L_int = int(vel_L)
    print('velocity limit')
    print(vel_L)
    print(vel_L_int)
    Det_B_try = 1

    Qij = np.zeros(shape=(3,3))
    Qij[0,1] = C16*m1*m1 + C66*m2*m1 + C56*m3*m1 + C12*m1*m2 + C62*m2*m2 + C52*m3*m2 + C14*m1*m3 + C64*m2*m3 + C54*m3*m3
    Qij[0,2] = C15*m1*m1 + C65*m2*m1 + C55*m3*m1 + C14*m1*m2 + C64*m2*m2 + C54*m3*m2 + C13*m1*m3 + C63*m2*m3 + C53*m3*m3
    Qij[1,0] = C61*m1*m1 + C21*m2*m1 + C41*m3*m1 + C66*m1*m2 + C26*m2*m2 + C46*m3*m2 + C65*m1*m3 + C25*m2*m3 + C45*m3*m3
    Qij[1,2] = C65*m1*m1 + C25*m2*m1 + C45*m3*m1 + C64*m1*m2 + C24*m2*m2 + C44*m3*m2 + C63*m1*m3 + C23*m2*m3 + C43*m3*m3
    Qij[2,0] = C51*m1*m1 + C41*m2*m1 + C31*m3*m1 + C56*m1*m2 + C46*m2*m2 + C36*m3*m2 + C55*m1*m3 + C45*m2*m3 + C35*m3*m3
    Qij[2,1] = C56*m1*m1 + C46*m2*m1 + C36*m3*m1 + C52*m1*m2 + C42*m2*m2 + C32*m3*m2 + C54*m1*m3 + C44*m2*m3 + C34*m3*m3

    for v in range(1, vel_L_int):
        # Calculate rho vel-squared
        rv2 = rho * v ** 2

        # CORRECT Q matrix calculations
        Qij[0,0] = C11*m1*m1 + C61*m2*m1 + C51*m3*m1 + C16*m1*m2 + C66*m2*m2 + C56*m3*m2 + C15*m1*m3 + C65*m2*m3 + C55*m3*m3 - rv2
        Qij[1,1] = C66*m1*m1 + C26*m2*m1 + C46*m3*m1 + C62*m1*m2 + C22*m2*m2 + C42*m3*m2 + C64*m1*m3 + C24*m2*m3 + C44*m3*m3 - rv2
        Qij[2,2] = C55*m1*m1 + C45*m2*m1 + C35*m3*m1 + C54*m1*m2 + C44*m2*m2 + C34*m3*m2 + C53*m1*m3 + C43*m2*m3 + C33*m3*m3 - rv2
        Qij_trans = np.transpose(Qij)
        Qij_inv = np.linalg.inv(Qij)

        # Create a new Nik matrix
        TR_ik = -1*np.matmul(Tij_inv, Rij_trans)
        TI_ik = Tij_inv
        QRTR_ik = -Qij + np.matmul(np.matmul(Rij, Tij_inv), Rij_trans)
        RT_ik = -1*np.matmul(Rij, Tij_inv)

        # Nik Creation
        Nik_r1to3 = np.concatenate((TR_ik,TI_ik),axis=1)
        Nik_r4to6 = np.concatenate((QRTR_ik,RT_ik),axis=1)
        Nik_whole = np.concatenate((Nik_r1to3,Nik_r4to6))

        # Eigenvalues and Eigenvectors of Nik
        eigvals, eigvecs = eig(Nik_whole)

        ## The following code sorts the eigenvalues for those with negative imaginary numbers, and conducts the matrix
        ## operations to generate the B, A, and Z matrices from the COLUMNS in Pythons representation of eigenvectors
        eigvecsT = np.transpose(eigvecs)
        output_ab = output_ab_neg_imag = eigvecsT[eigvals.imag < 0]
        output_abT = np.transpose(output_ab)

        ### This is the B matrix (bottom 3 vectors assumed as b)
        B_matrix = output_b = np.delete(output_abT, [0,1,2], axis=0)
        B_matrixT = np.transpose(B_matrix)

        ### This is the A matrix (these are the displacement vectors, and when A is combined with B, the surface impedance (Z) matrix can be found)
        A_matrix = output_a = np.delete(output_abT, [3,4,5], axis=0)
        det_B = np.linalg.det(B_matrix)
        det_cc_B = det_B.conjugate()
        det_B_x_det_cc_B = det_B*det_cc_B
        v_real = v.real
        det_B_x_det_cc_B_real = det_B_x_det_cc_B.real

        if det_B_x_det_cc_B_real < Det_B_try:
            RSW_vel = v_real
            Det_B_try = det_B_x_det_cc_B_real

    print('RSW =')
    print(RSW_vel)
    print('Min |B|x|B|* =')
    print(Det_B_try)

    col_to_be_added2 = np.array([p1, P, p2, RSW_vel])
    RSW_matrix = np.column_stack((RSW_matrix,col_to_be_added2))

    print('RSW vel matrix is')
    print(RSW_matrix)


text:
Q: How does rpy2 handles warnings in R? In [1]: import rpy2

In [2]: import rpy2.robjects as robjects

In [3]: robjects.r['warning']("hello")
Out[3]:
<StrVector - Python:0x7f115a1e34d0 / R:0x1243d18>
['hello']

It seems warning messages are directly transformed to string, which is correct.
But where is the waring?
While in R, it would print
Warning message:
hello

in red.
So how can I know if a function has triggered any warnings?


text:
Q: How to convert element of variant to std::string ( c++ ) How to convert element of variant to std::string??
void Function(const std::string str)
{
~~
}

std::variant<std::string, int, float> a{ 32 };

i should pass element of a to Function.
i can't change argument of Function. and i don't wanna add any helper function.
i just wanna convert element of a to string.
i tried many ways. but everything didn't works.
i know i can do this through std::get<std::string>(a), std::get<int>(a), std::get<float>(a)
but i need many try catch statements to do this.
i wanna know more clever ways.

A: You can use std::visit with some if constexprs. If the variant holds a string, no conversion required; just call Function. Otherwise use std::to_string to convert a numeric argument:
#include <iostream>
#include <string>
#include <variant>

template<class> inline constexpr bool always_false_v = false;

void Function(const std::string str)
{
    std::cout << str << std::endl;
}

int main()
{
    std::variant<std::string, int, float> a{ 32 };

    std::visit([](auto&& arg) {
        using T = std::decay_t<decltype(arg)>;
        if constexpr (std::is_same_v<T, std::string>)
            return Function(arg);
        else if constexpr (std::is_arithmetic_v<T>)
            return Function(std::to_string(arg));
        else
            static_assert(always_false_v<T>, "non-exhaustive visitor!");
    }, a);

    return 0;
}

Demo

A: To get the active element of a variant, regardless of its type, use visit. In order to visit the variant, you'll need a template function that can accept all of the contained types. That template can convert the argument to a string, for example using std::to_string, and pass that as an argument to Function.


text:
Q: why is this c program giving runtime error my program is to take input of integers and  add sum of odd negative numbers to even positive numbers but i am getting runtime error,can anyone find mistake.
#include <stdio.h>

int main(void)
 {

int i,j,m,n,a[m],w;

    scanf("%d",&n);
    for(i=0;i<n;i++)
    {   int s=0,d=0;
        scanf("%d",&m);
        for(j=0;j<m;j++)
        {
            scanf("%d",&a[j]);
            if((a[j]<0)&&(a[j]%2!=0))
             s=s+a[j];
        else if((a[j]>0)&&(a[j]%2==0))
        d=d+a[j];
        }
        printf("%d",s+d);
            }
    return 0;
}

A: in your code
a[m]

is erroneous. value of m is used as uninitialized.
To solve your issue, you can use dynamic memory allocation for a variable int * a based on the user input of m.
Note:

*

*Always initialize your local variables.

*Check the return value of scanf() for successful input.

*[A request] C ignores white-spaces [mostly]. Use them to make your code more human-readable.

A: Your mistake is this:
int a[m]
What you expect to be value of m? Change to a[256]. Or define int *a then after scanning m: a = malloc( m * sizeof (int) ).

A: If you want
a[m];

From C99 you have VLA
int m;
scanf("%d",&m);
int a[m];

Because I see in your code you are trying to scan the size of the array.
Alternatively you can have a dynamic array
int *a = malloc(sizeof(int) * m);

@Sourav has already mentioned the reason for crash.
The value of m is undeterminate.

A: declaration of array caused the runtime error please refer to this http://www.tutorialspoint.com/cprogramming/c_arrays.htm


text:
Q: custom error message for Rails build-in validation helper If I have a model like:
class Person < ActiveRecord::Base
   validates_presence_of :name, :login, :email
end

In the view form, if I leave say email empty and submit the form the error message by Rails will be :
email can't be blank.

I am wondering, how can I customize this error message for Rails build-in validation helpers?
I mean I would like :name, :login field use the default error message, but only want :email raise the message like "You have to provide email address" . How to achieve this?
I am using Rails v2.3.2

A: Custom error message (default is: "can't be blank").
class Person < ActiveRecord::Base
   validates_presence_of :name, :login
   validates_presence_of :email, :message => 'your custom messages'
end

http://railsapi.com/doc/v2.3.2/classes/ActiveRecord/Validations/ClassMethods.html#M001871


text:
Q: How to alternate grid pattern for unknown number of items I want to create a repeating grid. Three items per row.
First row: item one spans 2 cols and 2 rows. Followed by item two and item three spanning 1 col and 1 row.
Second row would be inverse: item one and item two span 1 col and 1 row. item 3 spans 2 cols and 2 rows.
See image below for what I'm trying to do. I wanting this for an infinite amount of rows and items.

.container {
  width: 100%;
  margin: 0 auto;
  max-width: 80%;
  display: grid;
  grid-template-columns: 1fr 1fr 1fr;
  gap: 10px;
}

h2 {
  font-size: 16px;
  font-family: sans-serif;
  font-weight: normal;
}

.item {
  background: pink;
}

.item:nth-child(3n+1) {
  grid-column: auto /span 2;
  grid-row: auto /span 2;

}

.item:nth-child(3n+2),
.item:nth-child(3n+3) {
  /* grid-area: 1 / 3 / 2 / 4; */
  border: 1px solid red;
  grid-column: auto /span 1;
  grid-row: auto /span 1;
}

.container.two .item:nth-child(3n+1) {
    border: 5px solid yellow;
    grid-area: 1 / 1 / 2 / 2;
  }

.container.two .item:nth-child(3n+2) {
    border: 5px solid orange;
    grid-area: 2 / 1 / 3 / 2;

  }

.container.two .item:nth-child(3n+3) {
    border: 5px solid red;
    grid-area: 1 / 2 / 3 / 4;
  }

img {
  max-width: 100%;
}

I have this using "grid-column" and "grid-row"...

    First

    Second

    Third

I want to alternate that, but I only understand how to with "grid-area"...

    First

    Second

    Third

But I want to have an unlimited amount of items alternate those patterns...

    First

    Second

    Third

    First

    Second

    Third

    First

    Second

    Third

    First

    Second

    Third

    First

    Second

    Third

A: You can do it like below:

.container {
  display:grid;
  grid-template-columns:repeat(3,1fr); /* 3 columns */
  grid-auto-flow:dense; /* make sur to fill all the area */
  grid-auto-rows:50px; /* height of one row */
  grid-gap:5px;
}
.container * {
  background:red;
}
/* the pattern repeat each 6 elements */
.container :nth-child(6n + 1),
.container :nth-child(6n + 6){
  grid-area:span 2/span 2; /* 1 and 6 take 2 rows and 2 columns */
}

.container :nth-child(6n + 5){
  grid-column:1; /* 5 at first column */
}


text:
Q: Spring @Lookup method having String[] argument using full annotations configuration I have a JavaFX application and i want to do injection of a prototype scopped bean in a Singleton scopped bean using Lookup method and all my configuration is using javax.inject API
@Named
@Singleton
public abstract class DataModel {

    public ObservableList<Series<Number, Number>> observableList;

    public DataModel() {
        observableList = FXCollections.observableArrayList();
    }

    public void refresh(String[] selectedCountries) {
        observableList.clear();
        SeriesDataAdater seriesDataAdapter = getPopulationFirstCaseRelativeSeriesDataAdapter(selectedCountries);
        observableList.addAll(seriesDataAdapter.getSeriesList());
    }

    @Lookup()
    public abstract FirstCaseDateX_NewCasesPerPopulationY_SeriesDataAdapter getPopulationFirstCaseRelativeSeriesDataAdapter(String[] selectedCountries);
}

@Named
@Scope("prototype")
public class FirstCaseDateX_NewCasesPerPopulationY_SeriesDataAdapter extends SeriesDataAdater{

    @Inject
    public FirstCaseDateX_NewCasesPerPopulationY_SeriesDataAdapter(String[] selectedCountries, DataCache cache) {
        super(cache, selectedCountries);
    }

    @Override
    public List<Series<Number, Number>> getSeriesList() {
        ....
    }

    @Override
    public Series<Number, Number> getSeries(String country) {
        ....
    }

}

i have this exception :

Caused by: org.springframework.beans.factory.BeanCreationException:
  Error creating bean with name
  'firstCaseDateX_NewCasesPerPopulationY_SeriesDataAdapter' defined in
  file
  [D:\JAVA\workspaces\covid-19\covid19-unified-start-time-line-chart\target\classes\com\othmen\test\covid19\seriesdatasource\FirstCaseDateX_NewCasesPerPopulationY_SeriesDataAdapter.class]:
  Could not resolve matching constructor (hint: specify index/type/name
  arguments for simple parameters to avoid type ambiguities)

i think he is not able to inject the argument selectedCountries because it is a simple type (String[]) but i dont know how to give him more informations (name or index) like he want.
i think i can solve this problem by creating a custom class as wrapper for my String[] parameter or by definning a FactoryBean for my String[] which will allow me to give him a Qualifier and the add @Qualifier in the prototype  constrcutor but is there an easier way to give him a Qualifier ?

A: Move DataCache from constuctor to separate setter with @Autowired annotation. @Lookup should match constuctor parameters' types and parameters count, you can't use partial of definition.


text:
Q: How to check if a type is instantiated from a certain variadic template class in a template function? Let's say I have:
template <typename...>
class Foo { };

Then I define another function:
template <typename... T>
void Bar(const T&... arguments) { }

How do I check if all Ts passed to Bar are all instantiated from Foo? Like:
Foo<int> a;
Foo<int, int> b;
Bar(a, b); // OK
int c;
Bar(a, b, c); // ill-formed

I want a way to detect ill-formed arguments like Bar(a, b, c); Is there a way to do this?

A: You can create a trait to test for instantiations of Foo, and then fold it across all your parameters.
template <typename>
struct is_foo : std::false_type {};

template <typename... Ts>
struct is_foo<Foo<Ts...>> : std::true_type {};

template <typename T>
constexpr bool is_foo_v = is_foo<T>::value;

template <typename... T>
void Bar(const T&... arguments) {
    static_assert((is_foo_v<T> && ...), "arguments must all be Foos");
}

See it on coliru


text:
Q: getting ftp return code 530 (not logged in) in welcome banner before paramiko tries to authenticate I am writing a python script using paramiko to automate a daily download from a remote ftp host. The script connects successfully but then says the banner is bad and quits. It disconnects before trying to authenticate.
I get this exception: "SSHException: Error reading SSH protocol banner", and according to the log the last line of the banner is "530 Please login with USER and PASS."  Note the return code 530 which means "not logged in". I think this is what paramiko takes exception to.
I am indeed using a username and password (see code below) but the host seems to expect those before paramiko gets around to showing them. The problem occurs in Transport.start_client() which comes before Transport.auth_password() inside Transport.connect().
When I connect manually from the command line I can trigger the 530 message with this:
ftp -nd ftp.server.com

(The -n prevents auto-login which I think is the cause of the 530, and the -d enables debugging so I can actually see it.) The 530 line follows immediately after the banner, but isn't actually part of it. I know this because if I remove the -n I don't get it, but am immediately prompted for credentials. So paramiko must be doing something analogous to the -n option.
How can I either...

*

*prevent the 530 line in the first place, or

*get paramiko to accept/ignore that line

...so it can proceed to authentication? I assume paramiko's more advanced features can handle situations like this, but I am at a loss.
Details
Here is my code, which I think is pretty boiler plate:
#! /usr/bin/python2.7

import paramiko
import logging

logging.getLogger('paramiko').setLevel(logging.DEBUG)
paramiko.util.log_to_file('paramiko_log')

host = 'ftp.server.com'
port = 21
user = 'anonymous'
password = 'me@email.com'
# It is an anonymous server so I really am signing in with
# username 'anonymous' and my email address for a password.

t = paramiko.Transport((host, port))
t.connect(username=user, password=password)
ftp = paramiko.SFTPClient.from_transport(t)
# if I could get this far, this is where I would download the file.
ftp.close()
t.close()

Here is the log produced from running the above code:
DEB [20180725-08:52:34.230] thr=1   paramiko.transport: starting thread (client mode): 0xb69bb090L
DEB [20180725-08:52:34.231] thr=1   paramiko.transport: Local version/idstring: SSH-2.0-paramiko_2.4.1
DEB [20180725-08:52:34.287] thr=1   paramiko.transport: Banner: 220-This system is for authorized users only.
...[several more 220 lines]...
DEB [20180725-08:52:34.289] thr=1   paramiko.transport: Banner: 530 Please login with USER and PASS.
ERR [20180725-08:52:36.293] thr=1   paramiko.transport: Exception: Error reading SSH protocol banner
ERR [20180725-08:52:36.294] thr=1   paramiko.transport: Traceback (most recent call last):
ERR [20180725-08:52:36.294] thr=1   paramiko.transport:   File "/usr/lib/python2.7/site-packages/paramiko/transport.py", line 1893, in run
ERR [20180725-08:52:36.294] thr=1   paramiko.transport:     self._check_banner()
ERR [20180725-08:52:36.294] thr=1   paramiko.transport:   File "/usr/lib/python2.7/site-packages/paramiko/transport.py", line 2049, in _check_banner
ERR [20180725-08:52:36.294] thr=1   paramiko.transport:     'Error reading SSH protocol banner' + str(e)
ERR [20180725-08:52:36.294] thr=1   paramiko.transport: SSHException: Error reading SSH protocol banner

I've tried...

*

*increasing Transport.banner_timeout (a common suggestion for questions relating to this particular paramiko exception) but does not help because it is not timing out.

*splitting Transport.connect(...) into Transport.start_client() and Transport.auth_password(user, password), but it changes nothing. The problem is inside start_client().


text:
Q: Passing kwargs to a function with multiprocessing.pool.map for pandas Dataframe I have written a function that takes in a dataframe with keywords arguments as shown below:
df1 = df1.apply(add_data_ip2, axis=1, result_type="expand")

The process takes 20 minutes. the function add_data_ip2 takes in a dataframe and reads the stock symbol under the "Ticker" column and does an api call to retrieve financial info and manipulates the data through math to calculate a score. The score is under saved in the "Score" column of the same df. The function returns the same dataframe.
The df contains approximately 1500 ticker symbols and I am trying to run the following parallel processing code to reduce the waiting time, but with no luck. The function keeps running with no indication of any output. Can anyone advise what is the problem? Is there anything wrong with the way I am passing in the kwargs into the function. Have tried searching stackoverflow for answers with no luck. Appreciate the help.
from functools import partial
mapfunc = partial(add_data_ip2, axis=1, result_type="expand")

p = mp.Pool(mp.cpu_count())
df1= p.map(mapfunc, df1)
df1

Another alternative block also doesn't give any output either.
from multiprocessing import  Pool

def parallelize_dataframe(df, func, n_cores=4):
        df_split = np.array_split(df, n_cores)
        pool = Pool(n_cores)
        df = pd.concat(pool.map(func, df_split))
        pool.close()
        pool.join()
        return df

train = parallelize_dataframe(df1, mapfunc)'

A: As for me your partial is wrong.
You can't send df to partial partial(add_data_ip2,...) and run as df.apply(add_data_ip2, ...) because partial will try to run it as add_data_ip2(..., df)
Other problem: axis=1, result_type="expand" are parameters for df.apply()  but partial will run it as add_data_ip2(..., axis=1, result_type="expand")
As for me you should define normal function
def mapfunc(dfx):
    return dfx.apply(add_data_ip2, axis=1, result_type="expand")

or lambda
mapfunc = lambda dfx: dfx.apply(add_data_ip2, axis=1, result_type="expand")

But as I know Pool can't work with lambda because it has to save function and data in pickle and later process has to read it - but pickle can't save lambda

Code which I used for tests
import pandas as pd
from functools import partial
from multiprocessing import Pool
import numpy as np

data = {
    'A': [1,2,3],
    'B': [4,5,6],
    'C': [7,8,9]
}

df = pd.DataFrame(data)
print('--- original ---')
print(df)

def add_data_ip2(row):
    row['A'] += 10
    row['B'] += 100
    row['C'] += 1000
    return row

# --- test 1 ---
#new_df = df.apply(add_data_ip2, axis=1, result_type="expand")
#print(new_df)  # OK

# --- test 2 ---
#mapfunc = partial(add_data_ip2, axis=1, result_type="expand")
#new_df = mapfunc(df)  # ERROR
#print(new_df)

# --- test 3 ---
#mapfunc = lambda df: df.apply(add_data_ip2, axis=1, result_type="expand")
#new_df = mapfunc(df)  # OK
#print(new_df)

# --- test 4 ---
def mapfunc(df):
    return df.apply(add_data_ip2, axis=1, result_type="expand")

new_df = mapfunc(df)  # OK
print('--- mapfunc ---')
print(new_df)

# --- test Pool ---

p = Pool()

parts = np.array_split(df, 4)

results = p.map(mapfunc, parts)

print('--- Poll results ---')
for item in results:
    print(item)
    print('---')

print('--- concat new df ---')
new_df = pd.concat(results)
print(new_df)


text:
Q: CUDA texture memory space When I bind an array to a texture in CUDA,

*

*is that array copy to a texture space? or,

*is that array reference as a texture?

If the answer is 1., then i can bind a texture and safety fetch data from the texture memory space while I write the result to the array, which is allocated in global memory.
If the answer is 2., then, is the texture memory a global memory space where the data is cached and spatially fetched?
I'd like to know about this topic, as I've seen some question related to this topic and I've not the answer clear right now.
Thanks in advance.

A: The answer is the second option, but from there things get a little more complex. There is no such thing as "texture memory", just global memory which is accessed via dedicated hardware which include an on GPU read cache (6-8kb per MP depending on card, see table F-2 in Appending F of Cuda Programming Guide) and a number of hardware accelerated filtering/interpolation actions. There are two ways the texture hardware can be used in CUDA:

*

*Bind linear memory to a texture and read from it in a kernel using the 1D fetch API. In this case the texture hardware is really just acting as a read-through cache, and (IIRC) there are no filtering actions available.

*Create a CUDA array, copy the contents of linear memory to that array, and bind it to a texture. The resulting CUDA array contains a spatially ordered version of the linear source, stored in global memory in some sort of (undocumented) space filling curve. The texture hardware provides cached access to that array, include simultaneous memory reads with hardware accelerated filtering.

You might find the overview of the GT200 architecture written by David Kanter worth reading to get a better idea of how the actual architecture implements the memory hierarchy the APIs expose.


text:
Q: Sending Database emails to multiple recipients while tweaking the body i need to send emails to approx, twenty recipients each day, i build a temp table with two columns
Email_Body
Email_address
there are at max 50 rows in the table each day
i want to loop though this table and execute sp_send_email
EXEC msdb.dbo.sp_send_dbmail
        @Profile_name = 'DBA',
        @recipients = @email_address,
        @body = @Email_Body,
        @subject = 'Test Email'

is there a way to do this without a cursor?
any links to an example would be appreciated, i have searched and can't find such an example. i am sure it is a very common process.

A: You might try the solution found here.

A: I think this code sample would help:
while (@count <=(select COUNT(*) from @table))
begin
select top 1 @Recepient_Email=Emp_Email,@mailBody=body from @table where ID=@count
EXEC msdb.dbo.sp_send_dbmail
    @profile_name='Profile1',
    @recipients=@Recepient_Email,
    @subject = 'This is subject of test Email'
    @body = @mailbody,
    @body_format = 'HTML'
    set @count =@count +1
    END

A: --Email Campaign.
declare @HtmlModel varchar(max)
declare @HtmlBody varchar(max)
SELECT @HtmlModel = EmailBody
FROM EmailCampaigns
WHERE ID = 1
--a different process will have created an awesome looking well formed html with our known
--placeholders for [FirstName] [LastName] [Phone] [Email] that might ber substituted for individualization
--PRINT @HtmlModel;
SET @HtmlBody=''

declare
    @mailID int,
    @id    int,
    @first varchar(64),
    @last  varchar(64),
    @phone varchar(64),
    @email varchar(64)

    declare c1 cursor for
    --################################
    SELECT ID,
           ISNULL(FirstName,'Friend') AS FirstName,
           ISNULL(LastName,'') AS LastName,
           ISNULL(Phone,''),
           ISNULL(Email ,'')
           --the row_number is so that if i put your name in the database five times, you only get a single email.
    FROM (
          select ROW_NUMBER() over (partition by email order by email,len(firstname)desc,len(lastname)desc ) AS RW, *
          from RawContacts
          where email <> '') x
    WHERE RW = 1
    --this WHERe stays in place until we are ready to go LIVE with the email.
      and email IN('lowell@somedomain.com','otherReviewer@somedomain.com')
    --################################
    open c1
    fetch next from c1 into @id,@first,@last,@phone,@email
    While @@fetch_status <> -1
      begin
        SET @HtmlBody = REPLACE(@HTMLModel,'[FirstName]',@first)
        SET @HtmlBody = REPLACE(@HtmlBody,'[LastName]',  @last)
        SET @HtmlBody = REPLACE(@HtmlBody,'[Phone]',     @phone)
        SET @HtmlBody = REPLACE(@HtmlBody,'[Email]',     @email)
        --EXEC msdb.dbo.sp_send_dbmail
             @Profile_name = 'Database Mail Profile Name',
             @recipients=@email,
             @subject = 'Our non profits Call for Volunteers',
             @body = @HtmlBody,
             @body_format = 'HTML',
             @mailitem_id = @mailID OUTPUT
    --@body_format = 'TEXT'
        INSERT INTO CampaignRecipients(Campaign,RawContactID,MailSentID,MailSentDate)
          SELECT 1,@id,@mailID,GETDATE()
        fetch next from c1 into @id,@first,@last,@phone,@email
        end
    close c1
    deallocate c1

GO


text:
Q: How to click on the Security Warning window using Selenium webdriver in IE 11? Security Warning Window
This image pops up when I click on "Continue to this website (not recommended)."

A: Please Try This, It works.
public void TestSSLerror() {

    //Download IEDriver exe and past in project
    driver = new FirefoxDriver();

    //Open WebSite for time being let's take http://test.com
    driver.get("https://test.com");

    //now we are going to use javascipt ,This will click on "Continue to this website (not recommended)" text and will
    //push us to the page
    driver.navigate().to("javascript:document.getElementById('overridelink').click()");
}

A: It is better if you can disable the security check by bypassing using required credentials, if it is not related to the test(saves time), otherwise you need to go for a third party tool like auto-it to automate it.


text:
Q: How to set default datatype I have an ItemsControl in which all the items except the type AType should have the same view. How could I do that?
I've tried object as DataType but it is forbidden (there is simplified example below):
<ItemsControl>
    <ItemsControl.Resources>
        <DataTemplate DataType="AType">
            <TextBox />
        </DataTemplate>
        <DataTemplate DataType="System:Object">
            <Border>
                <TextBlock Text="{Binding}" />
            </Border>
        </DataTemplate>
    </ItemsControl.Resources>
</ItemsControl>

A: The best bet is to use a Template Selector, like this one
That way you can easily specify the template based on whatever condition you like.


text:
Q: Create a table from the results of a recursive query (with statement) I want to make a new (persistent) table from the results of a recursive query in SQLite.
For instance, let's make a table with columns (n, fct), where n denotes a natural number and fct its factorial:
-- factorial of n = 0, 1, ..., 5
WITH RECURSIVE fact_i (n, fct) AS (
     VALUES (0, 1)
     UNION ALL
     SELECT n+1, fct * (n+1) FROM fact_i
     WHERE n < 5)
SELECT * FROM fact_i;

which results in
0|1
1|1
2|2
3|6
4|24
5|120

However, I'd like to store the results in a persistent table, say factorials.
I tried
CREATE TABLE factorials (n, fct) AS
WITH RECURSIVE fact_i (n, fct) AS (
     VALUES (0, 1)
     UNION ALL
     SELECT n+1, fct * (n+1) FROM fact_i
     WHERE n < 5)
SELECT * FROM fact_i;

or
WITH RECURSIVE fact_i (n, fct) AS (
     VALUES (0, 1)
     UNION ALL
     SELECT n+1, fct * (n+1) FROM fact_i
     WHERE n < 5)
CREATE TABLE factorials (n, fct) AS
SELECT * FROM fact_i;

Yet both result in a syntax error.
Is there a way to create such a table in SQLite?

A: Yes, it is possible(wrapping with additional SELECT * FROM ()):
CREATE TABLE factorials AS
SELECT *
FROM (
WITH RECURSIVE fact_i (n, fct) AS (
     VALUES (0, 1)
     UNION ALL
     SELECT n+1, fct * (n+1) FROM fact_i
     WHERE n < 5)
SELECT * FROM fact_i) s;

db<>fiddle demo
EDIT:
Actually, all you need to do is removing column list from CREATE TABLE:
CREATE TABLE factorials AS
WITH RECURSIVE fact_i (n, fct) AS (
     VALUES (0, 1)
     UNION ALL
     SELECT n+1, fct * (n+1) FROM fact_i
     WHERE n < 5)
SELECT * FROM fact_i;

db<>fiddle demo2


text:
Q: How can I get taxonomy term name using term slug & post ID using build in WordPress function or class? I have the following SQL query:
SELECT t.name FROM wp_posts p
    INNER JOIN wp_term_relationships tr ON tr.object_id = p.id
    INNER JOIN wp_terms t ON tr.term_taxonomy_id = t.term_id
    WHERE p.id = 1451
    AND t.slug = 'xxx';

It gets the term name (wp_term.name) using a given post id and slug (wp_term.slug).
The SQL query works, but how can I get the slug name by using a built in WordPress function or class?

A: This can be done in multiple different ways. Depending on the context, one way may be better than the other ways.
Using WP_Term_Query class:
Most wp_term related queries are internally done using the WP_Term_Query class. So if you need different options, using this class can be very useful. For example:
// all of these arguments are optional
$args = array(
    // object_ids can be a single post id or array of post ids
    'object_ids' => get_the_ID(),
    // taxonomy can be just a single taxonomy string or array of taxonomies
    'taxonomy' => array( 'category', 'post_tag' ),
    // if you need only a specific slug
    'slug'  => 'your-slug-here'
);
$term_query = new WP_Term_Query( $args );
foreach( $term_query->get_terms() as $term ) {
    echo "{$term->name} ({$term->taxonomy})";
}

Using get_the_terms function:
For theme template files (e.g. single.php), get_the_terms() function may be more appropriate. It internally uses cache functions, so it's probably more efficient in this context. For example:
$terms = get_the_terms( get_the_ID(), 'post_tag' );

if( $terms ) {
    $term = wp_list_pluck( $terms, 'name', 'slug' );
    if( isset( $term['some-post-tag'] ) )
        echo '
' . $term['some-post-tag'] . '
';
    else
        echo '
No tag found with [some-post-tag]
';
}

For this implementation, wp_list_pluck() function may be useful, since get_the_terms() doesn't support slug directly.
Using get_term_by function:
Since each WordPress taxonomy term slug is unique, so basically if you know the slug from some other source, then post ID may not be needed at all. In this case, you may use the get_term_by function. For example:
// $terms = get_term_by( 'slug', 'some-category-slug', 'category' );
$terms = get_term_by( 'slug', 'some-post-tag', 'post_tag' );
if( $terms ) {
    echo $terms->name;
}

get_term_by function doesn't support post ID, but as I said, you may not need post ID at all.


text:
Q: Powershell - Pulling string from txt, splitting it, then concatenating it for archive I have an application where I am getting a list of new\modified files from git status, then I take the incomplete strings from that file, concatenate them with the root dir file path, then move those files to an archive. I have it half working, but the nature of how I am using powershell does not provide error reports and the process is obviously erroring out. Here is the code I am trying to use. (It has gone through several iterations, please excuse the commented out portions) Basically I am trying to Get-Content from the txt file, then replace ? with \ (for some reason the process that creates the txt love forward slashes...), then split that string at the spaces. The only part of the string I am interested in is the last part, which I am trying to concatenate with the known working root directory, then I am attempting to move those to an archive location. Before you ask, this is something we are not willing to track in git, due to the nature of the files (they are test outputs that are time stamped, we want to save them on a per test run basis, not in git) I am still fairly new to powershell and have been banging my head against this rock for far too long.
    Get-Content $outfile | Foreach-Object
{
  #$_.Replace("/","\")
  #$lineSplit = $_.Split(' ')
  $_.Split(" ")
  $filePath = "$repo_dir\$_[-1]"
  $filePath.Replace('/','\')
  "File Path Created: $filePath"
  $untrackedLegacyTestFiles += $filePath
}

Get-Content $untrackedLegacyTestFiles | Foreach-Object
  {
    Copy-Item $_ $target_root -force
    "Copying File: $_ to $target_root"
  }
}

the $outfile is a text file where each line has a partial file path leading to a txt file generated by a test application we use. This info is provided by git, so it looks like this in the $outfile txt file:
!! Some/File/Path/Doc.txt

The "!!" mean git sees it as a new file, however it could be several characters from a " M" to "??". Which is why I am trying to split it on the spaces and take only the last element.
My desired output would be to take the the last element of the split string from the $outfile (Some/File/Path/Doc.txt) and concatenate it with the $repo_dir to form a complete file path, then move the Doc.txt to an archive location ($target_root).

A: To combine a path in PowerShell, you should use the Join-Path cmdlet. To extract the path from your string, you can use a regex:
$extractedPath = [regex]::Match('!! Some/File/Path/Doc.txt', '.*\s(.+)$').Groups[1].Value
$filePath = Join-Path $repo_dir $extractedPath

The Join-Path cmldet will also convert all forward slashes to backslashes so no need to replace them :-).
Your whole script could look like this:
Get-Content $outfile | Foreach-Object {
    $path = Join-Path $repo_dir ([regex]::Match($_, '.*\s(.+)$').Groups[1].Value)
    Copy-Item $path $target_root -force
}

If you don't like to use regexin your code, you can also extract the path using:
$extractedPath = '!! Some/File/Path/Doc.txt' -split ' ' | select -Last 1

or
$extractedPath = ('!! Some/File/Path/Doc.txt' -split ' ')[-1]


text:
Q: Can you query where contacts come from or add a filter to prevent deleted contacts from coming back? I have been monitoring my all contacts and it has been jumping 10000+ every day.  I doubt these are authentic contacts
Is it possible to somehow do a query of where these contacts are coming from?
Also is it possible to add a filter to a sych data extension to prevent contacts from coming in if they have been deleted>

A: Usually, Salesforce queries do not retrieve deleted records unless ALL ROWS is used.
To retrieve only deleted contacts
SELECT Id, name, IsDeleted FROM Contact WHERE IsDeleted = TRUE ALL ROWS

To Retrieve non-Deleted contacts only (add filter contion on isDeleted)
SELECT Id, name, IsDeleted FROM Contact WHERE IsDeleted = FALSE


text:
Q: Question about parent/child relationships and components I'm currently trying to port a project from vuex/REST to vue-apollo. The project shows a list of events, and each event can be expanded to show details, including attendees.
So I'm having an EventList component, that fetches the events and all attributes necessary for the list. And I have a EventDetails child component that is expanded from the list onclick. EventDetails requires some event data as well as the list of attendees to render. Problem is, I cannot find an elegant way to build the queries.
Currently, I have one query for events, that is executed by the EventList component:
query Events($type: [String!]) {
  events(type: $type) {
    id
    name
    attendeeCount
  }
}

Inside the EventList component, I'm passing the event ID to the EventDetails child component, which then in turn queries the API for attendees:
query Event($id: ID!) {
  event(id: $id) {
    id
    name
    attendeeCount
    attendees {
      id
      name
      paymentState
    }
  }
}

The parent component (simplified):
<template>
  <EventDetails v-for="event in events" :eventId="event.id" />
</template>

<script lang="ts">
import …

@Component({
  apollo: {
    events: { … }
  },
  components: {
    EventsDetails
  }
})
export default class EventList extends Vue {
  events: Event[] = []
}
</script>

The child component (simplified):
export default class EventDetails extends Vue {
  @Prop(Number) eventId!: ID
  // I'd like to pass in the complete event object here, and just
  // fetch another attribute "attendees" via graphql, like this:
  @Prop(Object) event!: Event

  apollo: {
    // Passing in the event as prop conflicts with this.
    // How can I fetch more attributes for a passed in object?
    // Is this even possible? Do I have to fetch everything again?
    // Is it possible with vue-apollo to just fetch the attendees
    // and return them as property "attendees" in the EventDetails
    // component?
    event: {
      query: gql`
        query Event($id: ID!) {
          event(id: $id) {
            ...event
            attendees {
              id
              aasmState
              event {
                id
                attendeeSelectionClosed
              }
              ticket {
                id
                companyName
                position
              }
            }
          }
        }
        ${eventFragment}
      `,
      variables() {
        return { id: this.eventId }
      },
      error(error) {
        console.log(error)
      }
    }
  }
}

The problem with this approach is, with the query named event, that I cannot pass in the already fetched event as a prop, so that event data has to be fetched again. Also, event details cannot be rendered immediately after expanding the EventDetails panel (waiting for query execution).
So is there a way to pass in the event data (not just the id) and query just the attendees via GraphQL? The only possible solution I've found is adding another query attendees to the GraphQL server, which I'd like to avoid, because attendees are always grouped under an event and we always know the parent event object.
But is this considered good architecture in GraphQL land? Add a query type for each an every object type you're dealing with, even if always know the parent and querying via the parent works?
It's well possible that I'm trying to do something stupid here, I'm still pretty new to GraphQL architectures.
Your help is greatly appreciated.

A:
So is there a way to pass in the event data (not just the id) and query just the attendees via GraphQL?

No, 'ask' in parent query for parts needed at once in list/details view (f.e. attendees names). Every extension of parent query - asking for superset makes a new request, not using already fetched data (from cache). Ask for more ealier to save requests.

The only possible solution I've found is adding another query attendees to the GraphQL server, which I'd like to avoid, because attendees are always grouped under an event and we always know the parent event object.

In react (I don't use vue) you can pass data as props from parent component - no need to mix this data into query request.
You can ask for attendees 'directly' (not by event) using simple filter on attendees, f.e. attendees (eventID:'some id') {.... - of course realized by attendees resolver


text:
Q: ERR undefined while installing airbnb eslint npx install-peerdeps --dev eslint-config-airbnb
install-peerdeps v3.0.3
Installing peerdeps for eslint-config-airbnb@latest.
npm install eslint-config-airbnb@18.2.1 eslint@^7.2.0 eslint-plugin-import@^2.22.1 eslint-plugin-jsx-a11y@^6.4.1 eslint-plugin-react@^7.21.5 eslint-plugin-react-hooks@^1.7.0 --save-dev

ERR undefined

idk what's that. Already tried to reinstall node(both LTS and current). The path variable is valid.

A: I resolved this by explicitly installing the dependent npm packages i.e. npm install [package]@[version] --save-dev rather than using the npx install-peerdeps shortcut.
The npm package page for eslint-config-airbnb details how to list the dependencies using: npm info "eslint-config-airbnb@latest" peerDependencies
For version 18.2.1 this gave:
{
  eslint: '^5.16.0 || ^6.8.0 || ^7.2.0',
  'eslint-plugin-import': '^2.22.1',
  'eslint-plugin-jsx-a11y': '^6.4.1',
  'eslint-plugin-react': '^7.21.5',
  'eslint-plugin-react-hooks': '^4 || ^3 || ^2.3.0 || ^1.7.0'
}

Log files showing details about the error are located at ~/.npm/_logs/.
The log file shows that npx install-peerdeps chooses ^7.2.0 for eslint and ^1.7.0 for eslint-plugin-react-hooks. BUT the latter eslint-plugin-react-hooks@^1.7.0 requires eslint@"^3.0.0 || ^4.0.0 || ^5.0.0 || ^6.0.0" (according to the log file) hence the error resolving the dependency tree.
I explicitly installed the latest of all packages (i.e. npm install eslint --save-dev etc) which installed the following versions (from package.json) which are in line with the dependencies above.
 "devDependencies": {
    "eslint": "^7.25.0",
    "eslint-config-airbnb": "^18.2.1",
    "eslint-plugin-import": "^2.22.1",
    "eslint-plugin-jsx-a11y": "^6.4.1",
    "eslint-plugin-react": "^7.23.2",
    "eslint-plugin-react-hooks": "^4.2.0"
  }

A: You just need to run:
(
  export PKG=eslint-config-airbnb;
  npm info "$PKG@latest" peerDependencies --json | command sed 's/[\{\},]//g ; s/: /@/g' | xargs npm install --save-dev "$PKG@latest"
)

Instead, as stated in the official docs

A: I had the same problem. My problem was that I had permissions erros when I was installing global packages. First I tried to change the permissions for my node_modules but that didn't worked for me, so I just configured npm to use a different directory.
Here you can see how you can do that:
https://stackoverflow.com/a/55274930

A: *

*First run npm info "eslint-config-airbnb@latest" peerDependencies to check the dependency versions

*Use the versions for your own "npm install string" ex. npm i -D eslint@7.2.0 eslint-plugin-import@2.22.1 eslint-plugin-jsx-a11y eslint-plugin-react@7.21.5 eslint-plugin-react-hooks@^4


text:
Q: what does type 'Future' is not a subtype of type 'Stream?' means? Can someone please let me know where im doing wrong and what changes have to be done in the code in order to overcome this error of  'Future' is not a subtype of type 'Stream?'.Earlier the error was like Future' is not a subtype of type 'Widget' for which i wrapped the wwidget undet the StreamBuilder.Doing so resulted in this error.
The below is the code which results in this error
class _StudentDashboardState extends State<StudentDashboard> {
  userdetails userdetail;
  String res;

  final FirebaseAuth _firebaseAuth = FirebaseAuth.instance;

  final CollectionReference student_details =
      FirebaseFirestore.instance.collection('students');
  final CollectionReference tutor_details =
      FirebaseFirestore.instance.collection("tutors");

  String uid = FirebaseAuth.instance.currentUser.uid;

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

  displayPercentage() async {
    var percentage = 0.0;
    var totalClassesTook;
    var totalClassesAttended;
    try {
      totalClassesTook = await tutor_details.doc(uid).get().then((doc) async {
        var val = await doc.data()['TotalClassesTook'];
        return val;
      });

      totalClassesTook = await totalClassesTook == null ? 0 : totalClassesTook;

      totalClassesAttended =
          await student_details.doc(uid).get().then((doc) async {
        var val = await doc.data()['TotalClassesAttended'];
        return val;
      });
      totalClassesAttended =
          await totalClassesAttended == null ? 0 : totalClassesAttended;
      percentage =
          await ((totalClassesAttended / totalClassesTook) * 100.0) / 100.0;
    } catch (e) {
      percentage = 0.0;
    }
    return Center(
      child: ListView(children: <Widget>[
        Padding(
          padding: EdgeInsets.symmetric(vertical: 150.0),
          child: new CircularPercentIndicator(
            radius: 120.0,
            lineWidth: 13.0,
            animation: true,
            percent: percentage,
            center: new Text(
              "$percentage",
              style: new TextStyle(fontWeight: FontWeight.bold, fontSize: 20.0),
            ),
            footer: Padding(
              padding: EdgeInsets.symmetric(horizontal: 10.0, vertical: 10.0),
              child: new Text(
                "Attendance Percentage",
                style:
                    new TextStyle(fontWeight: FontWeight.bold, fontSize: 17.0),
              ),
            ),
            circularStrokeCap: CircularStrokeCap.round,
            progressColor: Colors.purple,
          ),
        ),
      ]),
    );
  }
      @override
  Widget build(BuildContext context) {
     return Container(
      child: SafeArea(
        child: StreamBuilder(
            stream: displayPercentage(),
            builder: (context, snapshot) {
              return Scaffold(
                appBar: AppBar(
                  backgroundColor: Colors.lightGreen,
                  title: Text('Student Welcome'),
                  actions: <Widget>[
                    TextButton.icon(
                        onPressed: () async {
                          await _auth.signOut();
                          Navigator.of(context).pushNamed('/homepage');

                    },
                    icon: Icon(Icons.person),
                    label: Text('Logout'))
              ],
            ),
            body:
                displayPercentage(),
          );
        }),
  ),
);

}

A: Your displayPercentage function is marked as async which makes whatever the function returns wrapped into a Future automaticallu.
You are returning a Widget which makes the function's return type Future<Widget>. But since you have not mentioned it specifically while defining the function, dart is assuming it to Future<dynamic>.
Now, coming to your StreamBuilder, the parameter stream is supposed to be assigned a Stream. But you are assigning it your function which is actually a Future<dynamic>.
This is why it is giving the error saying that, it expects a Stream<dynamic> but you are giving it a Future<dynamic> and since Future is not a sub class that extends from Stream, the error says Future<dynamic> is not a subtype of type Stream<dynamic>.
To fix this, change your StreamBuilder into a FutureBuilder like this,
@override
Widget build(BuildContext context) {
  return Container(
    child: SafeArea(
      child: FutureBuilder(
        future: displayPercentage(),
        builder: (context, snapshot) {

          // since futures dont immediately give a value, if data is null the show loader
          if (snapshot.data == null) return CircularProgressIndicator();

          // Since data is not null, we can return Scaffold
          return Scaffold(
            appBar: AppBar(
              backgroundColor: Colors.lightGreen,
              title: Text('Student Welcome'),
              actions: <Widget>[
                TextButton.icon(
                    onPressed: () async {
                      // await _auth.signOut();
                      Navigator.of(context).pushNamed('/homepage');
                    },
                    icon: Icon(Icons.person),
                    label: Text('Logout'))
              ],
            ),
            // Since your Future holds the Center widget that you are sending, use it like this
            body: snapshot.data,
          );
        },
      ),
    ),
  );
}


text:
Q: Is there a way to do object (with its attributes) serializing to xml? Create a class (call it FormElement).  That class should have some properties like the metadata they have with data elements (name, sequence number, value—which is just a string, etc).
This class has as attributes of type Validation Application Block Validation classes.
I want to serialize it to xml and deserialize it.  Verify that all properties of the class including the validation application block attributes survive serialization.
some suggestion?

A: The .NET framework has this built in, using C# you would do it like this:
// This code serializes a class instance to an XML file:
XmlSerializer xs = new XmlSerializer(typeof(objectToSerialize));

using (TextWriter writer = new StreamWriter(xmlFileName))
{
     xs.Serialize(writer, InstanceOfObjectToSerialize);
}

And this snippet  is an example of how to deserialize an XML file back to a class instance:
// this code creates a class instance from the file we just made:
objectToSerialize newObject;
XmlSerializer xs = new XmlSerializer(typeof(objectToSerialize));

using (TextReader reader = new StreamReader(xmlFileName))
{
    newObject = (ObjectToSerialize) xs.Deserialize(reader);
}

You must mark your class with the [Serializable] attribute for these to work. If you want to make your XML output a little more pretty, you can use [XmlElement] and [XmlAttribute] attributes on your class properties to have them serialize into your schema of choice.

A: By saying serialize, do you mean use the official Serialization mechanism, or achieve a similar effect?
If your objects are beans, you could use reflection to write a general service that takes a class and writes down its class name and properties. It can similarly read materials from the XML and generate the object (which is what Apache Digester essentially does).

A: What Jonathon Holland said.
However, you also asked about validation.  If you use the code Jonathan posted, all of your properties will serialize and de-serialize correctly.  But if you really want to check it, there is a property you can set with your XmlSerializer object for a *.xsd schema to validate against.  You can create the schema easily enough from your class by using the xsd.exe command-line tool that is included with Visual Studio.
Also, it sounds like you might want to control whether certain properties of your class are serialized as attributes or elements.  Jonathon touched on that, but I want to show an example:
[Serializable]
public class FormElement
{
   [XmlAttribute]
   public string Name {get; set;};

   [XmlAttribute]
   public int Sequence {get; set;};

   [XmlAttribute]
   public string Value {get; set;};

   [XmlElement]
   public Validation OnValidate{get; set;}

   [NonSerialized]
   public string UnimportantProperty {get; set;};

}

Finally, the type for every property that you want to serialize must also be serializable, and complicated types must be serialized as XmlElements.  Otherwise you won't be able to do it.

A: XStream is a pretty good java library for doing just that.


text:
Q: Unknown hanging when I use Numeric in Swift I got no idea why my code breaks Xcode, it does not throw an error or warning, but also it get hanged for no reason! What I am doing wrong there?
Xcode Version 13.2.1 (13C100)
struct ContentView: View {
    @State private var activeValue: CGFloat = 1.0 {
        didSet(oldValue) {
            didSetFunction(totalValue: 10, oldValue: oldValue, value: &activeValue)
        }
    }

    var body: some View {
        Button("+") { activeValue += 1.0 }
    }
}

func didSetFunction<T>(totalValue: T, oldValue: T, value: inout T) where T: Numeric & Comparable {
    if (oldValue != value) {
        if (value >= totalValue) { value = totalValue }
        else if (value < 0) { value = 0 }
    }
}

A: This is actually a pretty interesting question because, as you wrote in a comment on @matt's answer, "it has no issue using same method for didSet of a custom struct, how ever using my method in view combined with State wrapper make issue!"
So, what's happening in your code, where you use @State? Let's de-sugar it to figure it out. We'll go through two phases of de-sugaring.
First, let's rewrite your code to remove the inout parameter. In theory, Swift implements an inout parameter by passing a copy of the value into the receiving function, and then when the function returns, it assigns the possibly-modified parameter value back to its original storage. (In practice it may use a more efficient implementation, but the effect must be equivalent.) We'll make that explicit by returning the possibly-modified value instead of using inout:
struct ContentView: View {
    @State private var activeValue: CGFloat = 1.0 {
        didSet(oldValue) {
            activeValue = update(totalValue: 10, oldValue: oldValue, value: activeValue)
        }
    }

    var body: some View {
        Button("+") { activeValue += 1.0 }
    }
}

func update<T>(totalValue: T, oldValue: T, value: T) -> T
where T: Numeric & Comparable {
    guard oldValue != value else { return value }
    return max(0, min(value, totalValue))
}

Now the assignment back to activeValue is explicit.
Next, we'll de-sugar the use of the @State property wrapper. When you use a property wrapper like @State that has a projectedValue property, Swift converts your property into three properties: one stored property and two computed properties. They look like this:
struct ContentView: View {
    private var _activeValue: State<CGFloat> = State(wrappedValue: 1.0)

    private var $activeValue: Binding<CGFloat> { _activeValue.projectedValue }

    private var activeValue: CGFloat {
        get { _activeValue.wrappedValue }
        nonmutating set {
            let oldValue = _activeValue.wrappedValue

            _activeValue.wrappedValue = newValue

            // THIS IS YOUR didSet CODE.
            activeValue = update(totalValue: 10, oldValue: oldValue, value: activeValue)
        }
    }

    var body: some View {
        Button("+") { activeValue += 1.0 }
    }
}

Now we can see why your @State-using code has infinite recursion. The activeValue setter calls update and assigns the result to activeValue. Since activeValue is a computed property, the only way to perform this assignment is by calling the activeValue setter again—from inside the activeValue setter!
Let's compare that with a version that doesn't use @State:
struct ContentView: View {
    private var activeValue: CGFloat = 1.0 {
        didSet(oldValue) {
            activeValue = update(totalValue: 10, oldValue: oldValue, value: activeValue)
        }
    }

    var body: some View {
        Button("+") {
            var me = self
            me.activeValue += 1.0
        }
    }
}

In this version, the assignment to activeValue happens directly within the didSet observer of the activeValue stored property. When a didSet observer of a stored property assigns to its own property, Swift does not call the willSet and didSet observers of that property again. So there is no recursion.
(The calls to willSet and didSet are only suppressed if the assignment happens directly inside the body of the didSet observer. If didSet calls out to a function that then performs the assignment, that will recursively call didSet.)

A: You have an infinite recursion and consequently a stack overflow:
7   SwiftApp   0x10a15c6ba ContentView.activeValue.setter + 234
8   SwiftApp   0x10a15c2d5 ContentView.activeValue.didset + 229 (ContentView.swift:15)
9   SwiftApp   0x10a15c6d9 ContentView.activeValue.setter + 265
10  SwiftApp   0x10a15c2d5 ContentView.activeValue.didset + 229 (ContentView.swift:15)
11  SwiftApp   0x10a15c6d9 ContentView.activeValue.setter + 265
12  SwiftApp   0x10a15c2d5 ContentView.activeValue.didset + 229 (ContentView.swift:15)
13  SwiftApp   0x10a15c6d9 ContentView.activeValue.setter + 265
14  SwiftApp   0x10a15c2d5 ContentView.activeValue.didset + 229 (ContentView.swift:15)
... (and so on)

Your activeValue setter calls a function that changes (through the inout parameter) the value of activeValue — which triggers the setter, which calls the function, which changes the value, which triggers the setter, which calle\s the function, which changes the value... Loop-loop-loop-kaboom.


text:
Q: Как сгенерировать ID для сериализуемого объекта? Мне нужно проидентифицировать данные и сериализовать их.
Следующий идентификатор не подходит, потому что статические поля не сериализуются:
public class MyClass implements Serializable {
    private static int inc = 0;
    private int id;

    public MyClass() {
        this.id = inc++;
    }
}

Как лучше всего идентифицировать объекты в таком случае?

A: Вам значение генератора нужно хранить в другом месте. В базе или в файле (в обоих случаях предусмотреть атомарный доступ к генератору).
Или, как вариант, использовать для идентификации UUID
public class MyClass implements Serializable {
    private UUID id;

    public MyClass() {
        this.id = UUID.randomUUID();
    }
}

Update
Как тут меня поправляют метод randomUUID() стандартного класса UUID генерирует UUID 4 версии. Т.е. случайный набор значений. И хоте вероятность совпадения двух сгенерированных значений мала, но она есть.
Чтобы получить гарантированно уникальный UUID вам нужно генерировать UUID любой другой версии (1, 2, 3, 5). Они базируются на текущем времени и уникальном идентификаторе компьютера.
К сожалению, стандартный класс их генерировать не умеет. Но можно подключить внежнюю библиотеку, которая умеет это делать. Например JUG (java-uuid-generator)

A: Надо делать так:
public class MyClass implements Serializable {
    transient private static AtomicInteger idCounter=new AtomicInteger(0);
    private int id;

    public MyClass() {
        this.id=idCounter.addAndGet(1); //генерация при создании объекта
    }
}

В этом случае:

*

*Гарантируется атомарность генерации идентификаторов

*Гарантируется невмешательство генератора в сериализацию (transient)

В примере @AntonShchyrov генерация на основе рандома не гарантирует уникальность идентификатора


text:
Q: when to use shared_from_this() If I want to return a shared_ptr for class A, I should use shared_from_this() feature. But I think this will work after I defined a shared_ptr for A already. So if another place wants a shared_ptr I just use the one I made. I wonder when to use shared_from_this().
sample code:
class A : public enable_shared_from_this<A> {
public:
    int a = 0;
    shared_ptr<A> get_this() {
        return shared_from_this();
    }
};

int main() {
    shared_ptr<A> ptr_a(new A);
    cout << ptr_a.use_count() << endl;
    shared_ptr<A> ptr_b = ptr_a->get_this();
    // if somewhere else wants a ptr I just use, shared_ptr<A> ptr_b = ptr_a; after pass it
    // into a function, what situation should i use shared_from_this() for instead ???
    cout << ptr_a.use_count() << endl;
    cout << ptr_b.use_count() << endl;
}

A: You appear to have a misunderstanding about shared_ptr and shared_from_this.
You don't need to use shared_from_this in order to retrieve a shared_ptr if you already have one. In your example, you could just do:
auto ptr_a = std::make_shared<A>();
auto ptr_b = ptr_a;

However, there are cases where a design requires that a class be aware of its shared lifetime -- and must be able to retrieve a shared_ptr to itself. In such a case, you can't simply do: std::shared_ptr<A>{ this } because this would be producing a new shared_ptr node that is tracking the pointer of this -- which could result in a bad/double deletion.
shared_from_this() solves this by allowing the internals of the class to be able to retrieve safe shared_ptr object to the object that was allocated. In my experience, this pattern is most common with asynchronous callback handlers. For example:
auto A::do_something_async() -> void
{
    auto self = shared_from_this();
    std::thread{[self]{
        // do something long-living with 'self'
    }}.detach();
}

Note: I am not advocating for this style of code; just that this is a possible use for it. In general I find it better to design classes such that it never relies on knowing its own lifetime.


text:
Q: Many-to-many that shows columns with null I'm having some difficulty trying to figure how to adjust my query. I'm not very good at SQL queries as it's not my forte. Anyway, I'm not sure what I'm doing wrong. Here's my table setup.
ID | Customer
---+-------------
1  | John
2  | Jane
3  | Steve

ID | Assets
---+-------------
1  | RealEstate
2  | Currency
3  | Stocks

CustomerID | AssetConfigurationId | Status
-----------+----------------------+-------
     1     |           1          |  E
     1     |           2          |  F
     1     |           3          |  X
     2     |           3          |  X

And if I query customer = 3, I want to get the following
AssetConfigurationId | Status
---------------------+------------
         1           | null
         2           | null
         3           | X

Currently have this. I'm trying to understand how I can use left join to show all the assets and just have the values of the statuses to null for a specific customer. Right now it only shows the 3rd row. Trying to do this in a SQL Server stored procedure so that my .net application can get a list of the assets already and I'll just modify the statuses when it comes to converting them to objects.
select
    ac.Id,
    r.Status
from
    assets ac
left join
    assets_ref r on r.AssetConfigurationId = ac.Id
where
    r.CustomerID = 3

A: Move your WHERE condition in the inner query.
select
    ac.Id,
    r.Status
from assets ac
left join
(select * from assets_ref where CustomerID = 3) r
on r.AssetConfigurationId = ac.Id;

A: You can use multiple conditions in JOINs:
select
    ac.Id,
    r.Status
from assets ac
left join assets_ref r
    on r.AssetConfigurationId = ac.Id
    and CustomerID = 3;


text:
Q: After disconnecting from wifi I must "killall wpa_supplicant" before I can reconnect Everytime I disable wifi or lose connection to that network I must do a "killall wpa_supplicant" before I can reconnect. If I don't do that, the system keeps saying "[my-chosen-wifi-point] is disconnected, you are offline" every 30 seconds until I do the killall thing.
I have a recently (2 days ago) updated Ubuntu system.
When looking for a solution I found a similar problem here but the solutions there would not work for me well as I need to be able to occassionally dynamically change wifi access points (when I move around a bit):
Need to restart network interfaces and kill wpa_supplicant, how to fix?
Additionally when I digged around in syslog, I found the following suspicious error messages: "NetworkManager  nl_recvmsgs() error: (-33) Dump inconsistency detected, interrupted". A quick Google search for this message turned out an as-of-today-unfixed 1 years old bug here (or it is unfixed according to Bugzilla):
https://bugs.launchpad.net/ubuntu/+source/network-manager/+bug/1118446
Additionally, this issue started when once the machine with my Ubuntu crashed (ran a program with root rights that had a "poweroff" kernel call embedded in it, caused instant unclean power down, after booted up the NetworkManager/wpa_supplicant combo appeared to not recover properly and the wifi is broken like this since then).
What I would like to know is where exactly is that "dump" about whose "inconsistency" the NetworkManager is complaining so I can do a rm -[r]f on it to get rid of the problem. Or is there anything else wrong out there?
I also think the answer to the question(s) in the last paragraph could help with more questions, for example:
Ubuntu disconnecting from wifi
Also note to myself. This answer could provide a somewhat working solution:
How do I run a simple Zenity script after disconnecting from WiFi?
The trick is to tell the system to "killall wpa_supplicant" when network is down. But I am not sure whether it is going to work correctly (I don't want the wireless to die when I disconnect a wired connection for example). And it will not help much with my reconnect on access point change problem.


text:
Q: React : Why is my localStorage clear on redirect (url change)? I am trying to persist data between pages, a variable that I collect in my url. So my user will enter a url like : https://my-solution/event/:identifier
I want to keep that identifier but I need to go through authentification first. I store my identifier in the local storage or Session storage before the redirection and when I redirect to https://my-solution/auth, this entry disappear from local storage.
Once the auth succeed and I store my user jwt token in this very same local storage, it persists ! My identifier is been deleted but my token persist (and every variable stored after that btw); After my token is being stored I can redirect all I want, and my data persist. I don't understand what's happening...
It is a create-react-app solution. Working with react-router and redux.
Is this linked to the way I redirect ? I use <Redirect> from react-router but also windows.location.href sometimes (inside useEffect callbacks).
I did tried to store a non-dynamic variable like a basic string :
localStorage.setItem("test", "mytestValue")

And this entry does persists. Is this behavior related to dynamic values ?
I do have a complicated workaround : passing the data through location.search in every url and trying in every component to store it until the data persists in the local storage... But I want to know if I am doing something wrong here.
Thank you !
Here is my architecture flow :
Index.tsx
import React from 'react';
import ReactDOM from 'react-dom';
import './index.scss';

import App from './App';
import * as serviceWorker from './serviceWorker';
import { BrowserRouter } from 'react-router-dom';
import { createStore, applyMiddleware } from 'redux';
import { Provider } from 'react-redux';
import reducer from './reducers';
import thunk from 'redux-thunk';
import { signalRMiddleware } from './middlewares/signalRMiddleware';

import 'bootstrap/dist/css/bootstrap.css';
import 'primereact/resources/themes/nova/theme.css';
import 'primereact/resources/primereact.min.css';
import 'primeicons/primeicons.css';

const store = process.env.REACT_APP_WITHOUT_SIGNALR == "true" ? createStore(reducer, applyMiddleware(thunk)) : createStore(reducer, applyMiddleware(thunk, signalRMiddleware()))
ReactDOM.render(
    <Provider store={store}>
        <BrowserRouter basename={process.env.PUBLIC_URL}>
            <App />
        </BrowserRouter>
    </Provider>,
    document.getElementById('root')
);

App.tsx
import React from 'react';
import './App.css';
import Router from './components/Router';
import moment from 'moment';
import 'moment/locale/fr';
moment().locale('fr');

function App() {
  return (
      <Router />
  );
}

export default App;

Router.index
import React from 'react';
import { Route, Switch } from 'react-router-dom';
import ProtectedRoute from './ProtectedRoute';
import UtilsService from '../../services/utils.service';

function Router() {
    const AuthRouters = UtilsService.getRoute('/auth').component;
    const BackofficeRouters = UtilsService.getRoute('/backoffice').component;
    const EventLayout = UtilsService.getRoute('/').component;
    const MultiEventLayout = UtilsService.getRoute('/multiEvents').component;
    const ChatLayout = UtilsService.getRoute('/chat').component;
    const ChatOtoLayout = UtilsService.getRoute('/chat_oto').component;
    const QuestionsLayout = UtilsService.getRoute('/questions').component;
    const PlanningLayout = UtilsService.getRoute('/planning').component;
    const AccueilMobileLayout = UtilsService.getRoute('/accueil_mobile').component;

    return (
        <Switch>
            <Route path="/auth" render={(props: any) => <AuthRouters {...props} />} />
            <ProtectedRoute path="/backoffice" isBackoffice={true} render={(props: any) => <BackofficeRouters {...props} exact />} />
            <ProtectedRoute path="/multiEvents" isBackoffice={false} render={(props: any) => <MultiEventLayout {...props} />} />
            <ProtectedRoute path="/room/:id" isBackoffice={false} render={(props: any) => <EventLayout {...props} />} />
            <ProtectedRoute path="/event/:identifier" isBackoffice={false} render={(props: any) => <EventLayout {...props} />} />
            <ProtectedRoute path="/questions/:idButton" isBackoffice={false} render={(props: any) => <QuestionsLayout {...props} />} />
            <ProtectedRoute path="/chat_oto" isBackoffice={false} render={(props: any) => <ChatOtoLayout {...props} />} />
            <ProtectedRoute path="/chat/:id" isBackoffice={false} render={(props: any) => <ChatLayout {...props} />} />
            <ProtectedRoute path="/planning/:idEvent" isBackoffice={false} render={(props: any) => <PlanningLayout {...props} />} />
            <ProtectedRoute path="/accueil_mobile/:idEvent" isBackoffice={false} render={(props: any) => <AccueilMobileLayout {...props} />} />
            <ProtectedRoute path="/" isBackoffice={false} render={(props: any) => <EventLayout {...props} />} />
        </Switch>
    );
}

export default Router;

ProtectedRoute.tsx
return (
        <Route
            {...rest}
            render={props => {
                let eventUrlIdentifier = "";
                if(props.match.path === "/event/:identifier"){
                    let url = props.match.url;
                    let s = url.split("/");
                    eventUrlIdentifier = s[2];
                }
                if (!fetchAllConfLoading && isClientSettingsLoaded) {
                    //process auth anonymous
                    if (user == null) {
                        if (clientSettings.monoEventId != undefined && clientSettings.allowAnonymous != undefined) {
                            if (!clientSettings.allowAnonymous) {
                                // Redirection vers /Auth si la connexion anonyme n'est pas autorisé pour un mono-event
                                return (
                                    <Redirect to={{ pathname: '/Auth', state: { from: props.location }, search: eventUrlIdentifier }} />
                                );
                            }
                            else {
                                return (
                                    <Redirect to={{ pathname: '/auth/anonyme', state: { from: props.location }, search: eventUrlIdentifier }} />
                                );
                            }
                        }


text:
Q: Assign Data To Value Dynamically In Ionic I'm running the for loop inside row and want to assign data to value field from filterData. I don't want to assign data to value dynamically.
<ion-row *ngFor="let type of filterData">
    <ion-segment [(ngModel)]="selectedSegment" (ionChange)="onSegmentChanged($event)">
       <ion-segment-button value="Must be came from *ngFor">
        {{type.key}}
       </ion-segment-button>
    </ion-segment>
    </ion-row>

filterData array holds:
this.filterData=[
  {"key":"Budget","value":"a1","type":"bar","labelid":"17"},
  {"key":"Parking Capacity","value":"a2","type":"checkbox","labelid":"12"},
  {"key":"Venue","value":"a3","type":"checkbox","labelid":"3"},
  {"key":"No.of Rooms","value":"a4","type":"checkbox","labelid":"15"},
  {"key":"Max.Capacity","value":"a5","type":"bar","labelid":"1"},
  {"key":"Function Type","value":"a6","type":"checkbox","labelid":"11"}];

I want to assigne value data that is in json's value field of elements and not able to do that .
Is there any way to do that ?

A: You can bind value to ion-segment-button by "value={{type.value}}" or [value]="type.value".
<ion-segment-button [value]="type.value">
  {{type.key}}
</ion-segment-button>

<ion-segment-button value="{{type.value}}">
  {{type.key}}
</ion-segment-button>

see working demo.


text: Q: Linear Algebra with Reflection Point P(-2,5) is reflected on the line y=2x/5. How do you find the coordinates of P using linear algebra? P(-2,5) needs to be mapped across the x axis without using the difference formula