text:
Q: User Selected Columns of 2D Array in C++ I am trying to write a C++ program, that will take the user defined number of columns at run time and create a two dimensional array that will have
Columns = given at run time
Rows = 3Columns
How should I initialize a 2D array where the rows and columns are not initially constants. Any link or tutorial help will be appreciated.

A: I think you are looking for dynamic multi-dimensional arrays. Googlefu should help, leads to this article:
http://www.cplusplus.com/forum/beginner/63/
Look near the bottom.

A: You provided us a little information, I guess you are asking for a C++ code that first takes column number from user and then calculates rows on the basis of formula and finally creates a two dimensional array, right ?
 Formula given : rows = 3columns.
I've written a C++ code for you
I've tested this code on my linux( ubuntu ) platform , I hope this is what you are asking.

#include <iostream>
#include<math.h>
#define kary 3 // Your k-ary truth table - 3 for ternary truth table(0,1,2), 2 for binary truth table(1,2)

using namespace std;
int main()
{
    int rows,cols,i,j;  // Variable declaration
    cout<<"\n Enter required number of columns =  ";
    cin>>cols;
    rows = pow(kary,cols);
    cout<<"\n Calculated number of rows =  "<<rows;
    int arr[rows][cols]; // Array declaration
    for (i=0; i<rows; i++)
    {
        for (j=0; j<cols; j++)
           arr[i][j]=((i/(int) pow(kary, j)) % kary); //logic
    }
    cout<<"\n Your array holds this data \n";
    for(i = 0; i < rows; i++)
    {
        for (j=cols-1; j>=0; j--)
            cout<<"\t"<<arr[i][j];
        cout<<"\n";
    }
    return 0;
}


text:
Q: Jmeter Math Confusion I have A problem With The Jmeter Tool it dosen't view result i'm testing from my local host and i don't know where is the problem
This is my Recording templete
And This is my Local Host That I want To test It
I Don't Know What Is The wrong

A: *

*You need to configure your browser to use JMeter as the proxy

*If you're recording HTTPS traffic you need to import JMeter's certificate, see HTTPS recording and certificates chapter of HTTP(S) Test Script Recorder JMeter User Manual entry for more details

*In case of any problems check jmeter.log file for any suspicious entries

Also be aware of an alternative way of recording a JMeter test: JMeter Chrome Extension, in this case you won't have to worry about proxies and certificates, just follow your test scenario steps in the browser and once done you will be able to export recorded requests in form of JMeter's .jmx test script

redpajama_set_name: RedPajamaStackExchange


text:
Q: Cannot force JavaFX TableView to refresh from another Window/Controller I have two windows and two controllers.
In the first window is a button which opens a second window and TableView. The second window is a form where I insert properties of my class. After inserting I click on "Save" and add new created object to a static list. This should be shown in a TableView. When I use only one window and one controller everything works fine but splitting the functionality as described in two windows the TableView is not refreshed.
Here is my minimal example:
MAIN CONTROLLER
public class Controller {

    @FXML
    public TableView tableView;

    @FXML
    private Button openWindow;

    // called by the FXML loader after the labels declared above are injected:
    public void initialize() {

        TableColumn mailColumn = new TableColumn("E-Mail");
        tableView.getColumns().addAll(mailColumn);
        mailColumn.setCellValueFactory(new PropertyValueFactory<Person,String>("mail"));

        openWindow.setOnAction((event) -> {
            new PersonInputForm(event);
        });

    }

    // ######   Receiver TableView Action Handling #######
    public void updateReceiverList(){
        final ObservableList<Person> data = FXCollections.observableArrayList(Memory.receiverList);
        tableView.getItems().clear();
        tableView.getItems().addAll(data);
    }

}

SECONDARY CONTROLLER
public class PersonInputFormController {

    @FXML
    private TextField mail;

    @FXML
    private AnchorPane personInputFormAnchorPane;

    private Controller mainController ;
    Stage stage;

    public void setStage() {
        stage = (Stage) personInputFormAnchorPane.getScene().getWindow();
    }

    public void setMainController(Controller mainController){
        this.mainController = mainController;
    }

    public void save(){
        Memory.saveReceiver(mail);
        mainController.updateReceiverList();
        stage.close();
    }

}

MAIN WINDOW
public class Main extends Application {

    @Override
    public void start(Stage primaryStage) throws Exception{

        FXMLLoader loader = new FXMLLoader(getClass().getResource("sample.fxml"));
        Parent root = loader.load();
        Scene scene = new Scene(root);
        primaryStage.setScene(scene);
        primaryStage.setResizable(false);
        primaryStage.show();
    }

    public static void main(String[] args) {
        launch(args);
    }
}

SECONDARY WINDOW
public class PersonInputForm {

    public PersonInputForm(ActionEvent event) {

        Stage stage = new Stage();

        FXMLLoader mainFxmlLoader = new FXMLLoader(getClass().getResource("../sample.fxml"));
        try {
            mainFxmlLoader.load();
        } catch (IOException e) {
            e.printStackTrace();
        }
        Controller mainController = mainFxmlLoader.getController();

        FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("PersonInputForm.fxml"));
        Parent root = null;
        try {
            root = (Parent)fxmlLoader.load();
        } catch (IOException e) {
            e.printStackTrace();
        }

        stage.setScene(new Scene(root));
        stage.initOwner(
                ((Node) (event.getSource())).getScene().getWindow() );

        PersonInputFormController controller = fxmlLoader.<PersonInputFormController>getController();
        controller.setStage();
        controller.setMainController(mainController);

        stage.show();

    }
}

MEMORY
public class Memory {

    public static sample.Person sender = new sample.Person();
    public static ArrayList<sample.Person> receiverList = new ArrayList();

    static public void saveReceiver(TextField mail){
        Person receiver = new Person();
        receiver.setMail(mail.getText());
        receiverList.add(receiver);
    }

}

OBJECT
public class Person {

    private SimpleStringProperty mail = new SimpleStringProperty();

    public String getMail() {
        return mail.get();
    }

    public SimpleStringProperty mailProperty() {
        return mail;
    }

    public void setMail(String mail) {
        this.mail.set(mail);
    }

}

I found the following similar sounding topics:
How to set items of a TableView in a different controller class in JavaFX?
Javafx Update a tableview from another FXML
But, I still don't understand how my problem can be solved.
Thanks in advance!

A: In your PersonInputForm class' constructor you create an FXMLLoader to load sample.fxml. You then give the controller resulting from this load—a Controller instance—to your PersonInputFormController instance you generate later on. The problem with this is the Controller instance that invoked new PersonInputForm(event) is not the same instance you give to the PersonInputFormController. Remember, each time you call FXMLLoader.load you create a new scene graph connected to a new controller instance.
As you are calling new PersonInputForm(event) from within an instance of Controller, and it's this instance of Controller you need to call updateReceiverList() on, the easiest fix is to pass this to PersonInputForm as well. Then remove the code responsible for loading sample.fxml.
public PersonInputForm(ActionEvent event, Controller mainController) {
    // code...
    controller.setMainController(mainController);
}

Note: It feels wrong to have all this behavior in a constructor.
While the above will solve your problem (I believe), having to clear-and-replace the items of a TableView is not the ideal approach. Take a look at updateReceiverList():
public void updateReceiverList(){
    // Copies Memory.receiverList into new ObservableList
    final ObservableList<Person> data = FXCollections.observableArrayList(Memory.receiverList);
    tableView.getItems().clear();
    // Copies data into the TableView's items list
    tableView.getItems().addAll(data);
}

That code copies a collection into another collection twice. This can become quite expensive when you have a large number of elements. It would be better if you had an observable model that your different controllers could observe and react to.
For instance, you're using an ArrayList to store/share your Persons where you could be using an ObservableList. You could then use tableView.setItems(Memory.receiverList) and any updates your PersonInputFormController makes to the receiverList will be automatically seen by the TableView. As you don't appear to be using multi-threading, this setup shouldn't cause any problems. When, or if, you start utilizing background threads, remember that you must never update the UI—directly or indirectly—from a background thread.
However, using global state (i.e. public static variables) is not ideal either. I recommend reading up on different application architectures such as: Model-View-Controller (MVC), Model-View-Presenter (MVP), Model-View-ViewModel (MVVP), etc. Then try to apply one of them to your application as appropriate.

Some links:

*

*Applying MVC With JavaFx

*Passing Parameters JavaFX FXML

I'd like to point out one more thing about your code. You're using a lot of raw types. Don't use raw types. For instance, you should have:
@FXML private TableView<Person> tableView;

And:
TableColumn<Person, String> mailColumn = new TableColumn<>("E-Mail");
// which lets you use the diamond operator here
mailColumn.setCellValueFactory(new PropertyValueFactory<>("mail"));

And:
// You're missing the <> on the right hand side
public static ArrayList<Person> receiverList = new ArrayList<>();


text:
Q: How to Import Excel File to Database with Mapping Laravel Hi i created a demo project that i can with import excel files and get them into my database with laravel excel but what i want to do is with mapping not just a simple import and get them into the database like if the excel file is missing a field or a name i want like to specify each field alone
like field name alone gender alone
here is my code
Studentsimport.php
<?php

namespace App\Imports;

use App\Models\Student;
use Illuminate\Support\Collection;
use Maatwebsite\Excel\Concerns\ToCollection;
use Maatwebsite\Excel\Concerns\WithHeadingRow;
use Maatwebsite\Excel\Concerns\WithValidation;

class StudentsImport implements ToCollection, WithHeadingRow,WithValidation
{
    /**
    * @param Collection $collection
    */
    public function collection(Collection $rows)
    {
        foreach($rows as $row){
            $data=[
                'name'=>$row['name'],
                'gender'=>$row['gender'],
                'email'=>$row['email_address'],
                'grade'=>$row['grade'],
                'mobile_number'=>$row['mobile_number']
            ];
            Student::create($data);
        }
    }

    public function rules(): array
    {
        return[
            'name'=>'required',
            'gender'=>'required',
            'email_address'=>'required|unique:students,email',
            'grade'=>'required',
            'mobile_number'=>'required'
        ];
    }
}

view.blade.php

Import Excel Data In Laravel

    @if($errors->any())

Following errors exists in your excel file

            @foreach ($errors->all() as $error)

{{$error}}

            @endforeach

    @endif
    <form action="/import" method="POST" enctype="multipart/form-data">
        @csrf
        <input type="file" name="student_file" accept=".xlsx,.xls,.csv" required>

        <input type="submit" value="Upload">
    </form>

                S.N.
                Name
                Gender
                Grade
                Email Address
                Mobile Number

            @php
                $i=0;
            @endphp
            @forelse ($students as $student)

                    {{++$i}}
                    {{$student->name}}
                    {{$student->gender}}
                    {{$student->grade}}
                    {{$student->email}}
                    {{$student->mobile_number}}

            @empty

                    No Students

            @endforelse

studentsController.php
<?php

namespace App\Http\Controllers;

use App\Imports\StudentsImport;
use App\Models\Student;
use Illuminate\Http\Request;
use Maatwebsite\Excel\Facades\Excel;

class StudentController extends Controller
{
    public function index(){
        $students = Student::all();
        return view('welcome',compact('students'));
    }
    public function import(Request $req){
        Excel::import(new StudentsImport,$req->file('student_file'));
        return back();
    }
}


text:
Q: Optimal (approximated) path Algorithm (distance + priority) I need to write an algorithm for the following scenario:

Given a set of points (cities) on a map I have to visit. Each of these cities has a priority, from 1 (you need to go there ASAP) to 5 (no rush, but go there eventually). I have limited ressources so I can not visit all the priority-1 cities at first. (E.g if NY and SF have priority 1 and Washington has Priority 5, I'm looking for a path NY-Washington-SF not NY-SF-Washington).

I don't know it it matters, but n (# of cities) will usually be around 10-20.
I found a presentation of "The Hierarchical Traveling Salesman Problem" (Panchamgam, Xiong, Golden and Wasi) which is kind of what I'm looking for but the corresponding article is not publicly accessible.
Can you recommend existing algorithms for such scenarios? Or point me in the right direction what to search for?
An approximation would be alright. My scenario is not as life-threatening as in the scenario described by Panchamgam et. al. It's important to avoid unnecessary detours caused by the priorities without ignoring them completely.

A: In standard TSP you want to minimize the total length of the route. In your case you want to basically optimize two metrics: the length of the route, and how early high priority cities appear on the route. You need to put these two metrics into a single metric, and how you do that might have an impact on the algorithm choice. For example, map the city priorities to penalties, e.g.
1  ->  16
2  ->  8
3  ->  4
4  ->  2
5  ->  1

Then use as the metric you want to minimize the total sum of (city_penalty * distance_to_city_from_start_on_route). This pushes the high priority cities to the beginning of the route in general but allows for out of priority order traversal if otherwise the route becomes too long. Obviously the penalty values should be experimentally tuned.
With this metric, you can then use e.g. standard stochastic search approach --- start with a route and then swap cities or edges on the route in order to decrease the metric (use simulated annealing or tabu search).

A: An upper bound of 20ish puts dynamic programming in play. There's an O(n^2 2^n)-time algorithm for plain old traveling salesman path that goes like this. For each end vertex (n) and subset of vertices containing that end vertex (2^(n - 1)), we're going to determine the cheapest tour that visits the entire subset. Iterate over the subsets so that each set comes after its proper subsets (e.g., represent the sets as bit vectors and count from 0 to 2^n - 1). For each end vertex v in a subset S, the cheapest tour of S is either just v (if S = {v}) or it consists of a cheapest tour of S - {v} (computed already) followed by v. Each vertex w in S - {v} is a possibility for the next to last vertex of the tour of S - {v}.
You haven't completely specified how the priorities interact with the goal of minimizing the distance. One could, for example, translate the priorities into deadlines (you must visit this vertex before traveling x distance). The dynamic program adapts easily for this setting: the only modification needed is to assign cost +infinity if the time to reach the specified end vertex is too great. There are a lot of other possibilities here; you can have an objective consisting of a sum over each individual vertex of some vertex-dependent function of the distance to reach that vertex.
From an engineering standpoint, the nice thing about implementing an exact algorithm is that it is much easier to test (just compare with brute force).


text:
Q: Homebrew python Install I am new to programming and when I install python3.7 with homebrew it adds two interpreters to vscode. Why is this and which should I be using.
I have installed using $brew install python3
Python 2.7.10 64-bit  (macOS native)
/usr/bin/python

Python 3.7.3 64-bit
/usr/local/bin/python3

Python 3.7.3 64-bit
/user/local/opt/python/bin/python3.7

A: You can run $ which python3 in the terminal and will see the path to the interpreter.

A: I can see you issued the below command for installation.
brew install python3
Normally only the latest version gets installed. To install python 2.7, you have to execute the below command. Did you run this?
brew install python@2
Anyway, I'd recommend using the 3.7 environment. However. if you are using this to run a python application which was written in 2.7 version, you should be using that.


text:
Q: How to get value from json knowing a specifc id in a cURL command My cURL command returns me some json data like the following :
{
    "all":[
        {
            "id":"1",
            "actions":[
                "power",
                "reboot"
            ]
        },
        {
            "id":"2",
            "actions":[
                "shutdown"
            ]
        },
        {
            "id":"3",
            "actions":[
                "backup"
            ]
        }
    ]
}

Knowing only the id, how can I return the actions values into a variable ? I know how to parse IDs but how can I get the actions ?
Here is the cURL command :
#!/bin/bash
IDS=$(curl https://DOMAIN/API -H "X-Auth-Token: $TOKEN" | python -c "import sys, json; print [i['id'] for i in json.load(sys.stdin)['all']]")

$IDS will output all IDS from the json.

Exemple:
If I search for id = 1, I will retreive ["power", "reboot"]

I can also retreive actions with :
#!/bin/bash
ACTIONS=$(curl -s https://DOMAIN/API -H "X-Auth-Token: TOKEN" | python -c "import sys, json, re; print [ i['allowed_actions'] for i in json.load(sys.stdin)['servers']]")

I thought doing something like this :
#!/bin/bash
ACTIONS=$(curl -s https://DOMAIN/API -H "X-Auth-Token: TOKEN" | python -c "import sys, json, re; print [ if i['id'] == '1': i['allowed_actions'] for i in json.load(sys.stdin)['servers']]")

But I have syntax error.
How can I translate this code into a single command line code ?
for i in json.load(sys.stdin)['all']:
    if i['id'] == '1':
        print(i['actions'])

A: Generally the norm is to not use exec in python but since you wanted to be in one line, here you go
cat temp | python -c "exec(\"import sys,json \nfor i in json.load(sys.stdin)['all']:\n    if i['id'] == '1':\n        print(i['actions'])\")"

While saying this I suggest just creating another python file and let this job be done by that file , Hope it helps :)

A: From CLI, you could use jq;
curl -s "http://api.icndb.com/jokes/random" | jq '.value.joke'

In your case, it would probably be something like (not tested) :
ACTIONS=$(curl -s "https://DOMAIN/API" | jq '.all.actions')

More information/examples for jq;
https://medium.com/cameron-nokes/working-with-json-in-bash-using-jq-13d76d307c4


text:
Q: Displays a string of linked images How do I displays a string of linked images for a post using php?
Terms
http://domain.com/106.jpg,http://domain.com/109.jpg,http://domain.com/112.jpg

<?php the_field( 'gallery' ); ?>
`

A: You can do it by using explode() function:
$string = 'http://domain.com/106.jpg,http://domain.com/109.jpg,http://domain.com/112.jpg';
$split = explode ( ',', $string );

It will return an array. So you can print this way:
echo $split[0]; //will print http://domain.com/106.jpg
echo $split[1]; //will print http://domain.com/109.jpg
//and so on


text:
Q: How to represent repeating month in ISO 8601 I try to promote the usage of ISO8601. How can every month of any year and halves of theses months be representated in ISO 8601?
We use a perpetual calendar in Excel where there are 2 column headers : first row is January, February, etc. and below a column subdivided into 2, something like this following example:
       | Tasks  | January | February |  March   | ...
       |        |    |    |     |    |     |    | ...
       |  task1 |    | X  |     |  X |     |    | ...
       |  task2 |    |    |  X  |    |     |    | ...

How to best merge these header rows into in a meaningful row, written Jan-<first half> | Jan-<second-half> | etc. in an easily readable form. I think January-01 | January-02 is obviously not the answer. If this is not the right way to do it, please, describe how to deal with this kind of repetition.
This question is different from the one about representing date ranges I've redirected to as in the later start and end years/dates are indicated. My question is about recurring approximate date spans.
Thanks


text:
Q: If a function $ f(x) $ depends only on $ |x| $ then its Fourier transform depends only on $ |w| $ Let $ f\in L^1(\mathbb{R}^3,\mathbb{C} ) $ be a function such that for $ x_1,x_2\in \mathbb{R}^3 $ such that   $ |x_{1}|=|x_{2}| $ we have $ f\left(x_{1}\right)=f\left(x_{2}\right) $.
I have to prove that also for any $ \omega_{1},\omega_{2}\in\mathbb{R}^{3} $ we have $ \mathcal{F}\left\{ f\right\} \left(\omega_{1}\right)=\mathcal{F}\left\{ f\right\} \left(\omega_{2}\right) $.
Here's what I have tried:
Note that $ \mathcal{F}\left\{ f\right\} \left(\omega\right)=\frac{1}{\left(2\pi\right)^{3}}\intop_{\mathbb{R}^{3}}f\left(x\right)e^{-i\omega\cdot x}dx $
(where $ \omega \cdot x $ is the dot product of 3dimensional vectors).
Now I want to switch to spherical cooredinates, so I'll note
$ \omega=\left(R\sin\left(\theta_{1}\right)\cos\left(\varphi_{1}\right),R\sin\left(\theta_{1}\right)\sin\left(\varphi_{1}\right),R\cos\left(\theta_{1}\right)\right) $
and $ x=\left(r\sin\left(\theta\right)\cos\left(\varphi\right),r\sin\left(\theta\right)\sin\left(\varphi\right),r\cos\left(\theta\right)\right) $
So that $ \mathcal{F}\left\{ f\right\} \left(\omega\right)=\frac{1}{\left(2\pi\right)^{3}}\intop_{0}^{\infty}\intop_{0}^{\pi}\intop_{0}^{2\pi}f\left(r,\theta,\varphi\right)e^{-irR\left(\sin\theta_{1}\cos\varphi_{1}\sin\theta\cos\theta+\sin\theta_{1}\sin\varphi_{1}\sin\theta\sin\varphi+\cos\theta_{1}\cos\theta\right)}r^{2}\sin\theta d\varphi d\theta dr $
and since $ r $ is radial I can just write $ f(r) $. Also I will use trigonometric identities to get:
$ =\frac{1}{\left(2\pi\right)^{3}}\intop_{0}^{\infty}\intop_{0}^{\pi}\intop_{0}^{2\pi}f\left(r\right)e^{-irR\left(\sin\theta_{1}\sin\theta\cos\left(\varphi-\varphi_{1}\right)+\cos\theta_{1}\cos\theta\right)}r^{2}\sin\theta d\varphi d\theta dr $
All I have to do is to show that the integral does not depend on $ \theta_1 , \varphi_1 $
But I got stuck here. Any help would be appreciated.
Thanks in advance.


text:
Q: jQuery animated number counter from zero to value on hover of Anchor tag    $({ Counter: 0 }).animate({
  Counter: $('.Single').text()
}, {
  duration: 1000,
  easing: 'swing',
  step: function() {
    $('.Single').text(Math.ceil(this.Counter));
  }
});

Digit
I need a jQuery animated number counter from zero to value on hover of anchor tag section , is that even possible ?

150

A: Like this?

function startCounter() {
  const maxCounter = $('.Single').data('counter');
  $({
    Counter: 0
  }).animate({
    Counter: maxCounter
  }, {
    duration: 1000,
    easing: 'swing',
    step: function() {
      $('.Single').text(Math.ceil(this.Counter));
    }
  });
}

$('#magic').on('mouseenter', startCounter);

Hover me


text:
Q: Spring boot. How do I get data from the input field and then multiply it with data from the database? The question arises about how to output data from a dynamic form, which, depending on how many items are in the database, creates input fields. I.e. there are fields that are created automatically and you need to get the numbers that will be entered there.
I really appreciate any help you can provide.
Here is the dynamic form code.
<form action="/" method="post"  th:object="${Elements}">
    <div th:each="el : ${elementsGet}">
        <h3 th:text="${el.name}"/>
        <input type="text" name="value" th:placeholder="${el.value}">
    </div>
    <button type="submit" class="btn btn-primary">Submit</button>
</form>

Controller Code
 @GetMapping("/")
    public String main(Model model) {
        Iterable<Elements> elements = elementsRepo.findAll();
        model.addAttribute("elementsGet", elements);
        return "main";
    }

 @PostMapping("/")
    public String getElements(@ModelAttribute("Elements") Elements elements,  Model model) {

        System.out.println(elements.getValue().toString());

        return "main";
    }

I tried to output data through the object, but nothing came out.


text:
Q: ngModel make datePicker date of today return null My date picker is set default to today, which benefit the status of what my code is running at the moment. I want to be able to pass the value of it so I use ngModel and it make my datePicker null. I found that ngInit can hard code default value but the problem is I don't know what represent dateTime.Now in ngInit.
<mat-form-field>
  <mat-label>Angular forms</mat-label>
  <input matInput [matDatepicker]="picker1" [formControl]="date" [(ngModel)]="datePicker">
  <mat-datepicker-toggle matSuffix [for]="picker1"></mat-datepicker-toggle>
  <mat-datepicker #picker1 [(ngModel)]="datePicker"></mat-datepicker>
</mat-form-field>

A: Just remove ngmodel from <mat-datepicker like this <mat-datepicker #picker1></mat-datepicker>
Here is an example project which has developed using mat-date-picker with ngModel
https://stackblitz.com/edit/angular-cj6bjs?file=app%2Fdatepicker-overview-example.html
Other than that u can find this example in Stackblitz https://stackblitz.com/angular/dlerqrdamjl?file=app%2Fdatepicker-value-example.html and it has developed using Reactive forms.


text:
Q: Progressive Video Download on iOS I am trying to implement Progressive Downloading of a video in my iOS application that can be played through AVPlayer. I have already implemented a downloader module that can download the files to the iPad. However, I have discovered I cannot play a file that is still being written to
So, as far as I can tell, my only solution would be through downloading a list of file 'chunks' and then keep playing through every file as they are ready (ie: downloaded), probably using HLS
Searching I have come across this question which implements the progressive download through hls but other than that, I can find no other way
However, I keep coming across search results that say how to configure web servers to leverage the iOS support for HTTP Progressive Downloading, but with no mention of how to do it from the iOS side
So, any one have any ideas and/or experience about this?
EDIT: I have also found there could be a way of doing it other way around (ie: streaming, then writing streamed data to disk) which was suggested by this question but still cannot get it to work as it seems it does not work with non-local assets!

A: From what you say, you might want to change approach and attempt to stream the file. Downloading and playing at the same time, I would say is the definition of Streaming. I hate when people post links to the Apple documentation but in this instance reading a tiny bit of this documentation will help you more than I ever can. It should all make sense if you are lready working with connections and video, you just need to change your approach.
The link: https://developer.apple.com/library/ios/documentation/networkinginternet/conceptual/streamingmediaguide/Introduction/Introduction.html


text:
Q: How to redirect correctly using header in php? My code -
<?php
    error_reporting(E_ALL);
?>
<?php
    session_start();

    if(isset($_POST["subLogin"]))
    {
        $uname = trim($_POST["tbUser"]);
        $pass = $_POST["pasUser"];
        if($uname == "")
        {
            header('Location: index.php?e=1');
        }
        else if($pass == "")
        {
            header('Location: index.php?e=2');
        }
        $unameF = "";
        $passF = "";

        $userfile = fopen("DB/userDB.txt", "r");
        while(!feof($userfile))
        {

            $arr1 = explode(":", fgets($userfile));
            $unameF = trim($arr1[1]);
            $arr1 = explode(":", fgets($userfile));
            $passF = trim($arr1[1]);
            $arr1 = explode(":", fgets($userfile));
            $type = trim($arr1[1]);
            if($unameF == $uname)
            {
                $_SESSION["uname"] = $uname;
                $_SESSION["type"] = $type;
                header('Location: welcome.php');
            }
        }
        header("Location: index.php?e=0");
    }
    else
    {
        header('Location: index.php');
    }
?>

Here, "header("Location: index.php?e=0");" always gets executed even if the username matches. And "welcome.php" is never reached. If "header("Location: index.php?e=0");" this line is commented out, then it works fine. Any solutions??

A: Call exit() after your redirect.
header('Location: index.php?e=1');
exit();


text:
Q: Using c# interface in a c++ project with VS express 1013 I am trying to include a c# interface into a c++ header file which belongs to a clr library.
I add the additional directory and as soon as I include the interface and try to build the c++ project, I get loads of errors leading to the cs file, like:

Do I mess up some VS settings?

A: It is impossible to #include "IImagesToVideoConverter.cs". The C++ compiler cannot understand c# code. You need to put a c# project and a c++ project in the same solution, reference the c# project from the c++ project, and (i think) #using <the.dll>

A: including a C# source in a C++ compile makes no sense. They are different languages, why would you ever expect this to work?
Perhaps you want to make a COM interface between them, in which case you use a #import directive.


text:
Q: Java: calling the base method class from a second derived class This is what I'm trying to do:
class A {
    void myMethod() {
        // execute A
    }
}

class B extends A {
    void myMethod() {
        // execute B
    }
}

class C extends B {
    void myMethod() {
        // execute C
        // execute myMethod in A, without touching myMethod in B OR both
    }
}

I'd like to do this conditionally, that is sometimes call what's in myMethod inside B and other times not, but always call myMethod inside A.
By calling super.myMethod() in C I get myMethod of B, but I only want myMethod of A. Is that possible? I've heard of "virtual" things, but I don't know how to use them... yet.

A: No, it is not possible in Java on purpose. Class B overrides and therefore hides the implementation of myMethod in A from further deriving classes. Allowing C to call myMethod of A would violate this encapsulation. Consider a case where B.myMethod performs some updates before internally calling A.myMethod which are important for the correct functionality of B. Without these updates, the contract of B could be violated. Therefore, it should not be possible to call A.myMethod in a derived class without calling B.myMethod.
Usually, your design is flawed if you want to do stuff like this.
Of course, you can do stuff like suggested by Dave in the comments: You can alter the implementation of B.myMethod to call A.myMethod. This is okay, because B retains the control over when to call A.myMethod. Therefore, it can take care that its contract is not violated.
Another idea is to factor out the behaviour you want from A into another method and call this one.

A: If you need this, A.myMethod() probably does too much. Try to refactor it into several smaller methods with access level protected.
That allows you to call these methods from both B and C.

A: While I agree with most answers about possibly changing the design, to directly answer you could pass in a variable boolean into the first method. The entirety of the logic in B's method should depend on a conditional if statement depending on the boolean. Make sure to make a call to super.myMethod() outside of this if statement.
Something like this:
void myMethod(boolean execB) {
// execute B
super.myMethod(execB);
    if(execB)
    {
        //B logic
    }
}

This is however, not the best in practice, because only B's method is using the variable, hence why refactoring the design  might be a good decision.


text:
Q: Add tab stop at: doesn't work in Word list Hello everybody and thanks in advance:
I'm trying to use the first line indent effect in a Word list, but I'm not getting it, although it looks correct in the preview. What am I doing wrong?

A: I have achieved the desired effect by adding another tab stop. To add it I had to disable Set left and first indent  with tabs and backspaces


text:
Q: How to detect CSS flex wrap event I have flex container with items inside. How to detect flex wrap event? I want to apply some new css to elements that have been wrapped. I suppose that it is impossible to detect wrap event by pure css. But it would be very powerful feature! I can try to "catch" this break point event by media query when element wraps into new line/row. But this is a terrible approach. I can try to detect it by script, but it's also not very good.

I am very surprised, but simple $("#element").resize() doesn't work to detect height or width changes of flex container to apply appropriate css to child elements. LOL.
I have found that only this example of jquery code works
jquery event listen on position changed
But still terribly.

A: Little bit improved snippet on jQuery for this purpose.
wrapped();

$(window).resize(function() {
   wrapped();
});

function wrapped() {
    var offset_top_prev;

    $('.flex-item').each(function() {
       var offset_top = $(this).offset().top;

      if (offset_top > offset_top_prev) {
         $(this).addClass('wrapped');
      } else if (offset_top == offset_top_prev) {
         $(this).removeClass('wrapped');
      }

      offset_top_prev = offset_top;
   });
}

A: I've modified sansSpoon's code to work even if the element isn't at the absolute top of the page. Codepen: https://codepen.io/tropix126/pen/poEwpVd
function detectWrap(node) {
    for (const container of node) {
        for (const child of container.children) {
            if (child.offsetTop > container.offsetTop) {
                child.classList.add("wrapped");
            } else {
                child.classList.remove("wrapped");
            }
        }
    }
}

Note that margin-top shouldn't be applied to items since it's factored into getBoundingClientRect and will trigger the wrapped class to apply on all items.

A: Here's one potential solution. There might be other gotchas and edge cases you need to check for.
The basic idea is to loop through the flex items and test their top position against the previous sibling. If the top value is greater (hence further down the page) then the item has wrapped.
The function detectWrap returns an array of DOM elements that have wrapped, and could be used to style as desired.
The function could ideally be used with a ResizeObserver (while using window's resize event as a fallback) as a trigger to check for wrapping as the window is resized or as elements in the page change due to scripts and other user-interaction. Because the StackOverflow code window doesn't resize it won't work here.
Here's a CodePen that works with a screen resize.

var detectWrap = function(className) {

  var wrappedItems = [];
  var prevItem = {};
  var currItem = {};
  var items = document.getElementsByClassName(className);

  for (var i = 0; i < items.length; i++) {
    currItem = items[i].getBoundingClientRect();
    if (prevItem && prevItem.top < currItem.top) {
      wrappedItems.push(items[i]);
    }
    prevItem = currItem;
  };

  return wrappedItems;

}

window.onload = function(event){
  var wrappedItems = detectWrap('item');
  for (var k = 0; k < wrappedItems.length; k++) {
    wrappedItems[k].className = "wrapped";
  }
};
div  {
  display: flex;
  flex-wrap: wrap;
}

div > div {
  flex-grow: 1;
  flex-shrink: 1;
  justify-content: center;
  background-color: #222222;
  padding: 20px 0px;
  color: #FFFFFF;
  font-family: Arial;
  min-width: 300px;
}

div.wrapped {
  background-color: red;
}

A

B

C

A: I'm using a similar approach in determining if a
 has been wrapped in an
 that has it's display set to flex.
ul = document.querySelectorAll('.list');

function wrapped(ul) {

    // loops over all found lists on the page - HTML Collection
    for (var i=0; i 0) {
                li[j].className = 'wrapped';
            } else {
                li[j].className = 'unwrapped';
            }
        }
    }
}

A: I noticed elements will typically wrap in relation to the first element. Comparing offset top of each element to the first element is a simpler approach. This works for wrap and wrap-reverse. (Probably won't work if elements use flex order)

var wrappers = $('.flex[class*="flex-wrap"]'); //select flex wrap and wrap-reverse elements

    if (wrappers.length) { //don't add listener if no flex elements
        $(window)
            .on('resize', function() {
                wrappers.each(function() {
                    var prnt = $(this),
                        chldrn = prnt.children(':not(:first-child)'), //select flex items
                        frst = prnt.children().first();

                    chldrn.each(function(i, e) { $(e).toggleClass('flex-wrapped', $(e).offset().top != frst.offset().top); }); //element has wrapped
                    prnt.toggleClass('flex-wrapping', !!prnt.find('.flex-wrapped').length); //wrapping has started
                    frst.toggleClass('flex-wrapped', !!!chldrn.filter(':not(.flex-wrapped)').length); //all are wrapped
               });
            })
            .trigger('resize'); //lazy way to initially call the above
    }
.flex {
    display: flex;
}

.flex.flex-wrap {
    flex-wrap: wrap;
}

.flex.flex-wrap-reverse {
    flex-wrap: wrap-reverse;
}

.flex.flex-1 > * { /*make items equal width*/
    flex: 1;
}

.flex > * {
  flex-grow: 1;
}

.cc-min-width-200 > * { /*child combinator*/
  min-width: 200px;
}

Hello

There

World

A: If someone wants to find the last element of the row from where wrapped elements started can use the below logic. It's applicable for multiple lines as well
       window.onresize = function (event) {
            const elements = document.querySelectorAll('.borrower-detail');
            let previousElement = {};
            let rowTop = elements[0].getBoundingClientRect().top;
            elements.forEach(el => el.classList.remove('last-el-of-row'))
            elements.forEach(el => {
                const elementTop = el.getBoundingClientRect().top;

                if (rowTop < elementTop) {
                    previousElement.classList.add('last-el-of-row');
                    rowTop = elementTop;
                }

                previousElement = el;
            })
        };


text:
Q: How to Separate NSString Data I Have one NSString* string;
String = "ID: 12 34 56 78       Class:C"
Now i want to distinguish the ID data in one variable and Class data in another,
How can i separate this two from single String
I have used :
NSScanner* Scanner = [NSSCanner ScannerWithString:@"String"]
 NSCharacterSet* seperator = [NSCharacterSet CharacterSetWithCharacterInString:@":"];
 NSString* text;

 while([Scanner isAtEnd] == NO)
 {
    [Scanner ScanUpToCharacterFromSet:Seperator intoString:@"text"];
    [Scanner scanUpToCharactersFromSet:newLine intoString:NULL];
    NSLog(@"%@",text);

 }

This won't separate my String from ID and Class, tell me how can i do this
my O/p should be :
12 34 56 78
C
This is one scenario i have array of Strings and in each i want to separate my string with another keyword ....

A: Use NSString's rangeOfString function
NSString *myString = @"ID: 12 34 56 78 Class:C";
NSRange range = [myString rangeOfString:@"Class"];
NSString *idStr = [myString substringToIndex:range.location];
NSString *classStr = [myString substringFromIndex:range.location];
NSLog(idStr);
NSLog(classStr);

I got this on my Log
2014-02-07 15:56:29.951 Hello[5493:903] ID: 12 34 56 78
2014-02-07 15:56:29.959 Hello[5493:903] Class:C

A: Regular expressions are the way to go.
First create your NSRegularExpression:
NSError *error = nil;
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:@"ID:(.*?)Class:(.*?)" options:0 error:&error];

With this you are creating a regular expression to match what's in parentheses. Then, match your regular expresion with your string:
NSMutableArray *resultArray = [NSMutableArray arrayWithCapacity:0];

NSArray *matchArray = [regex matchesInString:yourString options:0 range:NSMakeRange(0, [yourString length])];
for(NSTextCheckingResult *result in matchArray)
{
    if(result.range.location != NSNotFound)
    {
        NSInteger rlen = result.numberOfRanges;
        for(NSInteger i=1;i<rlen;i++)
        {
            NSRange range = [result rangeAtIndex:i];
            [resultArray addObject:[yourString substringWithRange:range]];
        }
    }
}

And after this you'll have this:
resultArray[0] => ID data,
resultArray[1] => Class data
You may need to adjust the regular expression to skip blanks, but that's basically it.


text:
Q: Cannot render React page because of 404 error Good day!
I tried to create my first React-application.
This is package.json:
 {
   "name": "budget",
   "version": "1.0.0",
   "scripts": {
     "start": "lite-server"
   },
  "devDependencies": {
    "lite-server": "^2.2.1"
  }
}

html-page:

     <meta charset="utf-8"/>
     <title>Menu</title>

jsx:
 class MainMenu extends React.Component {
   render() {
      return

            Date
            Operation
            Amount
            Item of expenditure
            Balance

     }
 }

ReactDOM.render(
     <MainMenu/>,
     document.getElementById("app")
);

When I trying to start app, I receive page with only title: Cannot GET /
In developer tools I see the following error: Failed to load resource: the server responded with a status of 404 (Not Found)
Just in case the structure of project:


text:
Q: Partial animal string matching in R I have a dataframe,
d<-data.frame(name=c("brown cat", "blue cat", "big lion", "tall tiger",
                     "black panther", "short cat", "red bird",
                     "short bird stuffed", "big eagle", "bad sparrow",
                     "dog fish", "head dog", "brown yorkie",
                     "lab short bulldog"), label=1:14)

I'd like to search the name column and if the words
"cat", "lion", "tiger", and "panther" appear, I want to assign the character string feline to a new column and corresponding row species.
If the words "bird", "eagle", and "sparrow" appear, I want to assign the character string avian to a new column and corresponding row species.
If the words "dog", "yorkie", and "bulldog" appear, I want to assign the character string canine to a new column and corresponding row species.
Ideally, I'd store this in a list or something similar that I can keep at the beginning of the script, because as new variants of the species show up in the name category, it would be nice to have easy access to update what qualifies as a feline, avian, and canine.
This question is almost answered here (How to create new column in dataframe based on partial string matching other column in R), but it doesn't address the multiple name twist that is present in this problem.

A: There may be a more elegant solution than this, but you could use grep with | to specify alternative matches.
d[grep("cat|lion|tiger|panther", d$name), "species"] <- "feline"
d[grep("bird|eagle|sparrow", d$name), "species"] <- "avian"
d[grep("dog|yorkie", d$name), "species"] <- "canine"

I've assumed you meant "avian", and left out "bulldog" since it contains "dog".
You might want to add ignore.case = TRUE to the grep.
output:
#                 name label species
#1           brown cat     1  feline
#2            blue cat     2  feline
#3            big lion     3  feline
#4          tall tiger     4  feline
#5       black panther     5  feline
#6           short cat     6  feline
#7            red bird     7   avian
#8  short bird stuffed     8   avian
#9           big eagle     9   avian
#10        bad sparrow    10   avian
#11           dog fish    11  canine
#12           head dog    12  canine
#13       brown yorkie    13  canine
#14  lab short bulldog    14  canine

A: An elegant-ish way of doing this (I say elegant-ish because, while it's the most elegant way I know of, it's not great) is something like:
#Define the regexes at the beginning of the code
regexes <- list(c("(cat|lion|tiger|panther)","feline"),
                c("(bird|eagle|sparrow)","avian"),
                c("(dog|yorkie|bulldog)","canine"))

....

#Create a vector, the same length as the df
output_vector <- character(nrow(d))

#For each regex..
for(i in seq_along(regexes)){

    #Grep through d$name, and when you find matches, insert the relevant 'tag' into
    #The output vector
    output_vector[grepl(x = d$name, pattern = regexes[[i]][1])] <- regexes[[i]][2]

}

#Insert that now-filled output vector into the dataframe
d$species <- output_vector

The advantage of this method are several-fold

*

*You only have to modify the data frame once in the entire process, which increases the speed of the loop (data frames do not have modification-in-place; to modify a data frame 3 times, you're essentially relabelling and recreating it 3 times).

*By specifying the length of the vector in advance, since we know what it's going to be, you increase speed even more by ensuring that the output vector never needs more memory allotted after it is created.

*Because it's a loop, rather than repeated, manual calls, the addition of more rows and categories to the 'regexes' object will not require further modification of the code. It'll run just as it does now.

The only disadvantage - and this applies to, I think, most solutions you're likely to get, is that if something matches multiple patterns, the last pattern in the list it matches will be its 'species' tag.

A: Another way is to create lookup tables and combine matching by index with grep and match
d<-data.frame(name=c("brown cat", "blue cat", "big lion", "tall tiger",
                     "black panther", "short cat", "red bird",
                     "short bird stuffed", "big eagle", "bad sparrow",
                     "dog fish", "head dog", "brown yorkie",
                     "lab short bulldog"), label=1:14)

avian <- c("bird", "eagle", "sparrow")
canine <- c("dog", "yorkie", "bulldog")
feline <-  c("cat", "lion", "tiger", "panther")

lu <- stack(tibble::lst(avian, canine, feline))
lu2 <- stack(sapply(lu$values, grep, x = d$name, ignore.case = TRUE))
lu2$ind <- as.character(lu$ind[match(as.character(lu2$ind), lu$values)])

d$species <- d$name
d$species[lu2$values] <- as.character(lu2$ind)

d
#>                  name label species
#> 1           brown cat     1  feline
#> 2            blue cat     2  feline
#> 3            big lion     3  feline
#> 4          tall tiger     4  feline
#> 5       black panther     5  feline
#> 6           short cat     6  feline
#> 7            red bird     7   avian
#> 8  short bird stuffed     8   avian
#> 9           big eagle     9   avian
#> 10        bad sparrow    10   avian
#> 11           dog fish    11  canine
#> 12           head dog    12  canine
#> 13       brown yorkie    13  canine
#> 14  lab short bulldog    14  canine

Created on 2021-11-13 by the reprex package (v2.0.1)


text:
Q: How we can set minDate and maxDate of Bootstrap datetimepicker in MVC 4 on selection of DropDownListFor item I want to set MinDate or MaxDate of Bootstrap datetimepicker on selection of DropDownListFor in MVC. This is reason for this is in India some pay scale released on a year. if A pay scale releasing year is 2005. then no one show that I am getting this pay scale from 2002.
This is my jQuery code:
$('#datepickerFrom1').datetimepicker({
        viewMode: 'years',
        format: 'DD/MM/YYYY'
    });

    $('#datepickerTo1').datetimepicker({
        viewMode: 'years',
        format: 'DD/MM/YYYY',
        useCurrent: false
    });

    $("#datepickerFrom1").on("dp.change", function (e) {
        $('#datepickerTo1').data("DateTimePicker").minDate(e.date);
    });
    $("#datepickerTo1").on("dp.change", function (e) {
        $('#datepickerFrom1').data("DateTimePicker").maxDate(e.date);
    });

This is jQuery for selection on dropdownlistfor item:
$(document).ready(function () {
    //Dropdownlist Selectedchange event
    $("#ddlPayScaleCode").change(function () {
        $.ajax({
            type: 'POST',
            url: '@Url.Action("GetMaxMinDate")',
            dataType: 'json',
            data: { id: $("#ddlPayScaleCode").val() },
            success: function (citys) {
                // states contains the JSON formatted list
                // of states passed from the controller
                $.each(citys, function (i, city) {
                    //$("#ddlPSU").append('<option value="' + city.Value + '">' + city.Text + '</option>');
                    if (i == 0) {
                       $('#datepickerFrom1').datetimepicker({
                                                    minDate: '01 Jan 2015'
                       }).datetimepicker("update");;

                        alert(city.Value + i.toString());

                    }

                });
            },
            error: function (ex) {
                alert('Failed to retrieve states.' + ex);
            }
        });
        return false;
    })
});

This is design code:

                  Add Experience(s):

                    @Html.LabelFor(model => model.DesignationAndPlaceOfPosting)

                     @Html.TextBoxFor(model => model.DesignationAndPlaceOfPosting, new { @class = "form-control" })

                    @Html.ValidationMessageFor(model => model.DesignationAndPlaceOfPosting)

                    @Html.LabelFor(model => model.NameOfOrganization)

                   @Html.TextBoxFor(model => model.NameOfOrganization, new { @class = "form-control" })

                     @Html.ValidationMessageFor(model => model.NameOfOrganization)

                  @Html.LabelFor(model => model.PayScaleCode)

                    @Html.DropDownListFor(model => model.PayScaleCode, ViewBag.PayScaleCode1 as IEnumerable<SelectListItem>, "select", new { id = "ddlPayScaleCode", @class = "form-control" })

                    @Html.ValidationMessageFor(model => model.PayScaleCode)

                   Period  @Html.LabelFor(model => model.PeriodFrom1)

                     @Html.TextBoxFor(model => model.PeriodFrom1, "{0:dd/MM/yyyy}", new { @class = "form-control datepickerFrom1", id = "datepickerFrom1", placeholder = "DD/MM/YYYY" })

                    @Html.ValidationMessageFor(model => model.PeriodFrom1)

                   Period    @Html.LabelFor(model => model.PeriodTo)

                    @Html.TextBoxFor(model => model.PeriodTo1, "{0:dd/MM/yyyy}", new { @class = "form-control datepickerTo1", id = "datepickerTo1", placeholder = "DD/MM/YYYY" })
                    <input type="text" id="txtMindate" value="01 January 2016" />
                    <input type="text" id="txtMaxDate" value="01 December 2016" />

                    @Html.ValidationMessageFor(model => model.PeriodTo1)

                 Reporting to Designation

                     @Html.TextBoxFor(model => model.ReportingToDesignation, new { @class = "form-control" })

                    @Html.ValidationMessageFor(model => model.ReportingToDesignation)

                 Self Declaration
Whether meets the mandatory requirement

                    @Html.DropDownListFor(model => model.SelfDeclarationExpCode, ViewBag.VwSelfDeclarationExp as IEnumerable<SelectListItem>, "select", new { id = "ddlSelfDeclarationExpCode", @class = "form-control" })

                    @Html.ValidationMessageFor(model => model.SelfDeclarationExpCode)

                 If yes, nature of duties in support of the declaration
 (in not more than 250 characters)

                     @Html.TextAreaFor(model => model.RelevantExperienceDetails, new { id = "txtbxRelevantExperienceDetails", @class = "form-control", style = "height:65px;" })

                    @Html.ValidationMessageFor(model => model.RelevantExperienceDetails)

                     @* <input type='button' id='button111' class='removebtn' />*@
                        @*<input type="button" id="txt" value="Add More" style="width: 150px; font-family:Verdana"
                               class="btn btn-md btn-success fa fa-lg" />*@
                        <input type="submit" id="btnExperience" value="Save Experience" style="width: 150px; font-family:Verdana"
                               class="btn btn-md btn-success fa fa-lg" />

A: You will want to look at https://jqueryui.com/datepicker/#min-max.
You can do something like this:
$( "#datepickerTo1" ).datepicker({ minDate: -20, maxDate: "+1M +10D" });

Or edit this code:
$('#datepickerTo1').datetimepicker({
    viewMode: 'years',
    format: 'DD/MM/YYYY',
    useCurrent: false,
    minDate: -20,
    maxDate: "+1M +10D"
});

To refine this answer, you will need to give more information on your restrictions.


text:
Q: Short story where a researcher pursues evidence that a small farm has a breeding stock of dodos I read this about 3-4 years ago, I think, in the 2015-2018 timeframe, as the first story in a collection, in English. I don't remember what the other stories were about. I forget exactly how the researcher comes to this information, maybe through an old photograph where he spots the dodo in the background, long after when they were considered extinct, but there's a farm which has a flock of "ugly chickens" which apparently were the result of an ancestor receiving a few dodos that they've been breeding. By the time he gets the evidence, I think that group of dodos are all dead, although he finds their bones, which prove that they survived for some time. I think he does locate one last living dodo (I think it might have been with a spinster, who was difficult to track down because she'd changed her name), but of course, it's not enough to actually save the bird. Nonetheless, he feels satisfied for having chased this dodo down this far.
He might have been a journalist rather than a researcher. I have vague memories of him wiring for money to continue his pursuit, with the prize being either the proof of the dodo's survival for research, or for a news story. I think there was also a bit of narrative going on with the family with the dodos seeing them as a sign of their misfortune, maybe resulting in their demise when they're poisoned or otherwise killed to get the figurative albatross off their necks.

A: And... found it. "The Ugly Chickens" by Howard Waldrop

I was idly leafing through Greenway's Extinct and Vanishing Birds of the World. The city bus was winding its way through the ritzy neighborhoods of Austin, stopping to let off the chicanas, black women, and Vietnamese who tended the kitchens and gardens of the rich.
"I haven't seen any of those ugly chickens in a long time," said a voice close by.

...

"I used to live near some folks who raised them when I was a girl," she said. She pointed.
I looked down at the page my book was open to.
What I should have said was: "That is quite impossible, madam. This is a drawing of an extinct bird of the island of Mauritius. It is perhaps the most famous dead bird in the world. Maybe you are mistaking this drawing for that of some rare Asiatic turkey, peafowl, or pheasant. I am sorry, but you are mistaken."

And indeed, he was too late.

And five huge birds—twice as big as turkeys, legs capped like for Thanksgiving, drumsticks the size of Schwarzenegger's biceps, whole-roasted, lying on their backs on platters large as cocktail tables.
The people in the crowd sure look hungry.
"We ate for days," said Alma.
· · · · ·
I already have the title for the Scientific American article. It's going to be called "The Dodo Is Still Dead."

A: FuzzyBoots definitely has answered his own question; but for the sake of partial matches to the question of extinct bird populations being found, I can think of two other stories that are partial matches to this:

*

*Robert W Chambers' short story "Harbor Master", subsequently turned, with other, stories into the novel "In Search of the Unknown". Read it here on Project Gutenberg. In this story a breeding pair of Great Awk  is captured by a person living at a remote site, who then sends a letter about the birds to the Bronx Zoo (New York) who send someone out to collect them. The birds escape capture under the influence of a mysterious creature called the "Harbor Master" which attacks the protagonists. The story has a bit of a "Lovecraftian" feel to it.

*Gerald Durrell's "The Mockery Bird". In this humorous story an island nation is gaining independence and transitioning to self-governance. The native peoples are divided into two groups, one of which worship an extinct bird. To assist the governance transition process, the main protagonist arrives on the island to find that the islanders plan to build some infrastructure, including a large hydro-electric dam in a remote valley. The protagonist visits the largely unexplored valley and discovers a population of the "extinct" bird, which, as it turns out is intimately connected to the life-cycle of the islands main export crop. The story is loosely based on the re-discovery of Takahē in New Zealand, including the colouration of the bird and some of its behaviours.


text:
Q: prevent search button from clearing search bar text After clicking "search" on the keyboard, the search bar text clears.  Is there a way to keep the text in the search bar? Why would it disappear?
Note:  I'm using the search display controller to activate and deactive the search

A: I found this from a somewhat related question... but the following code should keep the search term visible when the user clicks the search button.
-(void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
    NSString *str = searchBar.text;
    [self.searchController setActive:NO animated:YES];
    self.searchController.searchBar.text = str;
}


text:
Q: Is it possible to edit Babel transpiled files in Chrome devtools workspace? Dragging a local folder of files into the devtools adds them to the workspace so that you can persistently edit them. I just discovered the feature. However my files are all Babel transpiled and then I edit a file and hit cmd-s to save the changes Chrome checks the source and trips over es6 import statements with the error: Unexpected token import
Is there a way to make chrome not check the syntax? If it just edited the file without trying to compile it, Babel could pick it up and inject the changes via hot module replacement probably.

A: I recently watched this presentation named "Debugging the Web" on the new Chrome devtools. At around 15mins he talks about this subject.
Before you could make it work with proper configuration. With this update it should work out of the box!


text:
Q: Help needed with the most trivial protobuf-net example Observe the following trivial piece of code:
  [ProtoContract]
  public class B
  {
    [ProtoMember(1)] public int Y;
  }

  [ProtoContract]
  public class C
  {
    [ProtoMember(1)] public int Y;
  }

  class Program
  {
    static void Main()
    {
      var b = new B { Y = 2 };
      var c = new C { Y = 4 };
      using (var ms = new MemoryStream())
      {
        Serializer.Serialize(ms, b);
        Serializer.Serialize(ms, c);
        ms.Position = 0;
        var b2 = Serializer.Deserialize<B>(ms);
        Debug.Assert(b.Y == b2.Y);
        var c2 = Serializer.Deserialize<C>(ms);
        Debug.Assert(c.Y == c2.Y);
      }
    }
  }

The first assertion fails!
Each Serialize statement advances the stream position by 2, so in the end ms.Position is 4. However, after the first Deserialize statement, the position is set to 4, rather than 2! In fact, b2.Y equals 4, which should be the value of c2.Y!
There is something absolutely basic, that I am missing here. I am using protobuf-net v2 r383.
Thanks.
EDIT
It must be something really stupid, because it does not work in v1 either.

A: You have to use the SerializeWithLengthPrefix/ DeserializeWithLengthPrefix methods in order to retrieve a single object from you stream. this should be working:
var b = new B { Y = 2 };
var c = new C { Y = 4 };
using (var ms = new MemoryStream())
{
    Serializer.SerializeWithLengthPrefix(ms, b,PrefixStyle.Fixed32);
    Serializer.SerializeWithLengthPrefix(ms, c, PrefixStyle.Fixed32);
    ms.Position = 0;
    var b2 = Serializer.DeserializeWithLengthPrefix<B>(ms,PrefixStyle.Fixed32);
    Debug.Assert(b.Y == b2.Y);
    var c2 = Serializer.DeserializeWithLengthPrefix<C>(ms, PrefixStyle.Fixed32);
    Debug.Assert(c.Y == c2.Y);
}


text:
Q: c# create a virtual port using VSPE I'm trying to create a virtual port using a VSPE api .
I try to run the demo code , I get no errors - but it doesn't create me the port .
any idea why?
this is the api guide :
http://grzelewski.net/docs/VSPE/CCOMinterface.html
and this is the code :
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using VSPELib;

namespace VSPE_API_Test
{
    public partial class Form1 : Form
    {
        private VSPEApiClass vspe;

        public Form1()
        {
            InitializeComponent();
            vspe = new VSPEApiClass();
            int result;
            string activationKey = "SRBGMZSYPuIHWILsmLjF5CDyBL3GQYD0IPIEvcZBgPQg8gS9xkGA9CDyBL3GQYD0IPIEvcZBgPQg8gS9xkGA9CDyBL3GQYD0IPIEvcZBgPQg8gS9xkGA9CDyBL3GQYD0IPIEvcZBgPQg8gS9xkGA9CDyBL3GQYD0IPIEvcZBgPRJEEYxlJg + 4gdYguyYuMXkIPIEvcZBgPQg8gS9xkGA9CDyBL3GQYD0IPIEvcZBgPQg8gS9xkGA9CDyBL3GQYD0IPIEvcZBgPQg8gS9xkGA9CDyBL3GQYD0IPIEvcZBgPQg8gS9xkGA9CDyBL3GQYD0IPIEvcZBgPQg8gS9xkGA9JyUaC2ZWE1DZV2 + wYWlRm7FFYrW3MDbZg8MkQsOQ8r1IPIEvcZBgPQg8gS9xkGA9LzrhjimHDiMlKqr6pSiw9CDl9n + 0bAgFr2ho7nXjCoTMHYzt4tsbEkJGNktLGVG42SZ63UbmIUNcKmfhSzXldVCLhfvZv3StR9c / vkYG471Nh62eC1qIYuBUvm + a3BK8iR0POD8w5ovtuYr0T8aQP3eh4b8lUwnPHG9NRJxerttq / +/ zX7c++9LDSQym3ThbWesK + A + X / vNw9qDgYt1dsJxDEEytsCRiT7bTiV5Djh1RlpIwETXWA089hiE9OYd7GpjKLq5dQOqSVcA3Fg1Wfdbqn / yn8q0 / AIDOd0iZlbVeLY68zKh1Di4gGEoa1kR8EOBp2mxeaFrfwUm3DsJ5Pc04f7aEw9XljfBUwl / bAs3LVH5HRii8lXZvUVvnnfpcQ == 1F250CF0960AE1C09E9450C816DE1232"; // <-----  PUT ACTIVATION KEY HERE
                                       // display VSPE API info
            label1.Text = vspe.vspe_getVersionInformation();
            // activate VSPE API
            result = vspe.vspe_activate(activationKey);
            // initialize API
            result = vspe.vspe_initialize();

            label2.Text = "Done!";
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private void Info_Click_Click(object sender, EventArgs e)
        {
            // get devices count
            int count = vspe.vspe_getDevicesCount();
            string result = "Devices count: " + count.ToString() + "\n";
            // enumerate devices
            for (int i = 0; i < count; ++i)
            {
                // get device ID
                int deviceId = vspe.vspe_getDeviceIdByIdx(i);
                string name, initString;
                int ok, used;
                vspe.vspe_getDeviceInfo(deviceId, out name, out initString, out ok, out used);
                result += name + " (" + initString + ") OK=" + ok.ToString() + "\n";
            }
            MessageBox.Show(result);

        }

        private void CreateDevice_Click(object sender, EventArgs e)
        {
            int result;
            // Stop emulation
            result = vspe.vspe_stopEmulation();
            // Deatroy all devices
            result = vspe.vspe_destroyAllDevices();
            // Add Connector (COM9, no baud rate emulation)
            result = vspe.vspe_createDevice("Connector", "9;0");
            // Start emulation
            result = vspe.vspe_startEmulation();
        }
    }
}

when I run the "Info" button - I get
Devices count: 0

*

*if you have another why to create a virtual port - I will be glad to hear and do it

Thanks ,


text:
Q: Foreach, Object reference not set as an instance of an object c# I wanted to create all individual food objects, which has be picked up by the player but somehow I keep getting the error; object reference not set as an instance of an object.
int indexFood;

public Sprite(Graphics paper)
{
    while (indexFood < 50)
    {
        foodArray[indexFood] = new Food();
        indexFood++;
    }
}

public void DrawFood(Graphics drawArea)
{
    foreach (Food food in foodArray)
    {
        food.DrawFood(drawArea);
        food.XPos = 8;
        food.XPos += 32;
    }
}

This is the foodClass method code:
public void DrawFood(Graphics drawArea)
{
    drawArea.FillEllipse(new SolidBrush(Color.Yellow), xPosFood, yPosFood, size, size);
}


text:
Q: Use Enum for user role I have this Entity for users and roles:
@Entity
@Table(name="test")
public class Test implements Serialazable {
    ....
    @Column(length = 25)
    private String role;
    .....
}

I want to use this Enum to hold the available types:
public enum Role implements GrantedAuthority {
  ROLE_ADMIN, ROLE_CLIENT;

  public String getAuthority() {
    return name();
  }

}

The questions is how I can use this Enum to insert the selected current role and also to get the value from the database and populate the Enum.
Cna you guide me how to implement this because it's not very clear for me?

A: I give you an example, you need:

*

*create a enum class

*create a converter:
@Converter(autoApply = true)
public class RoleConverter implements AttributeConverter<Role, String> {

    @Override
    public String convertToDatabaseColumn(Role role) {
        return role.getRoleName();
    }

    @Override
    public Role convertToEntityAttribute(String dbData) {
        return Role.getFromShortName(dbData);
    }
}

The persistence provider will do the rest.

A: The most common option to map an enum value to and from its database representation in JPA is to use the @Enumerated annotation. This way, we can instruct a JPA provider to convert an enum to its ordinal or String value.
This post can help you.
https://www.baeldung.com/jpa-persisting-enums-in-jpa


text:
Q: How would I optimize a nested for loop with linq How would i write this with linq?
foreach (var to in allCurrentTradeObjects)
{
    foreach (var ro in theseWantMe)
    {
        if (ro.Type != to.Type
                || ro.MaxRent < to.Rent
                || ro.MinRooms > to.Rooms
                || ro.MinSquareMeters > to.SquareMeters
                || ro.MaxPrice < to.Price
                || ro.MinFloors > to.Floors
                || ro.TradeObjectId == to.TradeObjectId
                || ro.TradeObjectId == myTradeObject.TradeObjectId)
        {
            continue;
        }
        RatingListTriangleModel rlt = new RatingListTriangleModel
        {
            To1Id = myTradeObject.TradeObjectId,
            To2Id = to.TradeObjectId,
            To3Id = ro.TradeObjectId,
            T1OnT2Rating = 0,
            T2OnT3Rating = 0,
            T3OnT1Rating = 0,
            TotalRating = 0
        };

        //_context.RatingListTriangle.Add(rlt);
        this.InsertOrUpdate(rlt);

    }
}
this.Save();

A: var query = from to in allCurrentTradeObjects
            from ro in theseWantMe
            where ro.Type == to.Type &&
                  ro.MaxRent >= to.Rent &&
                  ro.MinRooms <= to.Rooms &&
                  ro.MinSquareMeters <= to.SquareMeters &&
                  ro.MaxPrice >= to.Price &&
                  ro.MinFloors <= to.Floors &&
                  ro.TradeObjectId != to.TradeObjectId &&
                  ro.TradeObjectId != myTradeObject.TradeObjectId
            select new RatingListTriangleModel
            {
                To1Id = myTradeObject.TradeObjectId,
                To2Id = to.TradeObjectId,
                To3Id = ro.TradeObjectId,
                T1OnT2Rating = 0,
                T2OnT3Rating = 0,
                T3OnT1Rating = 0,
                TotalRating = 0
            };

foreach(var rlt in query)
   this.InsertOrUpdate(rlt);

this.Save();

A: Start by converting the skeleton of the nested loops to LINQ:
 var rtls = allCurrentTradeObjects
     .SelectMany(to => theseWantMe.Select(ro => new {to, ro}));

This gives you a list of pairs {to, ro}. Now add filtering by inverting the continue condition:
 var rtls = allCurrentTradeObjects
     .SelectMany(to => theseWantMe.Select(ro => new {to, ro}));
     .Where(p => p.ro.Type == p.to.Typpe && p.ro.MaxRent >= p.to.Rent && ...)

Finally, add a Select to call `new:
 var rtls = allCurrentTradeObjects
     .SelectMany(to => theseWantMe.Select(ro => new {to, ro}));
     .Where(p => p.ro.Type == p.to.Typpe && p.ro.MaxRent >= p.to.Rent && ...)
    .Select(p => new RatingListTriangleModel {
        To1Id = myTradeObject.TradeObjectId,
        To2Id = p.to.TradeObjectId,
        To3Id = p.ro.TradeObjectId,
        ...
    });

With rtls list in hand, you can call InsertOrUpdate in a loop.

A: Following is the method syntax.
allCurrentTradeObjects.Select (
            to => to.theseWantMe.Where ( ro => !(ro.Type != to.Type
                || ro.MaxRent < to.Rent
                || ro.MinRooms > to.Rooms
                || ro.MinSquareMeters > to.SquareMeters
                || ro.MaxPrice < to.Price
                || ro.MinFloors > to.Floors
                || ro.TradeObjectId == to.TradeObjectId
                || ro.TradeObjectId == myTradeObject.TradeObjectId))
               .Select({
                             var rlt =  new RatingListTriangleModel
                              {
                                 To1Id = myTradeObject.TradeObjectId,
                                 To2Id = to.TradeObjectId,
                                 To3Id = ro.TradeObjectId,
                                 T1OnT2Rating = 0,
                                 T2OnT3Rating = 0,
                                 T3OnT1Rating = 0,
                                TotalRating = 0
                            };
                           this.InsertOrUpdate(rlt);
                           return rlt;
                         } ).ToArray();
 this.Save();

A: There are many answers here advocating SelectMany (or double from).  These are "optimize for readability" answers in that they do not change the N*M nested loop performance of this operation.
You shouldn't use that approach if both collections are large.  Instead, you should take advantage of the well defined relationship between your two collections, and the hashing in Enumerable.Join to reduce the operation to N+M.
var myTradeObject = GetThatOneObject();

IEnumerable<RatingListTriangleModel> query =
  from to in allCurrentTradeObjects
 //pre-emptively filter to the interesting objects in the first collection
  where to.TradeObjectId == myTradeObject.TradeObjectId
 //take advantage of hashing in Enumerable.Join - theseWantMe is enumerated once
  join ro in theseWantMe
    on to.Type equals ro.Type
 //remaining matching criteria
  where to.Rent <= ro.MaxRent   //rent is lower than max
    && ro.MinRooms <= to.Rooms   //rooms are higher than min
    && ro.MinSquareMeters <= to.SquareMeters  //area is higher than min
    && to.Price <= ro.MaxPrice     //price is lower than max
    && ro.MinFloors <= to.Floors   // floors are higher than min
    && to.TradeObjectId != ro.TradeObjectId //not same trade object
  select CreateRatingListTriangleModel(myTradeObject, to, ro);

foreach(RatingListTriangleModel row in query)
{
  this.InsertOrUpdate(row);
}
this.Save();

A: To increase readability I would start by refactoring the complicated condition and move it to a neat little function (It can also be a method of the object)
private bool IsMatchingTradeObject (TradeObject to, SomeOtherObject ro, int TradeObjectId)
{
  return ro.Type == to.Type &&
                  ro.MaxRent >= to.Rent &&
                  ro.MinRooms <= to.Rooms &&
                  ro.MinSquareMeters <= to.SquareMeters &&
                  ro.MaxPrice >= to.Price &&
                  ro.MinFloors <= to.Floors &&
                  ro.TradeObjectId != to.TradeObjectId &&
                  ro.TradeObjectId != TradeObjectId;
}

Second I would do the same with the creation and initialization of the RatingListTriangleModel, i.e. move it to a small method and give it a meaningful name.
private RatingListTriangleModel CreateModel(TradeObject to, SomeOtherObject ro, int TradeObjectId)
{
  return new RatingListTriangleModel
    {
        To1Id = myTradeObject.TradeObjectId,
        To2Id = to.TradeObjectId,
        To3Id = ro.TradeObjectId,
        T1OnT2Rating = 0,
        T2OnT3Rating = 0,
        T3OnT1Rating = 0,
        TotalRating = 0
    };

The remaining code is much easier to read
   foreach (var to in allCurrentTradeObjects)
     foreach (var ro in theseWantMe)
       if (IsMatchingTradeObject(to, ro, myTradeObject.TradeObjectId))
         this.InsertOrUpdate(CreateModel(to, ro, myTradeObject.TradeObjectId));

this.Save();

Converting this to LINQ is easy:
allCurrentTradeObjects.Select (
  to => to.Where (
    ro => IsMatchingTradeObject (to, ro, myTradeObject.TradeObjectId)
    )
  ).Select(
     {
       this.InsertOrUpdate(CreateModel(to, ro, myTradeObject.TradeObjectId));
       return null;
     }
  );
 this.Save();

However, the foreach-loops seem easier to read.


text:
Q: How do i implement callback/await to my code? So, I have been working on this code for the past few days and tried to implement callback/await/whatever is needed to no avail.
The question is, how do i wait with response until i get lets say a callback from both functions? (and how would i implement that)
In short what I want to do is:

*

*POST happens, getpTracks()

*From getpTracks() we go on to dbChecks() for each track we got

*Check from db if track is found, if it is push to final array.

*If not, go to scrapeUrl()

*After both functions are done running, response to POST with final array.

I've band-aided the code with some funky code checking every 250ms if the amount of tracks requested matches the amount of tracks in final array. But that isn't really what i'm looking for since if theres more than one POST request at a time it gets really broken.
Current code:
app.post("/spotify/playlist", (req, res) => {
  pTracks = [];
  let playlistId = req.body.id;
  t0 = performance.now();
  getpTracks(playlistId);
  let waitTime = setInterval(waitTillReady, 250);
  function waitTillReady() {
    counterLoop++;
    console.log("a: " + countera + "||" + pTracks.length);
    console.log("b: " + counterb + "||" + pTracks.length);
    console.log("a + b: " + (countera + counterb) + "||" + pTracks.length);
    console.log("Loop: " + counterLoop);
    // REPLACE WITH ASYNC OR CALLBACK!!
    if (
      countera == pTracks.length ||
      counterb == pTracks.length ||
      countera + counterb == pTracks.length ||
      counterLoop == 35 // 75 items scraping took on avg 4.8sec
    ) {
      countera = 0;
      counterb = 0;
      clearInterval(waitTime);
      res.send(pTracks);
      t1 = performance.now();
      console.log("Call took " + (t1 - t0) + " milliseconds.");
      pTracks = [];
    }
  }
});

function getpTracks(args) {
  spotifyApi.getPlaylistTracks(args, { limit: 75 }).then(function(data) {
    let temp = data.body.items;
    for (let b = 0; b < temp.length; b++) {
      let trackName = temp[b].track.name;
      for (let e = 0; e < temp[b].track.artists.length; e++) {
        var trackArtist = temp[b].track.artists[e].name;
      }
      dbChecks(trackName, trackArtist);
      //let trackId = temp[b].track.id + ",";
      //spotifyApi.getAudioFeaturesForTracks([trackId]).then(function(data) { // bpm, key etc
    }
  });
}

function dbChecks(trackName, trackArtist) {
  url = "https://www.songsterr.com/a/wa/bestMatchForQueryString?s=";
  //console.log(trackArtist + '|||' + trackName);
  //console.log(url)
  dbSongsterr
    .findOne({ artist: trackArtist, track: trackName }) // get results from mongo
    .then(response => {
      if (
        //if we find results,
        response != null &&
        response.artist == trackArtist &&
        response.track == trackName
      ) {
        countera++;
        pTracks.push({
          //push them into array
          artist: response.artist,
          name: response.track,
          url: response.url,
          tuning: response.tuning
        });
      } else if (response == null) {
        //if no results found, go webscrape
        urli = url + trackName + "&a=" + trackArtist; // url constructor
        pTracks.push({
          artist: trackArtist,
          name: trackName,
          url: urli
        });
        scrapeUrl(urli, trackName, trackArtist);
      }
    })
    .catch(error => {
      console.log("Error: " + error);
    });
}

function scrapeUrl(url, track, artist) {
  url = url;
  console.log(artist + "|||" + track);
  rp({
    url: url,
    resolveWithFullResponse: true,
    transform: function(body) {
      return cheerio.load(body);
    }
  })
    .then(async res => {
      counterb++;
      tempartist = artist.replace(/\s+/g, "");
      artistSongsterr = await res(".artist-1u304B") // tab page artist name
        .text()
        .replace(/\s+/g, "");
      //console.log(artistSongsterr);
      if (
        artistSongsterr != "" &&
        artistSongsterr.toLowerCase() == tempartist.toLowerCase()
      ) {
        // maybe add check for song aswell
        tuning = res(".tuning-1cQdvc").text(); // tab page tuning
        //console.log(tuning);
        if (tuning != "") {
          for (let y = 0; y < pTracks.length; y++) {
            if (pTracks[y].name == track && pTracks[y].tuning == null) {
              pTracks[y] = { ...pTracks[y], ...{ tuning: tuning } };
              dbSongsterr.insert({
                artist: artist,
                track: track,
                url: url,
                tuning: tuning
              });
            }
          }
        }
      } else {
        dbSongsterr.insert({
          // if didnt pass artist name check then
          artist: artist,
          track: track,
          url: false,
          tuning: false
        });
        //console.log('Artist check fail')
      }
    })
    .catch(err => {
      counterb++;
      console.log("Site crawl fail");
      pTracks.push({
        artist: track,
        name: track,
        url: false,
        tuning: false
      });
      dbSongsterr.insert({
        artist: artist,
        track: track,
        url: false,
        tuning: false
      });
    });
}

A: A few general advices:

*

*You usually never need globals (so declare them properly), functions should return the results they produce, if variables should beshared between multiple functions pass them explicitly.

*Don't mix .then chains with awaits, it looks ugly, is confusing and might introduce subtle bugs.
That said your functions should be async:
async function scrapeUrl(url, track, artist, result = []) {
  console.log(artist + "|||" + track);

  try {

   const res = await rp({
    url,
    resolveWithFullResponse: true,
    transform: function(body) {
      return cheerio.load(body);
    },
   });

   const tempartist = artist.replace(/\s+/g, "");
   const artistSongsterr = await res(".artist-1u304B") // tab page artist name
          .text()
          .replace(/\s+/g, "");

      if (artistSongsterr  && artistSongsterr.toLowerCase() == tempartist.toLowerCase()) {
        // maybe add check for song aswell
        const tuning = res(".tuning-1cQdvc").text(); // tab page tuning

        if (tuning) {
          for (const el of pTracks) {
            if (el.name == track && !el.tuning) {
              el.tuning = tuning;

              result.push({ url, track, artist, tuning });
            }
          }
        }
      } else {
        result.push({
          // if didnt pass artist name check then
          artist,
          track,
          url: false,
          tuning: false
        });
        //console.log('Artist check fail')
      }
    }
   } catch(error) {
      console.log("Site crawl fail");
      result.push({
        artist: track,
        name: track,
        url: false,
        tuning: false
      });

   }

   return result;
}

async function dbChecks(trackName, trackArtist, result = []) {
  const url = "https://www.songsterr.com/a/wa/bestMatchForQueryString?s=";

  try {
    const response = await dbSongsterr
      .findOne({ artist: trackArtist, track: trackName }) // get results from mongo

    if (
      //if we find results,
      response &&
      response.artist == trackArtist &&
      response.track == trackName
    ) {

      result.push({
        //push them into array
        artist: response.artist,
        name: response.track,
        url: response.url,
        tuning: response.tuning
      });
  } else {
    //if no results found, go webscrape
    const urli = url + trackName + "&a=" + trackArtist; // url constructor
    result.push({
      artist: trackArtist,
      name: trackName,
      url: urli
    });
    await scrapeUrl(urli, trackName, trackArtist, result);
  }
 } catch(error) {
  console.log("Error: " + error);
 }

 return result;
}

async function getpTracks(args) {
  const result = [];

  const data = await spotifyApi.getPlaylistTracks(args, { limit: 75 });
  let temp = data.body.items;

  for (const { track: { name: trackName, artists  }} of  temp) {

    const trackArtist = artists[artists.length - 1].name;
    // TODO: use Promise.all to parallelize
    await dbChecks(trackName, trackArtist, result);

  }

  return result;
}

That can be used in the endpoint as:
app.post("/spotify/playlist", async (req, res) => {
  res.send(await getpTracks(req.body.id));
});


text:
Q: Table with multicolumn highlighted row I'm trying to make the following table:

I can create the structure easily. However I have a problem in the row colour:
\newcolumntype{L}[1]{>{\raggedright\let\newline\\\arraybackslash\hspace{0pt}}m{#1}} % table type

\begin{table}[H]
\caption{Summary}
\label{tab:Summary}
\makebox[\textwidth]{ %to center the table if exceed page width
    \begin{tabular}{L{1cm} L{4cm}  L{4cm}  L{4cm}}
        %Title
        \hline \rowcolor{black}
        \multicolumn{4}{L{13cm}}{\textcolor{white}{Title goes here}} \TBstrut \\
        \hline \rowcolor{black}
        %
        \textcolor{white}{id}           &
        \textcolor{white}{Description}  &
        \textcolor{white}{Formula}      &
        \textcolor{white}{Notes} \TBstrut \\ \hline
        %
        text & text  & $equation$  & Text \TBstrut \\ \hline
\end{tabular}}
\end{table}

I get the following:

I also tried replacing it with the following but I get the same result
\multicolumn{4}{L{13cm}}{\cellcolor{black}\textcolor{white}{Title goes here}} \TBstrut \\

I assume that this is due the missing margins (left/right) from the border for each cell. Any idea how to fix?
Note that the cell type is from: How to create fixed width table columns with text raggedright/centered/raggedleft?

A:
\documentclass{article}
\usepackage[table]{xcolor}

\begin{document}

\begin{table}
\caption{Summary}
\label{tab:Summary}
    \begin{tabular}{m{1cm} m{4cm}  m{4cm}  m{4cm}}
        %Title
        \hline \rowcolor{black}
        \multicolumn{4}{c}{\textcolor{white}{Title goes here}}  \\
        \hline \rowcolor{black}
        %
        \textcolor{white}{id}           &
        \textcolor{white}{Description}  &
        \textcolor{white}{Formula}      &
        \textcolor{white}{Notes}  \\ \hline
        %
        text & text  & $equation$  & Text  \\ \hline
\end{tabular}
\end{table}
\end{document}


text:
Q: WCF Rest Method with abstract request type - Error: Cannot create an abstract class In short, I have exposed a REST-ful endpoint for my WCF service like so:
<endpoint address="Rest" binding="webHttpBinding" behaviorConfiguration="web" contract="ServicesLayer.ServiceContract.IService" name="service-web" />

And I've added the WebInvoke attribute to all methods on the service interface like so:
[WebInvoke]
[OperationContract]
Response GetStuff(RequestBase Request);

Everything works fine for methods which have a request type that is concrete. But for any method with an abstract request type such as the one above in which RequestBase is abstract, the following error is returned: Cannot create an abstract class.
How do I force this method to interpret the request as one of RequestBase's derived types when calling this RESTfully?
Note: I did try to remove 'abstract' keyword from the RequestBase class, yet it still gets interpreted as a RequestBase rather than one of its derived classes, so that didn't solve any issues really.
Thanks in advance.

A: For those wondering how this looks in JSON. In my case, I needed to add the schema string.
This example assumes that you have a BasePersonCriteria which is abstract, and PersonNameCriteria which inherits BasePersonCriteria. I also had an attribute [KnownType(typeof(PersonNameCriteria))] on BasePersonCriteria.
If this is your request and criteria:
[DataContract(Namespace = "http://schemas.stackoverflow.com/core/persons/2018/11/14/criterias")]
public class PersonNameCriteria : BasePersonCriteria
{
    [DataMember]
    public string Name { get; set; }
}

[DataContract(Namespace = "http://schemas.stackoverflow.com/core/persons/2018/11/14/criterias")]
[KnownType(typeof(PersonNameCriteria))]
public abstract class BaseAccountCriteria
{
}

[DataContract(Namespace = "http://schemas.stackoverflow.com/core/persons/2018/11/14/requests")]
public class GetPersonRequest
{
    [DataMember(IsRequired = true)]
    public BasePersonCriteria PersonCriteria { get; set; }
}

This is how the JSON should look:
{
    "PersonCriteria": {
        "__type": "PersonNameCriteria:http://schemas.stackoverflow.com/core/persons/2018/11/14/criterias",
        "Name": "John"
    }
}

A: Turns out I just needed to include the type in the json/xml request being sent. Once I added that it new which type to interpret it as. Thanks


text:
Q: java.lang.NullPointerException - in AddCell method Executing the Code Below : Null Point Exception is Thrown -----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
package eCommerceLive;
import java.io.File;
import jxl.Workbook;
import jxl.write.WritableSheet;
import jxl.write.WritableWorkbook;
import jxl.write.Label;
import jxl.write.WriteException;

public class dataSheet {

static Workbook wbook;
static WritableWorkbook wwbCopy;
static String ExecutedTestCasesSheet;
static WritableSheet shSheet;

public void readExcel()
{
try{
wbook = Workbook.getWorkbook(new File("D:\\Automation\\testSampleData.xls"));
wwbCopy = Workbook.createWorkbook(new File("D:\\Automation\\testSampleDataCopy.xls"), wbook);
shSheet = wwbCopy.getSheet(0);
}
catch(Exception e)
{
    e.printStackTrace();
}
}

public void setValueIntoCell(String strSheetName,int iColumnNumber, int iRowNumber,String strData) throws WriteException
{
    WritableSheet wshTemp = wwbCopy.getSheet(strSheetName);
    Label labTemp = new Label(iColumnNumber, iRowNumber, strData);

    try {
        wshTemp.addCell(labTemp);
         }
        catch (Exception e)
        {

            System.out.println("Hello");
            e.printStackTrace();
        }
}

public void closeFile()
{
    try {
        // Closing the writable work book
        wwbCopy.write();
        wwbCopy.close();

        // Closing the original work book
        wbook.close();
    } catch (Exception e)

    {
        e.printStackTrace();
    }
}

public static void main(String[] args) throws WriteException
{
    dataSheet ds = new dataSheet();
    ds.readExcel();
    System.out.println("Hello");
    ds.setValueIntoCell("sheet1",5,1,"PASS");
    ds.setValueIntoCell("sheet1",5,2,"FAIL");
    ds.setValueIntoCell("sheet1",5,3,"PASS");
    ds.closeFile();
}

}


text:
Q: PHP Change background color, based on correct or incorrect answer So i'm working on a website on which you can teach newcommers some codes we need to know. This is on the site: A table, within a form, where you have to write in the correct code in an input field at certain fruits, vegetables and bread (supermarkt things..).
So like this: Image - Cucumber - fill in code here
At the end, there is a check if you filled in the right code.
But I want the input fields to change color, green if the answer is right and red if the answer is wrong.
This is what i got:
Index.html:
//Above here is the table
<?php
    if(isset($_POST['komkommer'])){

        /* Include PHP scripts first */
        include_once 'phpscripts/plu.php';
        include_once 'phpscripts/groentestore.php';
        include_once 'phpscripts/functions.php';

        /* Call the check functions */
        groenteCheck();
    }
    else {

    }
?>

A part of the form with the table (in index.php, loaded from an external php file):

    Komkommer
    <input type="text" autocomplete="off" name="komkommer" placeholder="...">

    Rode kool
    <input type="text" autocomplete="off" name="rodekool" placeholder="...">

And a part of the groenteCheck() in functions.php
if($komkommer != $plu_komkommer){
        echo '
Komkommer was niet juist! Jij voerde '.$komkommer.' in!
';
    }
    if($rodekool != $plu_rodekool){
        echo '
Rode kool was niet juist! Jij voerde '.$rodekool.' in!
';
    }

I tried to:
1. Make a PHP variable in index.html called $komkommerCheck and set that to "standard". In the table added this: class=<?php echo '"'.$komkommerCheck.'"';?>>. Then, in the if else statement, i set: $komkommerCheck = "correct" or $komkommerCheck = "wrong" ('wrong' and 'correct' are 2 classes, that makes the background color either red or green). But as soon as the check is done, the message "'
Komkommer was niet juist! Jij voerde '.$komkommer.' in!
';" appears, but the class doesnt get changed in index.php
I'm sorry if this is a bit unclear, but help is very appriciated!
Thank you :)

A: If you want to change the input color with PHP that is obviously only going to happen server side, meaning after you submit the form.  If you want to check to see if the input is correct as they type it, then you will need to be using JavaScript for this.  Here is an example for you, up vote please since I'm coding this for you.
http://jsfiddle.net/qhdsk784/1/
JS HERE
$( document ).ready(function() {
    $( "#carr" ).keyup(function() {
    var get_value = $("#carr").val();

            if(get_value == "stephen"){
        $("#carr").addClass('green');
    }
});
    });

HTML HERE

Enter stephen into the input to see change.

 <input type="text" name="carr" id="carr"value="">

CSS HERE
input{
    color:#fff;
    font-weight:bold;
    padding:7px;
    font-size:16px;
    background-color:#FA0000;
}
input.green{
    background-color:#479E00;
    color:#fff;
    font-weight:bold;
}


text:
Q: Should switching users switch TTY as well? In trying to troubleshoot user switching hangs and irregularity's I noticed if I log in as user A then switch to user B, and then press,  (TTY7) will take me directly back to the unlock prompt for user A.  (TTY8) will bring me to user B's X session. Adding user C to the mix adds  (TTY9).
Is this how user switching is suppose to work or is something not configured properly on my system? Aren't there only supposed to be 7 TTY sessions configured? I think this is the cause of my user switching issues.

A: Fast user switching opens another X server on the next available VT. There are at least 24 available VTs on a Linux system.


text:
Q: android problem to get latitude & longitude from a given address I am trying find lat & long from user given address, for that i am using following code,
GeoPoint pointForEnterAddr;

try {

    List<Address> address = coder.getFromLocationName(enterAddr, 1);

                    if (address == null)

                     pointForEnterAddr = null;

                    else {
                        Address location = address.get(0);
                        System.out.println("Lat in button click :"
                                + location.getLatitude());
                        System.out.println("Long in button click :"
                                + location.getLongitude());

pointForEnterAddr = new GeoPoint((int) (location.getLatitude() * 1E6),
                    (int) (location.getLongitude() * 1E6));

}
 catch (Exception ex) {
                    System.out.println("Error here :" + ex);
                }

But everytime it coming to catch part & shows exception,
java.io.IOException: Service not Available
How can i solve it and get proper output? Plz tell me.
Thank you

A: I found this for your questions, I think it is the bug of emulator. Look at this answer
Android; Geocoder, why do I get "the service is not available"?

A: Just to mention an alternative, you can use the Google Maps' REST based reverse geocoder. You can probably use this as a fallback. As you would be using Google Maps in your app too, you should be good with the API rules.


text:
Q: How to position jQuery slideshow inside png I am trying to put a simple jQuery slideshow inside of a png mockup of a phone for a simple website for our app. I am using bootstrap and have a jumbotron split into two columns. I would like the left side to have the mockup phone with fading screenshots and the right side to have a logo and description. I am using this slideshow.
Here is the js fiddle.
Here is what I have for html

√oots

This is some shit about the game.

and here is the css
.jumbotron {
    height: 600px;
}

.container {
    padding-top: 65px;
}

.fadein {
    position:relative;
    width:500px;
    height:332px;
}

.fadein img {
    position:absolute;
    left:0;
    top:0;
}

I have searched and searched and all I can tell is that something needs to be done about absolute vs. relative with the css. I also wanted this site to utilize Bootstrap's responsive features, but I can see that I will need to do something special to make that slideshow do that. Maybe everything I used was ridiculous and you know a better way to do this?

A: Here is a clean solution that will be easier to handle in case you decide to change your layout in the future. This is easier because you will just have to move the container of the phone, which will move the screen contents inside it as well, without having to re-position everything else. I mainly just made your phone class a container for the slide show, and made the phone mockup the BG of the phone class instead of using an img tag. Then I added a negative z-index value to get the screen content fitting nicely into the phone.
(You may want to consider getting the images the same size as the mockup's screen, therefore not cutting anything).
http://jsfiddle.net/h82ukey4/
**CSS**

    @import url('http://twitter.github.com/bootstrap/assets/css/bootstrap.css');
 .jumbotron {
    height: 600px;
}
.container {
    padding-top: 65px;
}
.fadein {
    position:relative;
    width:311px;
    height:480px;
    top: 40px;
    z-index: -1; /* Important. */
}
.fadein img {
    position: absolute;
    margin-left: auto;
    margin-right: auto;
    left: 0;
    right: 0;
    opacity: 0.5;
}
.phone {
    width: 311px;
    height: 573px;
    background-image: url('http://www.smoothsand.com/gradeply/images/mockup%20galaxy%20nexus.png'); /* Important. */
}

This should work, check the fiddle.
Hope this helps.

A: You just need to change the offset of your slideshow ( .fadein ) to be the same as your picture ( .phone ), then adjust accordingly to fit it onto the screen:
$('.fadein').offset({
    top: $('.phone').offset().top + 28,
    left: $('.phone').offset().left + 21
});

Here is the fiddle.


text:
Q: Simplest Discrete 3D Model of a Regular 2D Hyperbolic Tiling I only have a beginners level understanding of hyperbolic geometry, and I am afraid that the following question might be too vague, but here goes.
I know one can make real 3D models of regular tilings that should exist in 2D hyperbolic space. For example, if one keeps gluing together equilateral triangles so that 7 touch at each vertex then one can get a 3D model of the {3,7} tiling of 2D hyperbolic space. Making the triangles out of paper, and taping them together results in a 3D  model that looks like crinkled paper. Similar 3D models can be made by hyperbolic crochet. My question is, what if all the edges one uses in the hyperbolic tiling have to be rigid, and of the same length, in 3D. Are there any regular 2D hyperbolic tilings which can be embedded in 3D space to form a simple predictable pattern of rigid regular polygons in 3D ? For example, is there a nicely organized layout of equilateral triangles in 3D space corresponding to an embedding of the aforementioned {3,7} tiling.
To elaborate, I am thinking that the tiling of the sphere with triangles, 5 of which meet at a vertex, corresponds to the regular icosahedron (which is a 3D shape, made of regular, rigid polygons). I know the pseudosphere can be considered to be a 3D model of 2D hyperbolic space, and so I am wondering if there is some simple pattern of tiles on a discretized pseudosphere, which corresponds to a regular tiling of 2D hyperbolic space.