text:
Q: How to Copy a blob in azure to another container with node sdk I am trying to copy a blob in one container to another storage account in azure.
I am using @azure/storage-blob 12.0.0 but I cannot figure out how to copy a blob to another container without downloading it.
Maybe someone can help and post a quick example.
Stefan

A: If you want to copy blob with nodejs sdk @azure/storage-blob, you can use the method BlobClient.beginCopyFromURL to implement it. For more details, please refer to the document.
For example(copy blob from one container to another container in same storage account)
const { BlobServiceClient, StorageSharedKeyCredential } = require("@azure/storage-blob");

async function copy(){

    const account = "blobstorage0516";
    const accountKey=""
    const cert = new StorageSharedKeyCredential(account,accountKey)
    const blobServiceClient = new BlobServiceClient(
      `https://${account}.blob.core.windows.net`,
      cert
    );

    const sourceContainer=blobServiceClient.getContainerClient("test")
    const desContainer=blobServiceClient.getContainerClient("copy")
    //if the desContainer does not exist, please run the following code
    await desContainer.create()

    //copy blob
    const sourceBlob=sourceContainer.getBlobClient("emp.txt");
    const desBlob=desContainer.getBlobClient(sourceBlob.name)
    const response =await desBlob.beginCopyFromURL(sourceBlob.url);
    const result = (await response.pollUntilDone())
    console.log(result._response.status)
    console.log(result.copyStatus)
}

copy()


text:
Q: All my routes redirect to home page All my laravel routes keep redirecting back to the home page. For example when I go to localhost:8000/about it stays on the home page, localhost:8000/about shows up in the address bar but I'm still on the home page. I don't get an error. These last three (3) from this list redirect me to the home page:
<?php
//No auth needed to access these

Route::get('/course/detail/{id}', [
    'uses' => 'CourseController@show',
    'as' => 'course.detail'
]);

Route::get('/{pagenum?}', [
    'uses' => 'CourseController@showAll',
    'as' => 'courses'
]);

Route::get('/instructor/detail/{id}', [
    'uses' => 'InstructorController@showDetail',
    'as' => 'instructor.detail'
]);

Route::get('/about', function(){
    return view('frontend.about');
})->name('about');

Route::get('/contacts', function(){
    return view('frontend.contacts');
})->name('contacts');

Route::get('/search', [
    'uses' => 'CourseController@search',
    'as' => 'courses.search'
]);

I have routes above these where you need to be authenticated before accessing and I can access them when logged in. You don't need to be logged in to access those above. From the six (6) I mentioned above I am able to access the first three (3) without being redirected. The other three (3) redirect me to the the home page with no error
I'm not new to Laravel, the routes were working before. What could be the cause of this redirecting?

A: You've issue with sequence of defining the routes.
You've defined:
Route::get('/{pagenum?}', [
    'uses' => 'CourseController@showAll',
    'as' => 'courses'
]);

that acts like /anything-that-comes-here
and other route definitions for prefix / are being prevented by it.
so just move last 3 routes above of it:
Route::get('/about', function(){
    return view('frontend.about');
})->name('about');

Route::get('/contacts', function(){
    return view('frontend.contacts');
})->name('contacts');

Route::get('/search', [
    'uses' => 'CourseController@search',
    'as' => 'courses.search'
]);

Route::get('/{pagenum?}', [
    'uses' => 'CourseController@showAll',
    'as' => 'courses'
]);

A: The second route is the problem you have to place at the end:
Route::get('/{pagenum?}', [
    'uses' => 'CourseController@showAll',
    'as' => 'courses'
]);

redpajama_set_name: RedPajamaStackExchange


text:
Q: Как сделать аналог "бегущей строки" с помощью swiper.js? Проблема в том, что даже при delay: 0 происходит остановка перед сменой слайда. Как ее убрать полностью?

var swiper = new Swiper('#js-carousel', {
  slidesPerView: 3,
  spaceBetween: 30,
  speed: 2000,
  loop: true,
  autoplay: {
    delay: 0,
  },
});
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet" />
<link href="https://cdnjs.cloudflare.com/ajax/libs/Swiper/4.5.0/css/swiper.min.css" rel="stylesheet" />

A: Попробуйте в стилях заменить transition-timing-function на linear:
.swiper-wrapper {
  -webkit-transition-timing-function: linear !important;
          transition-timing-function: linear !important;
}

var swiper = new Swiper('#js-carousel', {
  slidesPerView: 3,
  spaceBetween: 30,
  speed: 2000,
  loop: true,
  //allowTouchMove: false, // можно ещё отключить свайп
  autoplay: {
    delay: 0,
    disableOnInteraction: false // или сделать так, чтобы восстанавливался autoplay после взаимодействия
  }
});
.swiper-wrapper {
  -webkit-transition-timing-function: linear !important;
          transition-timing-function: linear !important;
}

.swiper-slide img{
  max-width: 100%;
}
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet" />
<link href="https://cdnjs.cloudflare.com/ajax/libs/Swiper/4.5.0/css/swiper.min.css" rel="stylesheet" />


text:
Q: Force connect to Bluetooth device I have a Bluetooth speaker in my house. Myself and my partner periodically connect to it using either our phones (2 × Android) or laptops (1 × MacBook and 1 × laptop PC) to play music whilst at home. As far as I know, it's only possible to have a single device connected to a Bluetooth device at any given time.
The problem arises when one of us wants to play music from a device, but we are unable to pair with the speaker because some other device in the house is already paired. There is no way (that I'm aware of) of knowing which device is already connected, or where in the house that device is. The Bluetooth device we're connecting to is a StarTech Bluetooth wireless receiver - a normal speaker actually connects to this receiver. Since this device has no menus of any sort, there's no way to just walk up to the receiver and press a 'disconnect' button. In fact, simply turning-off-and-on-again doesn't work, as the device automatically re-pairs with the last device it was connected to.
There doesn't appear to be an option on any of the devices to 'force pair' with the music receiver device. I totally understand that this would normally be a security concern, but this is a speaker device in our own home, so we'd like to find a way to be able to override this security and allow forcibly disconnecting of any existing paired connections.
Is there any way to achieve this?

A: Actually there is a way to connect to a Bluetooth speaker that can only be connected to one device at a time when it is already connected to another device!
Make sure the Bluetooth speaker is off.
Go to settings, Bluetooth, and find your speaker (There should be a list of Bluetooth devices that you last connected to).
Tap on the Bluetooth speaker to connect, then turn the speaker on AFTER you pressed the connect button, while your device is trying to connect to it.
Your speaker then should connect to your device.
This trick worked for me and wanted to share this tip.

A: Unfortunately you can't force pair it. Unless you buy a new bluetooth speaker that allows multiple connections or comes with a software control panel such as the BlasterAXX. It is understandable that once a connection is established another device should not be able to terminate this connection and force a new one.
Receivers that allow only one connection are doomed to reconnect to the last device connected and the only way to resolve it is to disconnect the other device. I had a number of receivers and bluetooth speakers in the past and I always ran around the house to find the device that is connected to the speaker. If the receiver is not configured by the factory to allow multiple connections then you can't do much. Unless you want to crack open the receiver and start messing around with the chips (which I am sure you wouldn't like to do)
The ones I used had a pairing button, that once I pressed it a new search began and I was able to connect a different device. You should check if there is a similar option.
The logical way to proceed in the future, is to turn off your bluetooth on the device, after you are done, so that the receiver is free for a new connection. Now, if you want to find which device is connected, you can always use your phone to scan for nearby devices and go check every one of them if it is connected to the receiver.
Another way is to configure your devices so that they wouldn't automatically connect to the receiver, but only when you desire to. I am sure that every single device, or computer you are using has the option to connect automatically or not.
I understand this is not what you would like to hear but there is no other way. That's a common problem with devices that don't have a control panel available. If you are not willing to spend some money on a new device then try any of the things I mentioned, and I would suggest to have the receiver free for connections when you are not using it.

A: This is actually possible by spoofing your bluetooth mac then jamming the bluetooth connection. If you are lucky you will be able to connect once you stop the jamming

A: If you connect to the device and then turn your speaker on, that usually works.
But for the times that it doesn't and reset by holding down the Bluetooth button and the power button for 3 to 5 seconds and than you are good to go.

A: I've found that putting the device into pairing mode will allow it to connect to another device. You don't actually need to re-pair it with the host, you can just initiate the connection normally from the host, and it should force a disconnect with the other device.

A: If the device is portable simply walk away (with your device in hand) far enough that the device cannot find the the previous Bluetooth connection, then you will be able to connect your device without restriction. [I was using Xdobo X8 Bluetooth speaker]

A: If you're in this situation and the other device is inaccessible (e.g. in a sleeping person's room) then see if there's a reset function on the speaker.
Sometimes there is a physical reset button - often it's a small hole which accepts a straightened paper clip. Other times one of the main buttons has dual actions, and if it's held longer it could cause the speaker to enter pairing mode. This may not be described in the manual.
Activating this reset should cause the speaker to forget it's previous connection and be available again.
(At least that's the case for my Aukey SK-30, pressing Mode for a few seconds resets the connection).

A: I'm confused by all the other answers saying it can't be done.  On just about every BT device that I've owned (and its been a few!), if the device is switched OFF and you hold down the power button for ~5 seconds, it goes into seeking/pairing mode.  From there you just go through pairing process again on your phone/laptop whatever.
It is a small amount of hassle, but easy.


text:
Q: Run node js server in ubuntu I have tried so far installed node.js and npm via
sudo apt-get install nodejs  and sudo apt-get install npm . Then I tried typing node on bash nothing happens, I tried using node app.js nothing happens to no error

A: From our discussion here
After installing node.js and npm
Create a symbolic link for node:
sudo ln -s /usr/bin/nodejs /usr/bin/node

Now verify commands working with
node -v
npm -v

Run it by using,
node hello.js
In order to test the application, open another terminal session and connect to your web server. Be sure to substitute in the app server's private IP address for APP_PRIVATE_IP_ADDRESS, and the port if you changed it:
curl http://APP_PRIVATE_IP_ADDRESS:8080
reference here

A: You just need to install one more package to get the links all working:
sudo apt-get install nodejs-legacy
This was explained and answered in detail already here.

A: The node package that you installed when you ran sudo apt-get install node is not actually NodeJS. Instead, the node package actually predates NodeJS and installs Amateur Packet Radio.
The package you are looking for is actually nodejs. However, installing nodejs on Ubuntu will give you an outdated version of NodeJS. Alternatively, you can install NodeJS using a PPA or from Node Version Manager (nvm).
I've posted a comparison of the different installation methods with pros and cons. My personal preference when installing Node on an Ubuntu development machine is to install using NVM. If you're installing NodeJS on a production server, you'll be better off following instructions from Nodesource.


text:
Q: win32: child window not found in child's parent's children I have an Internet explorer page which generated a pop-up. I can get the parent from the pop-up window's handle:
>>> child.handle
15208472
>>> win32gui.GetParent(child.handle)
33230502

But I can't find the child's handle by using EnumChildWindows:
>>> win32gui.EnumChildWindows(win32gui.GetParent(child.handle), lambda hwnd,p: child_handles.append(hwnd), None)
>>> len(child_handles)
39
>>> child.handle in child_handles
False

I've done this recursively as well (getting the children of all the children) and still no child handle to be found. Why might this be the case?

A: A popup window isn't a child window, so can't be enumerated with EnumChildWindows.
When you called win32gui.GetParent you actually got the "owner" window of the popup, but "owner" and "parent" are two different things. See the MSDN entry for more infromation.


text:
Q: php UPDATE is crazy I'm trying to load massive data but I can't even load the first line in phpMyAdmin

What's wrong?

A: Enclose 3.5 within single quotes, it's not an integer.

A: Try this:
UPDATE alumnos_svm SET Parcial1 = '3,5' WHERE dni = 300;

There can be a problem of Locale. If You use American locale, there is a chance, that your numbers are interpreted incorrectly - decimal separator is not ".", but ","


text:
Q: Trigger Locking Table calculating Running Total I have the following trigger on a table in SQL Server 2012:
CREATE TRIGGER [dbo].[UpdateTotals]
   ON  [dbo].[DEC10assessmentData]
   AFTER UPDATE
AS
BEGIN
    -- SET NOCOUNT ON added to prevent extra result sets from
    -- interfering with SELECT statements.
    SET NOCOUNT ON;

    --update list pract test 1 total
    if update (list_practTest1_s1) or update (list_practTest1_s2)
    begin
        update DEC10assessmentData
        set list_practTest1_total = CAST(list_practTest1_s1 AS decimal(3 , 1)) + CAST(list_practTest1_s2 AS decimal(3 , 1))
        where
            TRY_CONVERT(decimal(3 , 1) , dbo.DEC10assessmentData.list_practTest1_s1) IS NOT NULL
            and TRY_CONVERT(decimal(3 , 1) , dbo.DEC10assessmentData.list_practTest1_s2) IS NOT NULL
        update DEC10assessmentData
        set list_practTest1_total = NULL
        where
            TRY_CONVERT(decimal(3 , 1) , dbo.DEC10assessmentData.list_practTest1_s1) IS NULL
            or TRY_CONVERT(decimal(3 , 1) , dbo.DEC10assessmentData.list_practTest1_s2) IS NULL
    end

    --update list test 1 total
    if UPDATE (list_test1_s1) or update (list_test1_s2)
    begin
        update DEC10assessmentData
        set list_test1_total = CAST(list_test1_s1 AS decimal(3 , 1)) + CAST(list_test1_s2 AS decimal(3 , 1))
        where
            TRY_CONVERT(decimal(3 , 1) , dbo.DEC10assessmentData.list_test1_s1) IS NOT NULL
            and TRY_CONVERT(decimal(3 , 1) , dbo.DEC10assessmentData.list_test1_s2) IS NOT NULL
        update DEC10assessmentData
        set list_test1_total = NULL
        where
            TRY_CONVERT(decimal(3 , 1) , dbo.DEC10assessmentData.list_test1_s1) IS NULL
            or TRY_CONVERT(decimal(3 , 1) , dbo.DEC10assessmentData.list_test1_s2) IS NULL
    end

    --update list pract test 2 total
    if update (list_practTest2_s1) or update (list_practTest2_s2)
    begin
        update DEC10assessmentData
        set list_practTest2_total = CAST(list_practTest2_s1 AS decimal(3 , 1)) + CAST(list_practTest2_s2 AS decimal(3 , 1))
        where
            TRY_CONVERT(decimal(3 , 1) , dbo.DEC10assessmentData.list_practTest2_s1) IS NOT NULL
            and TRY_CONVERT(decimal(3 , 1) , dbo.DEC10assessmentData.list_practTest2_s2) IS NOT NULL
        update DEC10assessmentData
        set list_practTest2_total = NULL
        where
            TRY_CONVERT(decimal(3 , 1) , dbo.DEC10assessmentData.list_practTest2_s1) IS NULL
            or TRY_CONVERT(decimal(3 , 1) , dbo.DEC10assessmentData.list_practTest2_s2) IS NULL
    end

    --update list test 2 total
    if UPDATE (list_test2_s1) or update (list_test2_s2)
    begin
        update DEC10assessmentData
        set list_test2_total = CAST(list_test2_s1 AS decimal(3 , 1)) + CAST(list_test2_s2 AS decimal(3 , 1))
        where
            TRY_CONVERT(decimal(3 , 1) , dbo.DEC10assessmentData.list_test2_s1) IS NOT NULL
            and TRY_CONVERT(decimal(3 , 1) , dbo.DEC10assessmentData.list_test2_s2) IS NOT NULL
        update DEC10assessmentData
        set list_test2_total = NULL
        where
            TRY_CONVERT(decimal(3 , 1) , dbo.DEC10assessmentData.list_test2_s1) IS NULL
            or TRY_CONVERT(decimal(3 , 1) , dbo.DEC10assessmentData.list_test2_s2) IS NULL
    end

    --update read total
    update DEC10assessmentData
    set read_total = ((read_test1_Scaled / 100 * 8) + (read_test2_scaled / 100 * 12)) / 20 * 100
    where
        read_test1_Scaled is not null and read_test2_scaled is not null

    --update read total to null where scores don't exist
    update DEC10assessmentData
    set read_total = NULL
    where
        read_test1_Scaled is null or read_test2_scaled is null

    --update write total
    update DEC10assessmentData
    set writ_total = (CAST(writ_literatureReview as decimal(3,1)) / 100 * 4
                        + CAST(writ_exposition as decimal(3,1)) / 100 * 8
                        + CAST(writ_groupReport as decimal(3,1)) / 100 * 8
                        + cast(writ_synthSummary as decimal(3,1)) / 100 * 8
                        + cast(writ_critEvaluation as decimal(3,1)) / 100 * 12) / 40 * 100
    where
        TRY_CONVERT(decimal(3 , 1) , writ_literatureReview) is not null and
        TRY_CONVERT(decimal(3 , 1) , writ_exposition) is not null and
        TRY_CONVERT(decimal(3 , 1) , writ_groupReport) is not null and
        TRY_CONVERT(decimal(3 , 1) , writ_synthSummary) is not null and
        TRY_CONVERT(decimal(3 , 1) , writ_critEvaluation) is not null

    --update write total where scores don't exist
    update DEC10assessmentData
    set writ_total = NULL
    where
        TRY_CONVERT(decimal(3 , 1) , writ_literatureReview) is null or
        TRY_CONVERT(decimal(3 , 1) , writ_exposition) is null or
        TRY_CONVERT(decimal(3 , 1) , writ_groupReport) is null or
        TRY_CONVERT(decimal(3 , 1) , writ_synthSummary) is null or
        TRY_CONVERT(decimal(3 , 1) , writ_critEvaluation) is null

    --update list total
    update DEC10assessmentData
    set list_total = ((list_test1_scaled / 100 * 8) + (list_test2_scaled / 100 * 12)) / 20 * 100
    where
        list_test1_scaled is not null and list_test2_scaled is not null

    --update list total to null where scores don't exist
    update DEC10assessmentData
    set list_total = NULL
    where
        list_test1_scaled is null or list_test2_scaled is null

    --update speak total
    update DEC10assessmentData
    set speak_total = (cast(speak_groupPres as decimal(3,1)) / 100 * 4
                        + CAST(speak_indivPres as decimal(3,1)) / 100 * 8
                        + cast(speak_tutorialDiscus as decimal(3,1)) / 100 * 8) / 20 * 100
    where
        TRY_CONVERT(decimal(3 , 1) , speak_groupPres) is not null and
        TRY_CONVERT(decimal(3 , 1) , speak_indivPres) is not null and
        TRY_CONVERT(decimal(3 , 1) , speak_tutorialDiscus) is not null

    --update speak total where scores don't exist to null
    update DEC10assessmentData
    set speak_total = NULL
    where
        TRY_CONVERT(decimal(3 , 1) , speak_groupPres) is null or
        TRY_CONVERT(decimal(3 , 1) , speak_indivPres) is null or
        TRY_CONVERT(decimal(3 , 1) , speak_tutorialDiscus) is null

    --update overall score
    update DEC10assessmentData
    set overall_total = (read_total + writ_total * 2 + list_total + speak_total) / 5

    --update rec/not rec's for skills and overall
    update DEC10assessmentData
    set read_rec = t.rec_read, writ_rec = t.rec_writ, list_rec = t.rec_list, speak_rec = t.rec_speak, overall_rec = t.rec_overall
    from dbo.udf_getDEC10RecSkillAndOverall() as t inner join DEC10assessmentData
    on t.studentID = DEC10assessmentData.studentID and t.assessmentLookup = DEC10assessmentData.assessmentLookup

    --update rec/not rec's for final rec
    update DEC10assessmentData
    set final_rec = t.rec_final
    from dbo.udf_getDEC10RecFinal() as t inner join DEC10assessmentData
    on t.studentID = DEC10assessmentData.studentID and t.assessmentLookup = DEC10assessmentData.assessmentLookup

END

GO

I am getting a trigger to calculate running totals in a table after updates to other columns in the table. As you can see, there is unfortunately a lot of casting of varchar values, however it does the job except for one issue - locking.
I intermittently get users complaining they can't perform updates and this seems to be because the trigger is locking the table. Is there any way to avoid this and how do I confirm this is what is happening? They are not updating the columns the trigger updates.
I get the following output from two updates that deadlock using Erland Sommarskog's beta_lockinfo:
rsctype locktype lstatus ownertype    waittime spid waittype
KEY         U   WAIT    TRANSACTION     2.192       LCK_M_U 69
DATABASE    S   grant   STW                     69
KEY         X   grant   TRANSACTION             69
OBJECT      IX  grant   TRANSACTION             69
PAGE        IU  grant   TRANSACTION             69
PAGE        IX  grant   TRANSACTION             69
KEY         U   WAIT    TRANSACTION     2.188       LCK_M_U 89
DATABASE    S   grant   STW                     89
KEY         X   grant   TRANSACTION             89
OBJECT      IX  grant   TRANSACTION             89
PAGE        IU  grant   TRANSACTION             89
PAGE        IX  grant   TRANSACTION             89

A: The first advice should probably be not to do use triggers and move the business logic to some other layer.
Your updates affects the whole table, that will probably produce a table lock:
update DEC10assessmentData
set overall_total = (read_total + writ_total * 2 + list_total + speak_total) / 5
etc

Why update other rows than the changed one?
How to work only on the updated row
For your calculations, use calculated columns instead.
Do you really need to do all the converting? Can't you fix your data types in your table definition instead?
But if this is something you absolutely have to do with triggers then maybe you could refactor your table so that you don't store the data in the same table but in two. That way the users would be able to update their data and you can update yours.


text:
Q: How to integrate Twilio MMS web hook in my java application I was working with twilio mms integration in my java application.i have some questions.
what will be the webhook request URL format?
how do I get the sender phone number?
how do I test it from the country other than US/Canda?

A: Twilio developer evangelist here.
You can read about what the Twilio request will look like here: https://www.twilio.com/docs/sms/twiml#twilios-request-to-your-application
Briefly, the request will be an HTTP POST request (by default, or you can change it to GET).
If it is a POST request, the body will be in the format application/x-www-form-urlencoded. The request parameters will include things like MessageSid for the incomin message's ID, Body for the text body and NumMedia for the number of attachments. You can read the URL of each attachment from the MediaUrl{n} parameters, where "n" Is the index of the media. The sender phone number will be the From parameter.
To test this from outside the US I usually buy a second Twilio number and use it along with the API to send messages to my primary number.


text:
Q: Trouble with GWT and Guava I am having difficulty make GWT work with Guava. I added guava-r09-gwt.jar to my classpath, and <inherits name="com.google.common.collect.Collect"/> (copied from this question) to my *.gwt.xml file. However, I still get the following error:

[ERROR] Line 99: No source code is
  available for type
  com.google.gwt.thirdparty.guava.common.collect.Lists;
  did you forget to inherit a required
  module?

The referenced line is:
List<String> suggs = Lists.newArrayList();

If I try the following inherits tag:
  <inherits name="com.google.common.collect.Lists"/>

Then GWT totally fails - going to the app in the browser gives a 404, and no URL appears in Eclipse's development panel.
What am I doing wrong?

A: You'll notice that com.google.gwt.thirdparty.guava.common.collect.Lists is not actually in the Guava jars. Try instead referencing com.google.common.collect.Lists and you should have some more success.

A: Buddy I had same problem (and asked here at StackOverflow), check it out in this thread. Hope that helps! And as Collin pointed out, you're having wrong import, don't use thirdpardy libraries from there.


text:
Q: How to display parent category with first level child in REST API I want help on WP REST API
I want to display Categories with a first level child with some attributes. Here how it should look like:
{
  Parent
  "id": 3,
  "name": "Football",
  "slug": "football"
  child {
            "id": 5,
            "name": "League",
            "slug": "league"
    }
}

Please, anyone help me...
Thanks

A: I am assuming you want these taxonomies data in each item of post_type JSON, but the logic is the same for taxonomies endpoint and JSON response.
I see two ways of achieving it.

*

*filtering the data using rest_prepare_post_type filter (Reference) or

*creating new field(s) using the register_rest_field function. (Reference)

I would recommend the second approach. This is the one I've used recently with a custom post type
Case 1: rest_prepare_post_type
In the first case, you would use the rest_prepare_post_type filter to get the data, generate the data you want, add it to the data array and return the filtered data. In this case, if the post type is "post", the hook is rest_prepare_post.
/**
 * @summary    Filters post rest response
 *
 * @description    Filters post rest response removing or adding certain information
 * @param     object    $data       The response object.
 * @param     object    $post       The original post type object.
 * @param     object    $request    Request used to generate the response.
 * @return    object    $data       The filtered response object.
 */
function wpse_283452_rest_prepare_post($data, $post, $request) {
    $_data = $data->data;
    // say you want to remove author from the response
    unset($_data['author']);
    // if you want to ADD fields, you would do the logic here and...
    // add it to the $_data array
    $data->data = $_data;
    // and finally return it
    return $data;
}
add_filter('rest_prepare_post', 'wpse_283452_rest_prepare_post', 10, 3);

If you want to the same for taxonomies, you would use rest_prepare_taxonomy/ (reference)
Case 2: register_rest_field (recommended)
You will register a new field with register_rest_field function and populate it the way you want using a callback
/**
 * Registers a new field on an existing WordPress object type.
 *
 * @since 4.7.0
 *
 * @global array $wp_rest_additional_fields Holds registered fields, organized
 *                                          by object type.
 *
 * @param string|array $object_type Object(s) the field is being registered
 *                                  to, "post"|"term"|"comment" etc.
 * @param string $attribute         The attribute name.
 * @param array  $args {
 *     Optional. An array of arguments used to handle the registered field.
 *
 *     @type string|array|null $get_callback    Optional. The callback function used to retrieve the field
 *                                              value. Default is 'null', the field will not be returned in
 *                                              the response.
 *     @type string|array|null $update_callback Optional. The callback function used to set and update the
 *                                              field value. Default is 'null', the value cannot be set or
 *                                              updated.
 *     @type string|array|null $schema          Optional. The callback function used to create the schema for
 *                                              this field. Default is 'null', no schema entry will be returned.
 * }
 */
register_rest_field(
    'post',
    'wpse_283452_taxonomies',
    array(
        'get_callback' => function ($object, $field_name, $request) {
            return wpse_283452_taxonomies_callback($object);
        },
    )
);

/**
 * @summary    Return and array with taxonomy info
 *
 * @description    Returns an array with taxonomy information in a custom way
 * @param     object    $object            The rest item original object
 * @return    array     $custom_taxonom    an array with taxonomy terms with their information in a custom way
 */
function wpse_283452_taxonomies_callback($object) {
    $post_id = $object['id'];
    $terms = wp_get_post_terms(
        $post_id,
        'business_type',
        array(
            'fields' => 'all',
        )
    );
    // here you should construct an array with the information in $terms in the way/structure you want
    return $terms;
}

For taxonomies, you would use the taxonomy slug instead of 'post' as the 1st argument on register_rest_field.
That's it.
Let me know if works.


text:
Q: Remove line breaks from between html tags I'm making a form (html & php) which is part of an admin section used to edit content for a website. I want to allow users to include some basic html. This works fine. I want to retain line breaks. This also works. My problem is that when someone writes something like this:

item one

item two

the line breaks between the lines of code are retained and turned into BRs when written out. This means that there's double spacing between each LI element. Now this can be fixed by writing the whole list section on one line but a) that makes it confusing to read and b) it's hard enough teaching people to use the codes let alone explaining extraineous line breaks.
What I want is some way to strip all /n out but ONLY between UL and /UL tags.

A: This regular expression removes all linebreaks/whitespaces between
 and
 that are not part of the text between
 and

/(?<=
|<\/li>)\s*?(?=<\/ul>|
)/is

php example:
 $output = preg_replace('/(?<=
|<\/li>)\s*?(?=<\/ul>|
)/is', '', $input);

input:

item one

item two

output:

item one

item two

EDIT: fixed

A: You might be able to get away with using a regular expression, although this will fail if the HTML is not well formed. This should match everything within HTML tags, because the regex is greedy by default.
<?php

$str = "Hello

item one

item two

";

$str = preg_replace_callback('~\<[^>]+\>.*\</[^>]+\>~ms','stripNewLines', $str);

function stripNewLines($match) {
    return str_replace(array("\r", "\n"), '', $match[0]);
}

echo nl2br($str);

Edit
Actually, this won't work. If there are two blocks of HTML with normal text in between, the text in the middle will also be stripped.

A: I'm having trouble understanding why line breaks are being turned into
.
What's doing that? Is it the PHP?
Doesn't HTML treat a line break the same as a space? Turning them into
 doesn't seem right.

A: This is an example to replace line breaks in html tag:
public function testLineBreaks()
{
    $html = 'some title';

    $pattern = "#</?\w+((\s+\w+(\s*=\s*(?:\".*?\"|'.*?'|[^'\">\s]+))?)+\s*|\s*)/?>#";
    $html = preg_replace_callback(
        $pattern,
        function($match){
            $txt = str_replace(array("\r", "\n"), ' ', $match[0]);
            return preg_replace("/[[:blank:]]+/"," ",$txt);
        },$html
    );

    $this->assertEquals('some title', $html);
}


text:
Q: How to pass parameters from jQuery to laravel route Im trying to pass an integer parameter to a laravel method. I can't seem to get the format right in the jQuery?
Route method
/**
 * @return mixed
 */

public function appendMediaImage($adid){
    $user_id = Auth::user()->id;
    $ads_images = Media::whereUserId($user_id)->whereAdId($adid)->whereRef('ad')->get();

    return view('admin.append_media', compact('ads_images'));
}

jQuery
if (data.success == 1){
                        $('#uploaded-ads-image-wrap').load('{{ route('append_media_image','adid':'50') }}');
                    } else{
                        alert("fail");
                        toastr.error(data.msg, '<?php echo trans('app.error') ?>', toastr_options);
                    }

Route definition
Route::get('append-media-image', ['as'=>'append_media_image', 'uses' => 'AdsController@appendMediaImage']);

A: The second parameter of the route helper should be an array defining the parameters for the route.
You can do it this way instead:
$('#uploaded-ads-image-wrap').load('{{ route('append_media_image', ['adid' => 50]) }}');

Edit: You also need to change your route to cater for the adid parameter.
Route::get('append-media-image/{adid}', 'AdsController@appendMediaImage')->name('append_media_image');


text:
Q: Oscilloscope voltage readings factor of 10 too high. Is this due to the impedance? For a university physics experiment, I built a circuit to test voltage (and conductance) steps across a nanowire break junction. The break junction was in a circuit with an I-V converter, and the I-V output was fed to an oscilloscope. The voltage steps measured matched the theory, however they were all a factor of 10 too large. Is this due to the impedance of the oscilloscope? I can't retrieve the exact model now but it was Tektronix and the standard oscilloscope used across the university, so I assume it is 1MOhm. Is there anything else involving the impedance (or any other factor) that could be causing the factor of 10?
I double checked the I-V contributions of all components in the circuit, such as the feedback resistor in the converter, and couldn't find anything so can only conclude it is the oscilloscope. But electronics is not my forte so I am not sure how an oscilloscope could cause x10 to the voltage.

A: Some of the probes used with oscilloscopes incorporate a very high impedance input circuit right at the probe tip. This circuit attenuates the signal by a factor of 10. Some oscilloscopes can automatically recognize whether such a probe, usually called a "ten-to-one" probe, is in use but other oscilloscopes require the user to manually change a setting.
My guess is that your oscilloscope assumed that such a probe was being used when in fact it was not, so the recorded voltages are too large by a factor of 10.


text:
Q: How to access $scope object from multiple templates? I am trying to login to an API with username and password and then get a token use it to get some resources, first is a post request and second is get request. both requests are made and I checked the scope object, I got both $scope.userInfo and $scope.projects. The problem is, after logging in, I am redirecting to home page which is a different template and trying to access $scope from there but, I get nothing
controller.js
/*jshint esversion: 6 */
var app = angular.module('main', ['ngRoute']);

app.config(function($routeProvider) {
  $routeProvider.when('/', {
    templateUrl: './components/welcome.html',
    controller: 'LoginController'
  }).when('/home', {
    templateUrl: './components/home.html',
    controller: 'LoginController'
  }).otherwise({
    template: '404 Resource Not Found'
  });
});

app.controller('LoginController', function($scope, $http, $location) {
  $scope.login = function() {
    var { username, password } = $scope;
    $http({
      url: 'url',
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        'X-Client-Type': 'browser'
      },
      data: { username, password }
    }).then(function(response) {
      $scope.userInfo = response.data;
      console.log(response.data);
    }).then(function() {
      $http({
        method: 'GET',
        url: 'url2',
        headers: {
          'Content-Type': 'application/json',
          'X-Authtoken': $scope.userInfo.authtoken
        },
      }).then(function(response) {
        $scope.projects = response.data;
      }).then(function() {
        $location.path('/home');
      });
    });
  };
});

welcome.html

Sign In

                <form>

                        <input type="text" class="form-control" placeholder="username" ng-model="username">

                        <input type="password" class="form-control" placeholder="password" ng-model="password">

              <button class="btn float-right login_btn" ng-click="login()">Login</button>

                </form>

home.html

Welcome username!

         user avatar

User Template

{{userInfo.user.name}} //

          Vancouver, BC Canada

          user details...

                        #
                        Project

                      //{{project.number}}
                      //{{project.name}}

                     2
                    second project

I am new to angularJS, thanks in advance. Please let me know if there is something unclear

A: If you redirect to another place (home, ...) you will loss client side data. You should get the data from server again or don't redirect and only change the state (use single page features).
Also if you want to share data between controllers, you can use "factories" or "services".


text:
Q: How to get to sandboxed environment of content script in Chrome JS console If I open up the JavaScript console in Chrome Developer Tools to debug my extension's content scripts, I don't get the context of the content scripts.  For example, jQuery isn't accessible, and I can't get access to my global variables unless I go to the debugger and set up a breakpoint.
Am I just missing something?  It would be great to be able to check my global variables from the JS console or invoke jQuery.

A: It is not possible at the moment to perform evaluations in context of a content script except the described way of setting a breakpoint/inserting debugger statement and pausing inside the script. I filed a bug on this,  You can add yourself to the CC list to track its progress.

A: You can achieve this indirectly by triggering the debugger in the isolated world of the content script:

*

*Select the tab whose content scripts you wish to inspect

*Open the dev tools for that tab

*Open the inspector for your extension's background page (or any other extension page) in a popup window

*Run chrome.tabs.executeScript(undefined, {'code': 'debugger'})
You should also be able to use the debugger keyword directly in your content script, if there's a place in the execution that you wish to inspect.


text:
Q: Import configuration and relational data Suppose that a user has multiple items. Each item would have complex configuration - multiple tables with relationships.
Each configuration table would have an id and a item_id which is a  FK to items table.
My question is given that we have a relational database and we export all tables to a text format (csv,json, etc) how can we reimport this data for  another item as cloned?
Importing just data would be easy since a new id will be generated for every row. However creating a id means that foreign keys would be invalid.
The only way I figured to solve this issue is to store data first(without FKs) for all tables and then knowing each table new PK update foreign keys. I could use a dictionary to map old ids with new ones.
Is there a cleaner way to achieve something like that?

A: A better solution might be to use the "insert .. select" form of the insert statement.  If your items have an auto-incrementing [primary] key, then inserting a record without specifying that column will cause the database to allocate a new value, which you can then retrieve using a DBMS-specific function.
select * from month_days ;
+----+---------+------+
| ID | Month   | Days |
+----+---------+------+
|  1 | January |   31 |
+----+---------+------+

insert into month_days ( Month, Days )
select 'March', Days
from month_days ;

select * from month_days ;
+----+---------+------+
| ID | Month   | Days |
+----+---------+------+
|  1 | January |   31 |
|  2 | March   |   31 |
+----+---------+------+

A: Some databases like SQL Server have a means to disable constraint testing for just such purposes.  I think it goes without saying that you should be sure you know what you're doing in such mode.  To play it safe, you would disable the individual rules rather than disable all constraints and in the case of failure, rollback, and then enable constraints again.


text:
Q: Как реализовать поиск по нескольким полям? Здравствуйте уважаемые!
Проблема заключается в реализации поиска по нескольким полям. Имеется БД, где есть: Наименование объекта, структурное подразделение, год и исполнитель. На странице имеется таблица (4 поля) и одна кнопка поиска, юзер вводит значение в поля или же будет выпадающий список (список значений в БД для определенного поля).
Вот собственно сам вопрос, как реализовать и возможно ли выполнить поиск с строгими значениями с выпадающего списка? хотя бы знать куда копать.
Спасибо, уже который день мучаюсь.
Модель
class Year(models.Model):
    title = models.CharField(max_length=4, verbose_name='Год')
    slug = models.SlugField(max_length=4, verbose_name='Slug Год', unique=True)

    def __str__(self):
        return self.title

    class Meta:
        verbose_name = 'Год'
        verbose_name_plural = 'Год'
        ordering = ['title']

lass Subject(models.Model):
    title = models.CharField(max_length=100, verbose_name='Наименование объекта')
    slug = models.SlugField(max_length=100, verbose_name='Slug Наименование объекта', unique=True)

    def __str__(self):
        return self.title

    class Meta:

        verbose_name = 'Наименвоание объекта'
        verbose_name_plural = 'Наименвоание объекта'
        ordering = ['title']

class Post(models.Model):
    title = models.CharField(max_length=100, verbose_name='Пост', blank=False, null=True, )
    slug = models.SlugField(max_length=100, verbose_name='Slug Пост', unique=True)
    content = models.TextField(blank=True, verbose_name='Контент')
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='Опубликовано')
    document = models.FileField(upload_to='doc/%Y/', blank=False, null=True, verbose_name='Документ')
    # Название = в скобках ссылка на модель Subject.
    # Задает название связи постов с моделью Subject (related_name='posts')
    year = models.ForeignKey(Year, on_delete=models.PROTECT, related_name='posts', blank=False, null=True,
                             verbose_name='Год')
    subject = models.ForeignKey(Subject, on_delete=models.PROTECT, related_name='posts', blank=False, null=True,
                                verbose_name='Наименование объекта')
    division = models.ForeignKey(Division, on_delete=models.PROTECT, related_name='posts', blank=False, null=True,
                                 verbose_name='Подразделения')
    executor = models.ForeignKey(Executor, on_delete=models.PROTECT, related_name='posts', blank=False, null=True,
                                 verbose_name='Исполнитель')
    surveys = models.ForeignKey(Surveys, on_delete=models.PROTECT, related_name='posts', blank=False, null=True,
                                verbose_name='Вид обследования')
    format = models.ForeignKey(Format, on_delete=models.PROTECT, related_name='posts', blank=False, null=True,
                               verbose_name='Формат документа')

    def __str__(self):
        return self.title

    def get_absolute_url(self):
        return reverse('post', kwargs={"slug": self.slug})

    class Meta:
        verbose_name = 'Пост'
        verbose_name_plural = 'Пост'
        ordering = ['-created_at']

url приложения
from django.urls import path
from .views import *

    urlpatterns = [

        path('', Home.as_view(), name='home'),
        path('surveys/<str:slug>', PostBySurveys.as_view(), name='surveys'),
        path('post/<str:slug>', get_post, name='post')
    ]

вьюс
class Home(ListView):
    model = Post

    template_name = 'blog/index.html'
    context_object_name = 'posts'

    def get_context_data(self, *, object_list=None, **kwargs):
        context = super().get_context_data(**kwargs)
        context ['title'] = 'G'
        return context

class PostBySurveys(ListView):
    template_name = 'blog/index.html'
    context_object_name = 'posts'
    allow_empty = False

    def get_queryset(self):
        return Post.objects.filter(surveys__slug=self.kwargs['slug'])

    def get_context_data(self, *, object_list=None, **kwargs):
        context = super().get_context_data(**kwargs)
        context ['title'] = Surveys.objects.get(slug=self.kwargs['slug'])
        return context

выпадающий список
<select class="form-select" aria-label="Default select example" style="margin-top: 10px; background-color: darkgray;">
    <option selected>Название объекта</option>
        {% for s in subjects %}
            <option>{{ s.title }}</option>
        {% endfor %}

    </select>
<select class="form-select" aria-label="Default select example" style="margin-top: 10px; background-color: darkgray;">
    <option selected>Подразделение</option>
    <option value="1">One</option>
    <option value="2">Two</option>
    <option value="3">Three</option>
</select>
<select class="form-select" aria-label="Default select example" style="margin-top: 10px; background-color: darkgray;">
    <option selected>Испонитель</option>
    <option value="1">One</option>
    <option value="2">Two</option>
    <option value="3">Three</option>

Таблица

{% for post in posts %}

    {{ post.id }}

     {{ post.subject }}

     {{ post.division }}

     {{ post.created_at|date:"d.m.y" }}

        <button type="button" class="btn btn-secondary" data-toggle="tooltip" data-placement="top"
                title="{{ post.document }}">Скачать
        </button>

     {{ post.executor }}

{% endfor %}


text:
Q: How do I apply a custom multi-variate function to each row of a data frame in R? Suppose I have a data frame with columns named "foo" and "bar"
mydata <- data.frame(foo=rnorm(100), bar=rnorm(100))

and suppose I have a custom scalar function that expects scalar inputs "x" and "y" and produces a scalar output, for example
myfunction <- function(x, y) { if (x>0) y else x }

How do I apply myfunction to every row of mydata with x being foo, and y being bar?
Yes, I know this specific example is a ridiculously simple and can be done very easily in R, but I'm interested in the pattern.Imagine that myfunction is very complex, and the variable names of myfunction have to be mapped onto the column names of mydata. What is the general solution?

A: mydata <- data.frame(x=rnorm(100), y=rnorm(100))
myfunction <- function(x, y) { if (x>0) y else x }

# with plyr (requires the argument names to match)
plyr::mdply(mydata, myfunction)

# with base functions
with(mydata, mapply(myfunction, x, y))

A: You can use mapply
mapply(myfunction, mydata$foo, mydata$bar)

A: Vectorize is syntactic sugar for mapply designed for this situation. It's very useful for vectorizing complicated code to feed into R functions that expect it, eg outer, integrate, uniroot, etc.
myfunction <- Vectorize(myfunction)

myfunction(mydata$foo, mydata$bar)


text:
Q: Question about Noether theorem For the Noether theorem for pseudoeuclidean 4-spacetime a-current $J_{a}^{\mu}$ is equal to
$$
J_{a}^{\mu} = \frac{\partial L}{\partial (\partial_{\mu}\Psi_{k})}Y_{k, a} - \left( \frac{\partial L}{\partial (\partial_{\mu}\Psi_{k})}\partial_{\nu}\Psi_{k} - \delta_{\nu}^{\mu}L \right) X_{a}^{\nu},
$$
$$
\quad Y_{k, a} = \left(\frac{\partial F_{k}(\Psi , \omega)}{\partial \omega^{a}}\right)_{\omega = 0}, \quad X_{a}^{\nu} = \left(\frac{\partial f^{\nu}(x , \omega)}{\partial \omega^{a}}\right)_{\omega = 0},
$$
$F_{k}$ - function of field transformation, $f^{\nu}$ - function of coordinates transformation, $ \omega^{a}$ - parameter of transformation.
The charge is equal to
$$
\partial_{\mu}J_{a}^{\mu} = 0 \Rightarrow Q_{a} = \int J_{a}^{0} (t, \mathbf r)d^{3}\mathbf r .
$$
How to "reduce" the number of dimentions in this theorem for euclidean 3-space (i.e. get the formulation of theorem for euclidean space)?


text:
Q: Wordpress gives 404 in any page with any kind of permalink, but when I change the theme it works. How to fix? I have a wordpress theme that has the page.php, but it gives 404 in any page that I create, even using the plain permalink (http://localhost:8080/?page_id=33141).
But when I change to wordpress theme the page works.
I think it is not about htacces, because none of the themes should work.
Could the theme redirect all pages to 404? I didn't find anything in the code.
Could someone refresh my mind?
Thanks.
I am running it in a docker container but I dont think it has influence because the other theme works.

A: Try go to setting->permalink and click save and clear cache and fresh page.

A: go to settings-> permalinks and save the permalinks and also clear the cache. sometime it is occurring due to cache.
And also sometimes it may happens due to permission is declined from cpanel
Go to cpanel and then right click select permission and change the permission. It may be helpful


text:
Q: Outputting HTML with echo considered bad practice in PHP? In PHP, I'm using an if statement to identify whether a user is logged in or not, and depending on the result, displaying the main menu (if logged in) or a "you need to login" message if not. I am doing this like so:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

    <meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
    <link rel="stylesheet" href="style.css" type="text/css" />
    <title>Home</title>

    <?php
       if($_SESSION['loggedIn'] == 1) {
          echo "
MAIN MENU stuff goes here
";
       } else {
          echo "
Please login...
";
       }
    ?>

As you can see, the code to display either the main menu or the "please login" message is produced by an echo. Is this bad practice, perhaps there's a better way?
By the way, I've cut out most of the HTML from the echos in my snippet above. The main menu is made up of a list, but I didn't bother including that as it's irrelevant to the question, I guess.

A: There's nothing wrong with echo for html, when used in moderation. Just don't use it for long multi-line blocks. You'll invariably end up with some ugly construct requiring escaping and whatnot, which makes things even uglier to read.
If the html you're outputting is "static" (no variables to insert), then consider breaking OUT of php mode (?>) and simply dumping the html as is. If you do need to insert variables, then consider using a HEREDOC, which act like a double-quoted string, but without the quotes.

A: Why not write it like this?
<?php if($_SESSION['loggedIn'] == 1): ?>

MAIN MENU stuff goes here

<?php else: ?>

Please login...

<?php endif; ?>

Using the alternative control structures seperates your markup from your code a bit more.

A: <?php if (condition) { ?>

        some stuff

<?php } ?>

The beauty of PHP is that you can do this.

A: I consider it to be bad practice. Not sure about what anyone else thinks. For one thing, it looks terrible in text editors with syntax highlighting, then you have to worry about escaped strings, etc.
This is how I do it:

      <? if ($_SESSION['loggedIn'] === 1): ?>

Main Menu stuff goes here

      <? else: ?>

Please log in...

      <? endif ?>

You can hop out of the PHP tags and use straight up HTML. There are pros and cons to doing it this way. I like it way better than echoing stuff out. Other options would be to render new views into those areas based on the results of the if statements. Lots of possibilities, but the above is just one way to make that a little cleaner and (I think) better.

A: If your project gets to a reasonable size, there's essentially no way around a clean separation of presentational elements and program logic, just for the sake of maintainability and scalability. So what you're doing in your current code doesn't really matter; in the long run, you should look into a clean design approach from the outset.
There are many existing solutions, usually involving some sort of layout templates which are loaded by the code.

A: There is no true 'best practice', although some will argue that they prefer one or the other. Ideally if you separate HTML from PHP, you're isolating the backend of your application from the frontend, therefore making it easier to read, modify and maintain.
As for your code, I might modify it so it is more concise (depending on what you mean by 'MAIN MENU stuff ...' I'd reconsider this edit):

    <?= ($_SESSION['loggedIn'] == 1) ? 'MAIN MENU stuff goes here' : 'Please login...'; ?>

A: Some consider it bad practice, that's true of anything. I like to not use echo.  If you do it this way it is more clear to editors such as Dreamweaver what you want and get all the autocomplete benefits.
<?php
if ($loggedin)
{
?>
Thank you for being logged in.

<?php
}
else
{
?>
Please login
<?php
}
?>


text:
Q: Trouble assigning responseText from jQuery ajax call I have been working on a simple test giver app. Everything has worked fine with the JSON allQuestions object embedded in code. Now I want to move the allQuestions object out of the index file and into test.json and retrieve it via jQuery AJAX call.
I assume I need to keep allQuestions as a global variable, because I manipulate it in other places in the script.
I get an "allQuestions is null error" first time it is encountered in script.
Tried declaring it as an array and I got an allQuestions undefined exception. Here is the jsfiddle version with JSON embedded (sorry I haven't figured out yet how to use AJAX functiaonality in jsfiddle yet). When I comment out the json and substitute :
var allQuestions = null;
    // jQuery AJAX request to read JSON formatted Test Questions & Answers from file
     $.ajax({
        url: "test.json",
        dataType: "json",
        success: function(result) {
           allQuestions = result;
        }
      });

I see via firebug I get response ok:
[{
    question: ["Who is Prime Minister of the United Kingdom?", "Who is the Vice-President of the United
 States?", "Who is Chancellor of Germany?", "Who is the Prime Minister of Canada?"],
    choices: [
      ["David Cameron", "Gordon Brown", "Winston Churchill", "Tony Blair"],
      ["Barack Obama", "Bernie Sanders", "Nancy Pelosi", "Joe Biden"],
      ["Franz Ritz", "Angela Merkel", "Jan Schroeder", "John Stevens", "Karl Marx"],
      ["Wayne Gretsky", "Pierre Trudeau", "Mike Myers", "Justin Trudeau", "Justin Bieber"]
    ],
    correctAnswer: [0, 3, 1, 3]
  }]

but allQuestions is null. I don't seem to be able to get into the success function at all because when I step thru it with breakpoint it goes right over the success option and returns. I tried even just doing an alert(result) with no success (no pun intended).
Any insight will be most appreciated.

A: The piece that you're probably missing is that AJAX calls are asynchronous.
So what happens is:
- you initialize allQuestions
- you *start* requesting allQuestions to the server
- you render the page, and allQuestions is still NULL
- the server replies, but now it's too late.

So what do you do? You place the rendering functions within the AJAX success function:
$.post(..., function(reply) {
    allQuestions = reply;
    renderOnPage(allQuestions);
});

You will probably discover that this approach no longer requires allQuestions to be a global - all relevant functions will just pass it along among themselves.


text:
Q: Decompression of bz2 file fails with error So far I've tried to decompress using mac command line tool bzip2 -dc , it throws this error : 'huff+mtf data integrity (CRC) error in data', I've even tried recovering files using bzip2recover command it converted my 4 mb file into 6000 small bz2 files with success message however decompression of all those files failed with the same error
Using python bz2 package : this throws error 'IO error Invalid data stream'
Using Apache nifi, It says Java.io.exception unexpected end of stream.
Data was fed to GSC bucket using this chain 'Palo alto block' -> 'pubsub' -> 'GCS bucket'.
All this indicates that data might be corrupt but I am not sure(can't simply blame Pub Sub). has anyone ever faced similar situation?
any kind of help will be appreciated.
you can find a sample bz2 file here

A: Maybe it is already decompressed?
Can you do a "tar -tf file.bz2"?
Or can you try to get the file type, for example with "file.bz2"


text:
Q: Fail to compile python with Cython on Windows 7 I am trying to compile my python project, and I compile the main file with PyInstaller, and the rest with Cython.
On linux it all goes well, but when I tried on Windows 7, it didn't work. I had to install the .NET framework 4.6, and then the visual studio build tools 2019. It all installed well, even though it took ages, and I tried running the setup.py file again, but this time I got this error:
running build_ext
building 'objects.blocks' extension
C:\Program Files (x86)\Microsoft Visual Studio\2019\BuildTools\VC\Tools\MSVC\14.26.28801\bin\HostX86\x64\cl.exe /c /nologo /Ox /W3 /GL /DNDEBUG /MD -IC:\Users\Kolterdyx\AppData\Local\Programs\Python\Python38\include -IC:\Users\Kolterdyx\AppData\Local\Programs\Python\Python38\include "-IC:\Program Files (x86)\Microsoft Visual Studio\2019\BuildTools\VC\Tools\MSVC\14.26.28801\include" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.18362.0\ucrt" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.18362.0\shared" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.18362.0\um" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.18362.0\winrt" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.18362.0\cppwinrt" /Tcbuild\objects/blocks.c /Fobuild\temp.win-amd64-3.8\Release\build\objects/blocks.obj
blocks.c
C:\Program Files (x86)\Microsoft Visual Studio\2019\BuildTools\VC\Tools\MSVC\14.26.28801\bin\HostX86\x64\link.exe /nologo /INCREMENTAL:NO /LTCG /DLL /MANIFEST:EMBED,ID=2 /MANIFESTUAC:NO /LIBPATH:C:\Users\Kolterdyx\AppData\Local\Programs\Python\Python38\libs /LIBPATH:C:\Users\Kolterdyx\AppData\Local\Programs\Python\Python38\PCbuild\amd64 "/LIBPATH:C:\Program Files (x86)\Microsoft Visual Studio\2019\BuildTools\VC\Tools\MSVC\14.26.28801\lib\x64" "/LIBPATH:C:\Program Files (x86)\Windows Kits\10\lib\10.0.18362.0\ucrt\x64" "/LIBPATH:C:\Program Files (x86)\Windows Kits\10\lib\10.0.18362.0\um\x64" /EXPORT:PyInit_blocks build\temp.win-amd64-3.8\Release\build\objects/blocks.obj /OUT:build\lib.win-amd64-3.8\objects\blocks.cp38-win_amd64.pyd /IMPLIB:build\temp.win-amd64-3.8\Release\build\objects\blocks.cp38-win_amd64.lib
   Creating library build\temp.win-amd64-3.8\Release\build\objects\blocks.cp38-win_amd64.lib y objeto build\temp.win-amd64-3.8\Release\build\objects\blocks.cp38-win_amd64.exp
Generating code
Code generation finished
building 'objects.enemy' extension
C:\Program Files (x86)\Microsoft Visual Studio\2019\BuildTools\VC\Tools\MSVC\14.26.28801\bin\HostX86\x64\cl.exe /c /nologo /Ox /W3 /GL /DNDEBUG /MD -IC:\Users\Kolterdyx\AppData\Local\Programs\Python\Python38\include -IC:\Users\Kolterdyx\AppData\Local\Programs\Python\Python38\include "-IC:\Program Files (x86)\Microsoft Visual Studio\2019\BuildTools\VC\Tools\MSVC\14.26.28801\include" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.18362.0\ucrt" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.18362.0\shared" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.18362.0\um" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.18362.0\winrt" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.18362.0\cppwinrt" /Tcbuild\objects/enemy.c /Fobuild\temp.win-amd64-3.8\Release\build\objects/enemy.obj
enemy.c
C:\Program Files (x86)\Microsoft Visual Studio\2019\BuildTools\VC\Tools\MSVC\14.26.28801\bin\HostX86\x64\link.exe /nologo /INCREMENTAL:NO /LTCG /DLL /MANIFEST:EMBED,ID=2 /MANIFESTUAC:NO /LIBPATH:C:\Users\Kolterdyx\AppData\Local\Programs\Python\Python38\libs /LIBPATH:C:\Users\Kolterdyx\AppData\Local\Programs\Python\Python38\PCbuild\amd64 "/LIBPATH:C:\Program Files (x86)\Microsoft Visual Studio\2019\BuildTools\VC\Tools\MSVC\14.26.28801\lib\x64" "/LIBPATH:C:\Program Files (x86)\Windows Kits\10\lib\10.0.18362.0\ucrt\x64" "/LIBPATH:C:\Program Files (x86)\Windows Kits\10\lib\10.0.18362.0\um\x64" /EXPORT:PyInit_enemy build\temp.win-amd64-3.8\Release\build\objects/enemy.obj /OUT:build\lib.win-amd64-3.8\objects\enemy.cp38-win_amd64.pyd /IMPLIB:build\temp.win-amd64-3.8\Release\build\objects\enemy.cp38-win_amd64.lib
   Creating library build\temp.win-amd64-3.8\Release\build\objects\enemy.cp38-win_amd64.lib y objeto build\temp.win-amd64-3.8\Release\build\objects\enemy.cp38-win_amd64.exp
Generating code
Code generation finished
building 'objects.item' extension
C:\Program Files (x86)\Microsoft Visual Studio\2019\BuildTools\VC\Tools\MSVC\14.26.28801\bin\HostX86\x64\cl.exe /c /nologo /Ox /W3 /GL /DNDEBUG /MD -IC:\Users\Kolterdyx\AppData\Local\Programs\Python\Python38\include -IC:\Users\Kolterdyx\AppData\Local\Programs\Python\Python38\include "-IC:\Program Files (x86)\Microsoft Visual Studio\2019\BuildTools\VC\Tools\MSVC\14.26.28801\include" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.18362.0\ucrt" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.18362.0\shared" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.18362.0\um" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.18362.0\winrt" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.18362.0\cppwinrt" /Tcbuild\objects/item.c /Fobuild\temp.win-amd64-3.8\Release\build\objects/item.obj
item.c
C:\Program Files (x86)\Microsoft Visual Studio\2019\BuildTools\VC\Tools\MSVC\14.26.28801\bin\HostX86\x64\link.exe /nologo /INCREMENTAL:NO /LTCG /DLL /MANIFEST:EMBED,ID=2 /MANIFESTUAC:NO /LIBPATH:C:\Users\Kolterdyx\AppData\Local\Programs\Python\Python38\libs /LIBPATH:C:\Users\Kolterdyx\AppData\Local\Programs\Python\Python38\PCbuild\amd64 "/LIBPATH:C:\Program Files (x86)\Microsoft Visual Studio\2019\BuildTools\VC\Tools\MSVC\14.26.28801\lib\x64" "/LIBPATH:C:\Program Files (x86)\Windows Kits\10\lib\10.0.18362.0\ucrt\x64" "/LIBPATH:C:\Program Files (x86)\Windows Kits\10\lib\10.0.18362.0\um\x64" /EXPORT:PyInit_item build\temp.win-amd64-3.8\Release\build\objects/item.obj /OUT:build\lib.win-amd64-3.8\objects\item.cp38-win_amd64.pyd /IMPLIB:build\temp.win-amd64-3.8\Release\build\objects\item.cp38-win_amd64.lib
   Creating library build\temp.win-amd64-3.8\Release\build\objects\item.cp38-win_amd64.lib y objeto build\temp.win-amd64-3.8\Release\build\objects\item.cp38-win_amd64.exp
Generating code
Code generation finished
building 'objects.player' extension
C:\Program Files (x86)\Microsoft Visual Studio\2019\BuildTools\VC\Tools\MSVC\14.26.28801\bin\HostX86\x64\cl.exe /c /nologo /Ox /W3 /GL /DNDEBUG /MD -IC:\Users\Kolterdyx\AppData\Local\Programs\Python\Python38\include -IC:\Users\Kolterdyx\AppData\Local\Programs\Python\Python38\include "-IC:\Program Files (x86)\Microsoft Visual Studio\2019\BuildTools\VC\Tools\MSVC\14.26.28801\include" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.18362.0\ucrt" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.18362.0\shared" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.18362.0\um" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.18362.0\winrt" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.18362.0\cppwinrt" /Tcbuild\objects/player.c /Fobuild\temp.win-amd64-3.8\Release\build\objects/player.obj
player.c
C:\Program Files (x86)\Microsoft Visual Studio\2019\BuildTools\VC\Tools\MSVC\14.26.28801\bin\HostX86\x64\link.exe /nologo /INCREMENTAL:NO /LTCG /DLL /MANIFEST:EMBED,ID=2 /MANIFESTUAC:NO /LIBPATH:C:\Users\Kolterdyx\AppData\Local\Programs\Python\Python38\libs /LIBPATH:C:\Users\Kolterdyx\AppData\Local\Programs\Python\Python38\PCbuild\amd64 "/LIBPATH:C:\Program Files (x86)\Microsoft Visual Studio\2019\BuildTools\VC\Tools\MSVC\14.26.28801\lib\x64" "/LIBPATH:C:\Program Files (x86)\Windows Kits\10\lib\10.0.18362.0\ucrt\x64" "/LIBPATH:C:\Program Files (x86)\Windows Kits\10\lib\10.0.18362.0\um\x64" /EXPORT:PyInit_player build\temp.win-amd64-3.8\Release\build\objects/player.obj /OUT:build\lib.win-amd64-3.8\objects\player.cp38-win_amd64.pyd /IMPLIB:build\temp.win-amd64-3.8\Release\build\objects\player.cp38-win_amd64.lib
   Creating library build\temp.win-amd64-3.8\Release\build\objects\player.cp38-win_amd64.lib y objeto build\temp.win-amd64-3.8\Release\build\objects\player.cp38-win_amd64.exp
Generating code
Code generation finished
building 'objects.PhysicObjects.__init__' extension
creating build\temp.win-amd64-3.8\Release\build\objects\PhysicObjects
C:\Program Files (x86)\Microsoft Visual Studio\2019\BuildTools\VC\Tools\MSVC\14.26.28801\bin\HostX86\x64\cl.exe /c /nologo /Ox /W3 /GL /DNDEBUG /MD -IC:\Users\Kolterdyx\AppData\Local\Programs\Python\Python38\include -IC:\Users\Kolterdyx\AppData\Local\Programs\Python\Python38\include "-IC:\Program Files (x86)\Microsoft Visual Studio\2019\BuildTools\VC\Tools\MSVC\14.26.28801\include" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.18362.0\ucrt" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.18362.0\shared" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.18362.0\um" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.18362.0\winrt" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.18362.0\cppwinrt" /Tcbuild\objects/PhysicObjects/__init__.c /Fobuild\temp.win-amd64-3.8\Release\build\objects/PhysicObjects/__init__.obj
__init__.c
creating Z:\Programming\Python\GameDev\VoidShips\build\lib.win-amd64-3.8\objects\PhysicObjects
C:\Program Files (x86)\Microsoft Visual Studio\2019\BuildTools\VC\Tools\MSVC\14.26.28801\bin\HostX86\x64\link.exe /nologo /INCREMENTAL:NO /LTCG /DLL /MANIFEST:EMBED,ID=2 /MANIFESTUAC:NO /LIBPATH:C:\Users\Kolterdyx\AppData\Local\Programs\Python\Python38\libs /LIBPATH:C:\Users\Kolterdyx\AppData\Local\Programs\Python\Python38\PCbuild\amd64 "/LIBPATH:C:\Program Files (x86)\Microsoft Visual Studio\2019\BuildTools\VC\Tools\MSVC\14.26.28801\lib\x64" "/LIBPATH:C:\Program Files (x86)\Windows Kits\10\lib\10.0.18362.0\ucrt\x64" "/LIBPATH:C:\Program Files (x86)\Windows Kits\10\lib\10.0.18362.0\um\x64" /EXPORT:PyInit___init__ build\temp.win-amd64-3.8\Release\build\objects/PhysicObjects/__init__.obj /OUT:build\lib.win-amd64-3.8\objects\PhysicObjects\__init__.cp38-win_amd64.pyd /IMPLIB:build\temp.win-amd64-3.8\Release\build\objects/PhysicObjects\__init__.cp38-win_amd64.lib
LINK : error LNK2001: external symbol PyInit___init__ not resolved
build\temp.win-amd64-3.8\Release\build\objects/PhysicObjects\__init__.cp38-win_amd64.lib : fatal error LNK1120: 1 external not resolved
error: command 'C:\\Program Files (x86)\\Microsoft Visual Studio\\2019\\BuildTools\\VC\\Tools\\MSVC\\14.26.28801\\bin\\HostX86\\x64\\link.exe' failed with exit status 1120

Why is this happening and how can I fix it?


text:
Q: Formula calculator in jQuery I'm attempting to finish a calculator which calculates values visa versa based on input.
When I'd like to calculate the PPM, I need the MGM3 and the Mol
When I'd like to calculate the MGM3, I need the PPM and the Mol
Now, the thing is that it's not working correctly. I'm still new to this kind of calculations. I hope someone could help me fix this.
Above fixed
Update: Only in firefox there occurs an error when using 3 numbers behind the dot.
For example, fill in:
• mol: 30
• Mg/m3: 0,15
After completion supplement the mg/m3 with several numbers and the outcome is invalid. How do I fix this?

// formula for ppm =    mg/m3 * 24.45 / mol
// formula for mg/m3 =  ppm * mol / 24.45

 $('input.value').keyup(function(){
    var ppm = $('#ppm');
    var mgm3 = $('#mgm3');
    var mol = $('#mol');

    if( $('#ppm').val() != '') {
        $('#mgm3').attr('disabled', true);

        $(this).calculateMGM3;
    } else {
        $('#mgm3').attr('disabled', false);
    }

    if( $('#mgm3').val() != '') {
        $('#ppm').attr('disabled', true);

        $(this).calculatePPM;
    } else {
        $('#ppm').attr('disabled', false);
    }

    function calculateMGM3() {
        var mol = $('#mol').val();
        var ppm = $('#ppm').val();
        var calcMGM3 = (( ppm * mol ) / 24.45 );
        $mgm3.val( calcMGM3 );
    }

    function calculatePPM() {
        var mol = $('#mol').val();
        var mgm3 = $('#mgm3').val();
        var calcPPM = (( mgm3 * 24.45 ) / mol );
        $ppm.val( calcPPM );
    }
});

<form id="calc">

MG/M³ - PPM Calculator

        PPM
        <input class="value" type="number" name="ppm" id="ppm">

        MG/M³
        <input class="value" type="number" name="mgm3" id="mgm3">

        Molmassa
        <input class="value" type="number" name="mol" id="mol">

</form>

A: I fixed a fair few errors in your code

*

*calculateXX functions were inside the event handler - don't need to be, moved outside

*When calling a method you need parentheses, so changed $(this).calculatePPM to simply calculatePPM() (no idea why you had $(this) in front.

*Added parseFloat to where you're readng numeric values from text fields.

*You were using aliased variables like $ppm but these were not declared anywhere. It is actually good practice to not keep using jQuery selectors, and to cache references to fields in a variable. But to keep the change minimal I have not done this. I suggest you do though.

// formula for ppm =    mg/m3 * 24.45 / mol
// formula for mg/m3 =  ppm * mol / 24.45

 $('input.value').keyup(function(){
    var ppm = $('#ppm');
    var mgm3 = $('#mgm3');
    var mol = $('#mol');

    if( $('#ppm').val() != '') {
        $('#mgm3').attr('disabled', true);

        calculateMGM3();
    } else {
        $('#mgm3').attr('disabled', false);
    }

    if( $('#mgm3').val() != '') {
        $('#ppm').attr('disabled', true);

        calculatePPM();
    } else {
        $('#ppm').attr('disabled', false);
    }
});

function calculateMGM3() {
    var mol = parseFloat($('#mol').val());
    var ppm = parseFloat($('#ppm').val());
    var calcMGM3 = (( ppm * mol ) / 24.45 );
    $('#mgm3').val( calcMGM3 );
}

function calculatePPM() {
    var mol = parseFloat($('#mol').val());
    var mgm3 = parseFloat($('#mgm3').val());
    var calcPPM = (( mgm3 * 24.45 ) / mol );
    $('#ppm').val( calcPPM );
}

<form id="calc">

MG/M³ - PPM Calculator

        PPM
        <input class="value" type="number" name="ppm" id="ppm">

        MG/M³
        <input class="value" type="number" name="mgm3" id="mgm3">

        Molmassa
        <input class="value" type="number" name="mol" id="mol">

</form>

A: Probably not the most efficient way, but this is what I accomplished. Now it seems to work like charm.
jQuery(document).ready(function($) {
    $('input#ppm').keyup(function(){
        if( $('#ppm').val() != '') {
            $('#mgm3').attr('disabled', true);
            calculateMGM3();
        } else {
            $('#mgm3').attr('disabled', false);
        }
    });

    $('input#mgm3').keyup(function(){
        if( $('#mgm3').val() != '') {
            $('#ppm').attr('disabled', true);
            calculatePPM();
        } else {
            $('#ppm').attr('disabled', false);
        }
    });

    $('input#mol').keyup(function(){
        if( $('#mgm3').prop('disabled') ) {
            calculateMGM3();
        }
        if( $('#ppm').prop('disabled') ) {
            calculatePPM();
        }
    });

    function calculateMGM3() {
        var mol = parseFloat($('#mol').val());
        var ppm = parseFloat($('#ppm').val());
        var calcMGM3 = parseFloat(( ppm * mol ) / 24.45 ).toFixed(2);
        $('#mgm3').val( calcMGM3 );
    }

    function calculatePPM() {
        var mol = parseFloat($('#mol').val());
        var mgm3 = parseFloat($('#mgm3').val());
        var calcPPM = parseFloat(( mgm3 * 24.45 ) / mol ).toFixed(2);
        $('#ppm').val( calcPPM );
    }
});


text:
Q: Проблема с четкостью изображения в canvas Впервые использую canvas. При загрузке туда изображения оно получается размытым. Как добиться чтоб оно выглядело также четко как оригинал?

<canvas id="canvas"></canvas>

let elem = document.getElementById("canvas")
let ctx = elem.getContext('2d')
let pic = new Image()
pic.src = "http://afriendinparis.com/wp-content/uploads/2015/06/Vue_Paris.jpg"
let k = (pic.width/pic.height)/17
let width = (pic.width*k).toFixed(0),
    height = (pic.height*k).toFixed(0)
pic.onload = function() {
  /* ctx.imageSmoothingEnabled = false; */
  ctx.drawImage(pic, 0, 0, width, height);
}

Код на https://jsfiddle.net/shegby/L9d61hxf/


text:
Q: C# Replacing "/ with " - double quote backlash with double quote and others I'm trying to parse some HTML that has a bunch of escaped chars inside it, a lot of
\t, \n, \r, and every double quote is escaped by a backslash. Sample HTML:

\n    We're sorry, we were unable to retrieve your requested document or image.

I'm trying to replace these characters by doing this:
 var xpar = new XML.Parser(wConn.RawString.Replace("\\n", "").Replace("\\t", "").Replace("\\r","").Replace("\\\"", "\""))

The parser errs out because there's something else in the HTML it doesn't like, but in the exception the string is the same as it was before, the backslashes are all still there. What am I doing wrong?

A: The problem is that replacement method take \n \r \t as a code and not as text that you want.
You can use a regular expressions to achieve that.
var patternToMatch = "\\\\(n|r|t|\\\")";
var replacement = "";
var escapedString = Regex.Replace(inputString, patternToMatch, replacement);

modify the pattern to match with your requirements but basically this expression can solve your problem.


text:
Q: Create external jar file and add to Netbeans 8.2 We have been trying to create JAR files from the LanguageTool (LT) Desktop version we downloaded that contains various JAR files. LT at this link made the statement that we needed all the files in these folders libs org and META-INF in our project. LT has repied they have no experience with Netbeans or JavaFX.
LT Directions
The app was built on Windows 7 with Netbeans 8.2 as a JavaFX 8 and Maven JDK 1.8
We tried following this tutorial the author was not much for proper code formatting and failed to mention that LT is not thread safe. We seldom work with threads but think our code is correct?
TUTORIAL
To install the Class AmericanEnglish.class which is in the LT Desktop zip file we extracted we used this process
cd  C:\Users\Me\Documents\A A A A A LT UnZip\LanguageTool-4.7\LanguageTool-4.7
jar cf languagesLIBS.jar libs/*
jar cf languagesORG.jar  org/*
jar cf languagesMETA.jar META-INF/*
Here is where it gets odd to our limited knowledge of adding Dependencies to Netbeans
1.  Open the Projects tab.
2.  Right-click on Dependencies.
3.  Select Add dependency.
4.  Set groupId to: language(can be anything)
5.  Set artifactId to: en (can be anything)
6.  Set version to: 4.7(can be anything)
7.  Click Add to continue.
Dependency is added to pom.xml and appears under the Libraries node of Maven project. Continue:
1.  Expand Dependencies.
2.  Right-click on library (e.g., group.id).
3.  Select Manually install artifact.
4.  Set Artifact to install with the Java Archive (.jar) file path.
5.  Click Install locally.
This process did place the AmericanEnglish.class in a JAR and it is found by Netbeans
import org.languagetool.JLanguageTool;
import org.languagetool.language.AmericanEnglish;
import org.languagetool.rules.RuleMatch;
Here is the error when we try to populate the JLanguageTool with AmericanEnglish
While the error NoClassDefFoundError would seem to indicate that the app can not find the
AmericanEnglish.class and that is the cause of the error ClassNotFoundException
Our question obviously is how do we fix this ?
And are we crating the external JAR files correctly?
Exception in thread "Thread-4" java.lang.NoClassDefFoundError: com/google/common/cache/CacheLoader
at com.mycompany.maventest.CheckSpellController.lambda$ini$0(CheckSpellController.java:43)
at java.lang.Thread.run(Thread.java:748)
Caused by: java.lang.ClassNotFoundException: com.google.common.cache.CacheLoader
at java.net.URLClassLoader.findClass(URLClassLoader.java:382)
at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:349)
at java.lang.ClassLoader.loadClass(ClassLoader.java:357)

We also see these warnings when we Clean and Build the project
The POM for languagetool:LIBS:jar:4.7 is missing, no dependency information available
The POM for languagetool:ORG:jar:4.7 is missing, no dependency information available
The POM for languagetool:META:jar:4.7 is missing, no dependency information available
exec-maven-plugin:1.2.1:exec (unpack-dependencies) @ mavenTEST
When the Clean and Build is run we see the dependencies unpack
Here is the few lines of code that cause the error
static JLanguageTool langTool;

public void ini(){
  new Thread(() -> {
      langTool = new JLanguageTool(new AmericanEnglish());
  }).start();
}

The ini() method is called from the initialize method

The necessary JAR files are in the Dependencies folder
The project imports these files

A: You need to use the actual JAR and the process where you thought it was a bit ODD
Is not the correct way to add JAR files. The extracted ZIP folder has all the gold or should we say JAR's. Here are a few screen shots and directions. That said we are still getting the NoClassDefFoundError so we will work on fixing that part of the question
Delete the three JAR's you added LIBS-4.7.jar META-4.7.jar and ORG-4.7.jar
We would also suggest opening the .m2 folder and under /repository/org/languagetool delete the languagetool folder. Do NOT worry everything will get recreated.
Right Click Dependencies folder and select Add Dependency
In the Query text field enter "org.languagetool"
Here is a comment we did not find languagetool 4.7 JAR's as central only local ? ?
You might like to try and use the central 4.6 JAR's
Expand the org.languagetool:languagetool-core folder and select the 4.7.jar
Once that JAR is in the Dependency folder Right Click ad select Copy Location
Now Right Click the same JAR once more and select Manually Install Artifact
In the Artifact To Install text box paste with a Ctrl + V
This will take you to the location of the JAR select it and presto magic the Artifact is added
Notice the language-en-4.7 we created this JAR file because we could not find AmericanEnglish.class in any of the downloaded files. See Last screen shot
Here are the screen shots in the order to match the above direction

I am not holding my breath that using the downloaded 4.7 JAR,s is the best idea
You might try reaching out to Maven and Language Tool and ask why LT 4.7 is not in the repository!
Best of Luck


text:
Q: in php, what will happen if CURLOPT_CAPATH is not set when CURLOPT_SSL_VERIFYPEER is set to true The problem is about using curl in PHP.
Some other answers said that curl will reject any ssl connection, however, I can send https requests as normal.
curl.cainfo in php.ini is not set.
Will curl use system default ca bundle when CURLOPT_CAPATH is not set?

A: From the documentation:
CURLOPT_CAINFO

This option is by default set to the system path where
libcurl's cacert bundle is assumed to be stored, as
established at build time.

So, if your system stores the cacert bundle in the default location, which is likely /etc/ssl/certs/, then it should find it.

A: Here you can use CURLOPT_CAPATH Like below.

You have to give path of your SSL Certificate in this line curl_setopt($curl_handle, CURLOPT_CAINFO, "/etc/pki/tls/cert.pem");

$curl_handle=curl_init();
curl_setopt($curl_handle, CURLOPT_URL,$link);
curl_setopt($curl_handle, CURLOPT_CONNECTTIMEOUT,2);
curl_setopt($curl_handle, CURLOPT_VERBOSE, true);
curl_setopt($curl_handle, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl_handle, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($curl_handle, CURLOPT_CAINFO, "/etc/pki/tls/cert.pem");
$buffer = curl_exec($curl_handle);
$buffer_decode = json_decode($buffer);
curl_close($curl_handle);


text:
Q: SNMP pass-through command not returning with snmpget I am trying to get some scripts working in my snmpd.conf file using pass, however calling snmpget on the OID is returning
No Such Instance currently exists at this OID

in the snmpd.conf I have
pass .1.3.6.1.4.1.13732.100.2.1  /bin/sh       /usr/share/snmp/local/terminal

and when I call
snmpget -c public -v2c 127.0.0.1 .1.3.6.1.4.1.13732.100.2.1.1

I get the no such instance error. Why does the snmpget not seem to find the pass in the conf file and use the script?
It is able to find the OID in the MIB because the snmpget returns the MIB plus the object name with the error
Please let me know if any more info is needed to help answer this question

A: You can debug snmpd by starting it foreground as snmpd -f -Lo -Ducd-snmp/pass.
Add the below lines to /etc/snmpd.conf
rocommunity testCommunityString localhost
pass .1.3.6.1.4.1.13732.100.2.1  /bin/sh /home/user/smpd_pass/test.sh

Download sample pass script and change PLACE asPLACE=".1.3.6.1.4.1.13732.100.2.1" to create test.sh pass script.
Now running snmpwalk -c testCommunityString -v2c 127.0.0.1 .1.3.6.1.4.1.13732.100.2.1 would show the values defined in the file.


text:
Q: countably compact if $(X,\tau)$ is not countably compact.
is the below topology $T_1$ space and countably compact?
$$\mu = \{U\in\tau:p\notin U\}\cup\{U\in\tau: p\in U\text{ and }X\setminus U\text{ is countably compact in }(X,\tau)\}$$

A: Certainly $\langle X,\mu\rangle$ need not be $T_1$ if $\tau$ is not $T_1$. If $\tau$ is $T_1$, then $\mu$ is $T_1$; to see this, just show that for each $x\in X$, $\{x\}$ is closed in $\langle X,\mu\rangle$. HINT: Finite sets are always compact.
To show that $\langle X,\mu\rangle$ is countably compact, proceed in the most straightforward fashion: let $\mathscr{U}$ be a countable $\mu$-open cover of $X$. There must be some $U_0\in\mathscr{U}$ such that $p\in U_0$. Clearly $\mathscr{U}\setminus\{U_0\}$ is a $\mu$-open cover of $X\setminus U_0$. What do you know about the set $X\setminus U$?


text:
Q: jQuery hide/show specific div element This is my html code

Солодкі млинці з яблучним варенням.

                        200 г    714 ккал

Млинці з сиром та курагою

                    Weight:
                    200 g

Солодкі млинці з яблучним варенням.

                        200 г    714 ккал

Млинці з сиром та курагою

                    Weight:
                    200 g

When user clicked on H2 tag (with 'product_title' class) , then
hid the DIV element (with class 'product_details') of that Article tag
not other Div element outside this Article .tag
This is my jQuery code:
jQuery('.product_details').hide();
jQuery('.product_title').click(function(e){
e.preventDefault();
// hide all span
var $this = jQuery(this).parent().find('div');
jQuery(".product_details").not($this).hide();

// here is what I want to do
$this.toggle();

});

But this code is not working properly

A: You may use .prev() method for this like:
$('.product_title').click(function(){
   $(this).prev('.product_details').hide();
})

Using $(this) we are only targeting product_details div before the currently clicked product_title element.

A: The element you want to target is a sibling of the element that triggers the click event, so you can use the .siblings() method to select the previous element, or you can also travel the dom to the parent element (article) then select the element you want to target via .find() method :
$(".product-title").on('click', function () {
  $(this).siblings('.product-details').hide('fast');
});
// OR
$(".product-title").on('click', function () {
  $(this).closest('article').find('.product-details').hide('fast');
});


text:
Q: C# simple Event Raising - using "sender" vs. custom EventArgs Consider this scenario.  I have an object, lets call it.... Foo.  Foo raises a simple event named "Loaded".  As part of the information for the event, consumers will need to know which foo object raised the event.  Our team has adopted the following pattern.
1)  Create a new class that inherits from EventArgs - for example,
    FooEventArgs : System.EventArgs.
2)  Add a property of type Foo to the FooEventArgs, which is set by being passed in via the constructor.
3)  Declare the event using the generic version of EventHandler, so
public event EventHandler<FooEventArgs> Loaded;

4)  Raise the event from the Foo class with the following signature:
Loaded(this, new FooEventArgs(this));

Essentially what this does is makes the "sender" the foo object, but it also puts the foo object reference into the event argument as a strongly typed property.
One advantage for doing this is that no one has to bother with casting "sender" when they handle the event, which lowers the coupling between the event consumer and the event raiser.  Another "advantage" is that if the type of the event raiser ever has to change, and hence the strongly typed property (which hopefully never happens), then instead of simply having code start to fail on the cast when it comes out as null, the API actually breaks so it can be fixed at compile time.
To me, this pattern seems like it might be overkill.  Should they be trusting the "sender" parameter more, and ditching the custom event arguments?  My team argues that no one really uses the sender parameter.  What's the best practice for passing out a reference to the event-raising object?
EDIT:  Great feedback so far, I'll leave this open for another day or so before I accept one.

A: The common pattern is to use sender and not add the sender separately to the EventArgs. The custom EventArgs is used for other state like a tree node for a tree event, a (settable) boolean for a cancelable event etc.
We use the common pattern since it is used by the BCL classes also, and making a difference for "self-made events" is potentially confusing. Also, we have a global IoC publisher-subscriber pattern but this one only works with the normal EventHandler delegate signature, since the types are not known in advance. In this case, a cast (for instance to a custom EventArgs) is necessary anyways, so we might just as well cast the sender.

A: I don't think this is overkill.  I agree with the advantages you state for having a separate FooEventArgs class.  One other advantage to doing it that way is that if you need to add more information to the event in the future you can just add more properties to the FooEventArgs and you don't need to change the delegate.

A: I would say that you drop the subclass of EventArgs and use the sender property to identify the sender of the event.  I think that the argument for following convention has merit, but the parameter in the EventArgs is not necessary.  I personally would drop it and just use the sender property.
If you want to pass it as a strong type, you could also just create a custom delegate to use for your event...
public delegate void LoadedHandler(FooEventArgs args);

that way you could have it as a strong type...  reusing delegates is great, but if they don't fit what you are trying to do you shouldn't feel constrained to only use the built in ones.

A: As far as recommended practices go, I've seen null supplied as sender in Windows Workflow Foundation quite a lot.  Ideally, your subscribers should be oblivious of the object that raises events.
So if you'd need to pass the caller object as a whole to handlers, you'd have to place it in an EventArgs-derived object.  Alternately, I prefer to explicitly pass the bits and pieces of Event raiser's/caller's state instead of the whole thing.
Well, sometimes it's easier to think dotNET 1.1, where
Control.Invoke()

is used as frequently as
int i;

A: I would say convention has a lot going for it. There is less to maintain in the longer run - esp. if you get new people in.

A: I guess it's a matter of preference to some degree but in my case when I read the consumers will need to know which foo object raised the event. I immediately thought that you can get the object which raised the event from the sender argument so what's the problem?
Your team has some valid points (in having strongly typed property), but I'd say that working with the framework guidelines instead of inventing your own would be a better decision in the long run.


text:
Q: GNotifier broke my Thunderbird profile I installed the GNotifier extension to Thunderbird.  The resulting notifications did not leave a persistent sign anywere in the GNOME desktop interface, which is what I installed GNotifier for.
When I removed GNotifier, I stopped receiving email popup notifications.  I tried reinstalling GNotifier, resetting the notification type to Thunderbirds default, and removing GNotifier again, but for some reason that didn't seem to work for me either.
I don't want to wipe my Thunderbird profile, but I want my mail notifications back!  Help!

A: Preferences -> Advanced -> Config Editor
Reset mail.biff.show_alert. After resetting it, the value will be true.

There were so many "user set" preferences, I had to search for "notif" and then "alert" before I found the problem.
("biff is a mail notification system for UNIX", in case you're puzzled where than name comes from).


text:
Q: Bottleneck when inserting many rows into different tables TLDR: I want to bulk insert into many initially empty tables at once, without the performance of each insert being affected too badly. I seem to be hitting a performance bottleneck I can't yet explain. I am looking for performance debugging avenues or advice on parallel inserts in Postgres.

I am prototyping a system and trying to import data into many Postgres tables at once as fast as possible. My example table has 100 columns (all short strings) and 20k rows. I can insert this data into a fresh Postgres table in around 30 seconds (*). However, if I run the same insert script 10 times against different (unrelated) tables, the performance of each individual insert drops dramatically - up to around 3.5 minutes for each table. The total insert (3 tables per process, 10 processes) takes around 8 minutes, so I am getting less than 2x speedup by running these queries in parallel vs. running them all one after the other for 30s each. I was hoping to get ~10x speedup with 10 parallel unrelated imports, until I reach some resource limit of the database host.
I am using an SSD-based Google Cloud SQL database with Postgres 12, 20vcpus and 75GB memory. While handling my 10 parallel fills, it uses less than 15% CPU, around 200 write ops per second (I am not clear what counts as one op in GCP), and around 10-15MiB/s data ingress. None of these feel like they should be a bottlneck for a relatively beefy host instance, but I can't understand what is slowing down these queries.
What should I check to investigate this bottleneck, and what should I be doing to import many tables in parallel efficiently?
My ideal solution would be to use 10x as much CPU (or whatever other resource) on the host instance, and complete the 10 parallel table loads in roughly the same time as a single one. I am hoping to be able to reach around 200 imports in parallel, even if it has to be spread over a few separate database hosts (non-ideally).
It seems clear that it is not (yet) CPU bound; att the tables at once can fit into memory a few times over, so it is not memory bound. I would be surprised to find it is IO or disk bound at this scale, but I don't know how to check or investigate these.
All the information I have been able to find has been about improving the speed of a single-table insert. Some examples:

*

*Populating a Database

*How to speed up insertion performance in PostgreSQL

*What's the fastest way to do a bulk insert into Postgres?
I haven't found anything addressing concurrent inserts into separate tables or databases on the same host.
I also tried having my 10 client processes import data into differewnt databases to each other, with almost exactly the same performance.
I tried switching my tables to be UNLOGGED. This made a big improvement to the speed when running 10 imports in parallel (down to around 45 seconds), but running 20 imports immediately jumped back up to 2-4 minutes per table.

(*) Currently for each single-table load I am using a single insert statement with all the rows at once:
insert into test_table values ('id1', 'Sample data 1', ...), ... ('idN', 'Sample data N', ...);

I have also tried bulk loading from a CSV file via copy, inserting in batches of 100 or 1000 records at a time, and increasing the power of the host instance, none of which makes any significant difference on my example. The tables have an externally-specified primary key and no other constraints. But improving the performance of a single-table import is not what this question is about!


text:
Q: SELECT Statement with if-else condition I want to modify sql statement which is very simple like
SELECT id
FROM page
WHERE name = "Test"

Now I want to change it something like
SELECT id
FROM page
WHERE name = "Test"
AND if idLanguage != idlanguage then idParent = idpage

what will the better way to do this?
Thank you

A: SELECT id
FROM page
WHERE name = "Test"
AND (idLanguage = idlanguage OR idParent = idpage)

is better because it is valid SQL syntax.

A: How about using a case statement? Please try:
SELECT id
FROM page
WHERE name = "Test" AND
idParent = (CASE WHEN idLanguage <> idlanguage THEN idpage ELSE idParent END)

A: If you're actually wanting to set the value of idParent in the database then you need an UPDATE statement before your select.
UPDATE page SET idParent = idpage
WHERE name = "Test"
    AND idLanguage != idlanguage;

SELECT id FROM page
WHERE name = "Test"


text:
Q: Little doubt in the proof of theorem" If f is analytic on $\mathbb D$, , then there exist analytic function h such that $h^2=f$. I have one little doubt in the proof of following theorem which I am reading from one article.
Notation: $\mathbb D = \{ z \in \mathbb C :  |z| < 1\}$
Theorem: If f is analytic on  $\mathbb D$, with $0 \notin f(\mathbb D)$, then there exist analytic function h on $\mathbb D$ such that $h^2=f$.
The proof starts like this. They have defined new function g on $\mathbb D$ as follows:
Take $g(0)$ such that $e^{g(0)}=f(0)$, and for other w in $\mathbb D$, define $g(w)= g(0)+\int_\gamma \frac{f'(z)}{f(z)} dz$, where $\gamma$ is smooth curve from $0$ to $w$. Then, clearly we have $g'(w)=\frac{f'(w)}{f(w)}$ and thus $g'(z)$ is well defined for all $z \in \mathbb D$, and thus $g$ is analytic on $\mathbb D$. Now here is my little doubt. Their explanation does not justify why $g$ is analytic at $0$, i.e. why $g$ is differentiable at $0$. Can someone help me out this.

A: Hint: $f (0) \neq 0$ so there exists $r>0$ such that $|f(z)| >r$ whenever $|z|$ is sufficiently small. Now verify that $g(w) \to g(0)$as $w \to 0$ by estimating the integral $\int_{\gamma} \frac {f'(z)} {f(z)}dz$. This implies that $g$ is necessarily analytic at $0$ also.
[Boundedness of $g$ in a neighborhood of $0$ implies that it has a removable singularity at $0$ and continuity now implies that $g$ is analytic at $0$].

A: You can let the smooth curve be $\gamma(t) = tw, t\in [0,1].$ Then
$$\frac{g(w)-g(0)}{w} = \frac{1}{w}\int_0^1 \frac{f'(tw)}{f(tw)}w\,dt=\int_0^1 \frac{f'(tw)}{f(tw)}\,dt.$$
As $w\to 0,$ the last integral $\to \dfrac{f'(0)}{f(0)}$ by the continuity of $f'/f$ at $0.$


text:
Q: Change loops on 2D List to LINQ I am relatively new to C# and newer to LINQ. I haven't found a good way to do this using LINQ (meaning an example on here that does almost exactly this, lol), but it seems like there should be a way to eliminate one of my loops.
I have a 2D List of List. I want to make a 2D List of averaged chunks of data of each of the sub Lists.
Example input:
averageSize = 2
input List = {{1,2,3,4},
 {5,6,7,8},
 {9,10,11,12}}
expected output List:
{{1.5,3.5},
 {5.5,7.5},
 {9.5, 11.5}}
I have working code with a foreach loop and a for loop. waveData is the input 2D list, averageSize is the number of values to average together
            int tempIndex = 0;
        List<List<double>> averages = new List<List<double>>();
        foreach (List<double> phaseData in waveData)
        {
            averages.Add(new List<double> { });
            for (int i = 0; i <= (phaseData.Count-averageSize); i+= averageSize)
            {
                averages[tempIndex].Add(phaseData.GetRange(i, averageSize).Average());
            }
            tempIndex++;
        }

A: Batch extension method from MoreLINQ package is exactly what you need. It takes the source enumerable and divides it into batches of given size.
Resulting LINQ expression will look like this:
public List<List<double>> CalculateBatchAverages(List<List<double>> data, int batchSize = 2)
{
    return data.Select(list => list
            .Batch(batchSize)
            .Select(batch => batch.Average())
            .ToList())
        .ToList();
}


text:
Q: Why cassandra-topology.properties "should be exactly the same on every node in the cluster"? According to the Datastax documentation, for PropertyFileSnitch, this property file: cassandra-topology.properties "should be exactly the same on every node in the cluster" (Datastax Documentation)
Why is it so and is this requirement really strict?
Context:  I would like to be able to provide different IPs for the same target node, depending on where the calling node (with the property file) is located. This is needed because of a complicated hybrid cloud/onpremise cluster and I want to avoid static public IPs.

A: This snitch gives you more control and better performance.
The nodes that are not identified here will be assumed to be in the default dc and rack.
Pleease note these explanations from the "Cassandra: The Definitive Guide", by Jeff Carpenter & Eben Hewitt, O'Reilly, June 2016, 2nd edition, p.138  regarding this matter.

Update the values in this file to record each node in your cluster to
  specify which rack contains the node with that IP and which data
  center it's in. Although this may seem difficult to maintain if you
  expect to add or remove nodes with some frequency, remember that it's
  one alternative, and it trades away a little flexibility and ease of
  maintenance in order to give you more control and better runtime
  performance, as Cassandra doesn't have to figure out where nodes are.
  Instead, you just tell it where they are.