text:
Q: Randomly get multiple rows from a table Right now I'm selecting 3 random rows from a table using ORDER BY Rand(); as pointed out all over the web this method is very slow. I am using it on a database with only 30 rows and it takes a long time to return the value. Most of the other solutions i've found only return one row.  What's the best way to return multiple random rows?
$get_projects_query =
  mysql_query(
    "SELECT p_id FROM project_data WHERE p_featured='1' ORDER BY Rand() LIMIT 3"
  ) or die(mysql_error());

while($project_row = mysql_fetch_array($get_projects_query)) {?>
  //Do stuff
}
//end three random featured projects loop)

A: First select the table count. Order by an index column (probably the primary key). Then select limit 1 with offset = to a random integer in the range of 0 to the table count.

A: If there are only 30 rows, you have a couple other options.
Option #1

*

*fetch all 30 rows.

*call shuffle()

*read the first 3 off the pile

Option #2

*

*Generate 3 random numbers from 0 to 29. Call them r1, r2, r3.

*SELECT ... WHERE p_id IN (r1, r2, r3)

Option #3

*

*SELECT p_id FROM ...

*while ($row = mysql_fetch_assoc($result)) $idList[] = $row["p_id"];

*shuffle($idList)

*SELECT ... WHERE p_id IN ($idList[0], $idList[1], $idList[2])

A: If you only have 30 rows why not download all 30 rows to your client and then generate 3 random row indexes

A: As everyone else said. Having only 30 items in your query do like this:

*

*do your query without RAND()

*build an array / object with all the items - E.g.: items[]

*generate 3 random numbers (x1, x2, x3) between 1 and the length of the array and then display them: items[1], items[2], items[3]
Or your query has only for the moment 30 results but in time it will be bigger and bigger?


text:
Q: svg background not painted qt I am trying to display the contents of a .svg file in a QGraphicsView in Qt. For this I use:
QImage image (SCENEWIDTH, SCENEHEIGHT, QImage :: Format_ARGB32);
QSvgRenderer * renderer = new QSvgRenderer (path_img); //path of .svg file
QPainter painter (& image);
renderer-> render (& painter);
QGraphicsSvgItem * f = new QGraphicsSvgItem ();
f-> setSharedRenderer (renderer);

scene2-> setSceneRect (QRectF (0, 0, SCENEWIDTH, SCENEHEIGHT))
scene2-> addItem (f);

ui-> view-> setScene (scene2);
ui-> view-> show ();

The content of the svg consists of several lines to draw that are painted over a background image, loaded into the svg using:
<image id = "img1" href = "sample.png" />

The sample.png image is in the same path as the .svg file I want to display. The browser paints the image correctly if I open it directly from the browser, but nevertheless in the QGraphicsView only the lines are painted, but not the background image.
I have tried many options from searches, but I can not find the reason why this is happening. Thanks for the help
This is a sample SVG file, the image sakura.jpg should be in the same directory as svg file:
    <svg xmlns="http://www.w3.org/2000/svg" version="1.0" style="background-color:black" width="1920" height="1080">
            <style>
.blue  { stroke:blue;  stroke-width:9; fill:transparent; }
.red   { stroke:red;   stroke-width:10; fill:transparent;}
            </style>

   <g class="zone05" transform="translate(0,0) rotate(0,0,0) scale(1)">
      <image id="img05" href="sakura.jpg"/>
      <path class="red" d="M 851 444 m -19 -19 l 38 38 m 0 -38 l -38 38" />
      <path class="red" d="M 475 520 m -19 -19 l 38 38 m 0 -38 l -38 38" />
      <path class="red" d="M 1047 790 m -19 -19 l 38 38 m 0 -38 l -38 38" />
      <path class="blue" d="M 1270 638 m -19 -19 l 38 38 m 0 -38 l -38 38" />
   </g>

</svg>

A: I try your code and it works but the only things that I added to your code,  I put svg file path inside QString and I add QGraphicsScenethat I'm sure you have this too. I push it in this repo for you to test it :
https://bitbucket.org/parisa_HR/stackoverflow/src/master/
   QGraphicsScene *scene2 = new QGraphicsScene(this);
    QImage          image(scene2->width(), scene2->height(), QImage::Format_ARGB32);
    QSvgRenderer   *renderer = new QSvgRenderer(QString(":/svgs/fire.svg"));      // path of .svg file
    QPainter        painter(&image);
    renderer->render(&painter);
    QGraphicsSvgItem *f = new QGraphicsSvgItem();
    f->setSharedRenderer(renderer);

    scene2->setSceneRect(QRectF(0, 0, scene2->width(), scene2->height()));
    scene2->addItem(f);

    ui->view->setScene(scene2);
    ui->view->show();

updated :
I changed my SVG file and add one jpeg file as an example of background.
but it works.

I also try png too.
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<svg
   id="Capa_1"
   enable-background="new 0 0 512 512"
   height="512"
   viewBox="0 0 512 512"
   width="512"
   version="1.1"
   sodipodi:docname="fire.svg"
   inkscape:version="1.1 (ce6663b3b7, 2021-05-25)"
   xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape"
   xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd"
   xmlns:xlink="http://www.w3.org/1999/xlink"
   xmlns="http://www.w3.org/2000/svg"
   xmlns:svg="http://www.w3.org/2000/svg">
  <defs
     id="defs15" />
  <sodipodi:namedview
     id="namedview13"
     pagecolor="#505050"
     bordercolor="#eeeeee"
     borderopacity="1"
     inkscape:pageshadow="0"
     inkscape:pageopacity="0"
     inkscape:pagecheckerboard="0"
     showgrid="false"
     inkscape:zoom="0.35976819"
     inkscape:cx="144.53751"
     inkscape:cy="523.94848"
     inkscape:window-width="1366"
     inkscape:window-height="670"
     inkscape:window-x="0"
     inkscape:window-y="27"
     inkscape:window-maximized="1"
     inkscape:current-layer="Capa_1" />
  <image
     width="512.33936"
     height="512.33936"
     preserveAspectRatio="none"
     xlink:href="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAA+gAAAPoCAIAAADCwUOzAAAACXBIWXMAAAsTAAALEwEAmpwYAAAA
[encoded data, 5868 characters]
"
     id="image1016"
     x="-3.6043305"
     y="1.78023" />
  <g
     id="g10"
     transform="matrix(0.31264363,0,0,0.31264363,30.205716,291.36914)">
    <path
       d="M 454.22,313.78 C 454.22,423.25 365.47,512 256,512 146.53,512 57.78,423.25 57.78,313.78 c 0,-37.65 10.49,-72.86 28.74,-102.83 0,0 25.24,53.86 68.6,36.45 17.05,-6.84 36.46,-26.05 18.16,-57.74 -19.74,-34.17 -9.27,-82.43 34.24,-100.9 C 256,68.18 256,0 256,0 c 4.88,3.13 76.59,50.67 50.28,111.89 -15.72,36.58 -17.6,80.91 15.09,90.71 39.12,11.74 59.77,-42.54 59.77,-42.54 44.59,36.34 73.08,91.7 73.08,153.72 z"
       fill="#fcd703"
       id="path2" />
    <path
       d="M 454.22,313.78 C 454.22,423.25 365.47,512 256,512 V 0 c 4.88,3.13 76.59,50.67 50.28,111.89 -15.72,36.58 -17.6,80.91 15.09,90.71 39.12,11.74 59.77,-42.54 59.77,-42.54 44.59,36.34 73.08,91.7 73.08,153.72 z"
       fill="#fe9100"
       id="path4" />
    <path
       d="m 351.2,416.82 c 0,59.92 -50.51,95.18 -95.2,95.18 -52.56,0 -95.17,-42.61 -95.19,-95.16 0,-0.02 0,-0.02 0,-0.04 -0.24,-19.81 4.04,-43.24 15.97,-70.43 l 38.91,11.38 c 0,-39.56 21.06,-66.17 40.31,-82.23 16.18,-13.48 31.1,-19.52 31.1,-19.52 4.88,58.84 39.4,93.06 51.47,114.71 10.45,18.76 12.63,30.39 12.63,46.11 z"
       fill="#ff7b49"
       id="path6" />
    <path
       d="M 351.2,416.82 C 351.2,476.74 300.69,512 256,512 V 275.52 C 272.18,262.04 287.1,256 287.1,256 c 4.88,58.84 39.4,93.06 51.47,114.71 10.45,18.76 12.63,30.39 12.63,46.11 z"
       fill="#fd435b"
       id="path8" />
  </g>
  <g
     id="g852"
     transform="matrix(0.31264363,0,0,0.31264363,289.55613,310.41629)">
    <path
       d="M 454.22,313.78 C 454.22,423.25 365.47,512 256,512 146.53,512 57.78,423.25 57.78,313.78 c 0,-37.65 10.49,-72.86 28.74,-102.83 0,0 25.24,53.86 68.6,36.45 17.05,-6.84 36.46,-26.05 18.16,-57.74 -19.74,-34.17 -9.27,-82.43 34.24,-100.9 C 256,68.18 256,0 256,0 c 4.88,3.13 76.59,50.67 50.28,111.89 -15.72,36.58 -17.6,80.91 15.09,90.71 39.12,11.74 59.77,-42.54 59.77,-42.54 44.59,36.34 73.08,91.7 73.08,153.72 z"
       fill="#fcd703"
       id="path844" />
    <path
       d="M 454.22,313.78 C 454.22,423.25 365.47,512 256,512 V 0 c 4.88,3.13 76.59,50.67 50.28,111.89 -15.72,36.58 -17.6,80.91 15.09,90.71 39.12,11.74 59.77,-42.54 59.77,-42.54 44.59,36.34 73.08,91.7 73.08,153.72 z"
       fill="#fe9100"
       id="path846" />
    <path
       d="m 351.2,416.82 c 0,59.92 -50.51,95.18 -95.2,95.18 -52.56,0 -95.17,-42.61 -95.19,-95.16 0,-0.02 0,-0.02 0,-0.04 -0.24,-19.81 4.04,-43.24 15.97,-70.43 l 38.91,11.38 c 0,-39.56 21.06,-66.17 40.31,-82.23 16.18,-13.48 31.1,-19.52 31.1,-19.52 4.88,58.84 39.4,93.06 51.47,114.71 10.45,18.76 12.63,30.39 12.63,46.11 z"
       fill="#ff7b49"
       id="path848" />
    <path
       d="M 351.2,416.82 C 351.2,476.74 300.69,512 256,512 V 275.52 C 272.18,262.04 287.1,256 287.1,256 c 4.88,58.84 39.4,93.06 51.47,114.71 10.45,18.76 12.63,30.39 12.63,46.11 z"
       fill="#fd435b"
       id="path850" />
  </g>
  <g
     id="g862"
     transform="matrix(0.31264363,0,0,0.31264363,65.90126,78.351391)">
    <path
       d="M 454.22,313.78 C 454.22,423.25 365.47,512 256,512 146.53,512 57.78,423.25 57.78,313.78 c 0,-37.65 10.49,-72.86 28.74,-102.83 0,0 25.24,53.86 68.6,36.45 17.05,-6.84 36.46,-26.05 18.16,-57.74 -19.74,-34.17 -9.27,-82.43 34.24,-100.9 C 256,68.18 256,0 256,0 c 4.88,3.13 76.59,50.67 50.28,111.89 -15.72,36.58 -17.6,80.91 15.09,90.71 39.12,11.74 59.77,-42.54 59.77,-42.54 44.59,36.34 73.08,91.7 73.08,153.72 z"
       fill="#fcd703"
       id="path854" />
    <path
       d="M 454.22,313.78 C 454.22,423.25 365.47,512 256,512 V 0 c 4.88,3.13 76.59,50.67 50.28,111.89 -15.72,36.58 -17.6,80.91 15.09,90.71 39.12,11.74 59.77,-42.54 59.77,-42.54 44.59,36.34 73.08,91.7 73.08,153.72 z"
       fill="#fe9100"
       id="path856" />
    <path
       d="m 351.2,416.82 c 0,59.92 -50.51,95.18 -95.2,95.18 -52.56,0 -95.17,-42.61 -95.19,-95.16 0,-0.02 0,-0.02 0,-0.04 -0.24,-19.81 4.04,-43.24 15.97,-70.43 l 38.91,11.38 c 0,-39.56 21.06,-66.17 40.31,-82.23 16.18,-13.48 31.1,-19.52 31.1,-19.52 4.88,58.84 39.4,93.06 51.47,114.71 10.45,18.76 12.63,30.39 12.63,46.11 z"
       fill="#ff7b49"
       id="path858" />
    <path
       d="M 351.2,416.82 C 351.2,476.74 300.69,512 256,512 V 275.52 C 272.18,262.04 287.1,256 287.1,256 c 4.88,58.84 39.4,93.06 51.47,114.71 10.45,18.76 12.63,30.39 12.63,46.11 z"
       fill="#fd435b"
       id="path860" />
  </g>
</svg>

As File that you send :

redpajama_set_name: RedPajamaStackExchange


text:
Q: C++ arrays and strstrok I'm working with the arrays in C++. So my input in the array is O3B4F2 and I want to have in output OOOBBBBFF?.. I'm reading about function strtrok but I don't understand that really good because it's dividing sentence on the tokens.
#include <iostream>
#include <string.h>
#include<stdlib.h>
using namespace std;
int main ()
{
  char a[100+1];
  cin>>a;
  char * pch;
  char dioba[]="0 1 2 3 4 5  6 7 8 9 ";
  pch = strtok (a,dioba);
  int c;
  for(int i=0;i<strlen(a);i++)
  {
      if(isdigit(a[i])==1)
      {

      }
  }
  while (pch != NULL)
  {
    cout<<pch<<endl;
    pch = strtok (NULL,dioba);
  }

  return 0;
}

Also, I try to resolve a similar task where I need to divide the array into sets of the letter. I have output need togo and I want to my output look like ne e d to go. So after letter e an o, I want to use white space or new line.
 #include <iostream>
    #include <iostream>
    #include <string.h>
    #include<stdlib.h>
    using namespace std;
    int main ()
    {
      char a[100+1];
      cin>>a;
      char b[100+1];
      int  i=0,j=0;
      for(i;i<strlen(a);i++)
       {
        if(a[i]=='a'||a[i]=='e'|| a[i]=='i')
            for(j;j<strlen(a);j++)
            {
                b[j]=' ';
            }
          b[j]= a[i];
         cout<<b<<endl;
       }
      return 0;
     }

A: For your first case, as mentionned in comments, no need to use strtok. Here is an example of code (although there are many ways to perform the requested task):
#include <iostream>
#include <string>
#include <sstream>

int main ()
{
  std::string s;
  std::cin >> s;
  std::istringstream stream(s);

  char pch;

  // fetch stream for the character to repeat until the end of the string
  while( stream >> pch )
  {
      char nbChars;
      // fetch length for repetition
      stream >> nbChars;
      // convert character to its integer value
      nbChars -= '0';
      // repeat character as many times as needed
      for(int i=0; i < nbChars;i++)
      {
          std::cout << pch;
      }
  }

  return 0;
}

For your second task, I propose this sample code, you can modify letters as needed.
#include <iostream>
#include <string>

int main ()
{
  std::string s;
  std::string needSpaceChars{"aeo"};

  // read content on standard input
  std::getline(std::cin, s);
  // for each char, check its value and add space after the letters defined in needSpaceChars variable
  for(char pch: s)
  {
      // display character first
      std::cout << pch;
      // add space if character is in the list of characters to handle
      if( needSpaceChars.find(pch) != std::string::npos )
      {
          std::cout << ' ';
      }
  }

  return 0;
}

A: The way you have described the problem, the input will always in form of char followed by int. Hence you have to pick in pair (char, int)and print it as per rule.
for(size_t i = 0; i < arr.size() - 1;) {
    int val = (int)arr[i+1] - 48;
    for(auto j = 0; i < val; j++) {
        cout << arr[i];
    }
    i += 2;
}

*

*First for() is for traversing through whole arr.

*Second for() is for printing the particular char for it's number of occurrences.

Note : Since the given arr is of type char you have to convert the second element of pair from char to int.


text:
Q: Angular guard not returning data I'm using google maps API to get maxLat,maxLng,minLat,minLng and then I want to resolve data from the database before create the component, this is for SEO metas and description
the problem is, that the guard is resolving the data, but not resolving the component
my GuardService.ts
@Injectable({
  providedIn: 'root'
})
export class BusquedaGuardService implements CanActivate {
  componentForm = {
    locality: 'long_name',
    administrative_area_level_2: 'short_name',
    administrative_area_level_1: 'short_name'
  };
  ubicacion: string
  maxLng
  minLng
  maxLat
  minLat
  constructor(private http: HttpClient,
    private router: Router,
    @Inject(PLATFORM_ID) private platformId: Object,
    private ngZone: NgZone,
    private mapaService: MapaService,
    private mapsAPILoader: MapsAPILoader) { }
  async getBounds() {
    let promise = new Promise((res, rej) => {
      this.mapsAPILoader.load().then(() => {
        this.ngZone.run(() => {
          let autocompleteService = new google.maps.places.AutocompleteService();
          autocompleteService.getPlacePredictions(
            {
              'input': this.ubicacion,
              'componentRestrictions': { 'country': 'cl' },
            },
            (list, status) => {
              if (list == null || list.length == 0) {
                // console.log("No results");
              } else {
                let placesService = new google.maps.places.PlacesService(document.createElement('div'));
                placesService.getDetails(
                  { placeId: list[0].reference },
                  (detailsResult: google.maps.places.PlaceResult, placesServiceStatus) => {
                    let direccion = ''
                    let contador = 0
                    for (var i = 0; i < detailsResult.address_components.length; i++) {
                      var addressType = detailsResult.address_components[i].types[0];
                      if (this.componentForm[addressType]) {
                        var val = detailsResult.address_components[i][this.componentForm[addressType]];
                        // $(`#${addressType}`).value = val;
                        if (addressType == 'locality') {
                          direccion = direccion + val
                          contador++
                        } else {
                          if (contador == 0 && addressType == "administrative_area_level_2") {
                            direccion = direccion + val
                            contador++
                          } else {
                            if (contador == 0 && addressType == "administrative_area_level_1") {
                              direccion = direccion + val
                            } else {
                              direccion = direccion + ", " + val
                            }
                          }
                        }
                      }
                    }
                    this.mapaService.setDireccion(direccion)
                    let e = detailsResult.geometry.viewport
                    let lat = e[Object.keys(e)[0]]
                    let lng = e[Object.keys(e)[1]]
                    // console.log(lat, lng)
                    this.maxLng = lng[Object.keys(lng)[1]]
                    this.minLng = lng[Object.keys(lng)[0]]
                    this.maxLat = lat[Object.keys(lng)[1]]
                    this.minLat = lat[Object.keys(lng)[0]]
                    let bounds = {
                      maxLat: this.maxLat,
                      maxLng: this.maxLng,
                      minLat: this.minLat,
                      minLng: this.minLng
                    }
                    this.mapaService.setBounds(this.maxLng, this.minLng, this.maxLat, this.minLat)
                    this.mapaService.setLatLng(detailsResult.geometry.location.lat(), detailsResult.geometry.location.lng())
                    console.log('aqui')
                    console.log(`${ipMarco}Instalaciones/Bounds/${this.maxLng}/${this.minLng}/${this.maxLat}/${this.minLat}`)
                    res(bounds)
                    // return this.http.get(`${ipMarco}Instalaciones/Bounds/${this.maxLng}/${this.minLng}/${this.maxLat}/${this.minLat}`).pipe(
                    //   map((res: any) => {
                    //     console.log(res)
                    //     return of(true)
                    //   }),
                    //   catchError(error => {
                    //     console.log('aqui')
                    //     console.log(error)
                    //     this.router.navigateByUrl('')
                    //     return of(false)
                    //   })
                    // )
                  }
                )
              }
            }
          );
        })
      })
    })
    let bounds = await promise
    console.log(bounds)
    return bounds
  }
  canActivate(route: ActivatedRouteSnapshot): Observable<any> {
    // return of(true)
    // console.log('aqui')
    if (route.queryParams['ubicacion']) {
      this.ubicacion = route.queryParams['ubicacion']
      if (this.ubicacion != undefined) {
        if (this.ubicacion != "") {
          return from(this.getBounds()).pipe(
            switchMap((bounds: any) => {
              return this.http.get(`${ipMarco}Instalaciones/Bounds/${bounds.maxLng}/${bounds.minLng}/${bounds.maxLat}/${bounds.minLat}`).pipe(
                map((res: any) => {
                  console.log(res)
                  return of(true)
                }),
                catchError(error => {
                  console.log('aqui')
                  console.log(error)
                  this.router.navigateByUrl('')
                  return of(false)
                })
              )
            })
          )
        }
      }
    }
  }
}

my app-routing.module.ts
const routes: Routes = [
  {
    path: '',
    component: InicioComponent
  },
  {
    path: 'busqueda',
    component: BusquedaComponent,
    canActivate: [BusquedaGuardService],
    resolve: { data: BusquedaResolveService }
  },
];

@NgModule({
  imports: [RouterModule.forRoot(routes, {
    scrollPositionRestoration: 'enabled',
  })],
  exports: [RouterModule]
})
export class AppRoutingModule { }

my resolve.service.ts
@Injectable({
  providedIn: 'root'
})
export class BusquedaResolveService {

  constructor(private mapaService:MapaService,
    private http:HttpClient) {
      console.log('nose')
    }
  resolve(route: ActivatedRouteSnapshot) {
    let maxLng = this.mapaService.getBoundsUnaVez().maxLng
    let minLng = this.mapaService.getBoundsUnaVez().minLng
    let maxLat = this.mapaService.getBoundsUnaVez().maxLat
    let minLat = this.mapaService.getBoundsUnaVez().minLat
    console.log(maxLng,minLng,maxLat,minLat)
    return this.http.get(`${ipMarco}Instalaciones/Bounds/${maxLng}/${minLng}/${maxLat}/${minLat}`);
  }
}

Edit
I realized my mistake, instead using a guard to get data I needed to use resolve
this is my new resolve.service.ts:
import { Injectable, NgZone, PLATFORM_ID, Inject } from '@angular/core';
import { ActivatedRouteSnapshot, Router } from '@angular/router';
import { MapaService } from './mapa.service';
import { ipMarco } from 'src/global';
import { HttpClient } from '@angular/common/http';
import { MapsAPILoader } from '@agm/core';
import { isPlatformBrowser } from '@angular/common';

@Injectable({
  providedIn: 'root'
})
export class BusquedaResolveService {
  componentForm = {
    locality: 'long_name',
    administrative_area_level_2: 'short_name',
    administrative_area_level_1: 'short_name'
  };
  ubicacion: string
  maxLng
  minLng
  maxLat
  minLat
  constructor(private mapaService: MapaService,
    private http: HttpClient,
    private ngZone: NgZone,
    private router: Router,
    private mapsAPILoader: MapsAPILoader,
    @Inject(PLATFORM_ID) private platformId: Object,) {
  }
  async getBounds() {
    if (isPlatformBrowser(this.platformId)) {
      let promise = new Promise((res, rej) => {
        this.mapsAPILoader.load().then(() => {
          this.ngZone.run(() => {
            let autocompleteService = new google.maps.places.AutocompleteService();
            autocompleteService.getPlacePredictions(
              {
                'input': this.ubicacion,
                'componentRestrictions': { 'country': 'cl' },
              },
              (list, status) => {
                if (list == null || list.length == 0) {
                  // console.log("No results");
                } else {
                  let placesService = new google.maps.places.PlacesService(document.createElement('div'));
                  placesService.getDetails(
                    { placeId: list[0].reference },
                    (detailsResult: google.maps.places.PlaceResult, placesServiceStatus) => {
                      let direccion = ''
                      let contador = 0
                      for (var i = 0; i < detailsResult.address_components.length; i++) {
                        var addressType = detailsResult.address_components[i].types[0];
                        if (this.componentForm[addressType]) {
                          var val = detailsResult.address_components[i][this.componentForm[addressType]];
                          // $(`#${addressType}`).value = val;
                          if (addressType == 'locality') {
                            direccion = direccion + val
                            contador++
                          } else {
                            if (contador == 0 && addressType == "administrative_area_level_2") {
                              direccion = direccion + val
                              contador++
                            } else {
                              if (contador == 0 && addressType == "administrative_area_level_1") {
                                direccion = direccion + val
                              } else {
                                direccion = direccion + ", " + val
                              }
                            }
                          }
                        }
                      }
                      this.mapaService.setDireccion(direccion)
                      let e = detailsResult.geometry.viewport
                      let lat = e[Object.keys(e)[0]]
                      let lng = e[Object.keys(e)[1]]
                      // console.log(lat, lng)
                      this.maxLng = lng[Object.keys(lng)[1]]
                      this.minLng = lng[Object.keys(lng)[0]]
                      this.maxLat = lat[Object.keys(lng)[1]]
                      this.minLat = lat[Object.keys(lng)[0]]
                      let bounds = {
                        maxLat: this.maxLat,
                        maxLng: this.maxLng,
                        minLat: this.minLat,
                        minLng: this.minLng
                      }
                      this.mapaService.setBounds(this.maxLng, this.minLng, this.maxLat, this.minLat)
                      this.mapaService.setLatLng(detailsResult.geometry.location.lat(), detailsResult.geometry.location.lng())
                      console.log('aqui')
                      console.log(`${ipMarco}Instalaciones/Bounds/${this.maxLng}/${this.minLng}/${this.maxLat}/${this.minLat}`)
                      res(bounds)
                    }
                  )
                }
              }
            );
          })
        })
      })
      let bounds = await promise
      console.log(bounds)
      return bounds
    }
  }
  resolve(route: ActivatedRouteSnapshot): Promise<any> | boolean {
    if (route.queryParams['ubicacion']) {
      this.ubicacion = route.queryParams['ubicacion']
      if (this.ubicacion != undefined) {
        if (this.ubicacion != "") {
          return this.getBounds().then((bounds: any) => {
            return this.http.get(`${ipMarco}Instalaciones/Bounds/${bounds.maxLng}/${bounds.minLng}/${bounds.maxLat}/${bounds.minLat}`).toPromise()
              .then(respuesta => respuesta).catch(error => {
                console.log(error)
                this.router.navigateByUrl('')
                return false
              })
          })
        }
      }
    }
  }
}

and I deleted my guard, because I dont need it in this component

A: i solved by doing the operation in the resolve.service instead the guard
this worked for me
my resolve.service.ts
import { Injectable, NgZone, PLATFORM_ID, Inject } from '@angular/core';
import { ActivatedRouteSnapshot, Router } from '@angular/router';
import { MapaService } from './mapa.service';
import { ipMarco } from 'src/global';
import { HttpClient } from '@angular/common/http';
import { MapsAPILoader } from '@agm/core';
import { isPlatformBrowser } from '@angular/common';

@Injectable({
  providedIn: 'root'
})
export class BusquedaResolveService {
  componentForm = {
    locality: 'long_name',
    administrative_area_level_2: 'short_name',
    administrative_area_level_1: 'short_name'
  };
  ubicacion: string
  maxLng
  minLng
  maxLat
  minLat
  constructor(private mapaService: MapaService,
    private http: HttpClient,
    private ngZone: NgZone,
    private router: Router,
    private mapsAPILoader: MapsAPILoader,
    @Inject(PLATFORM_ID) private platformId: Object,) {
  }
  async getBounds() {
    if (isPlatformBrowser(this.platformId)) {
      let promise = new Promise((res, rej) => {
        this.mapsAPILoader.load().then(() => {
          this.ngZone.run(() => {
            let autocompleteService = new google.maps.places.AutocompleteService();
            autocompleteService.getPlacePredictions(
              {
                'input': this.ubicacion,
                'componentRestrictions': { 'country': 'cl' },
              },
              (list, status) => {
                if (list == null || list.length == 0) {
                  // console.log("No results");
                } else {
                  let placesService = new google.maps.places.PlacesService(document.createElement('div'));
                  placesService.getDetails(
                    { placeId: list[0].reference },
                    (detailsResult: google.maps.places.PlaceResult, placesServiceStatus) => {
                      let direccion = ''
                      let contador = 0
                      for (var i = 0; i < detailsResult.address_components.length; i++) {
                        var addressType = detailsResult.address_components[i].types[0];
                        if (this.componentForm[addressType]) {
                          var val = detailsResult.address_components[i][this.componentForm[addressType]];
                          // $(`#${addressType}`).value = val;
                          if (addressType == 'locality') {
                            direccion = direccion + val
                            contador++
                          } else {
                            if (contador == 0 && addressType == "administrative_area_level_2") {
                              direccion = direccion + val
                              contador++
                            } else {
                              if (contador == 0 && addressType == "administrative_area_level_1") {
                                direccion = direccion + val
                              } else {
                                direccion = direccion + ", " + val
                              }
                            }
                          }
                        }
                      }
                      this.mapaService.setDireccion(direccion)
                      let e = detailsResult.geometry.viewport
                      let lat = e[Object.keys(e)[0]]
                      let lng = e[Object.keys(e)[1]]
                      // console.log(lat, lng)
                      this.maxLng = lng[Object.keys(lng)[1]]
                      this.minLng = lng[Object.keys(lng)[0]]
                      this.maxLat = lat[Object.keys(lng)[1]]
                      this.minLat = lat[Object.keys(lng)[0]]
                      let bounds = {
                        maxLat: this.maxLat,
                        maxLng: this.maxLng,
                        minLat: this.minLat,
                        minLng: this.minLng
                      }
                      this.mapaService.setBounds(this.maxLng, this.minLng, this.maxLat, this.minLat)
                      this.mapaService.setLatLng(detailsResult.geometry.location.lat(), detailsResult.geometry.location.lng())
                      console.log('aqui')
                      console.log(`${ipMarco}Instalaciones/Bounds/${this.maxLng}/${this.minLng}/${this.maxLat}/${this.minLat}`)
                      res(bounds)
                    }
                  )
                }
              }
            );
          })
        })
      })
      let bounds = await promise
      console.log(bounds)
      return bounds
    }
  }
  resolve(route: ActivatedRouteSnapshot): Promise<any> | boolean {
    if (route.queryParams['ubicacion']) {
      this.ubicacion = route.queryParams['ubicacion']
      if (this.ubicacion != undefined) {
        if (this.ubicacion != "") {
          return this.getBounds().then((bounds: any) => {
            return this.http.get(`${ipMarco}Instalaciones/Bounds/${bounds.maxLng}/${bounds.minLng}/${bounds.maxLat}/${bounds.minLat}`).toPromise()
              .then(respuesta => respuesta).catch(error => {
                console.log(error)
                this.router.navigateByUrl('')
                return false
              })
          })
        }
      }
    }
  }
}


text:
Q: Push notification when application is in background Xamarin IOS FireBase We are developping an application for our client, push notifications are done for Android (background & foreground) and iOS (foreground). But nothing is fired when the payload is sent from Firebase when the application is in background.
[Export("messaging:didReceiveRemoteNotification")]
public override void DidReceiveRemoteNotification(
    UIApplication application,
    NSDictionary userInfo,
    Action<UIBackgroundFetchResult> completionHandler)
{
    displayNotification("notif1");
}

[Export("messaging:didReceiveMessage:")]
public void DidReceiveMessage(Messaging messaging, RemoteMessage remoteMessage)
{
    displayNotification("notif2");
}

{
  "validate_only": false,
  "message": {
    "data": {
      "action": "Create",
      "type": "A",
      "source": "WEB",
      "idDossier": "368",
      "idCartouche": "22953",
      "model": "{\"Id\":22953,\"...\":\"...\"}"
    },
    "notification": null,
    "android": null,
    "webpush": null,
    "apns": {
      "headers": {
        "apns-expiration": "0",
        "apns-priority": "10"
      },
      "payload": {
        "aps": {
          "alert": null,
          "badge": null,
          "sound": null,
          "content-available": 1,
          "mutable-content": 0,
          "category": null,
          "thread-id": null
        }
      }
    },
    "token": null,
    "topic": "d-368-u-77ffb0d907f04bfba8a0e3f35f7fd095",
    "condition": null
  }
}


text:
Q: Use some value from terraform file to json file I have multiple modules, and in each module there is some image with version updated in locals.tf.
also have descriptor.json file where these same image versions should be updated.
Now,
I wanted to ask if there is any way to use same locals.tf version to version used in descriptor.json.(without hardcoding)
Is there any way we can use variable in descriptor.json maybe?
//locals.tf
locals {

  xyz_image = "/image.path"
  xyz_image_version = "1.0.0"
}

//descriptor.json
{
  "service": "xyz",
  "external-resources": {
    "images":
    [
      {
        "name":"xyz_image",
        "version":"1.0.0" //version that should match with locals.tf version
      }
    ]

A: For this you could use the templatefile built-in function [1]:
resource "local_file" "descriptor" {
  content = templatefile("${path.module}/descriptor.json.tpl",
    {
       image_version = local.xyz_image_version
    }
  )
  filename = "${path.module}/descriptor.json"
}

The JSON template file (descriptor.json.tpl) would then have to look like:
{
  "service": "xyz",
  "external-resources": {
    "images":
    [
      {
        "name":"xyz_image",
        "version":"${image_version}"
      }
    ]
}

The image_version in the templated file is a placeholder variable which will be replaced by the value provided in the templatefile function call. The templated file will be used to create a file and save it locally in the module path with the name descriptor.json. You can add arbitrary number of variables to the templated file and as long as you provide the value for them in the function call, they will be replaced with that value. The JSON file can then be used as an input file where needed.

[1] https://www.terraform.io/language/functions/templatefile


text:
Q: Can't display custom post type categories on the page I have a custom post type called "case_studies" and it has 3 categories: "seo", "website-design" and "facebook-advertising".
I have several posts in the main page, and for each post I want to output what categories the post has.
For example, the latest post has a category of "seo" and "facebook-advertising", and I want it to be displayed in the page.
I have tried the get_the_terms(); function but I think I am using it incorrectly.
Here is the code of the page:

        <?php

           $args1 = array( 'post_type' => array('case_studies'), 'order' => 'DESC', 'posts_per_page' => 30, 'orderby' => 'date' );
           $loop = new WP_Query( $args1 );

           while ( $loop->have_posts() ) {

           $loop->the_post();

           $feat_image = wp_get_attachment_url( get_post_thumbnail_id($loop->ID));

        ?>

                    <a href="<?php the_permalink() ?>" class="blog_blocks">

                            <img src="<?php echo get_the_post_thumbnail_url(); ?>"/>

<?php the_title(); ?>

<?php echo wp_strip_all_tags( get_the_excerpt(), true ); ?>

                        Read More

        <?php } ?>

        <?php wp_reset_postdata(); ?>

Here is how the output looks right now and where I want categories to be displayed.


text:
Q: How do I fix this Django Import Error? This feels like one of those questions nobody will be able to answer but I'll ask it anyway.  I have a Django 1.6 project that is raising an import error when I try to access my site's home page via the Django development server:
ImportError at /
No module named photo

The error is occurring at this line at the top of one of my views:
# apps/photos/views.py
from classes.photo import Photo

Here is the stacktrace:
Request Method: GET
Request URL: http://localhost:8000/

Django Version: 1.6.2
Python Version: 2.7.5
Installed Applications:
('django.contrib.auth',
 'django.contrib.contenttypes',
 'django.contrib.sessions',
 'django.contrib.sites',
 'django.contrib.messages',
 'django.contrib.staticfiles',
 'django.contrib.admin',
 'django.contrib.admindocs',
 'apps.admin',
 'apps.account',
 'apps.home',
 'apps.members',
 'apps.messages',
 'apps.payment',
 'apps.photos',
 'apps.signin',
 'apps.profile',
 'scripts',
 'apps.try',
 'favicon',
 'django_nose',
 'django_extensions')
Installed Middleware:
('django.middleware.common.CommonMiddleware',
 'django.middleware.common.BrokenLinkEmailsMiddleware',
 'django.contrib.sessions.middleware.SessionMiddleware',
 'django.middleware.csrf.CsrfViewMiddleware',
 'django.contrib.auth.middleware.AuthenticationMiddleware',
 'django.contrib.messages.middleware.MessageMiddleware',
 'django.middleware.clickjacking.XFrameOptionsMiddleware')

Traceback:
File "/Users/me/venv/yearbook/lib/python2.7/site-packages/django/core/handlers/base.py" in get_response
  101.                 resolver_match = resolver.resolve(request.path_info)
File "/Users/me/venv/yearbook/lib/python2.7/site-packages/django/core/urlresolvers.py" in resolve
  318.             for pattern in self.url_patterns:
File "/Users/me/venv/yearbook/lib/python2.7/site-packages/django/core/urlresolvers.py" in url_patterns
  346.         patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
File "/Users/me/venv/yearbook/lib/python2.7/site-packages/django/core/urlresolvers.py" in urlconf_module
  341.             self._urlconf_module = import_module(self.urlconf_name)
File "/Users/me/venv/yearbook/lib/python2.7/site-packages/django/utils/importlib.py" in import_module
  40.         __import__(name)
File "/www/yearbook/conf/urls.py" in <module>
  16.     url(r'^photos/',             include('apps.photos.urls')),
File "/Users/me/venv/yearbook/lib/python2.7/site-packages/django/conf/urls/__init__.py" in include
  26.         urlconf_module = import_module(urlconf_module)
File "/Users/me/venv/yearbook/lib/python2.7/site-packages/django/utils/importlib.py" in import_module
  40.         __import__(name)
File "/www/yearbook/apps/photos/urls.py" in <module>
  5. from apps.photos.views import ack_photos_uploaded
File "/www/yearbook/apps/photos/views.py" in <module>
  11. from classes.photo import Photo

Exception Type: ImportError at /
Exception Value: No module named photo

Normally this type of problem is easy to solve but this one has me baffled.  I have a number of apps in my "yearbook" project including the photos app in question:
yearbook (Django project)
├── admin
├── apps (My various apps... see below)
├── bin
├── classes  (photo.py in here)
├── conf (my settings.py and config files)
├── manage.py
├── scripts
├── static
└── templates

apps
├── __init__.py
├── __init__.pyc
├── account
├── home
├── members
├── messages
├── photos  (<- problem occurs here)
├── profile
└── signin

classes/photo.py is Python module that contains a Photo class and various instance, static, and class methods needed to manipulate photos.  I use a class instead of a model because I don't need to store photo-related information in my database.
# classes/photo.py
class Photo:
    # instance variables and various methods here
    pass

What's strange about this error is that I can add "from classes.photo import Photo" to any of my other apps' views and I don't get this error.  In fact, my "admin" and "profile" apps import and make extensive use of the photo module's Photo class.  It only happens when I add it to my photos view.py file.  It feels like some sort of name collision but I don't see how that could be since the path for my class module is /www/yearbook/classes/photo.py but the view that tries to import it is in /www/yearbook/apps/photos/views.py.  Both the classes and apps/photos directories have empty __init__.py files in them.
Does anyone know what the problem might be?  This is particularly frustrating because it means my photo management app isn't able to manipulate photos using a photo class that I built to support managing photos.
Thanks!

A: I discovered what the problem was.  I also happened to have a classes.py file in my yearbook/apps/photos directory.  Django seems to have been confusing it with my years/classes directory when I tried to import Photo from my classes.photo module from within apps/photos/views.py.

A: Try to add a __init__.py to your folder classes. This way python knows it's part of your project.


text:
Q: I/O freeze on databases (SQL VSS) Our company is considering a new backup product that is an all in one sort of thing (file system, AD, SQL, etc). The product relies on VSS snapshots to create the full backups for the SQL databases. This causes an I/O freeze on the databases that usually just lasts a second or two, but can take up to 60 seconds (per Microsoft, I believe).
My question is how bad are I/O freezes for databases?  Also, is there any way to determine how long the I/O freeze will be?  I would think it would depend on a number of factors including: the size of the database, activity on it at the time, CPU usage, disk I/O, etc.
I have only been a DBA for less than a year and have not seen this myself, but my coworkers informed me that we have customers who do bulk data loads and in the past even a 1 second I/O freeze on the database will cause their jobs to fail.
We have voiced our concerns to management, but it is likely they will purchase the product.
Thanks for your help!

A: Yeah, this can be pretty bad! I've seen it go on for more than a minute.
There's no way to forecast it without testing it on your server, then checking the error log. You'll see messages for I/O being frozen, and I/O being thawed, along with timestamps.

There are some showstoppers you might wanna consider, though.
Microsoft recommends not doing more than 35 databases per snapshot.

We recommend that you create a snapshot backup of fewer than 35 databases at the same time.

And cloud vendors like AWS who use snapshots set a hard limit of 30 databases per instance.

You can create up to 30 databases on each of your DB instances running Microsoft SQL Server. The Microsoft system databases, such as master and model, don't count toward this limit.

Aside from data being frozen for a long time, you'll want to make sure that your snaps are transactionally consistent (dirty snaps can cause corruption), and that they play nice with your native backups.
For instance, most people will take daily snaps, but still take native log backups to meet RPO. You want to make sure that after you mount a snapshot, you can still restore log backups to get you to a point in time. Otherwise, you're losing all the data in between snapshots.
Of course, if you're in Simple recovery model, or your RPO is pretty wide open, it matters a bit less.


text:
Q: replace the anchor tag with a span or div or p I have a functionality where once the user clicks a link, an ajax request is made and if the request is made then the link shouldn't be clickable anymore.
Here is what I'm using to accomplish this:
$('a[id^="rsvp_"]').click (function (e) {
    e.preventDefault();
    $.post(
        $(this).data('url'),
        function(data) {
            $(this).replaceWith(function(){
                alert (data);
                return $("" + data + "");
            });
        }
    );
})  ;

This code will apply to any id starting with rsvp_ . Everything seems to work including the alert(data) however the anchor tag still remains there. I simply want to replace the anchor tag to something else.
The HTML snippet looks like this
Click to RSVP

Update
Please note that I have multiple links like this on the page i.e. rsvp_1, rsvp_2, rsvp_3 ..etc
I would just like to remove anchor tag on the link that the user clicked. not all the links on the page

A: Try this:
$('a[id^="rsvp_"]').click(function (e) {
    e.preventDefault();
    $.ajax($(this).data('url'), {
        method: 'POST',
        context: this
    }).done(function(data) {
        $(this).replaceWith("" + data + "");
    });
});

A: Try this
$(e.target).replaceWith(function(){
        return $("" + $(this).html() + "");
    });

A: You can achieve the same by using jquery .one method, which makes sure that each selected element is clickable only once.
In a situation like this, if possible, I would personally change all anchor tags to p or spans by default and then apply click once on the selected elements like:
$('p[id^="rsvp_"]').one ("click", function (e) {
    e.preventDefault();
    $.post(
        $(this).data('url'),
        function(data) {
            $(this).replaceWith(function(){
                alert (data);
                return $("" + data + "");
            });
        }
    );
});

more here

A: $("a").removeAttr("href");

better remove href of anchor.. or
  $(this).replaceWith(function(){
      return $("" + $(this).html() + "");
  });


text:
Q: SVG markers don't orient properly on a d3.svg.diagonal curve used as a D3 force layout link I'm a bit new to SVG and d3.js.
While drawing a graph with D3 force layout, I'm using a simple diagonal line generator and using marker-end to draw arrow heads.
When using arc instead of diagonal generator the arrow heads appear just fine. But using diagonal generator like in the code below doesn't produce proper markers:
var vis = this.vis = d3.select(el).append("svg:svg")
    .attr("width", w)
    .attr("height", h);

var force = d3.layout.force()
    .gravity(0.03)
    .distance(120)
    .charge(-800)
    .size([w, h]);

var linkDiag = d3.svg.diagonal()
    .projection(function(d)
    {
        return [d.x, d.y];
    });

vis.append("svg:defs")
        .selectAll("marker")
    .data(["normal", "special", "resolved"])
   .enter()
        .append("svg:marker")
    .attr("id", String)
    .attr("viewBox", "0 -5 10 10")
    .attr("refX", 15)
    .attr("refY", -1.5)
    .attr("markerWidth", 6)
    .attr("markerHeight", 6)
    .attr("orient", "auto")
    .append("svg:path")
    .attr("d", "M 0,-5 L 10,0 L0,5");

...and then also:
    force.on("tick", function() {
        link.attr("x1", function(d) { return d.source.x; })
            .attr("y1", function(d) { return d.source.y; })
            .attr("x2", function(d) { return d.target.x; })
            .attr("y2", function(d) { return d.target.y; })
        .attr("d", linkDiag)
        .attr("marker-end", function(d) { return "url(#special)"; });

    });

The markers are not oriented at all with the vertices.
Any help would be appreciated!

A: It only appears as if the arrows aren't pointing in the right direction because you're moving the arrowhead to a new position via refX and refY.
For example, check out this code which draws diagonals in various directions. The arrowheads appear correctly, with the exception of the one at 180 degrees, but that's probably due to a rounding error.
Now, try changing refX on line 10 to a value of, say, 5. Now, the arrowheads close to the horizontal appear incorrect. To see this more dramatically, try changing the value to 8.
What's happening is you're hiding part of the diagonal so the line appears to be ending at an earlier point, which is curved slightly differently from the actual end-point. The same thing will happen if the arrowhead is too large so that it overlays part of the curve. Note that for diagonals in d3, which are symmetrical bezier curves, the arrowheads should always appear pointing perfectly horizontally or vertically. You can see exactly what's happening by reducing the arrowhead's opacity.

A: Can you specify you question a little more?
However with even running you code I think you problem might be
.attr("orient", "auto")

Try to specify pos


text:
Q: Windows seems to recognize a directory as a file. Is there a way to change it? I've recently tried downloading polarssl from here :
https://polarssl.org/download/polarssl-1.2.8-gpl.tgz
My winrar (on Windows Vista) opens the archive which seems to contain a single FILE. While in the winrar I can open it as if it was a directory, leading me to think that it's either a double archive or a directory which windows somehow erroneously takes as a file. However when I extract it (and not the contents of it), windows sees it as a file without an extension (and is unable to open it in any way).
Is the file a directory and if so how do I let windows know that it is one ? Is it perchance a double archive ?
I tried to google to no avail. Hope it's not a too newbish question :)

A: .tgz is a shortened file extension for .tar.gz (possibly for use on operating systems / filesystems that have trouble with a double file extension) which is, indeed "double archived". More precisely, it means that a directory and its contents first got archived into a .tar file. Then this file got compressed as a whole into a .gz file. (Many compression programs / formats like .zip and .7z do both archiving and compression at once. However, archiving and compression are orthogonal, and in the land of Unix/Linux tools, are performed by different programs.)
The correct way of handling this format, regardless of which extension variant is used, in a GUI archiver would be decompressing it into a .tar file, that you could then unarchive. Alternately, handle it in the intuitive way that one would expect for a ZIP file and just decompress and unarchive in one go. WinRAR seems to do something silly, which is uncompress a foo.tgz file not into foo.tar, but merely strips the extensions and outputs foo.
A long-term solution would be getting a less bad archiver ;) However, either renaming foo.tgz into .tar.gz before decompressing, or renaming the extensionless foo into foo.tar should let you continue working with the file.


text:
Q: I cannot read string after realloc I have this function, I realocate memory, but when i want to read string it doesn't work=>error
Student is a Struct
void insertStudent(Student **myStudents, int *size)
{
    int newSize = *size + 1;
    *myStudents = (Student*)realloc(myStudents, newSize*sizeof(Student));
    printf("Enter your grade: ");
    scanf("%f", &(*myStudents)[*size - 1].nota);

    printf("Enter your first name: ");
    scanf("%s", &(*myStudents)[newSize-1].firstName);

    printf("Enter your second name: ");
    scanf("%s", &(*myStudents)[*size - 1].lastName);
    //Generate a new code
    /*int code = rand() % 1+1000;
    int ok = 0;
    while (ok == 0)
    {
        ok = 1;
        for (int i = 0; i < *size; i++)
            if ((*myStudents)[i].cod == code)
            {
                code = rand() % 1 + 1000;
                ok = 0;
            }
    }*/
    (*myStudents)[*size-1].cod = 7;
    printf("Your code is: %d. Do not forget it! ", 7);
}

A: void insertStudent(Student **myStudents, int *size)
{
    *myStudents = (Student*)realloc(myStudents, newSize*sizeof(Student));
                               //   ^ <- look here

This is a pointer to a pointer to your students. realloc() expects the pointer to the data originally allocated, so you most certainly have to pass *myStudents here!
Also change the code to use a temporary variable. realloc() may return NULL on error, in which case the original memory is still allocated and you have to free() it.
For calculating the size, it's better to use the expression syntax of sizeof (newSize * sizeof **myStudents) because this prevents errors when later changing the type.
For sizes, you should always use size_t, as this is guaranteed to hold any possible size of an object (int is not ...)
Further side note: converting to and from void * is implicit in C and it's arguably better style not to write this cast explicitly.
All in all, the code should be written like this
void insertStudent(Student **myStudents, size_t *size)
{
    size_t newSize = *size + 1;
    Student *newStudents = realloc(*myStudents, newSize * sizeof *newStudents);
    if (!newStudents)
    {
        free(*myStudents);
        *myStudents = 0;
        return; // check for this error in calling code
    }
    *myStudents = newStudents;
    *size = newSize;
    // [...]
}

A: You are reallocting to myStudents. It is not your intention and it is not possible.
From standard 7.22.3.5

void *realloc(void *ptr, size_t size);
Otherwise, if ptr does not match a pointer earlier returned by a
  memory management function, or if the space has been deallocated by a
  call to the free or realloc function, the behavior is undefined. If
  memory for the new object cannot be allocated, the old object is not
  deallocated and its value is unchanged.

Earlier you had undefined behavior, you didn't pass the originally allocated memory's address. Rather you passed a local variable. You had undefined behavior.
Student* t = realloc(*myStudents, newSize*sizeof(Student))
if(t){
  *myStudents = t;
  (*size)++;
}
else {
   perror("realloc failed");
   free(*myStudents);
   exit(EXIT_FAILURE);
}

Also as you are increasing the memory you should do increase it if the call is successful. Then consistently access *size-1 throughout the code, it is easier to handle and go through.
The right way to do it shown above. In case realloc returns NULL you won't lose the reference to the already allocated memory. Also with this comes the advise to check the return value of realloc. Casting is redundant in this case - don't do it.
In the scanf you can simply write
scanf("%s",(*myStudents)[newSize-1].firstName);

otherwise you were passing char (*)[] it expects char*.

A: realloc() needs pointer to the memory to be reallocated which is *myStudents and not myStudents.
Change
 *myStudents = (Student*)realloc(myStudents, newSize*sizeof(Student));

to
 *myStudents = (Student*)realloc(*myStudents, newSize*sizeof(Student));


text:
Q: Load ModernUI but also preload desktop on background
*

*Login

*Windows load modern UI

*Only when I click on the "Desktop" tile shortcut that my desktop is really loaded, it take a few seconds to open everything (like rainmeter and other things)

How can I make windows load both modern UI and my desktop on the background? I don't want to skip the modern UI just autoload the desktop.
Similar to add something.exe to the startup, but what executable should I use? I've tried explorer.exe but didn't work.

A: Windows 8 does load the desktop and any applications listed in the Startup group (presumably also the Run registry key) in the background after loading the start screen. This seems to occur a little later then if triggered manually but it is loaded automatically.
There is currently no native way to make it show the desktop automatically.


text:
Q: Razor MVC C #. Replaces the "." on "," Problem exists, razor replaces the value of the point (1.11) on the value of a comma (1,11)
It looks like the value:

But as displayed on the site:

Please tell me how to make that value was to the point, not a comma?

A: Seems that your current CultureInfo is set to one that uses the comma as decimal separator.
To correct this, you can either force the CultureInfo for the whole application. In your web.config add:
One way to correct this is to force the culture infoSet this in your web.config
<globalization uiCulture="en" culture="en-US" />

Or set a different CultureInfo for the current request only:
var culture = new Globalization.CultureInfo("ru-RU", false);
culture.NumberFormat.CurrencyDecimalSeparator  = ".";
Threading.Thread.CurrentThread.CurrentCulture = culture;

Or a third possibility is to provide a IFormatProvider argument to the ToString method:
@item.density.ToString(CultureInfo.InvariantCulture)

A: ToString returns a human-readable string that is culture-sensitive. For example, for an instance of the Double class whose value is zero, the implementation of Double.ToString might return "0.00" or "0,00" depending on the current UI culture. Your name is Sasha Vasilev, so your UI culture will be ru-RU and decimal separator will be ',' not '.' . You need to do this:
@item.density.ToString(NumberFormatInfo.InvariantInfo)


text:
Q: Is it possible to set a text on hover overlay I have made this row with 4 grid elements with Bootstrap 3.
Demosite can be seen here
The middle box in the grid is 600x410px(see demosite). I would really like to have a white text showing up when a person is hovering that middlebox. Is that possible? I am not quite sure if it is a container inside the overlay there has to be used?

  #front .row {
    padding-bottom: 0px!important;
  }
  body {
    background-color: #f5f5f5;
  }

  /* Set width between grid elements */

  .small-padding.top {
    padding-top: 10px;
  }

  .small-padding.bottom {
    padding-bottom: 10px;
  }

  .small-padding.left {
    padding-left: 5px;
  }

  .small-padding.right {
    padding-right: 5px;
  }

  .margin_bottom {
    margin-bottom: 10px;
  }

  .row [class*="col-"] {
    padding-right: 5px;
    padding-left: 5px;
  }

  .row {
    margin-left: -5px;
    margin-right: -5px;
  }

  .img-responsive {
    height: 100%;
  }

  /* Position of buttons/text in a single grid element */

  .inner-wrapper {
    background: none;
  }

  .centered {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
  }

  .bottom-right {
    position: absolute;
    bottom: 8px;
    right: 16px;
  }

  .bottom-left {
    position: absolute;
    bottom: 2%;
    left: 6%;
  }
/* Position text on full width banner */
  .header-container {
    color: white;
    margin: 0 5%;
  }
  .banner-text {
    position: absolute;
    bottom: 16%;
    left: 6%;
  }

  /* Color on text */

  .dark-font {
    color: #333;
  }

  .light-font {
    color: #fff;
    text-transform: uppercase;
  }

  /* Set full width on columns */

  @media (max-width: 768px) {
    .img-responsive {
      width: 100%;
      height: auto;
    }
    /* Maybe delete btn-success: */
    .btn-success {
      width: fit-content;
    }
  }

  @media (max-width: 991px) {
    h3 {
      font-size: 1.2em;
    }
  }
  .image-overlay {
    position:relative;
  }
  .overlay {
    position:absolute;
    transition:all .3s ease;
    opacity:0;
    transition:1.9s;
    background: #00b1bab8;
  }
  .image-overlay:hover .overlay {
    opacity:1;
  }
  .overlayFade {
    background: rgba(27, 27, 27, 0.5);
    top: 0;
    /* Like this */
    bottom: 0;
    left: 0;
    right: 0;
  }
<!DOCTYPE html>

  <title>FINAL WORKING</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

Har du et værksted eller en reservedelsbutik?

                          Så se de mange fordele her

Looking for having a good time

                          Here is where you should look

Looking for having a good time

                                  Here is where you should look

Looking for having a good time

                                  Here is where you should look

A:

 #front .row {
    padding-bottom: 0px!important;
  }
  body {
    background-color: #f5f5f5;
  }

  /* Set width between grid elements */

  .small-padding.top {
    padding-top: 10px;
  }

  .small-padding.bottom {
    padding-bottom: 10px;
  }

  .small-padding.left {
    padding-left: 5px;
  }

  .small-padding.right {
    padding-right: 5px;
  }

  .margin_bottom {
    margin-bottom: 10px;
  }

  .row [class*="col-"] {
    padding-right: 5px;
    padding-left: 5px;
  }

  .row {
    margin-left: -5px;
    margin-right: -5px;
  }

  .img-responsive {
    height: 100%;
  }

  /* Position of buttons/text in a single grid element */

  .inner-wrapper {
    background: none;
  }

  .centered {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
  }

  .bottom-right {
    position: absolute;
    bottom: 8px;
    right: 16px;
  }

  .bottom-left {
    position: absolute;
    bottom: 2%;
    left: 6%;
  }
/* Position text on full width banner */
  .header-container {
    color: white;
    margin: 0 5%;
  }
  .banner-text {
    position: absolute;
    bottom: 16%;
    left: 6%;
  }

  /* Color on text */

  .dark-font {
    color: #333;
  }

  .light-font {
    color: #fff;
    text-transform: uppercase;
  }

  /* Set full width on columns */

  @media (max-width: 768px) {
    .img-responsive {
      width: 100%;
      height: auto;
    }
    /* Maybe delete btn-success: */
    .btn-success {
      width: fit-content;
    }
  }

  @media (max-width: 991px) {
    h3 {
      font-size: 1.2em;
    }
  }
  .image-overlay {
    position:relative;
  }
  .overlay {
    position:absolute;
    transition:all .3s ease;
    opacity:0;
    transition:1.9s;
    background: #00b1bab8;
  }
  .image-overlay:hover .overlay {
    opacity:1;
  }
  .overlayFade {
    background: rgba(27, 27, 27, 0.5);
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    color: #fff;
    font-size: 15px;
  }
<!DOCTYPE html>

  <title>FINAL WORKING</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

Har du et værksted eller en reservedelsbutik?

                          Så se de mange fordele her

Dymmy Text

Looking for having a good time

                          Here is where you should look

Looking for having a good time

                                  Here is where you should look

Looking for having a good time

                                  Here is where you should look


text:
Q: Tell me something about these "component tensor" TQFT's I noticed that there is a class of TQFT's that exists for every dimension $n\geq1$. It's probably well-known because it's quite simple, but I'm looking for a standard name or a better way to think about it.
Let $n\text{-}\mathrm{Cob}$ denote the symmetric monoidal category of (unoriented) closed $(n-1)$-manifolds $M,N$ and cobordisms $M\sqcup N=\partial B\subseteq B\;$ between them. Let $\mathrm{Cospan}_{\mathrm{Fin}}$ denote the symmetric monoidal category of finite sets $X,Y$ and cospans between them $X\to C\to Y$. In both case the monoidal product is given by disjoint union.
Consider the monoidal functor
$$\pi_0: n\text{-}\mathrm{Cob}\to\mathrm{Cospan}_{\mathrm{Fin}}.$$
where $\pi_0(M)$ is the set of connected components in $M$. On morphisms it is given by
$$\pi_0(M\to B\leftarrow N)=(\pi_0M\to\pi_0B\leftarrow\pi_0N).$$
For every field $k$ and natural number $r$, there's a strong monoidal functor
$$\mathrm{tens}_r: \mathrm{Cospan}_{\mathrm{Fin}} \to \mathrm{Vect}_k$$
that sends a finite set $X$ to the $r^X$-dimensional vector space of order-$X$ tensors $T^{r,\ldots,r}$. For example, if $X=\{1,2\}$ then $\mathrm{tens}_r(X)\cong\mathrm{Mat}_{r\times r}\;\;$. The assignment $\mathrm{tens}_r$ is functorial via tensor multiplication, a straightforward generalization of matrix multiplication. The functor $\mathrm{tens}_r$ is strong monoidal because there is a natural isomorphism
$$\mathrm{tens}_r(n)\otimes\mathrm{tens}_r(n')\cong\mathrm{tens}_r(n+n').$$
The composite $\mathrm{tens}_r\circ\pi_0\colon n\text{-}\mathrm{Cob}\to\mathrm{Vect}_k\;\;$ is a strong monoidal functor for any $r,n\in\mathbb{N}$.
Questions:

*

*Is there a standard name for this sort of TQFT?

*Does it have any universal or other nice properties?

*Is it degenerate in any particular way?

A: The theory you describe is Dijkgraaf-Witten theory with target space a discrete set with $r$ elements. In general, if $X$ is a $\pi$-finite space (i.e., a space with finite homotopy groups, all but finitely many of which are non-trivial), then Dijkgraaf-Witten theory with target space $X$ is the functor $n\text{-}\mathrm{Cob} \to \mathrm{Vect}_k$ which associates to an $(n-1)$-manifold $M$ the vector space of functions $\pi_0\mathrm{Map}(M,X) \to k$, where $\mathrm{Map}(M,X)$ is the mapping space from $M$ to $X$ (here the assumption that $X$ is $\pi$-finite insures this mapping space is $\pi$-finite, and hence has only finitely many connected components). If $W$ is a cobordism from $M$ to $N$ and $\iota_M: M \hookrightarrow W$, $\iota_N: N \hookrightarrow W$ are the inclusions of $M,N$ in the boundary of $W$, then the associated linear map
$$ T_W: k^{\pi_0\mathrm{Map}(M,X)} \to k^{\pi_0\mathrm{Map}(N,X)} $$
is defined as follows: for a function $f: \pi_0\mathrm{Map}(M,X) \to k$ define $T_W(f): \pi_0(N,X) \to k$ by the formula
$$ T_W(f)(C) = \sum_{D \in \pi_0\mathrm{Map}(W,X) | \iota_N^*D = C}f(\iota_M^*D) $$
for $C \in \pi_0\mathrm{Map}(N,X)$, where $\iota_M^*: \pi_0\mathrm{Map}(W,X) \to \pi_0\mathrm{Map}(M,X)$ and $\iota_N^*: \pi_0\mathrm{Map}(W,X) \to \pi_0\mathrm{Map}(N,X)$ are the maps induced by pre-composition with $\iota_M$ and $\iota_N$ respectively. As explained in section 3 of this paper of Freed, Hopkins, Lurie and Teleman, this topological field theory should actually extend all the way down to $0$-manifolds, yielding a fully extended topological field theory. This can definitely be considered as a nice property. I'm not sure about any universal properties, but this theory is definitely related to a lot of interesting mathematics. As for degeneracy, the only form of degeneracy that comes to my mind is that the value associated to $M$ depends only on the homotopy type of $M$, so in terms of producing manifold invariant it cannot go beyond homotopy type. Note that when $X$ is a discrete set of size $r$ then $\pi_0\mathrm{Map}(M,X) = X^{\pi_0(M)}$ is a set of size $r^{\pi_0(M)}$ and the associated vector space is the space of tensors of order $\pi_0(M)$ and degree $r$, which is the case described in the question. Another case of special interest is when $X = BG$ is the classifying space of a finite group.


text:
Q: enquire.js, как правильно переместить элемент при изменении разрешения У меня есть блок с меню
...

И блок с кнопками

   <button>1</button>
   <button>2</button>

, как сделать чтобы было так на ширине меньше 900px

    ...
    <button>1</button>

   <button>2</button>

и вернуть обратно на ширине больше 900px
Я использую библиотеку enquire.js
Вот мой код, но он работает только один раз, дальше всё ломается
function minScreen() {
    console.log('Изменения')
    navigationList.append(callBackBtn);
}
function maxScreen() {
    headerBtnBlock.prepend(callBackBtn);
}
enquire.register('screen and (max-width:1240px)', {
    match : function() {
        window.addEventListener('resize', minScreen);
    },
    unmatch : function() {
        window.addEventListener('resize', maxScreen);
    },
});

A: Вопрос решён. Добавил проверку на ширину окна в обе функции и всё заработало


text:
Q: Pug `#{}` fails to load variable inside `onclick` So I am using a javascript object to render a list of items. My object looks like this:
{
            text: 'One',
            url: 'index.pug'
        },
        {
            text: 'Two',
            url: 'Two.pug'
        },
        {
            text: 'Three',
            url: 'Three.pug'
        }
}

The interesting part is when pug renders them. I am rendering them using something like this:
div
    ul.horizontalScroll
        each item in params.apps
            li
                a(onclick="loadXMLDoc(#{item.url})") #{item.text}

What I cannot figure out is why item.text renders correctly, but on click the link doesn't ping the function. In chrome inspector, I saw this:<a onclick="loadXMLDoc(#)">One </a>. Why is the argument not coming through as index.pug like it should??

A: Try concatenating the variable within the attribute:
a(onclick="loadXMLDoc('" + item.url + "')") #{item.text}

A: The accepted solution did not work for me.  I was able to move on with something slightly different.
a(onclick="loadXMLDoc('#{item.url}')") #{item.text}

Note the difference in single and double quotes.  Also watch out, because text autocomplete might try to add even more quotes.
This solution works because loadXMLDoc expects a string.  You need to use different quote chars so that the url string becomes nested inside of the attribute string when it is converted to html.


text:
Q: How to order by another table join by eager loading in Laravel I got product and stocks table;
products
id int
name varchar
created_at timestamp

stocks
id int
name varchar
product_id varchar
created_at timestamp

Product Model
public function validStock() {
    return $this->hasMany('Stock')->where('quantity', '>', 10);
}

If both have created_at, how to order by stocks's created_at, I've tried two methods and it's not work
Product::with('validStock')->orderBy('validStock.created_at', 'DESC');

Product::with(array('validStock' => function($q) {
    $q->orderBy('created_at', 'DESC');
}));

A: Instead of sorting after retrieving all data (which is impossible to do in an efficient way when paginating results) you can use a join.
(This answer is based on this one.)
Product::with('validStock')
    ->join('stocks', 'stocks.product_id', '=', 'products.id')
    ->select('products.*') // Avoid selecting everything from the stocks table
    ->orderBy('stocks.created_at', 'DESC')
    ->get();

The only thing I don't like about this is that it takes away some of the database abstraction, in that you have to write your table names here.
Note that I haven't tried this with a hasMany relationship in this direction, as you have it in your example (selecting products, and each product has many stocks). I've tried only with the hasMany in the other direction (eg selecting stocks, each of which has exactly one product).

A: You can not apply an order while querying an eagerly loaded relationship in Laravel. You can order the Collections after the query has been performed.
$products = Product::with(array('validStock'))
    ->get()
    ->each(function ($product)
    {
        $product->validStock = $product->validStock
            ->sortBy(function ($validStock)
            {
                return $validStock->created_at;
            })
            ->reverse();
    });

A: You should return $q in the closure:
Product::with(array('validStock' => function($q) {
    return $q->orderBy('created_at', 'DESC');
}));


text:
Q: Will this cause memory leak in java? This is an interview question but I'm not quite sure about the correct answer. Suppose we have some classes like:
public class A {
    public Object link;
    public A() {
        link = null;
    }
}

Then we create two instances:
A a1 = new A();
A a2 = new A();
a1.link = a2;
a2.link = a1;

Then we release the references:
a1 = null;
a2 = null;

Then the question is: as JVM would use GC mechanism. How would it handle this case? Will it instantly remove the two instances when it runs or just have the memory space signed and leave them alone? What if I have 1 million such instances that form a cycle and have no external references? Will the cleaning makes the GC thread hang?

A: The objects themselves can reference eachother with as many links (one million cycles as you mention) as you want. If there is no 'route' back to a thread, the objects are eligible for garbage collection, no matter how many other garbage eligible nodes they connect to.
Now this does not mean they WILL get collected, only that they're eligible. So if your garbage collector decides not to process them, then I suppose that could be considered a memory leak. You can't guarantee they'll disappear.

A: Cyclical references may cause memory leaks for naive implementations of certain garbage collection strategies such as reference counting.  (Which is not to say that reference counting is naive but that poor implementations may suffer from the problem.)
However, this problem is well known to people who implement GCs and it can be avoided.  Moreover, most modern JVMs use generational garbage collectors which typically do not suffer from such problems.

A: As per the current logic of code a1 has a member variable which points to a2 and a2 has ha member variable which points to a1. When you do a1 = null a1 becomes eligible for getting GCed. Same is case with a2. Now when GC runs then it tries to see what all objects are reachable starting from root and even though these two refer each other they become unreachable in chain starting from root (case of isolation) hence they get garbage collected without any issues.


text:
Q: node.js and v2ray websocket vless my problem maybe be some complex
i want to develop a v2ray(vless)+tls+websocket server with auth system
i dont want edit v2ray source code
i just want develop a middleware to handle auth with node.js
i wants verify user by username and password and add his ip to white ip list for my vpn port
i dont know how can i do this, i know ip is dynamic and i can re-register and replace it with client automatically
now i have 2 options with 2 questions:

*

*can i use ngingx? with nginx i can make a whiteListIP in config file and i can edit it and restart it with node.js app per user register, but it makes a question, for use new config you should restart nginx, it can reduce performance?i dont know nginx restarting how much time need

*can i register them with node.js and forward them request to vpn port?my mean is my node.js app is a middleware between user and vpn port to  auth requests, requests are websocket connection.
ty if u can help me


text:
Q: making a ajax live load can anyone know how can I make this as an ajax live load?
unfortunately, I have limited acknowledge about javascript/jquery/ajax
simply I want to load the search result on ajax live load
This is my javascript code to load the data but it will refresh the page
I want to not refresh the page and load the data on live load
<script type="text/javascript">

function get_url() {
    var urlPrefix   = 'https://example.com/home/courses?'
    var urlSuffix = "";
    var slectedCategory = "";
    var selectedLevel = "";
    var selectedIelts = "";
    var selectedCountry = "";
    var selectedPtype = "";
    var selectedDtype = "";
    var selectedLanguage = "";
    var selectedRating = "";

    //Get selected category
   $('.categories:checked').each(function() {
       selectedCategory = $(this).attr('value');
   });

     // Get selected  countries
    if($("#country-search-value-unique").val() != 'all'){
      selectedCountry = $("#country-search-value-unique").val();
    };

    if($("#ielts-search-value-unique").val() != 'all'){
      selectedIelts = $("#ielts-search-value-unique").val();
    };

    if($("#ptype-search-value-unique").val() != 'all'){
      selectedPtype = $("#ptype-search-value-unique").val();
    };

    if($("#dtype-search-value-unique").val() != 'all'){
      selectedDtype = $("#dtype-search-value-unique").val();
    };

    if($("#level-search-value-unique").val() != 'all'){
      selectedLevel = $("#level-search-value-unique").val();
    };

    if($("#price-search-value-unique").val() != 'all'){
      selectedPrice = $("#price-search-value-unique").val();
    };

    // Get selected difficulty Level
    $('.languages:checked').each(function() {
        selectedLanguage = $(this).attr('value');
    });

    // Get selected rating
    $('.ratings:checked').each(function() {
        selectedRating = $(this).attr('value');
    });

    urlSuffix = "category="+selectedCategory+"&&level="+selectedLevel+"&&ielts="+selectedIelts+"&&country="+selectedCountry+"&&ptype="+selectedPtype+"&&dtype="+selectedDtype+"&&language="+selectedLanguage+"&&rating="+selectedRating;
    var url = urlPrefix+urlSuffix;
    return url;
}
function filter() {
    var url = get_url();
    window.location.replace(url);
    //console.log(url);
}

function toggleLayout(layout) {
    $.ajax({
        type : 'POST',
        url : 'https://example.com/home/set_layout_to_session',
        data : {layout : layout},
        success : function(response){
            location.reload();
        }
    });
}

function showToggle(elem, selector) {
    $('.'+selector).slideToggle(20);
    if($(elem).text() === "show_more")
    {
        $(elem).text('show_less');
    }
    else
    {
        $(elem).text('show_more');
    }
}

$(document).on('click', '.catparent-label', function(e) {
                $(this).next('ul').fadeIn(); $('li.has').removeClass('is-active'); $('ul.tree').addClass('has-selection'); $('ul.tree').find("label").removeClass('is-seleted'); $(this).closest('li').addClass('is-active'); $(this).addClass('is-seleted'); $('ul.tree').find("input[type='checkbox']"); $(this).closest('li').find(".catparent"); $('.BackListDisciplines').show(); StudyFilter(); e.stopPropagation()
            }

        ); $(document).on('click', '.subcat-label', function(e) {
                $('ul.tree').find("label").removeClass('is-seleted'); $('ul.tree').find("input[type='checkbox']").prop('checked',  !1); $(this).addClass('is-seleted'); $(this).closest('li').find(".subcat"); StudyFilter(); e.stopPropagation()
            }

        ); $(document).on('click', '.BackListDisciplines', function(e) {
                $('li.has').removeClass('is-active'); $('ul.tree').find("label").removeClass('is-seleted'); $('ul.tree').removeClass('has-selection'); $('.tree ul').hide(); $('ul.tree').find("input[type='checkbox']"); $('.BackListDisciplines').hide(); StudyFilter()
            }

        );
</script>


text:
Q: HTML5 video background - strange layer on top? I am trying to add a video background to a page and have 2 problems/questions.

*

*I want the video stay in a div at the top of the page vs stay in full browser window (what is happening now)

*The video only appears after scrolling down the page. Almost as if there is a div over top. Can't figure it out.

Here is HTML and CSS:

.section-content {
  width: 50%;
  display: inline-block;
}
#section1 .section-container {
  height: 800px;
  width: 100%;
  text-align: center;
  background-color: ;
  padding-top: 100px;
}
video {
  position: fixed;
  top: 50%;
  left: 50%;
  min-width: 100%;
  min-height: 100%;
  width: auto;
  height: auto;
  z-index: -100;
  transform: translateX(-50%) translateY(-50%);
  background: url('') no-repeat;
  background-size: cover;
  transition: 1s opacity;
}
#section2 .section-container {
  height: 800px;
  width: 100%;
  text-align: center;
  background-color: ;
}
#section3 .section-container {
  height: 800px;
  width: 100%;
  text-align: center;
  background-color: ;
}
<video autoplay muted loop id="bgvid">
  <source src="http://callmenick.com/_development/video/full-screen-background-video/media/demo.mp4" type="video/mp4">
</video>

    ?

Main headline is here

Sub headline is here about stuff.

Assertively synergize enterprise-wide

Globally exploit value-added mindshare for B2C synergy. Authoritatively orchestrate technically sound meta-services and revolutionary infrastructures. Assertively synergize enterprise-wide communities before adaptive internal or "organic" sources.

A: Answer for 1)
Change your video position:fixed to position:absolute to keep it at the top.
Answer for 2)
Probably the video takes time to load due to external link and also large size. Try downloading the video and put it in your web resources folder to load it locally and also see if the size can be reduced of the video if its big. (Need more detail on this to solve as not able to reproduce sample: http://codepen.io/Nasir_T/full/rWjxeN/)
[Edit for issue # 2] - User found the problem and fixed on his own
Comment from M Hamilton: Got it! Had height:100%; margin: 0; padding: 0; in a body tag. Removed these and it works fine.

A: If the video in the example is representative of what you want to use (i.e. it is longer than just a few seconds and it has audio), you should not autoplay the video, and definitely not without providing quick-to-reach keyboard-accessible controls that allow the user to stop it!
Here is why:

*

*Some people, especially blind people, use a screen reader to access web content (and their computer or smart phone in general). Most screen readers use speech synthesis to tell the user what's on the page. When audio (or video containing audio) starts playing automatically, it will interfere with the screen readers speech output. So, if you do use audio that plays automatically, make it very short (at most a few seconds) and/or make sure that it is easy to pause or stop (a keyboard-accessible control for this should be very easy to reach). See Understanding Success Criterion 1.4.2 in the Web Content Accessibility Guidelines 2.0.

*Some people get distracted by moving content and then have difficulty interacting with the web content. See Understanding Success Criterion 2.2.2 in the Web Content Accessibility Guidelines 2.0:

(...) Content that moves or auto-updates can be a barrier to anyone who has trouble reading stationary text quickly as well as anyone who has trouble tracking moving objects. It can also cause problems for screen readers.
  Moving content can also be a severe distraction for some people. Certain groups, particularly those with attention deficit disorders, find blinking content distracting, making it difficult for them to concentrate on other parts of the Web page. (...)

See also Why Autoplay is an accessibility issue on AbilityNet (October 2015).


text:
Q: Flutter how can i map a list and pass it between screens I am stuck at passing my data list through pages. I have a list of data which i am showing by ListViewbuilder and i need to pass the data of a list in next page. But its showing error of <String, dynamic> is not a subtype of 'List<dynamic> I know error is because the second page expect a list or something but i am passing a list so why its showing ? or i need to map or something ?
My code
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

class OrderDetails extends StatefulWidget {
  final List text;

  // receive data from the FirstScreen as a parameter
  OrderDetails({Key key, @required this.text}) : super(key: key);

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

class _OrderDetailsState extends State<OrderDetails> {
  @override
  Widget build(BuildContext context) {
    print(widget.text);

    double stackWidth = MediaQuery.of(context).size.width;
    double stackHeight = MediaQuery.of(context).size.height;
    return Scaffold(
      appBar: AppBar(  centerTitle: true,backgroundColor: Colors.white, leading: IconButton(
        icon: Icon(Icons.arrow_back, color: Colors.black),
        onPressed: () => Navigator.of(context).pop(),
      ), title: Text('Order#314313', style: TextStyle(color: Colors.black),),),
      body: Column(
        children: <Widget>[
         Padding(
           padding: const EdgeInsets.all(15.0),
           child: Row(
             mainAxisAlignment: MainAxisAlignment.spaceBetween,
             children: <Widget>[
               Text('Custom Information', style: TextStyle(fontFamily: 'SFPROBOLD', fontWeight: FontWeight.bold, fontSize: 15),),
               Text('Delivery', style: TextStyle(fontFamily: 'SFPROBOLD', fontSize: 14, color: Color(0xffea6c7b), fontWeight: FontWeight.bold),)
             ],
           ),
         ),
          Container(
            width: double.infinity,
            color: Colors.white,
            child: Padding(
              padding: const EdgeInsets.all(15.0),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: <Widget>[
                  Text('Mohammad Bilal', style: TextStyle(fontFamily: 'SFPROBOLD', fontWeight: FontWeight.bold, fontSize: 17),),
                  SizedBox(height: stackHeight * 0.004,),
                  Text('+966 59 11111', style: TextStyle( fontSize: 14, color: Colors.grey),),
                  SizedBox(height: stackHeight * 0.01,),
                  Container(
                    height: stackHeight * 0.001,
                    color: Color(0xffeaeaea),
                  ),
                  SizedBox(height: stackHeight * 0.01,),
                  Text('Home | Eastern Ring Road', style: TextStyle(fontFamily: 'SFPROBOLD', fontWeight: FontWeight.bold, fontSize: 17),),
                  SizedBox(height: stackHeight * 0.004,),
                  Text('6, Building 9, Second floor, Lulu', style: TextStyle( fontSize: 14, color: Colors.grey),),
                ],
              ),
            ),
          ),
          Padding(
            padding: const EdgeInsets.all(15.0),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: <Widget>[
                Text('Items Ordered', style: TextStyle( fontSize: 15),),
                Padding(
                  padding: const EdgeInsets.all(8.0),
                  child: Container(
                    width: stackWidth * 0.1,
                    decoration: BoxDecoration(
                        color: Color(0xff008ac7),
                        borderRadius: BorderRadius.all(Radius.circular(5))
                    ),

                    child: Padding(
                      padding: const EdgeInsets.all(4.0),
                      child: Center(child: Text('PAID', style: TextStyle(color: Colors.white, fontSize: 9),)),
                    ),
                  ),
                )              ],
            ),
          ),
          Container(
            color: Colors.white,
            child: Padding(
              padding: const EdgeInsets.all(16.0),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: <Widget>[
                  Row(

                    children: <Widget>[
                      Text('2x', style: TextStyle(color: Color(0xff17b39e), fontSize: 15, fontWeight: FontWeight.bold),),
                      SizedBox(width: stackWidth * 0.04,),
                      Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: <Widget>[
                          Text('Chicken biryani', style: TextStyle(fontFamily: 'SFPROBOLD', fontWeight: FontWeight.bold, fontSize: 17),),
                          Text('Leg peice', style: TextStyle( fontSize: 14, color: Colors.grey),),
                        ],
                      ),
                    ],
                  ),
                  Text('450 SAR', style: TextStyle(fontFamily: 'SFPROBOLD', fontWeight: FontWeight.bold, fontSize: 17),),
                ],
              ),
            ),
          ),
          Container(
            height: stackHeight * 0.001,
            color: Color(0xffeaeaea),
          ),
          Container(
            color: Colors.white,
            child: Padding(
              padding: const EdgeInsets.all(16.0),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: <Widget>[
                  Row(

                    children: <Widget>[
                      Text('2x', style: TextStyle(color: Color(0xff17b39e), fontSize: 15, fontWeight: FontWeight.bold),),
                      SizedBox(width: stackWidth * 0.04,),
                      Column(
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: <Widget>[
                          Text('Chicken karahi', style: TextStyle(fontFamily: 'SFPROBOLD', fontWeight: FontWeight.bold, fontSize: 17),),
                          Text('Extra spicy', style: TextStyle( fontSize: 14, color: Colors.grey),),
                        ],
                      ),
                    ],
                  ),
                  Text('450 SAR', style: TextStyle(fontFamily: 'SFPROBOLD', fontWeight: FontWeight.bold, fontSize: 17),),
                ],
              ),
            ),
          ),
          Container(
            height: stackHeight * 0.001,
            color: Color(0xffeaeaea),
          ),
          Padding(
            padding: const EdgeInsets.all(15.0),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
              children: <Widget>[
                Text('Total (incl, Tax)', style: TextStyle(fontSize: 15,),),
                Text('65 SR', style: TextStyle(fontFamily: 'SFPROBOLD', fontSize: 15, fontWeight: FontWeight.bold),)
              ],
            ),
          ),
          Padding(
            padding: const EdgeInsets.all(15.0),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceEvenly ,
              children: <Widget>[
                Container(
                  width: stackWidth * 0.35,
                  height: stackHeight * 0.07,
                  decoration: BoxDecoration(
                    color: Color(0xff17b39e),
                      borderRadius: BorderRadius.all(Radius.circular(5))
                  ),
                  child: Center(child: Text('Accept', style: TextStyle(fontSize: 18, color: Colors.white, fontWeight: FontWeight.bold),))
                ),
                Container(
                    width: stackWidth * 0.35,
                    height: stackHeight * 0.07,
                    decoration: BoxDecoration(
                        color: Color(0xfffe6c6c),
                        borderRadius: BorderRadius.all(Radius.circular(5))
                    ),
                    child: Center(child: Text('Cancel', style: TextStyle(fontSize: 18, color: Colors.white, fontWeight: FontWeight.bold),))
                )
              ],
            ),
          ),

          Padding(
            padding: const EdgeInsets.all(15.0),
            child: Row(
              mainAxisAlignment: MainAxisAlignment.spaceEvenly ,
              children: <Widget>[
                Container(
                    width: stackWidth * 0.35,
                    height: stackHeight * 0.07,
                    decoration: BoxDecoration(
                        color: Color(0xff7d5f93),
                        borderRadius: BorderRadius.all(Radius.circular(5))
                    ),
                    child: Center(child: Text('Ready', style: TextStyle(fontSize: 18, color: Colors.white, fontWeight: FontWeight.bold),))
                ),
                Container(
                    width: stackWidth * 0.35,
                    height: stackHeight * 0.07,
                    decoration: BoxDecoration(
                        color: Color(0xfffe6c6c),
                        borderRadius: BorderRadius.all(Radius.circular(5))
                    ),
                    child: Center(child: Text('Cancel', style: TextStyle(fontSize: 18, color: Colors.white, fontWeight: FontWeight.bold),))
                )
              ],
            ),
          )
    ],
    ),
    );
  }
}

Second page code where i am trying to get data
class OrderDetails extends StatefulWidget {
  final List text;

  // receive data from the FirstScreen as a parameter
  OrderDetails({Key key, @required this.text}) : super(key: key);

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

I need help to print the list in second page.

A: You should set the generic type of the List in the receiving widget.
class OrderDetails extends StatefulWidget {
  final List<String, dynamic> text;

  // receive data from the FirstScreen as a parameter
  OrderDetails({Key key, @required this.text}) : super(key: key);

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


text:
Q: Botón para seleccionar el contenido de un GridView: aspx y C# Cómo podría configurar un botón que me seleccione TODOS los datos de las columnas de un GridView. Tengo configurado un botón con código java:
  <script type="text/javascript">
 function CopyGridView()
{
 var div = document.getElementById('GRILLA');
div.contentEditable = 'true';
var controlRange;
if (document.body.createControlRange) {
controlRange = document.body.createControlRange();
controlRange.addElement(div);
controlRange.execCommand('Copy');
}
div.contentEditable = 'false';
}
</script>

Pero me copia TODA la Grilla, junto con los titulos de cada columna. Es por ello que eh querido intentar solo copiar los datos, sin guardarlos en el portapapeles o mandarlo a un documento en Excel.


text:
Q: Munin access to MySQL According to several tutorials, the following should work:
Create a new user in MySQL.
$ mysql -uroot -p
> CREATE USER 'munin'@'localhost';
> exit;

Use that user in munin to access the database:
edit /etc/munin/plugin-conf.d/munin-node. At [mysql*] set the following:
[mysql*]
env.mysqlopts -u munin

Strange thing, is that running
 /usr/sbin/munin-node-configure --suggest | grep mysql

Which tells me that MySQL cannot access the database and that it tries to access the database using user root:
[DBI connect('mysql;mysql_connect_timeout=5','root',...) failed: Access denied for user 'root'@'localhost' (using password: NO)

This is a CentOS 5.5 machine.
Why should munin-node-configure ignore the setting in /etc/munin/plugin-conf.d/munin-node? Should I set this elsewhere? Reloading or restarting the munin-node deamon changes nothing either.

A: For Munin 1.4.7 there is error in documentation: mysql plugin looks for environment variables using another name.
You can check /usr/share/munin/plugins/mysql_
my %config = (
    'dsn'        => $ENV{'mysqlconnection'} || 'DBI:mysql:mysql',
    'user'       => $ENV{'mysqluser'}       || 'root',
    'password'   => $ENV{'mysqlpassword'}   || '',
);

So because the script doesn't check 'mysqlopts' I had to set up
[mysql*]
env.mysqluser username
env.mysqlpassword pass

then restart munin-node (just to be on the safe side).

A: for me wildcards didnt seem to work either but the following did work
[mysql_queries]
env.mysqlopts -u dev1


text:
Q: Populating field from variable in React. using css on it I have below form in react.
      const inputForm = [
                {"canHaveAnswer":true,"label":i18n.t("signature_name1_lab"),"placeholder":i18n.t("signature_name1"),"error_message":"","type":"text","types":["text","email","number"],
                {"canHaveAnswer":true,"label":i18n.t("signature_name2_lab"),"placeholder":i18n.t("signature_name2"),"error_message":"","type":"text","types":["text","email","number"],
                {"canHaveAnswer":true,"label":i18n.t("signature_phone_lab"),"placeholder":i18n.t("signature_phone"),"error_message":"","type":"number","types":["text","email","number"]
 ]

I am using this form like below.
return (
            <div>
                {i18n.t("signature_heading")}
                <ReactForm
                    data={inputForm}   --here I am refering
                    answer_data={[]}
                    ref="signature_form"
                    isValidation={isCheckValidation}
                />
            </div>
        )

these records getting displayed one by one in row.
I have to display them in same row. I know how to apply css but since it is form, how can I apply the same?


text:
Q: How to get dummies in complicated condition I have dataframe below
   col
A  a
A  b
A  c
B  d
B  e
C  f

I would like to get dummy variable
   a b c d e f
A  1 1 1 0 0 0
B  0 0 0 1 1 0
C  0 0 0 0 0 1

How can I get this?
I tried
df.col.get_dummies()
But I couldnt groupby.

A: You need groupby by index and aggregate max:
print (df.col.str.get_dummies().groupby(level=0).max())
   a  b  c  d  e  f
A  1  1  1  0  0  0
B  0  0  0  1  1  0
C  0  0  0  0  0  1

Or:
print (pd.get_dummies(df.col).groupby(level=0).max())
   a  b  c  d  e  f
A  1  1  1  0  0  0
B  0  0  0  1  1  0
C  0  0  0  0  0  1


text:
Q: Heat equation: interpretation of Fourier series constants I am pretty aware of the interpretation of the equation itself: $u_t=\lambda u_{xx}$ along with the boundary conditions $u(0,t)=u(l,t)=0$ and $u(x,0)=T(x)$, with $0<x<l$ (e.g., Gyu's answer Interpretation of the heat equation is an excellent explanation).
My question is something about the Fourier series that describes the initial temperature $T(x)=u(x,0)$.  When solving the equation (along with the boundary conditions), one realizes that the function $T(x)$ can be described as a Fourier series:
$$T(x)=\sum_{n=1}^{\infty} A_n \sin(\frac{n\pi x}{l}),$$
with $0<x<l$.  The $A_n$ can be completely described by integrating $\frac{2}{L}\int_0^l f(x)\sin(\frac{n\pi x}{l})dx$, which can be used to described the final solution of the PDE, namely,
$$u(x,t)=\frac{2}{l}\sum_{n=1}^{\infty} \bigg(\int_0^l f(x)\sin(\frac{n\pi x}{l})dx\bigg)e^{-\lambda((n^2\pi^2)/l^2)t}\sin(\frac{n\pi x}{l}).$$
Is there any physics interpretation of the $A_n$ in terms of this specific problem?  Moreover, is there any physics interpretation of the functions $A_n \sin(\frac{n\pi x}{l})$.
My questions are based on the idea that if we have a function that describes some vibration (like some sound) then its Fourier series can be understood as a decomposition of vibrations that caused the vibrations of $f(x)$ by overlapping (and then I can study the lower/higher frequencies).  This idea is used as an application for several problems, so I was wondering if there is something similar to it in the heat equation.
Thanks

A: In a first place the Fourier series is only a useful mathematical tool to analytically solve or approximate a partial differential equation (PDE). One should be careful to attribute too much physical meaning to these mathematical expressions.
Next you can regard the Fourier series as a trigonometric interpolation, which is an exact approximation of the PDE in the steady state $T(x)$ for $n\rightarrow\infty$. Here each individual summand can be intepreted as mode with a prefactor $A_n$ as weight. For example the first mode $A_0$ is the integral mean.
Note that the polynomial representation with a trigonometric basis is only one of many modal representations. You could also use other arbitrary polynomials. The interpretation of the weights would change each time.
Regards