text:
Q: Bootstrap Button Size Can you use the bootstrap responsive classes on buttons when using pull-right?. For example, <button class="col-xs-6">. I'm using pull-right to put both my buttons in-line with the header text.
Here is an example of what I'm trying to do: http://www.bootply.com/bk6be0CBuB
I'd like for these buttons to be wider then they are and break in a responsive manner.

        <button type="button" class="btn btn-primary">Button 1</button>
        <button type="button" class="btn btn-success">Button 2</button>

Header Text

A: No, you cannot use those classes on buttons with pull-right, and you also can't use percents with pull-right. You can make the button sizes be responsive however by setting the width for the buttons at all the different Twitter Bootstrap breakpoints using media queries. Here would be the media query for extra-small devices:
@media (max-width: 768px) {
    .btn {
        width: 100px;
    }
}

Just do that with the desired width of the button at each screen size, and if you are having some issues with sizes in-between breakpoints, make a new media query for that.


text:
Q: How can I draw a complication slot on my watch face? I'm developing my own Android watch face and everything works well until now. Now, I trying to create my first complication in order to show the seconds. I know that I need to create my own Data Provider for this complication. I already have seen some videos on YouTube and read some documentation. My questions are:

*

*How can I create a complication slot to be displayed on my what face?

*How can I set its position on the watch face?

*Will I have to create an activity for that?

A:
How can I create a complication slot to be displayed on my what face?

The easiest way is to use a ComplicaitonDrawable. It will handle all the logic of what to display (tilte, text, icon, etc) for you. It can also be styled to blend in with your watch face. Make sure to populate it with complication data whenever your watch face receives a callback:
@Override
public void onComplicationDataUpdate(int id, ComplicationData data) {
    mComplicationDrawable.setComplicationData(data);
}

How can I set its position on the watch face?

The ComplicationDrawable can easily be drawn anywhere on a canvas:
mComplicationDrawable.setBounds(myComplicationBounds);
mComplicationDrawable.draw(canvas, currentTimeMillis);

Will I have to create an activity for that?

You don't need an activity to set the position of the complication slot (unless you want the user to be able to select/change the position).
You do need a settings activity to let the user select a data provider for your complication slot. Google has been kind enough to provide a sample watch face that shows the recommended way to do this. It's available on GitHub.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Can I pick a random element from an array in C++? This has been bugging me for days:
#include <iostream>
using namespace std;

string words[] = {"cake", "cookie", "carrot", "cauliflower", "cherries", "celery"};
string word = words[rand() % 6];
string guess;
int lives = 3;

int main()
{
    std::cout << "Can you guess what word I'm thinking of? I'll give you a hint: it's a food that starts with the letter C. You have three tries. Good luck!" << std::endl;

    while(lives > 0)
    {
        std::cin >> guess;
        std::cout << std::endl;

        if(guess == word)
        {
            std::cout << "Wow, That's actually correct! Good job!" << std::endl;
            break;
        }
        else
        {
            lives--;

            std::cout << "Nope! You now have " << lives << " lives left." << std::endl;
        }
    }

    if(lives <= 0)
    {
        std::cout << "And... you lose!" << std::endl;
    }

    return 0;
}

I'm currently working on a word-guessing game, but when I try to pick a random element from my words array, it gets stuck on element 1 (i.e "cookie"). I used:
string words[] = {"cake", "cookie", "carrot", "cauliflower", "cherries", "celery"};
string word = words[rand() % 6];

Help would be appreciated.

A: If you want to do it C++ style, use , and for maintenance I think std::vector of std::string is a good choice too.
#include <iostream>
#include <vector>
#include <string>
#include <random>

int main()
{
    std::vector<std::string> words{ "cake", "cookie", "carrot", "cauliflower", "cherries", "celery" };

    // gets 'entropy' from device that generates random numbers itself
    // to seed a mersenne twister (pseudo) random generator
    std::mt19937 generator(std::random_device{}());

    // make sure all numbers have an equal chance.
    // range is inclusive (so we need -1 for vector index)
    std::uniform_int_distribution<std::size_t> distribution(0, words.size() - 1);

    for (std::size_t n = 0; n < 40; ++n)
    {
        std::size_t number = distribution(generator);
        std::cout << words[number] << std::endl;
    }
}

A: rand() is a pseudo random number generator. That means, given the same starting conditions (seed), it will generate the same pseudo random sequence of numbers every time.
So, change the seed for the random number generator (e.g. use the current time as a starting condition for the random number generator).
#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;

static const string words[] = {"cake", "cookie", "carrot", "cauliflower", "cherries", "celery"};

int main() {
   //variables moved to inside main()
   string guess;
   int lives = 3;

   srand(time(NULL));
   string word = words[rand() % 6];

A: if u didnt generate using a srand() function
ur programm will automatic generate for you with the seed 1
so you can proceed it like this:
#include<cstdlib>
#include<ctime>
...
int main()
{
    srand(time(NULL));
    ....
}

A: You shouldn't use rand in C++, there are far better random engines.
#include <iostream>
#include <array>
#include <random>

using namespace std;

// use std::array as a better alternative to C arrays
array words {"cake", "cookie", "carrot", "cauliflower", "cherries", "celery"};
string guess;
int lives = 3;

int main()
{
    std::mt19937 gen{std::random_device{}()}; // generates random numbers
    std::uniform_int_distribution<std::size_t> dist(0, words.size() - 1); // maps the random number to [0..number of words]

    int index = dist(gen);
    string word = words[index];

    ...
}


text:
Q: Uniform convergence on compact sets allows switching the limit and the integral. Why does uniform convergence on compact sets allows switching the limit and the integral?

A: In integral; if $f_n\to f$ uniformly on the compact $K$, then
$|\int_Kf_n-\int_Kf|=|\int_K(f_n-f)|\leq \|f_n-f\|_{K}\int_K1\to 0$, hence
$\int_Kf_n\to \int_Kf$.

A: To expand on Hamou's answer:
Suppose that a sequence $\{f_n\}$ of functions on a compact set is such that $f_n \to f$ uniformly.  We can then state that for any $\epsilon>0$, there is an $N$ such that $\sup_{K}|f(x) - f_n(x)| < \epsilon/(\int_K 1\,dx)$ whenever $n>N$.  It follows that for $n>N$, we have
$$
\left|\int_K f(x)\,dx - \int_K f_n(x)\,dx \right| =
\left|\int_K (f(x)- f_n(x))\,dx \right| \\
\leq \int_K |f(x)- f_n(x)|\,dx\\
\leq \int_K \frac{\epsilon}{\int_K 1\,dx}\,dx = \epsilon
$$
Thus, we conclude that
$$
\int_K f_n(x)\,dx \to  \int_K f(x)\,dx
$$
as $n \to \infty$.
Uniform convergence allows us to bound $f_n - f$, and compactness allows us to compute $\int_K 1\,dx$.


text:
Q: Updating a page won't have any effect I tried to update my about-us page by aligning all the picture to the right. And deleted some spaces to make the page tight.
But update clicking UPDATE button and view the page I still get the same old version of the page.
I checked the revisions and it indicated that I made changes/revisions a minute ago.
What could have been the cause of this?


text:
Q: clustering for categorical data with one column for observations I'm trying to cluster a dataset using 4 variables, all of which are categorical variables. I'd also like to include another numerical variable that's actually the number of observations of another column. My data is laid out like below:
ColA, ColB, ColC, ColD, ColE
where ColE would be the frequency of ColD; and all Columns A-D are categorical variable.
I don't want to use a supervising learning technique because of various reasons (the top one being I don't know what my result should be; only that I want to have k number of groups that are similar enough).
What's the best clustering algorithm to use for this? I've been thinking k-modes but that doesn't solve the problem of ColE being a feature of ColD.

A: Have you tried encoding the categorical variables into numeric?
http://fastml.com/converting-categorical-data-into-numbers-with-pandas-and-scikit-learn/
I would recommend starting with maybe two variables to apply K-modes and then iterate/increase the number of variables from there, as you analyze the results.

A: If you have only categorical variables, I would suggest to select a distance function (Hamming, Chi2,...), calculating the distance matrix between each observation, and then running a good old hierarchical clustering algorithm. You should try several distance functions to find the one giving the most meaningful results.


text:
Q: File gets truncated (not deleted) from current working directory I have this script verbatim, for some reason this script is truncated a file in the pwd, and I am not sure why:
#!/usr/bin/env bash

set -e;
cat run.r2g.internal.sh > "$(npm bin -g)/r2g"

when I run it, the local file run.r2g.internal.sh consistently gets truncated.
That file is really only reference by this line:
cat run.r2g.internal.sh > "$(npm bin -g)/r2g"

When I omit that line, the file is not truncated...
anyone know why that line would truncate the file? So weird.


text:
Q: ¿Cómo obtener una secuencia de números por línea? Quiero obtener unos números introducidos por teclado, separados por espacios y guardarlos en una pila.
Ejemplo:
1 2 3 4 5 6 <- una pila
11 14 1 12 13 <- otra pila
1 11 2 2 3 3 4 4 <- otra
...

Tengo esto, pero de esta forma no sé cómo separar el string en varios int:
string s;
while(getline(cin, s)){

}

A: Puedes usar std::stringstream, que te lo da todo hecho:
#include <iostream>
#include <sstream>

int main( ) {
  std::string cadena( "1 2 cucu 3 555 777" );
  std::stringstream ss( cadena );
  int tmp;

  do {
    ss >> tmp;

    if( ss.fail( ) ) {
      std::cout << "No es un numero!\n";
      break;
    }

    std::cout << "Numero: " << tmp << "\n";
  } while( !ss.eof( ) );

  return 0;
}

Numero: 1
  Numero: 2
  No es un numero!

Cambiando cadena a:
std::string cadena( "1   2  3       555 777" );

Numero: 1
  Numero: 2
  Numero: 3
  Numero: 555
  Numero: 777

Como ves, los espacios extra son correctamente ignorados.

A: He creado un algoritmo, pero solo funciona con ciertas reglas:

*

*Todos los números introducidos deben ser dígitos dentro del size del tipo int.

*Se utilizo la función stoi para convertir los números a enteros desde la referencia de un string. Quiere decir que el numero no
  puede exceder cierta cantidad de dígitos (el limite de un int)
  porque puede lanzarte una excepción.

*El input puede aceptar cualquier cantidad de espacios que separen los numeros. Es decir, los numeros pueden estar separados por 1 o mas
  espacios.

*Acepta números negativos no menores al menor numero del tipo int.

*Acepta cadenas que contengan numero entre caracteres. En este caso, solo tomara el primer numero que encuentre antes de un caracter que no sea un digito.

El algoritmo es el siguiente:
#include <iostream>
#include <string>

using namespace std;

int main()
{
    string s;
    string number;
    int indexOfNextSpace = 0;
    int characterValue;

    while(getline(cin, s)){

        for(unsigned int i = 0; i < s.length(); ){

            characterValue = s[i] - '0';

            if(characterValue >= 0 && characterValue <= 9 || s[i] == '-'){
                indexOfNextSpace = s.find(' ', i);
                if(indexOfNextSpace > 0){

                    number = s.substr(i, indexOfNextSpace - i);
                    i += (indexOfNextSpace - i);
                }
                else
                {
                    number = s.substr(i, s.length() - i);
                    i = s.length();
                }

               // print number as int
               cout << stoi(number) << " ";
            }
            else
                i++;
        }

        cout << endl;
    }

    return 0;
}}

La lógica utilizada para el algoritmo es la siguiente:

*

*Se itera cada caracter en el string.

*Se evalúa si el i-esimo dígito en la posición del string es un digito entre 0 y 9, o comienza con un símbolo negativo, de lo contrario lo omite.

*Se busca la posición del caracter ' ' entre la posición i y el length del string.

*Si hay un espacio, tomara el substring comprendido entre la posición i y el espacio. Si no encontró mas espacios después de la
  posición i, es porque el substring debe estar comprendido entre i y
  el final del string.

Casos de prueba:
input:
1234 -145 1 23439911
1234 -1939          9199  2   3        1
1-2-3-1 1 1 2  3      5
hola12  1235  1 333 4 -10000
1a  2b  3c       4d       f5             g6

output:
1234 -145 1 23439911
1234 -1939 9199 2 3 1
1 1 1 2 3 5
12 1235 1 333 4 -10000
1 2 3 4 5 6

PD: Ten en cuenta que la solución se hizo de esta manera, porque quieres obtener los numeros como int. Si quisieras el resultado como string, elimina la función que convierte el string a int (stoi). Esto te permite almacenar numeros de longitudes gigantezcas ya que lo almacenarás como cadenas y no como enteros, y al contrario de como esta hecho ahora, no te lanzará una excepción al introducir un numero gigante (mayor a la capacidad de un int).


text:
Q: matter.js rectangle won't collide I am using matter.js for physics and p5.js for rendering things. I was trying to simply create boxes when you click in the canvas and then when the boxes reaches the end of the canvas it collide with a ground but ground won't detect the collision with the box. i am assuming the problem is that ground is positioned correctly.
this the code

// module aliases
var Engine = Matter.Engine,
  World = Matter.World,
  Bodies = Matter.Bodies;

var x = 0;
var engine;
let frame = document.getElementById("frames");
var ground;

var boxs = [];
function setup() {
  //put setup code here
  createCanvas(640, 480);

  engine = Engine.create();
  // run the engine
  Engine.run(engine);
  ground = Bodies.rectangle(0, height / 2, width, 10);
  World.add(engine.world, ground);
}

function mousePressed() {
  boxs.push(new Box(mouseX, mouseY, 20, 20));
}

function draw() {
  x = x + 1;
  background(0);

  for (var i = 0; i < boxs.length; i++) {
    boxs[i].show();
  }
}

var Box = function (x, y, width, height) {
  this.box = Bodies.rectangle(x, y, width, height);
  this.h = height;
  this.w = width;
  World.add(engine.world, this.box);

  this.show = function () {
    push();
    fill(255);
    let pos = this.box.position;
    let angle = this.box.angle;
    translate(pos.x, pos.y);
    rotate(angle);
    rect(0, 0, this.w, this.h);
    rectMode(CENTER);
    pop();
  };
};

  <title>Ball Clash</title>

A: You should get into the habit of debugging your code. (That tutorial is for Processing, but many of the same ideas apply to P5.js.)

i am assuming the problem is that ground is positioned correctly.

So why don't you just check the position of the ground? I don't see anywhere that you're drawing the ground, why don't you start by doing that?
Or you could add this line into the draw() function:
console.log(ground.position);

Either way, you'll notice that the ground is falling, which makes sense because it's a rectangle, just like the other boxes which are falling.
To fix your problem, you need to figure out how to create a stationary box that doesn't move. I'm sure Googling "matter.js stationary rectangle" will return a ton of results, or you can consult their documentation.

A: Elaborating on Kevin's answer, add {isStatic: true} to the ground to prevent it from falling:
ground = Bodies.rectangle(0, height / 2, width, 10, {isStatic: true});
//                                                ^^^^^^^^^^^^^^^^^^


text:
Q: Tomcat common class loader not working as expected I'm trying to build a Docker image of Tomcat that uses Elastic logging. I followed the ECS Logging Java Reference documentation and added the required jars to $CATALINA_HOME/lib, however, it seems that the classes are not loaded by Tomcat.
Tomcat's class loader documentation states the following about the common class loader:

This class loader contains additional classes that are made visible to both Tomcat internal classes and to all web applications.
Normally, application classes should NOT be placed here. The locations searched by this classloader are defined by the common.loader property in $CATALINA_BASE/conf/catalina.properties. The default setting will search the following locations in the order they are listed:

*

*unpacked classes and resources in $CATALINA_BASE/lib

*JAR files in $CATALINA_BASE/lib

*unpacked classes and resources in $CATALINA_HOME/lib

*JAR files in $CATALINA_HOME/lib

If I understand the above correctly, placing the jars in $CATALINA_HOME/lib should be enough for the common loader to find them. However the logging is not formatted by the Elastic formatter.
As a workaround I added a setenv.sh file with a CLASSPATH variable that points to the jars I added. The logging is then printed correctly in ECS format.
Can someone please explain to me how I can get this to work without using the workaround and make use of the common class loader instead?
Below is my Dockerfile:
FROM tomcat:9-jre17

COPY conf/logging.properties conf/logging.properties

COPY lib/ecs-logging-core-1.5.0.jar lib/ecs-logging-core.jar
COPY lib/jul-ecs-formatter-1.5.0.jar lib/jul-ecs-formatter.jar
COPY lib/logback-ecs-encoder-1.5.0.jar lib/logback-ecs-encoder.jar

# Workaround
COPY bin/setenv.sh bin
RUN chmod +x bin/setenv.sh

EXPOSE 8080

CMD ["catalina.sh", "run"]

This is my logging.properties file:
handlers = java.util.logging.ConsoleHandler

.handlers = java.util.logging.ConsoleHandler

java.util.logging.ConsoleHandler.level = INFO
java.util.logging.ConsoleHandler.formatter = co.elastic.logging.jul.EcsFormatter
co.elastic.logging.jul.EcsFormatter.serviceName = tomcat
java.util.logging.ConsoleHandler.encoding = UTF-8

And this is the setenv.sh file that I use as a workaround, but that I would like to get rid of:
#!/bin/sh

export CLASSPATH="/usr/local/tomcat/lib/ecs-logging-core.jar:/usr/local/tomcat/lib/jul-ecs-formatter.jar:/usr/local/tomcat/lib/logback-ecs-encoder.jar"

The result that I'm expecting looks like this:
{"@timestamp":"2022-11-28T12:29:43.276Z","log.level": "INFO","message":"Server version name:   Apache Tomcat/9.0.69","ecs.version": "1.2.0","service.name":"tomcat","event.dataset":"tomcat","process.thread.name":"main","log.logger":"org.apache.catalina.startup.VersionLoggerListener"}

But the result that I'm getting without adding setenv.sh looks like this:
2022-11-28 13:44:20 Nov 28, 2022 12:44:20 PM org.apache.catalina.startup.VersionLoggerListener log
2022-11-28 13:44:20 INFO: Server version name:   Apache Tomcat/9.0.69


text:
Q: Image upload in React-CKEditor-5 using Laravel I want to upload an image using CKEditor-5 in React.js
My codes in the front side:

<CKEditor
editor={ClassicEditor}
data={`<p>${label} : ${placeholder}</p>`}
config={
    {
        ckfinder:{
            uploadUrl: "http://127.0.0.1:8000/api/upload/"
        }
    }
}
/>

And my codes in Laravel in "UploadController":

$imgpath = Storage::disk('public')->put("images/uploads", $request->file('upload'));
return response()->json([
    'default' => "http://127.0.0.1:8000/".$imgpath,
]);

After selecting the image, the image is successfully saved in my desired path. But a failure message appears on the front side
Do I have to install a package in Laravel?
I do not know where I am wrong?

A: You need to return the response in correct JSON format.
The correct Json response format would be:
{
  fileName: "FileName.jpg",
  uploaded: 1,
  url: "http://127.0.0.1:8000/".$imgpath
}


text:
Q: Filter using re module i have a list as presented below :
['\'STATE\\\': \\\'("DEVELOPMENT COMPLETE", "DEVELOPMENT IN PROGRESS", "WIP QA")\\\'}, \']']

Now I want to filter the part below , from the mentioned list using re module .
("DEVELOPMENT COMPLETE", "DEVELOPMENT IN PROGRESS", "WIP QA")

can anybody help me use re module?

A: Use :
>>> l = ['\'STATE\\\': \\\'("DEVELOPMENT COMPLETE", "DEVELOPMENT IN PROGRESS", "WIP QA")\\\'}, \']']
>>> re.search(r'(\([^\)]*\))' , l[0]).group(1)
'("DEVELOPMENT COMPLETE", "DEVELOPMENT IN PROGRESS", "WIP QA")'

And if you want your result as tuple, you can always use ast
>>> import ast
>>> ast.literal_eval(re.search(r'(\([^\)]*\))', l[0]).group(1))
('DEVELOPMENT COMPLETE', 'DEVELOPMENT IN PROGRESS', 'WIP QA')

Just in case, if your list contains multiple elements then you might need to iterate it and then use above re


text:
Q: How to delete a row from gridview without loading page? I have one Gridview in my web page. That is having 2 link fields edit and delete. If i click that link that will load full page. That time data i am losing the data which was there in the grid view. The Data which was there in the grid view is coming from user one by one.
When I am trying to edit the data by clicking edit link that will load the page and tries to fetch the data from grid view. Here i observed that row count of Grid is 0. So i am unable to edit the data which is there in the grid.
Can any one tell me how i can do this?

A: if i understood your problem correctly, you could try to save all the existing data rows BEFORE you are changing them.
There might be an "prechange" event which you could use to save the data befor they get lost.

*

*save the data into a internal list

*edit the selected data

*refresh only the grid control with the new edited data.

Toby


text:
Q: How to lock localization of DateTime in ASP.NET MCV4 C# I'm working with a group on a project that at one point requires a DateTime to be posted in a form. We added a simple jquery-ui datepicker to do that, and it worked fine on my English configured machine. However when they tried using it themselves on a Dutch configured machine, the DateTime started using a different format, while the datepicker kept the same English format, causing errors.
How do I lock the DateTime localization in MVC4 (or the overall localization) to English to fix this?
Alternatively, how do I detect the localization to make the datepicker use the different one?

A: Try this:
<globalization culture="en-US" uiCulture="en-US" />

*

*How to configure invariant culture in ASP.NET globalization?

*How to Set default language in web.config file ?
This will also fix potential problems with float's and etc (point vs comma)

A: You could use a DataAnnotation to your DateTime object
[DisplayFormat(DataFormatString = "{0:dd-MM-yyyy HH:mm}")]
public DateTime dateTime;

then edit your format string to the English standard.
If i am correct, it will always use this format.


text:
Q: Mac OSX Cataline not rebooting when cannot connect to wifi Several times I have had the experience that my Macbook Pro (13 inch, 2017, v10.15.5) will not reboot completely. The white progress bar gets very close to complete and then stalls.
Each time this happened I was having wifi connection problems.  The way I solve it is to reboot in safe mode, connect to the wifi, and then reboot.  When it first happened I took the Mac to the Apple store and they replaced the wifi hardware and the logic board. But it still continues to happen.
Is there a setting/fix that will stop this behaviour?


text:
Q: How to automatically make a copy of spreadsheet and rename it based on cell value (ex. name) Can someone help me figure this out please.
I need to automatically copy a spreadsheet (Contract) rename it based on the column value (customer name) and copy a row (customer details) into that newly created spreadsheet (details's sheet)
I was able to find a script to copy the file and rename it, but need help with copying the row,
and also if possible someone can help me with this existing script, if possible instead of clicking on the menu to run the script, have it run automatically whenever the new row is added.
Thank you in advance.
function onOpen() {
var ui = SpreadsheetApp.getUi();
ui.createMenu('Options')
.addItem('Generate Proposal','copyfilefromsource')
.addToUi();
}
function copyfilefromsource() {
var ui = SpreadsheetApp.getUi();

var sheet_merge = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Customers");
var last_row = sheet_merge.getLastRow();

var name = null;
var phone = null;
var date = null;
var dest_folder = null;
var sheets_created = 0;
var new_file = null;
var source_file = null;
var lead = null;
var range = sheet_merge.getRange(1, 1, last_row, 30);
var temp = null;

source_file = DriveApp.getFileById('1XotVWkmjyi8OBRGy6N6mosPf16YwvozfKYxums_oMJ'); //gets the source file to copy
dest_folder = DriveApp.getFolderById('17aawdMFOvF4clNcjA_JeK2v2Q9_VJnE'); //gets the ID of the folder to place the copied files into

if (last_row <= 1) {
SpreadsheetApp.getUi().alert("No rows to process!");
return
}
for (var i = 2; i <= last_row; i++) { // loop to go down evenery row from 2 until the endLogger.log( cell.getA1Notation() );
if (range.getCell(i, 30).getValue() == '') { //makes sure there is nothing in the column, i.e. can run the script with some students already been processed if it fails half way through.

name = range.getCell(i, 3).getValue(); //gets first name from the sheet
event_date = range.getCell(i, 6).getValue(); //gets event date from the sheet
phone = range.getCell(i, 5).getValue(); //gets phone from the sheet
lead = range.getCell(i,1).getValue(); //gets lead link
new_file = source_file.makeCopy(name + " - " + phone + " - " + event_date, dest_folder);

//Add the details that the process has worked
SpreadsheetApp.getActiveSheet().getRange(i,1).setValue('=HYPERLINK("' + new_file.getUrl() +'/","Lead")');
SpreadsheetApp.getActiveSheet().getRange(i,30).setValue(new_file.getId());
sheets_created++; // add to files created
}
}
ui.alert(sheets_created + " files were created!")
}

function testFolder(folderName){
var exist = true;
try{var testFolder = DocsList.getFolder(folderName)}
catch(err){exist=false}
return exist;
}

A: I'll at least start you out with your solution, and then I'll explain the next steps you should take. The below method will convert your row into an array, which you can manipulate as necessary.
let ss = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('YOUR SHEET NAME')
let sheetData = ss.getDataRange().getDisplayValues()
//Assuming that the data you want to copy is being added to the last row
let row = sheetData[ss.getLastRow()]

From there, you can choose each index in the row array, and place that specific piece of data wherever you want on the new sheet you create, as long as you specify the range. For example, if you want to take the 4th index of the row array and want to paste it to cell D43 of a different sheet, you would do:
SpreadsheetApp.getActiveSpreadsheet().getSheetByName('TARGET SHEET').getRange('D43').setValue(row[3])


text:
Q: csv file overwritten instead of appended in python Problem in Python- Only last numpy array is written to .csv file instead of all arrays being appended to it.How can I fix this?
import cv2, glob
from PIL import Image
import numpy as np
images = glob.glob('*.bmp')
    for image in images:
    img=cv2.imread(image,0)                                #original image
    re=cv2.resize(img, dsize=(128,128), interpolation=cv2.INTER_LINEAR)
    cv2.imwrite("resized_"+image,re)                       #resized image
    a = np.asarray(re)                                     #resized image is converted to pixels
    np.savetxt("sal.csv",a, delimiter=',')
    print(np.asarray(re))                                  #which are printed to csv file. Problem is only the last image pixel values are printed to csv file. Any suggestions to rectify this.


text:
Q: Change value of a randomly chosen entry of a sparse matrix row vec is one row of a sparse matrix.
vec = sparse.csc_matrix([[0,0,1,1,0,1,0,1]])

How can I randomly choose 2 entries with value '1' and change its value to 8?
I have tried
a,b,c = sparse.find(vec==1)
idx = numpy.random.choice(vec[a,b],2)
vec[idx] = 8

However I am getting dimension error because vec is one of the rows of a larger sparse matrix and is something like a nested array.

A: This converts your sparse row to a boolean mask for your operations.
ones = np.stack(np.where((vec==1).toarray())).T # [[i,j],[i,j]..]
chosen = np.random.choice(len(ones), 2) # [1,3]
for index in chosen:
    vec[tuple(ones[index])] = 8

Since this is by row I think you'll not run into memory problems.


text:
Q: How can I join the result of Get-ChildItem by a given character in PowerShell? I recently asked a question on how to join the result of ls which I tried to use for the result returned by Get-ChildItem but to no luck.
The command I am trying to join the result of (by let's say -) is:
Get-ChildItem -Path . -Filter bin -Recurse | where {$_.psiscontainer} | gci -Filter *test*.dll -Recurse | select {$_.FullName}

Any help is much appreciated.

A: You need to expand the FullName property so you can join strings instead of objects:
(Get-ChildItem -Path . -Filter bin -Recurse | where {$_.psiscontainer} | gci -Filter *test*.dll -Recurse | select -ExpandProperty FullName) -join ' - '


text:
Q: How do I perform a filter function on data from an Axios API call in React? I am having trouble displaying my yogaCard in the return statement. When I call it as {yogaCard} I get a message saying it is undefined.

  if (yogas.length > 0) {

                let yogaCard = yogas.filter((yoga) => {
                        if (searchPose === "") {
                            return yoga
                        }
                        else if (
                            yoga.english_name.toLowerCase().includes(searchPose.toLocaleLowerCase())) {
                                return yoga
                            }
                    }).map((yoga) => (

{yoga.english_name}

                    ))
            }
 return (
            <>

Yoga Poses

           <input type="text" class="input" placeholder="Search by pose" onChange={event => {setSearchPose(event.target.value)}}/>

             {yogaCard}

            </>
        )

    }

    export default IndexYogas

A: You're not showing how you're retrieving your yogas data from axios or any way to debug your current issue, but I'd recommend passing your data retrieved from axios to a child component that contains all those div boxes and formatting, etc.
function MainPage() {
    const [yogas, setYogas] = React.useState([]);
useEffect(() => {
        // axios call to populate data
        requestYogaInfo().then((resp) => {
            setYogas(resp.data); // this depends on the shape of your webservice response
        });
    }, []);

return (
        <>

Yoga Poses

               <input type="text" class="input" placeholder="Search by pose" onChange={event => {setSearchPose(event.target.value)}}/>

                 {yogas && yogas.length > 0
                     ? (
                     yogas.filter((yoga) => {
                        if (searchPose === "") {
                            return yoga
                        }
                        else if (
                     yoga.english_name.toLowerCase().includes(searchPose.toLocaleLowerCase())) {
                                return yoga
                            }
                    }).map((yoga) => (

{yoga.english_name}

                    ))
                     )
                     : null
                 }

        </>
        )
}


text:
Q: Map container to hostname other than localhost in Docker for Mac I am creating an Nginx container that I would like to access locally at http://api. Using Docker Machine, I assumed running docker-machine create default and docker-machine ip default to receive the IP and editing my hosts file to something like this:
# docker-machine ip default --> 192.168.99.100
192.168.99.100  api
should map requests to api\ to the Docker Machine IP and serve my content.
Two things are confusing me:

*

*I launch Docker through the Mac App and can create Nginx containers and access content at http://localhost. However, running docker-machine ls returns no machines. This is confusing because I thought Docker had to run on a VM.

*Starting from scratch and starting Docker Machine, then spinning up containers seems to have no effect. In other words, I still can access content at http://localhost but not http://api
Instead of accessing my container at http://localhost I want to access it at http://api. How do I do this?
I'm using Docker for Mac 17.12 and Docker Machine 0.14.

A: On the base of your this question:

Instead of accessing my container at http://localhost I want to access
  it at http://api. How do I do this?

Your docker run command:
docker run -it --rm --name test --add-host api:192.168.43.8 -p 80:80 apachehttpd

1st Thing: The --add-host flag add value to /etc/hosts in your container /etc/hosts so http://api will also response inside the container if ping inside that container.
This is how will ping response inside container

2nd Thing: Edit your host etc/hosts file and add
api 192.168.43.8 [your ip]

This is how you can see in Browser.


text:
Q: ¿Cómo hacer carousel y que las imagenes tengan height estandar? Saludos, tengo un pequeño problema, estoy tratando de hacer un carousel con Bootstrap y Jquery, todo bien allí, el problema que tengo es que si las imagenes tienen height diferente hace que se alteren los demas contenidos(navbar, jumbotron). Al cambiar la imagen del slide con la fechita, si la imagen tiene mas resolucion, hace que crezca el carousel. lo que quiero es que el carrousel tenga height estandar(fijo por asi decirlo), que no se haga mas grande sin importar el tamaño de la imagen.

$(document).ready(function() {
  // Add smooth scrolling to all links in navbar + footer link
  $(".navbar a, footer a[href='#myPage']").on('click', function(event) {
    // Make sure this.hash has a value before overriding default behavior
    if (this.hash !== "") {
      // Prevent default anchor click behavior
      event.preventDefault();

      // Store hash
      var hash = this.hash;

      // Using jQuery's animate() method to add smooth page scroll
      // The optional number (900) specifies the number of milliseconds it takes to scroll to the specified area
      $('html, body').animate({
        scrollTop: $(hash).offset().top
      }, 900, function() {

        // Add hash (#) to URL when done scrolling (default click behavior)
        window.location.hash = hash;
      });
    } // End if
  });

  $(window).scroll(function() {
    $(".slideanim").each(function() {
      var pos = $(this).offset().top;

      var winTop = $(window).scrollTop();
      if (pos < winTop + 600) {
        $(this).addClass("slide");
      }
    });
  });
})
body {
  font: 400 15px Lato, sans-serif;
  line-height: 1.8;
  color: #818181;
}

h2 {
  font-size: 24px;
  text-transform: uppercase;
  color: #303030;
  font-weight: 600;
  margin-bottom: 30px;
}

h4 {
  font-size: 19px;
  line-height: 1.375em;
  color: #303030;
  font-weight: 400;
  margin-bottom: 30px;
}

.carousel-inner>.item>img,
.carousel-inner>.item>a>img {
  width: 70%;
  margin: auto;
}

.jumbotron {
  background-color: #1B2F95;
  color: #fff;
  padding: 100px 25px;
  font-family: Montserrat, sans-serif;
}

.container-fluid {
  padding: 60px 50px;
}

.bg-grey {
  background-color: #f6f6f6;
}

.logo-small {
  color: #f4511e;
  font-size: 50px;
}

.logo {
  color: #f4511e;
  font-size: 200px;
}

.thumbnail {
  padding: 0 0 15px 0;
  border: none;
  border-radius: 0;
}

.thumbnail img {
  width: 100%;
  height: 100%;
  margin-bottom: 10px;
}

.carousel-control.right,
.carousel-control.left {
  background-image: none;
  color: #f4511e;
}

.carousel-indicators li {
  border-color: #f4511e;
}

.carousel-indicators li.active {
  background-color: #f4511e;
}

.item h4 {
  font-size: 19px;
  line-height: 1.375em;
  font-weight: 400;
  font-style: italic;
  margin: 70px 0;
}

.item span {
  font-style: normal;
}

.panel {
  border: 1px solid #f4511e;
  border-radius: 0 !important;
  transition: box-shadow 0.5s;
}

.panel:hover {
  box-shadow: 5px 0px 40px rgba(0, 0, 0, .2);
}

.panel-footer .btn:hover {
  border: 1px solid #f4511e;
  background-color: #fff !important;
  color: #f4511e;
}

.panel-heading {
  color: #fff !important;
  background-color: #f4511e !important;
  padding: 25px;
  border-bottom: 1px solid transparent;
  border-top-left-radius: 0px;
  border-top-right-radius: 0px;
  border-bottom-left-radius: 0px;
  border-bottom-right-radius: 0px;
}

.panel-footer {
  background-color: white !important;
}

.panel-footer h3 {
  font-size: 32px;
}

.panel-footer h4 {
  color: #aaa;
  font-size: 14px;
}

.panel-footer .btn {
  margin: 15px 0;
  background-color: #f4511e;
  color: #fff;
}

.navbar {
  margin-bottom: 0;
  background-color: #1B2F95;
  z-index: 9999;
  border: 0;
  font-size: 12px !important;
  line-height: 1.42857143 !important;
  letter-spacing: 4px;
  border-radius: 0;
  font-family: Montserrat, sans-serif;
}

.navbar li a,
.navbar .navbar-brand {
  color: #fff !important;
}

.navbar-nav li a:hover,
.navbar-nav li.active a {
  color: #f4511e !important;
  background-color: #fff !important;
}

.navbar-default .navbar-toggle {
  border-color: transparent;
  color: #fff !important;
}

footer .glyphicon {
  font-size: 20px;
  margin-bottom: 20px;
  color: #f4511e;
}

.slideanim {
  visibility: hidden;
}

.slide {
  animation-name: slide;
  -webkit-animation-name: slide;
  animation-duration: 1s;
  -webkit-animation-duration: 1s;
  visibility: visible;
}

@keyframes slide {
  0% {
    opacity: 0;
    transform: translateY(70%);
  }
  100% {
    opacity: 1;
    transform: translateY(0%);
  }
}

@-webkit-keyframes slide {
  0% {
    opacity: 0;
    -webkit-transform: translateY(70%);
  }
  100% {
    opacity: 1;
    -webkit-transform: translateY(0%);
  }
}

@media screen and (max-width: 768px) {
  .col-sm-4 {
    text-align: center;
    margin: 25px 0;
  }
  .btn-lg {
    width: 100%;
    margin-bottom: 35px;
  }
}

@media screen and (max-width: 480px) {
  .logo {
    font-size: 150px;
  }
}

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />

Chania

The atmosphere in Chania has a touch of Florence and Venice.

Chania

The atmosphere in Chania has a touch of Florence and Venice.

Flowers

Beautiful flowers in Kolymbari, Crete.

Flowers

Beautiful flowers in Kolymbari, Crete.

      Previous

      Next

      <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#myNavbar">

    </button>
      Repacar

ABOUT

SERVICES

PORTFOLIO

PRICING

CONTACT

Company

We specialize in blablabla

  <form>

      <input type="email" class="form-control" size="50" placeholder="Email Address" required>

        <button type="button" class="btn btn-danger">Subscribe</button>

  </form>

About Company Page

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Excepteur sint
        occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco
        laboris nisi ut aliquip ex ea commodo consequat.

<button class="btn btn-default btn-lg">Get in Touch</button>

Our Values

MISSION: Our mission lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip
        ex ea commodo consequat.

VISION: Our vision Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex
        ea commodo consequat. Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
        consequat.

SERVICES

What we offer

POWER

Lorem ipsum dolor sit amet..

LOVE

Lorem ipsum dolor sit amet..

JOB DONE

Lorem ipsum dolor sit amet..

GREEN

Lorem ipsum dolor sit amet..

CERTIFIED

Lorem ipsum dolor sit amet..

HARD WORK

Lorem ipsum dolor sit amet..

Portfolio

What we have created

Paris

Yes, we built Paris

New York

We built New York

San Francisco

Yes, San Fran is ours

What our customers say

"This company is the best. I am so happy with the result!"
Michael Roe, Vice President, Comment Box

"One word... WOW!!"
John Doe, Salesman, Rep Inc

"Could I... BE any more happy with this company?"
Chandler Bing, Actor, FriendsAlot

      Previous

      Next

Pricing

Choose a payment plan that works for you

Basic

20 Lorem

15 Ipsum

5 Dolor

2 Sit

Endless Amet

$19

per month

          <button class="btn btn-lg">Sign Up</button>

Pro

50 Lorem

25 Ipsum

10 Dolor

5 Sit

Endless Amet

$29

per month

          <button class="btn btn-lg">Sign Up</button>

Premium

100 Lorem

50 Ipsum

25 Dolor

10 Sit

Endless Amet

$49

per month

          <button class="btn btn-lg">Sign Up</button>

CONTACT

Contact us and we'll get back to you within 24 hours.

 Chicago, US

 +00 1515151515

 myemail@something.com

          <input class="form-control" id="name" name="name" placeholder="Name" type="text" required>

          <input class="form-control" id="email" name="email" placeholder="Email" type="email" required>

      <textarea class="form-control" id="comments" name="comments" placeholder="Comment" rows="5"></textarea>

          <button class="btn btn-default pull-right" type="submit">Send</button>

Espero puedan ver lo que quiero hacer y me puedan ayudar, gracias de antemano.

A: La clave esta en este fragmento del css:
.carousel-inner>.item>img,
.carousel-inner>.item>a>img {
    height: 150px !important;
    width: auto;
    margin: auto;
}

donde height: 150px !important; es para poner la altura que tu carousel necesita y width: auto; es para evitar que las imagenes se deformen

body {
  font: 400 15px Lato, sans-serif;
  line-height: 1.8;
  color: #818181;
}

h2 {
  font-size: 24px;
  text-transform: uppercase;
  color: #303030;
  font-weight: 600;
  margin-bottom: 30px;
}

h4 {
  font-size: 19px;
  line-height: 1.375em;
  color: #303030;
  font-weight: 400;
  margin-bottom: 30px;
}

.carousel-inner>.item>img,
.carousel-inner>.item>a>img {
  height: 150px !important;
  width: auto;
  margin: auto;
}

.jumbotron {
  background-color: #1B2F95;
  color: #fff;
  padding: 100px 25px;
  font-family: Montserrat, sans-serif;
}

.container-fluid {
  padding: 60px 50px;
}

.bg-grey {
  background-color: #f6f6f6;
}

.logo-small {
  color: #f4511e;
  font-size: 50px;
}

.logo {
  color: #f4511e;
  font-size: 200px;
}

.thumbnail {
  padding: 0 0 15px 0;
  border: none;
  border-radius: 0;
}

.thumbnail img {
  width: 100%;
  height: 100%;
  margin-bottom: 10px;
}

.carousel-control.right,
.carousel-control.left {
  background-image: none;
  color: #f4511e;
}

.carousel-indicators li {
  border-color: #f4511e;
}

.carousel-indicators li.active {
  background-color: #f4511e;
}

.item h4 {
  font-size: 19px;
  line-height: 1.375em;
  font-weight: 400;
  font-style: italic;
  margin: 70px 0;
}

.item span {
  font-style: normal;
}

.panel {
  border: 1px solid #f4511e;
  border-radius: 0 !important;
  transition: box-shadow 0.5s;
}

.panel:hover {
  box-shadow: 5px 0px 40px rgba(0, 0, 0, .2);
}

.panel-footer .btn:hover {
  border: 1px solid #f4511e;
  background-color: #fff !important;
  color: #f4511e;
}

.panel-heading {
  color: #fff !important;
  background-color: #f4511e !important;
  padding: 25px;
  border-bottom: 1px solid transparent;
  border-top-left-radius: 0px;
  border-top-right-radius: 0px;
  border-bottom-left-radius: 0px;
  border-bottom-right-radius: 0px;
}

.panel-footer {
  background-color: white !important;
}

.panel-footer h3 {
  font-size: 32px;
}

.panel-footer h4 {
  color: #aaa;
  font-size: 14px;
}

.panel-footer .btn {
  margin: 15px 0;
  background-color: #f4511e;
  color: #fff;
}

.navbar {
  margin-bottom: 0;
  background-color: #1B2F95;
  z-index: 9999;
  border: 0;
  font-size: 12px !important;
  line-height: 1.42857143 !important;
  letter-spacing: 4px;
  border-radius: 0;
  font-family: Montserrat, sans-serif;
}

.navbar li a,
.navbar .navbar-brand {
  color: #fff !important;
}

.navbar-nav li a:hover,
.navbar-nav li.active a {
  color: #f4511e !important;
  background-color: #fff !important;
}

.navbar-default .navbar-toggle {
  border-color: transparent;
  color: #fff !important;
}

footer .glyphicon {
  font-size: 20px;
  margin-bottom: 20px;
  color: #f4511e;
}

.slideanim {
  visibility: hidden;
}

.slide {
  animation-name: slide;
  -webkit-animation-name: slide;
  animation-duration: 1s;
  -webkit-animation-duration: 1s;
  visibility: visible;
}

@keyframes slide {
  0% {
    opacity: 0;
    transform: translateY(70%);
  }
  100% {
    opacity: 1;
    transform: translateY(0%);
  }
}

@-webkit-keyframes slide {
  0% {
    opacity: 0;
    -webkit-transform: translateY(70%);
  }
  100% {
    opacity: 1;
    -webkit-transform: translateY(0%);
  }
}

@media screen and (max-width: 768px) {
  .col-sm-4 {
    text-align: center;
    margin: 25px 0;
  }
  .btn-lg {
    width: 100%;
    margin-bottom: 35px;
  }
}

@media screen and (max-width: 480px) {
  .logo {
    font-size: 150px;
  }
}

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" />

Chania

The atmosphere in Chania has a touch of Florence and Venice.

Chania

The atmosphere in Chania has a touch of Florence and Venice.

Flowers

Beautiful flowers in Kolymbari, Crete.

Flowers

Beautiful flowers in Kolymbari, Crete.

      Previous

      Next

      <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#myNavbar">

    </button>
      Repacar

ABOUT

SERVICES

PORTFOLIO

PRICING

CONTACT

Company

We specialize in blablabla

  <form>

      <input type="email" class="form-control" size="50" placeholder="Email Address" required>

        <button type="button" class="btn btn-danger">Subscribe</button>

  </form>

About Company Page

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Excepteur sint
        occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco
        laboris nisi ut aliquip ex ea commodo consequat.

<button class="btn btn-default btn-lg">Get in Touch</button>

Portfolio

What we have created

Paris

Yes, we built Paris

New York

We built New York

San Francisco

Yes, San Fran is ours

What our customers say

"This company is the best. I am so happy with the result!"
Michael Roe, Vice President, Comment Box

"One word... WOW!!"
John Doe, Salesman, Rep Inc

"Could I... BE any more happy with this company?"
Chandler Bing, Actor, FriendsAlot

      Previous

      Next

Pricing

Choose a payment plan that works for you

Basic

20 Lorem

15 Ipsum

5 Dolor

2 Sit

Endless Amet

$19

per month

          <button class="btn btn-lg">Sign Up</button>

Pro

50 Lorem

25 Ipsum

10 Dolor

5 Sit

Endless Amet

$29

per month

          <button class="btn btn-lg">Sign Up</button>

Premium

100 Lorem

50 Ipsum

25 Dolor

10 Sit

Endless Amet

$49

per month

          <button class="btn btn-lg">Sign Up</button>

CONTACT

Contact us and we'll get back to you within 24 hours.

 Chicago, US

 +00 1515151515

 myemail@something.com

          <input class="form-control" id="name" name="name" placeholder="Name" type="text" required>

          <input class="form-control" id="email" name="email" placeholder="Email" type="email" required>

      <textarea class="form-control" id="comments" name="comments" placeholder="Comment" rows="5"></textarea>

          <button class="btn btn-default pull-right" type="submit">Send</button>

Para ajustarlo al ancho del div y además que tenga siempre un tamaño constante recomiendo poner la imagen como background del div de esta forma:

   .......

Adjunto un fiddle donde se puede ver de mejor forma.

A: Agrega en el css una clase .item img:
.item img{
    max-height:150px;
}

Si hay conflicto con otro css ponle !important
.item img{
    max-height:150px !important;
}


text:
Q: How to check that only one object of many is non-null? Only one object of three must not be null, two others must be null. The obvious naive solution would be like that:
    if (param1 != null && param2 == null && param3 == null) {
        doSomething(param1);
    } else if (param1 == null && param2 != null && param3 == null) {
        doSomethingElse(param2);
    } else if (param1 == null && param2 == null && param3 != null) {
        doOtherThings(param3);
    }

Is there more elegant solution to ensure that only one object is not null?

A: Well, I would maybe rethink the design of having all different parameters of which just a single one must be nonnull.
But anyways, you need to take two actions:

*

*check if exactly one param is nonnull

*then invoke a method based on the parameter which is nonnull.

You could achieve this by first writing a method which returns the position of the nonnull index of a list of params, but only if that's the only nonnull value:
OptionalInt nonnullIndex(List<?> params) {
    var nonnulls = IntStream.range(0, params.size())
        .filter(i -> params.get(i) != null)
        .toArray();
    return (nonnulls.length == 1 ? OptionalInt.of(nonnulls[0]) : OptionalInt.empty());
}

And then you could create a list of Consumers which each invoke their own method:
List<Consumer<String>> consumers = List.of(
    s -> doSomething(s),
    s -> doSomethingElse(s),
    s -> doOtherThings(s)
);

List<String> params = Arrays.asList(param1, param2, param3);
int index = nonnullIndex(params)
    .orElseThrow(IllegalArgumentException::new);
consumers.get(index).accept(params.get(index));

At last, I totally agree with Andy Turner:

If it's just 3 things, I'd stick with what you've got.

A: Honestly, I think what you have is fine. It's a little bit messy to look at, and error-prone (getting the param number wrong, getting != and == mixed up); but almost anything you do will just make it harder to understand at a glance.
For example, you could introduce a method like this:
boolean onlyFirstNonNull(Object first, Object second, Object third) {
  return first != null && second == null && third == null;
}

(You can make it variadic on the "must be null" parameters, but that's unnecessary here since you're always doing 3 things)
and invoke like
    if (onlyFirstNonNull(param1, param2, param3)) {
        doSomething(param1);
    } else if (onlyFirstNonNull(param2, param1, param3)) {
        doSomethingElse(param2);
    } else if (onlyFirstNonNull(param3, param1, param2)) {
        doOtherThings(param3);
    }

This gets around the problem of mixing up != and ==; but it's still easy to mix up param numbers; and the method isn't standard, so you don't necessarily grok what it means at a glance.

A: You can create an array and simply count nulls in a loop. This should work well if there are more than just three elements, and we are checking for exactly one null between them:
Object [] elements = { "a", null, "b" };
int s = 0;
for (int p = 0; p < elements.length; p++) {
    if (elements[p] == null) {
        s++;
    }
}
boolean oneNull = s == 1;

At the time of answering, nowhere in the header or text of the question is written about the need to know which element is null.

A: You can perform the enforcing the requirement of having exactly one non-null param as a precondition.
boolean hasExactlyOneNonNullParam = List.of(param1, param2, param3)
  .stream()
  .filter(Objects::nonNull)
  .count() == 1;

if (!hasExactlyOneNonNullParam) {
  // handle failed precondition
  return;
}

if (param1 != null) {
    doSomething(param1);
} else if (param2 != null) {
    doSomethingElse(param2);
} else {
    doOtherThings(param3);
}

A: You can create a method using varargs and count the non-null objects.
public static long getCountOfNonNullObjects(Object ... objects)
{
    return Arrays.stream(objects).filter(Objects::nonNull).count();
}

Then you can use your if statement like this
if (getCountOfNonNullObjects(obj,obj,obj) == 1)
    doSomething();

Note: You can use as many objects as you want

A: I think you should stick with what you have. But if you want to confuse your co-workers or your feature-self something like below should be eqivalent:
String res = "";
res += param1 == null ? 0:1;
res += param2 == null ? 0:1;
res += param3 == null ? 0:1;

switch (res){
    case "100": doSomething(param1);     break;
    case "010": doSomethingElse(param2); break;
    case "001": doOtherThings(param3);   break;
}

A: In order to add another option:
int action = 0;
if (param1 != null) {
    if (action == 0) action = 1;
    else  /* throw some error */;
}
if (param2 != null) {
    if (action == 0) action = 2;
    else  /* throw some error */;
}
if (param3 != null) {
    if (action == 0) action = 3;
    else  /* throw some error */;
}
switch (action) {
    case 1: soSomething(); break;
    case 2: doSomethingElse(); break;
    case 3: doOtherThings(); break;
    else:   /* throw error */;
}

The first 3 ifs are very similar. And the method can easily be used to process an array of arguments (set action to i + 1, where i is the variable used to iterate through the array).

A: The methods inside you if conditions are different from each other the complexity of your code cannot reduce. Yet you can make your code more clean like follows,
Note: Here I have assumed your params are type String
public boolean execute(String param , String... params) {
    return param != null && Arrays.stream(params).filter(Objects::isNull).count() == 2;
}

if      (execute(param1, param2, param3)) {doSomething(param1);}
else if (execute(param2, param1, param3)) {doSomethingElse(param2);}
else if (execute(param3, param1, param2)) {doOtherThings(param3);}

A: Or with Enum call ParamEnum.doSomething(par1, par2, par3)

public enum ParamEnum {
    PARAM1 {
        @Override
        protected boolean accepted(String par1, String par2, String par3) {
            return par1 != null;
        }

        @Override
        protected void doOperation() {
            doSomethingImportant();
        }
    }, PARAM2 {
        @Override
        protected boolean accepted(String par1, String par2, String par3) {
            return par2 != null;
        }

        @Override
        protected void doOperation() {
            doSomethingElse();
        }
    }, PARAM3 {
        @Override
        protected boolean accepted(String par1, String par2, String par3) {
            return par3 != null;
        }

        @Override
        protected void doOperation() {
            doOtherThings();
        }
    };

    public static void doSomething(String par1, String par2, String par3) {
        List<ParamEnum> paramEnums =
                Arrays.stream(ParamEnum.values()).filter(e -> e.accepted(par1, par2, par3)).collect(Collectors.toList());
        if(paramEnums.size() == 1) {
            paramEnums.get(0).doOperation();
        }
    }

    abstract boolean accepted(String par1, String par2, String par3);
    abstract void doOperation();
}

A: I prefer to use Stream to check these parameters.
if (Stream.of(param1, param2, param3).filter(Objects::nonNull).count() != 1) {
    throw new Exception();
}


text:
Q: Need to run a regression 1000 times I have a regression function called reg. I now need to run it 1000 times , capture the Rsquare value and t-stat in a histogram.
I tried running replicate as follows ( have taken n=5, to see results):
replicate(5,{
  seriese=matrix( rnorm(100*1,mean=0,sd=1), 100, 1)
  e <- matrix(ncol = 1, nrow = 100)
  for(i in 1:100){
    e[i] <- sum(seriese[1:i,1])
  }
  dataY <- cbind(seriese, e)
  seriesa=matrix( rnorm(100*1,mean=0,sd=1), 100, 1)
  x <- matrix(ncol = 1, nrow = 100)
  for(i in 1:100){
    x[i] <- sum(seriesa[1:i,1])
  }
  dataX <- cbind(seriesa, x)
  #convert to ts
  dataYTS=ts(dataY[,2])
  dataXTS=ts(dataX[,2])
  #run regression
  #check summary regression
  reg=lm(dataYTS~dataXTS)
},simplify=FALSE)

This reports the type of data, not the values.
replicate(5,{reg=lm(dataYTS~dataXTS)})
              [,1]        [,2]        [,3]        [,4]        [,5]
coefficients  Numeric,2   Numeric,2   Numeric,2   Numeric,2   Numeric,2
residuals     Numeric,100 Numeric,100 Numeric,100 Numeric,100 Numeric,100
effects       Numeric,100 Numeric,100 Numeric,100 Numeric,100 Numeric,100
rank          2           2           2           2           2
fitted.values Numeric,100 Numeric,100 Numeric,100 Numeric,100 Numeric,100
assign        Integer,2   Integer,2   Integer,2   Integer,2   Integer,2
qr            List,5      List,5      List,5      List,5      List,5
df.residual   98          98          98          98          98
xlevels       List,0      List,0      List,0      List,0      List,0
call          Expression  Expression  Expression  Expression  Expression
terms         Expression  Expression  Expression  Expression  Expression
model         List,2      List,2      List,2      List,2      List,2

A: The R-squared value is not part of the list that lm returns. To get that you need to extract the relevant leaf from the summary.lm list:
Rsq.vec <- replicate(5,{
  seriese=matrix( rnorm(100*1,mean=0,sd=1), 100, 1)
  e <- matrix(ncol = 1, nrow = 100)
  for(i in 1:100){
    e[i] <- sum(seriese[1:i,1])
  }
  dataY <- cbind(seriese, e)
  seriesa=matrix( rnorm(100*1,mean=0,sd=1), 100, 1)
  x <- matrix(ncol = 1, nrow = 100)
  for(i in 1:100){
    x[i] <- sum(seriesa[1:i,1])
  }
  dataX <- cbind(seriesa, x)
  dataYTS=ts(dataY[,2])
  dataXTS=ts(dataX[,2])
  summary(lm(dataYTS~dataXTS) )$r.squared
}, simplify=TRUE)

You can then do hist on that object. You say you want the 't-stat', but that request is unclear since there are multiple t-statistics even in that simple model. Perhaps you want the t-statistic for the second coefficient?, the t-statistic for the predictor variable. That could be also found using summary. The $coefficients leaf of that list is a matrix. Read the help page for summary.lm and it should be a simple modification of the code above.


text:
Q: Dynamically allocated array in C++ I am playing around with dynamically allocating an array in c++.  I have this code
#include <iosteam>
using namespace std;

void A(int* arr)
{
    for(int i = 0; i < 10; i++)
        cout << arr[i] << endl;
}

int main()
{
    int **nums;
    nums = new int*[10];
    for(int i = 0; i < 10; i++)
        nums[i] = new int(i);

    for(int i = 0; i < 10; i++)
        cout << *nums[i] << endl;

    cout << endl;
    A(*nums);
    return 0;
}

This gives me the output
0
1
2
3
4
5
6
7
8
9

0
0
0
0
0
0
33
0
1
0

My question is:  When the array is passed to the function A(int* arr), why does the array printed there have different output than what the array defined in main() has?  I have been studying dynamic allocation and double pointers, but I can't seem to figure this one out.  I have searched through SO questions and can't find a suitable answer to this question.  I would like to know if I can print the values of the array in the function A(), or if it is even possible to do it this way.  Any help is appreciated.

A: Your function:
void A(int* arr)
{
    for(int i = 0; i < 10; i++)
        cout << arr[i] << endl;
}

is getting called with A(*nums).
You are effectively executing:
for(int i = 0; i < 10; i++)
        cout << (*nums)[i] << endl;

which is equivalent to:
for(int i = 0; i < 10; i++)
        cout << nums[0][i] << endl;

You are seeing the effects of undefined behavior since you are accessing unauthorized memory.
Remember that you only have access to
num[0][0]
num[1][0]

....

num[9][0]

and not
num[0][0]
num[0][1]

....

num[0][9]

A: the answers above is quite right and you can modify your code as follows.
void A(int** arr)

{

    for(int i = 0; i < 10; i++)
       // cout << *arr[i] << endl; or bellow
        cout <<arr[i][0]<<endl;
}

reference in your main as "A(nums)";


text:
Q: Datetimepicker return an empty string as value I am using bootstrap datetimepicker for date range. I am trying to get the date value in angularjs controller like shown below. I also tried some other methods from stackoverflow posts. But what ever i do i get the date value as 'an empty string' in console log.
I have added resources in this order
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.43/css/bootstrap-datetimepicker.min.css">

Minimal HTML code related to issue.

       <input type='text'  ng-model="startDate" class="form-control" />

In Controller
$(function() {
        $('#datetimepicker6').datetimepicker({
            format : 'YYYY-MM-DD HH:mm:ss'
        });
        $("#datetimepicker6").on("dp.change", function(e) {
            $('#datetimepicker7').data("DateTimePicker").minDate(e.date);

             $scope.startDate = $("#datetimepicker6").val();
             alert("selected date is " + $scope.startDate);
        });
    });

A: Use a directive for the datepicker .
HTML Code:
<input class="form-control input-sm ll-skin-melon" jqdatepicker placeholder="2015-06-15" id="duedate" name = "duedate" ng-model="duedate">

Directive Code:
var drctv = angular.module('yourapp.directives', []);

drctv.directive('jqdatepicker', function() {
    return {
        restrict: 'A',
        require: 'ngModel',
        link: function(scope, element, attrs, ngModelCtrl) {
            console.log(element);
            element.datepicker({
                dateFormat: 'yy-mm-dd',
                minDate: 0
            });

            element.on("dp.change", function(date) {
                  scope.$apply(function() {
                            ngModelCtrl.$setViewValue(date);
                        });
             });

           /*You can also try this code*/

           element.datepicker().on('changeDate', function (ev) {
                  scope.$apply(function() {
                            ngModelCtrl.$setViewValue(date);
                  });
           });

        }
    };
});

I hope this will help you to solve your problem.

A: You can use e.date value inside the dp.change event. I have attached a small code snippet along with

<!DOCTYPE html>

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.43/css/bootstrap-datetimepicker.min.css">

                        <input type='text' class="form-control" />

Please look at this and let me know if this fit your requirement.


text:
Q: Drawing pie chart with chart.js I'm using chart.js from http://www.chartjs.org/.
I want to draw a pie chart, but nothing is displaying. I managed to draw line chart, so the Javascript is loaded.
HTML
<!-- Chart -->
<script type="text/javascript" src="_javascripts/chart/Chart.min.js"></script>
<!-- //Chart-->

    <canvas id="browsersChart" width="400" height="100"></canvas>
    <script>
    var ctx = document.getElementById("browsersChart");
    var myChart = new Chart(ctx, {
        type: 'pie',
        data: {
            datasets: [{
                label: 'Browsers',
                data: [14, 2, 2, 2, 1],
                backgroundColor: [
                    window.chartColors.red,
                    window.chartColors.orange,
                    window.chartColors.yellow,
                    window.chartColors.green,
                    window.chartColors.blue,
                ],
            }],
            labels: [
                "Chrome"
                "Firefox"
                ""
                "MSIE"
                "Mobile Safari"
                ]
            },
            options: {
                    responsive: true
            }
        };
    </script>

A: You have some typos in your code.
In the labels section, you need a comma after each label:
labels: [
    "Chrome", // These commas at the end need added.
    "Firefox",
    "",
    "MSIE",
    "Mobile Safari"
]

You also need to add a ) at the very end of the Chart declaration:
    options: {
        responsive: true
    }
}); // The rounded bracket here needs added

In the future, you should use the dev tools in your browser. The Console tab will tell you about errors like these. It explained exactly what line had errors.
After fixing these typos, I got a pie chart just as expected.


text:
Q: How does Spring @Configuration cache references to beans How does Spring prevent a second call to bar() when using Java based configurations?
I'm wondering compile time annotation processing or by proxying the method?
@Configuration
public class AppConfig {

  @Bean
  public Foo foo() {
      return new Foo(bar());
  }

  @Bean
  public Foo foo2() {
      return new Foo(bar());
  }

  @Bean
  public Bar bar() {
      return new Bar();
  }
}

A: Assuming you created your context a little something like
AnnotationConfigApplicationContext context =
    new AnnotationConfigApplicationContext(AppConfig.class);

Because of @Configuration, Spring will create a bean of type AppConfig and proxy it because it has @Bean methods. You should check out ConfigurationClassEnhancer for implementation details.
These methods aren't called on the object directly. Obviously they can't since they aren't known at compile time. They are called through reflection on the proxy.
So when you have
@Bean
public CustomBean foo() {
    return new CustomBean(bar());
}

which is equivalent to
@Bean
public CustomBean foo() {
    return new CustomBean(this.bar());
}

the this is referring to a proxy which caches the result of the method invocation and returns it immediately if it's called it before.

A: Spring does not "prevent" a call to bar().
Instead, at startup, spring generates a list of @Bean marked methods then calls each method one time.
If you want, you can call bar() a hundred times.
Spring, however; will only call it one time.


text:
Q: Emscripten Bindings: How to create an accessible C/C++ array from Javascript? I am using box2d and attempting to create a chain shape.
In order to create a chain shape or polygon shape I must pass an array of vectors in order to specify the geometry.
I do not see any documentation to help me accomplish this, and the notes about bindings here don't go into any detail about arrays.
How can I construct an array?

A: I have solved this problem by using these (as yet undocumented) emscripten features.
Note that I am accessing the functions and values (like ALLOC_STACK and wrapPointer) out of the Box2D object simply because that is the scope where I have found them to be exposed. They are emscripten-specific values, so for a different project and/or build settings it would be different.
// an alternative method that may work (shorter, less obvious code) is
// allocate([v1x,0,0,0,v1y,0,0,0,v2x,0,0,0,...], 'float', Box2D.ALLOC_STACK);
// 8 byte per vector * 4 vectors = 32 bytes of memory required
var buffer = Box2D.allocate(32, 'float', Box2D.ALLOC_STACK);
Box2D.setValue(buffer, left, 'float'); // v1x
Box2D.setValue(buffer+4, bottom, 'float'); // v1y
Box2D.setValue(buffer+8, right, 'float'); // v2x
Box2D.setValue(buffer+12, bottom, 'float'); // v2y
Box2D.setValue(buffer+16, right, 'float'); // v3x
Box2D.setValue(buffer+20, top, 'float'); // v3y
Box2D.setValue(buffer+24, left, 'float'); // v4x
Box2D.setValue(buffer+28, top, 'float'); // v4y
var ptr_wrapped = Box2D.wrapPointer(buffer, Box2D.b2Vec2);
shape.CreateLoop(ptr_wrapped, 4);
body.CreateFixture(shape,0.0);


text:
Q: IE not playback mp3 from php script i have problem with playback audio just only in IE.
The console does not show an error. I get file from php script and set this headers:
    $mime_type = "audio/mpeg";
    header("Content-Type: {$mime_type}");
    header('Content-Length: '.filesize($file));
    readfile($file);

In js:
    audio.src = source;
    audio.load();
    audio.addEventListener('canplay', function(){
        audio.play();
    }, true);

In source path to php script.

A: Add this meta tag to the head:

< meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">

and also

Try

audio/vnd.wave

because some browser do attempt content fixing wrong MIME types.


text:
Q: Aligning Materialize CSS collapsible horizontally? I am trying to change the default collapsible behavior in materialize css by aligning them horizontally.
I have got partial success in it by using the below code :

<!DOCTYPE html>

  <link rel = "stylesheet"
  href = "https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">

  <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">

filter_dramaFirst

Lorem ipsum dolor sit amet.

placeSecond

Lorem ipsum dolor sit amet.

whatshotThird

Lorem ipsum dolor sit amet.

But when I click the first collapsible-header, the other two collapsible headers drop below the collapsible-body of first collapsible.
When I click second collapsible-header then the first collapsible header is fixed(fine) but the third collapsible-header drops below the body of the second collapsible.
Clicking on the last collapsible header works fine (as expected).
Can someone give me a workaround for this?
Thanks in Advance,
Nikhil

A: You have to set position: absolute to collapsible-body but this is not a perfect way to do because as mentioned by @ic3b3rg, this component is not designed to work horizontally so instead of this you can use tabs or any other horizontal accordion.

<!DOCTYPE html>

  <link rel = "stylesheet"
  href = "https://cdnjs.cloudflare.com/ajax/libs/materialize/1.0.0/css/materialize.min.css">

  <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">

filter_dramaFirst

Lorem ipsum dolor sit amet.

placeSecond

Lorem ipsum dolor sit amet.

whatshotThird

Lorem ipsum dolor sit amet.


text:
Q: Phoenix Channel sending messages from a client outside the project I wanted to send a message to my user channel of my Phoenix Application. I have joined a user_token with the channel as users:user_token in the user_channel.ex . I was successful doing it from another controller called the toy_controller by calling a broadcast method. The broadcast method is in the user channel. And I have written a jQuery file to handle the events. I was looking for something which can send messages to the same channel from outside of the project, because I wanted to do some IoT stuff. I have tried a python module called occamy.socket and the JS client of Phoenix that it uses internally. Then, I found a disconnection always. I can't figure out the exact address of the websocket connection from Phoenix. If I am trying it with that Phoenix npm library in that project folder itself, it says ReferenceError: window is not defined always. And, I think it is because of the initialization part of the socket in the web/static/js/socket.js file where it's written as
let socket = new Socket("/socket", {params: {token: window.userToken}})

, but I am not sure. The thing that I have tried is below
var Socket = require("phoenix-socket").Socket;
var socket = new Socket("ws://localhost:4000/socket");

In the python client, I was also trying to connect to this address and got a disconnection error. I want to do it for IoT purposes, where I want to monitor sensor data of a user. Each user will be having their own sensors to be monitored. So, I have configured the channel topic:subtopic channel as users:user_token . I need to send messages from my raspberry pi to this channel using those unique tokens of the users. My user_channel, user.js, app.js and socket.js are given below.

//web/static/js/socket.js
import {Socket} from "phoenix"

let socket = new Socket("/socket", {params: {token: window.userToken}})

socket.connect()

export default socket

//web/static/app.js

import "phoenix_html"
import user from "./user"

#web/channels/user_channel.ex
defmodule Tworit.UserChannel do
    use Tworit.Web, :channel

    def join("users:" <> user_token, payload, socket) do
        if authorized?(payload) do
          {:ok, "Joined To User:#{user_token}", socket}
      else
          {:error, %{reason: "unauthorized"}}
      end
    end

    def handle_in("ping", payload, socket) do
        {:reply, {:ok, payload}, socket}
    end

    def handle_in("shout", payload, socket) do
       broadcast socket, "shout", payload
       {:noreply, socket}
    end

    def handle_out(event, payload, socket) do
        push socket, event, payload
        {:noreply, socket}
    end

     defp authorized?(_payload) do
       true
     end

    def broadcast_change(toy, current_user) do
       payload = %{
        "name" => toy.name,
        "body" => toy.body
       }
      Tworit.Endpoint.broadcast("users:#{current_user.token}", "change", payload)
    end

end

//web/static/js/user.js
import socket from "./socket"

$(function() {
  let ul = $("ul#em")

  if (ul.length) {
    var token = ul.data("id")
    var topic = "users:" + token

    // Join the topic
    let channel = socket.channel(topic, {})
    channel.join()
      .receive("ok", data => {
        console.log("Joined topic", topic)
      })
      .receive("error", resp => {
        console.log("Unable to join topic", topic)
      })
    channel.on("change", toy => {
     console.log("Change:", toy);
     $("#message").append(toy["name"])
    })
  }
});

A: Finally, I am able to send and receive messages asynchronously from a python program. It uses websockets asyncio module from python. I figured out the various events required for phoenix channels like 'phx_join' for joining a topic and all. So, the following program worked.
import asyncio
import websockets
import json
import time
from random import randint
import serial

from pyfirmata import Arduino, util

board = Arduino('/dev/ttyACM1')

it = util.Iterator(board)
it.start()
board.analog[0].enable_reporting()
board.analog[1].enable_reporting()
board.analog[2].enable_reporting()
board.analog[3].enable_reporting()

import RPi.GPIO as gpio

gpio.setmode(gpio.BCM)
gpio.setup(14, gpio.OUT)

async def main():
    async with websockets.connect('ws://IP_addr:4000/socket/websocket') as websocket:
        data = dict(topic="users:user_token", event="phx_join", payload={}, ref=None)
        #this method joins the phoenix channel
        await websocket.send(json.dumps(data))

        print("Joined")

        while True:
            msg = await retrieve() # waits for data from arduino analog pins
            await websocket.send(json.dumps(msg)) # sends the sensor output to phoenix channel

            print("sent")
            call = await websocket.recv() # waits for anything from the phoenix server
            control = json.loads(call)

            # I have sent values from 2 buttons for swicthing a led with event 'control'

            if(control['event'] == "control"):
                event(control['payload']['val']) #swiches the led as per the input from event 'control'

            print("< {}".format(call))

def event(val):
    if(val == "on"):
        gpio.output(14, True)
    if(val == "off"):
        gpio.output(14, False)

async def retrieve():
    #analog read
    load = board.analog[0].read()
    pf = board.analog[1].read()
    reading = board.analog[2].read()
    thd = board.analog[3].read()
    output = {"load": load, "pf": pf, "reading": reading,"thd": thd}

    msg = dict(topic="users:user_token", event="sensor_output", payload=output, ref=None) # with
    #event "sensor_outputs"
    #the phoenix server displays the data on to a page.

    print(msg)
    return(msg)

asyncio.get_event_loop().run_until_complete(main())
asyncio.get_event_loop().run_forever()


text:
Q: I use fetch to receive data from an api. How can i pass the data to php? What i want is to set the value of tipster opentips and profitallseason equal to the to the picks and win i receive from the api for each user. The structure of the data inside it are
[  {"user": "cryptosniper",
    "profitallseason": 197,
    "profitperseason": [{ "2021-2022": 197 }],
    "opentips": 4
    }
]

So what i want is for every user to dynamicaly change the $value_tipster_opentips and $value_tipster_profitallseason based on the values of the api. The code that i came up with until now is the following. I don't know how to pass the data from fetch to php.
add_action('wp_head', 'tipster_infos');

function tipster_infos(){
    $getArgs = array(
        'order' => 'DESC',
        'orderby' => 'name',
        'hide_empty'    => false
    );

    $categories = get_terms( 'tipster', $getArgs );
    foreach($categories as $category) {

        $value_tipster_user = get_term_meta( $category->term_id, 'tipster-user', true );
        $value_tipster_opentips = get_term_meta( $category->term_id, 'tipster-opentips',true );
        $value_tipster_profitallseason = get_term_meta( $category->term_id, 'tipster-profitallseason', true );

        echo "<script type='text/javascript'>
            fetch('https://metakomhsh.gr/betprgonostika/betapi.json',
                    {method: 'GET', // set FETCH type GET/POST
                    headers: {'Content-Type': 'application/json'}
            })
            .then(function (response) {
                console.log(response);
                return response.json();
            })
            .then(function (data) {
                console.log(data);
                for(info of data) {
                    if (info.user == '" . $value_tipster_user . "') {
                        $value_tipster_profitallseason = info.profitallseason;
                        $vlaue_tipster_opentips = info.opentips;
                    }
            }
    });
</script>";
}


text:
Q: How to properly select an area inside a numpy ndarray How to properly select a specific area inside a NumPy ndarray. For example, in the sample code below I want to select the 2x3 matrix that corresponds to the intersections of columns and rows of matrix M stored in a and b respectively,
M = np.random.rand(4,5)
print(M)
a = [0, 2]
b = [0, 2, 3]
Selection = M[a,b]

but I am getting:

IndexError: shape mismatch: indexing arrays could not be broadcast
together with shapes (2,) (3,)

when I want from matrix M:
[[0.36899449 0.02531732 0.04966994 0.66058884 0.26193009]
 [0.92893864 0.10193024 0.74850916 0.72822403 0.09112129]
 [0.28863096 0.45470087 0.01032583 0.30931807 0.42765045]
 [0.59819051 0.94057773 0.95352287 0.81818564 0.24220261]]

To get:
[[0.36899449 0.04966994]
 [0.28863096 0.01032583]
 [0.59819051 0.95352287]]


text:
Q: JAVA, IntelliJ IDEA и ошибка Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException Я очень, очень глупый новечёк. У меня есть ошибка но нет решения(((( A Google отказываеться помогать(((( Пожалуйста, сделайте это за него
Main
package com.company;

public class main {

public static void main(String[] args) {
     GUI window =  new GUI();
     javax.swing.SwingUtilities.invokeLater(window);
    }
}

GUI
package com.company;
import javax.swing.*;

public class GUI implements Runnable {
    JFrame frame;
    public void run() {
        initframe();

    }

    private void initframe() {
        frame.setLocationRelativeTo(null);
        frame.setTitle("Life game");
        frame.setSize(250, 100);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setVisible(true);
    }

}

Сама ошибка
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
    at com.company.GUI.initframe(GUI.java:12)
    at com.company.GUI.run(GUI.java:7)
    at java.desktop/java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:313)
    at java.desktop/java.awt.EventQueue.dispatchEventImpl(EventQueue.java:770)
    at java.desktop/java.awt.EventQueue$4.run(EventQueue.java:721)
    at java.desktop/java.awt.EventQueue$4.run(EventQueue.java:715)
    at java.base/java.security.AccessController.doPrivileged(AccessController.java:389)
    at java.base/java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:85)
    at java.desktop/java.awt.EventQueue.dispatchEvent(EventQueue.java:740)
    at java.desktop/java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:203)
    at java.desktop/java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:124)
    at java.desktop/java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:113)
    at java.desktop/java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:109)
    at java.desktop/java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
    at java.desktop/java.awt.EventDispatchThread.run(EventDispatchThread.java:90)

A: JFrame frame = new JFrame();

Забыли выделить память под объект


text:
Q: Boostrap Nav + Carousel + Footer keep relative heights I would like to know whether it is possible to keep relative heights from the three main components of a home html. In this case, bootstrap nav + carousel + footer. I would like to modify the height of the carousel so it is always around 70% of the screen with the other 20% for the nav and 10% for the footer. There is no image resizing problems since the carousel has only one background color and it is not an image. The html structure looks like this:
Here is the fiddle:

https://jsfiddle.net/q4t8bupc/

Thanks!

A: Please check this.

.header{height:20vh; background:#666}
.content{height:70vh; background:#ed0000;}
.footer{height:10vh; background:#03C;}


text:
Q: How to parse Bank information into particular format, plus java questions Doing a java assignment in CSE 205 at ASU, and I'm having a hard time understanding parsing. I've looked through our online textbook, and parsing rarely comes up and it's never given a full explanation. I've looked through the java api documentation a few times and I never understand what it's saying, so I hope someone isn't too frustrated as to explain how to do it.
The class is:
BankParser
The BankParser class is a utility class that will be used to create bank objects from a string. The BankParser class cannot be instantiated. It has the following method:
public static Bank bankParser(String lineToParse)
The bankParser method's argument will be a string in the following format:
bankName/bankID/city,state
A real example of this string would be:
Bank Arizona/10001/Phoenix,AZ
The bankParser method will parse this string, pull out the information, create a new bank object, set the attributes of the object, and return it.
So far this is my setup:
public class BankParser {

public static Bank bankParser(String lineToParse) {

}

}

Also, in my Bank class I have this toString method:
    public String toString() {
    String printInfo = ("\nBank name:\t" + bankName + "\nBank ID:\t" + bankID +     "\nBank address:\t" + bankAddress + "\n");
    return printInfo;

It gives me 2 markers in eclipse: that this overrides java.lang.Object.toString, and that the return type is missing. What does this all mean?? The return type is String, I don't see what the problem is with that, but the override I'm clueless
EDIT; This is what I've come up with for bankParser
    public static Bank bankParser(String lineToParse) {
    String[] returnValue = lineToParse.split("/");
    Bank temp = new Bank();
    temp.setbankName(returnValue[0]);
    temp.setbankID(returnValue[1]);
    temp.setbankAddress = (returnValue[2]); //this one won't work, see below
       return temp;
}

}

And THESE are the methods in Bank and Address that apply to bankParser
    public void setBankName(String bank1) {
    bankName = bank1;
}

public void setBankID(String bankID1) {
    bankID = bankID1;
}

public void setBankAddress(String city, String state) {
    bankAddress.setCity(city);
    bankAddress.setState(state);
}

In Address.java:
    public void setCity(String city1) {
    city = city1;
}

public void setState(String state1) {
    state = state1;
}

A: I would use library like Apache Common CSV for reading and writing.
Reader in = new StringReader("bankName/bankID/city,state");

Iterable<CSVRecord> parser = CSVFormat.newBuilder()
     .withDelimiter('/')
     .parse(in);

for (CSVRecord csvRecord : parse) {
     ...
}

A: Your bankParser method is empty. It needs to return a Bank object, and Java will complain until you do this.  You could always have it return null for now til, make it at least a compilable stub you figure this out:
public static Bank bankParser(String lineToParse) {
   Bank returnValue = null;
   // TODO: create a Bank object, assign to returnValue
   return returnValue;
}

As for your override bit, are you getting an error message? Or a warning? The code you've posted seems kosher, so it should compile. Please show the actual full message.
As for your actual parsing, I'd use String#split("/") to split the lineToParse into an array of tokens and then work with each token, create arguments for a Bank constructor call and create a Bank object.
i.e., code to show the concept:
String text = "Bank Arizona/10001/Phoenix,AZ";

String[] tokens = text.split("/");
System.out.println(java.util.Arrays.toString(tokens));


text:
Q: I was invited to meet Which is correct in the following?

I am invited to meet the president.
I am invited to meet with the president.

A: Both are correct. But there is still a nuance of meaning.

I am invited to meet with the president. ( I have a meeting with the president) - the verb meet is
intransitive(without object);

Whereas in your first sentence: the verb "meet" is transitive(with
object). ( most likely to mean = be in someone's presence );

Given that you are using the noun "president" and that word combination seems quite a bit more common to me, I would use "to meet with someone".
for instance
She and I have decided to meet up(also intransitive) later.
This brings us to the conclusion that some verbs in English can be both intransitive and transitive with little or no difference in meaning at all.
Also, here are some stats from Ngrams:
Meet the president vs meet with the president
According to ngrams, "to meet the president" is used slightly more often.


text:
Q: Am i using correct relationships in this UML class diagram? Should i keep android implementation in mind while making class diagram? I am working on a tourism android application as a final year project. But i am very confused in making the class diagram. I am not understanding should i keep android implementation in mind while creating the class diagram. I have made this so far

A: Regarding the relationships:

*

*Your Register has a local attribute typed User and you have a composite aggregation to User. It's better to used role names in such cases instead of the attributes. Just put -user near the diamond and remove the local attribute.

*The has a labels are superfluous. You use them with ERD, but in UML you don't need it. The relation between associated classes is expressed via role names much better.

*Keep class names singular (Place without 's', etc.).

Just to make you aware of this: when User composes Register it means that when you remove User it is responsible to also remove the composite Register. Looks like it should be the other way round. However, I just would remove the diamond and make it a simple association. The register just holds User references. Best to put according multiplicity towards User (that'd be 0..* most likely).
Regarding the "activity classes": As I understood your classes (like Register) inherit from some system class (I'd guess it's called Activity). That would be you draw a generalization from your class to that Activity. In order to not crowd your diagram you will omit that from the diagram. Remember: one diagram is one view on your diagram. You can and will have more than one view. So create another class diagram that just shows the generalization(s) without any other relation. Together these diagrams will represent a combined view of your design.


text:
Q: Modulo calculation by theorems Suppose that the order of $Z_n$ is $t$:
A) Calculate $a^t \mod n$ for an integer $a$ which is co-prime $n$
B) If ed = tk+1 and $c ≡m^e \mod n$ for some integers m,e,d,t.
Calculate $c^d \mod n$

A: Hint: Apply Chinese Remainder Theorem on the prime-power factors of $n$.


text:
Q: C# Random Reset, problemilla: repite secuencia para mis simulaciones de fisica, me hice 10 matrices de 800 datos, de momento los relleno alea para test.
NO hay manera, me salen las 10 graficas calcadas.
la cosa parece ir bien si pongo un break poin tras la carga de las 4 Ks, la puse hay para confirmar que funciona, y si, funciona, FUNCIONA CON LOS BREAKPOINS. (si paso de ellos a mitad de vueltas, a partir de ahi falla)
lo que me lleva a pensar que la semilla la toma del reloj, y al ser muy rapido no cambia.
si pongo la definicion del Rand fuera de la funcion tambien me fallaba, arriba el de defi de prototipos, ¿o como le llamais a eso los informaticos?
creo que intentare con un retardillo.
        public void Test()
    {
        Random Rand = new Random();   //poniendolo tras el public Class ClassReg tambien fallaba
        double k1 = Rand.NextDouble();
        double k2 = Rand.NextDouble();
        double k3 = Rand.NextDouble();
        double k4 = Rand.NextDouble();  //4 de las variables que siempre pilla las mismas//Aqui el breack point,
        for (int i = 0; i < 800; i++)
        {
            lee[i].d = 0.5 + 0.8 * k3 * Math.Sin((i + 2 * Rand.NextDouble() - 10) * 0.2*k1) + 0.4 * k4 * Math.Cos((i + 3 * Rand.NextDouble() - 5) * 0.25*k2);// no os asusteis esto genera ondas, es irrelevante
            ///lee[i].d = i/800.0;  //opcion genera una diago en pantalla,
        }
    }

A: LA RAIZ del problema: quiero ver 10 lineas similares, ¿que mejor que definir una clase generica y crear 10 objetos?.
SI, pero en la clase meti Test(), que genera las lineas aleatorias, y en esa clase esta el ramdom.
al crear los 10 objetos, todos nacen con la misma secuencia. (o esa es mi sospecha)
LA SOLUCION:
un unico randon fuera de esa clase.
intente lo de la semilla, retardos, hasta mi hice mi propia randon, nada funciono


text:
Q: Example 1.7 Girondo's Introduction to compact riemann surfaces Consider first the algebraic equation $$y^{2}=\prod_{k=1}^{2g+1}(x-a_k)$$ where $\{a_k\}_{k=1}^{2g+1}$ is a collection of $2g+1$ distinct complex numbers, and let
$$
S^\circ =\{(x,y) \in \mathbb{C}^{2}: y^{2}=\prod_{k=1}^{2g+1}(x-a_k) \}.
$$
We shall now define a chart $(U,\phi)$ around each given point $P_0=(x_0,y_0)$. As it is easier, we rather describe parametrizations:
1) If $x_0 \ne a_i$ for all $i$ (and so $y_0 \ne 0$), we take
$$
\phi^{-1}(z)=\left (z+x_0,\sqrt{\prod_{k=1}^{2g+1}(x-a_k)}\right ),
$$
defined in the disc $\{|z|<\epsilon\}$ with $\epsilon$ small enough for $z$ not to reach any of the values $a_i$. The branch of the square root is chosen so that its value at $z=x_0$ equals $y_0$ (and not $-y_0$).
2) For $P_0=(a_j,0)$, we take
$$
\phi_j^{-1}(z)=\left( z^{2}+a_j,z\sqrt{\prod_{k \ne j}(z^{2}+a_j-a_k)} \right), \, \, \, |z|<\epsilon,
$$
again with $\epsilon$ small enough to guarantee that $z^{2}+a_j$ does not reach $a_k$ for every $k \ne j$. Note that if we had taken the first coordinate to be $z+a_j$, then the second one would not to be a well-defined holomorphic function in $|z| < \epsilon$.
I don't understand why the second coordinate isn't a well-defined holomorphic function and why there's $z$ before the square root in the expression $\phi_j^{-1}(z)$.

A: Except for the $a_j$, above each point of the plane there are two points in the surface (corresponding to the two values of the square root). When you consider a small neighbourhood $W$ of a point $w \notin \{a_j : 1 \leqslant j \leqslant 2g+1\}$, you have two branches of
$$\sqrt{\prod_{j=1}^{2g+1}(x-a_j)}$$
defined in $W$, and the two branches give a parametrisation of the surface above $W$. The projection $\pi_W \colon S^\circ\cap \pi^{-1}(W) \to W$ looks like the projection from $W\times \{-1,1\}$ to $W$.
But in a small neighbourhood $W = D_\varepsilon(a_j)$ of one of the $a_j$, the projection looks different, it looks like $z \mapsto z^2$, in particular $S^\circ \cap \pi^{-1}(W)$ is connected (even $S^\circ \cap \pi^{-1}(W\setminus \{a_j\})$ is connected).
Suppose you have a parametrisation of $S^\circ$ around $(a_j,0)$, that is, two hlomorphic functions $\alpha,\,\beta \colon D_\varepsilon(0) \to \mathbb{C}$ with $\alpha(0) = a_j$, $\beta(0) = 0$, such that $\alpha'$ and $\beta'$ don't ever vanish in the same point (so it's a regular parametrisation), and with
$$\beta(z)^2 = \prod_{k=1}^{2g+1} \bigl(\alpha(z) - a_k\bigr).$$
If $\varepsilon$ is small enough,
$$\prod_{k\neq j} \bigl(\alpha(z) - a_k\bigr)$$
has no zeros in $D_\varepsilon(0)$, hence, since the disk is simply connected, a holomorphic square root, say $\rho$ (then $-\rho$ is the other square root). $\rho$ vanishes nowhere, so we obtain
$$\left(\frac{\beta(z)}{\rho(z)}\right)^2 = \alpha(z) - a_j.$$
$\beta/\rho$ is holomorphic, so $\alpha(z) - a_j$ must have a holomorphic square root. The simplest holomorphic function $\gamma$ on $D_\varepsilon(0)$ with $\gamma(0) = 0$ that isn't constant and has a holomorphic square root is $\gamma(z) = z^2$, which leads to the choice $\alpha(z) = z^2 + a_j$. The two square roots of $\alpha(z) - a_j$ are $z \mapsto z$ and $z \mapsto -z$, so we obtain
$$\beta(z) = \pm z\rho(z).$$
The sign can be absorbed in the choice of $\rho$, so altogether, we obtain the paramerisation
$$\phi(z) = \left(\alpha(z), z\sqrt{\prod_{k\neq j}\bigl(\alpha(z) - a_k\bigr)}\right).$$
Since $z$ is a square root of $\alpha(z) - a_j$, we could also write the second component as
$$\sqrt{\prod_{k=1}^{2g+1} \bigl(\alpha(z) - a_k\bigr)},$$
but pulling the factor $z$ out of the square root makes the mapping behaviour more obvious.


text:
Q: Shortcut for show in explorer texstudio When I right click on a file in the structure section of texstudio, one of the options is "show in explorer". Is there a way to define a shortcut for this option.

A: Keyboard shortcuts can be assigned only to Menu entries and to some basic editing functions as shown in the manual.
You can use a script in a personal macro and assign a keyboard shortcut to it.
This script will open the file explorer in the folder of the current file in the editor (uncomment the appropriate line for your operating system):
%SCRIPT
// needs TeXstudio v2.11.0 or newer
filename = app.getCurrentFileName()
workingDirectory = filename.substring(0, filename.lastIndexOf("/"))
//system("explorer .", workingDirectory) //for windows - tested
//system("xdg-open .", workingDirectory) //for linux - tested
//system("open .", workingDirectory) //for mac - untested