text:
Q: Adding horizontal scroll to a table whose columns are dynamically created I have a html table as below:

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

    <input type="button" value="Remove Row" data-bind="click: $parent.removeRow" class="btn btn-danger" />

The columns to these are generated dynamically via a knockout JS code. The columns can be ranging from 3 (minimum) to 20 something. So I am trying to add a horizontal scrollbar to it so that user can scroll to right. I also want to set a fixed width of column say 20%.
Below is my JS fiddle which I have.
https://jsfiddle.net/aman1981/6fjcuhcf/41/
But I have tried many changes to the css but its not adding scroll not its keeping the columns width fixed.
Please see I have used suggestions as per Add horizontal scrollbar to html table
But its not adding scroll. What else am I missing here?

A: I was able to add scroll and make my columns fixed width using this css:


text:
Q: How to recreate fragments (onCreate) in paging using FragmentStatePagerAdapter I'm stuck in a weird situation where I want the fragments to be recreated when paging is performed. I'm using FragmentStatePagerAdapter.
For example if I use 2 seekbars in 2 different fragments, I want the seekbar in second fragment to update itself according to the value of seekbar in the first fragment.
Without the paging method I'm using a static global variable that updates the seekbars when the fragments are created.
So when I use action bars with tabs i get expected results becasue when I cahnge tabs the fragments are created newly each time.
Now if I use paging method to swipe between these 2 fragments, the fragment states are retained and they dont update as expected becasue the onCreate is not called at all.
I've used
@Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}

in my extended FragmentStatePagerAdapter Class but no use.
What's the work around for this.
Please help!

redpajama_set_name: RedPajamaStackExchange


text:
Q: AWS Cognito Hosted disable account confirmation Currently with my Cognitio hosted mode there are a few options I am looking for.

*

*Can it disable having the require the account to be confirmed, or better, confirmed afer the initial login.

*After clicking the confirmed link in the email they have to then reenter their password, which they have forgotten by now (in 1 minute). Is it possible to stay logged in after clicking confirm?


text:
Q: При появлении клавиатуры NavigationBar появляется над клавиатурой NavigationBar поднимается над клавиатурой, а должен бать под ней

fragment xml
<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="@color/main_color"
xmlns:app="http://schemas.android.com/apk/res-auto"
tools:context=".ui.fragments.CreateFragment">

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <com.google.android.material.textfield.TextInputLayout
        android:id="@+id/name"
        style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:hint="@string/game_name"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="parent"
        app:errorEnabled="true"
        app:counterMaxLength="50">

        <com.google.android.material.textfield.TextInputEditText
            android:id="@+id/name_edit_text"
            android:maxLength="50"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />

    </com.google.android.material.textfield.TextInputLayout>

    <com.google.android.material.textfield.TextInputLayout
        android:id="@+id/description"
        style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:hint="@string/game_description"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="parent"
        app:counterEnabled="true"
        app:errorEnabled="true"
        app:counterMaxLength="500">

        <com.google.android.material.textfield.TextInputEditText
            android:id="@+id/description_edit_text"
            android:maxLength="500"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />

    </com.google.android.material.textfield.TextInputLayout>

    <com.google.android.material.textfield.TextInputLayout
        android:id="@+id/author"
        style="@style/author"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:hint="@string/game_author"
        app:helperTextEnabled="true"
        app:helperTextTextColor="@color/design_default_color_error"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="parent">

        <AutoCompleteTextView
            android:id="@+id/author_spinner"
            android:inputType="none"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />

    </com.google.android.material.textfield.TextInputLayout>

    <com.google.android.material.textfield.TextInputLayout
        android:id="@+id/genre"

  style="@style/Widget.MaterialComponents.TextInputLayout.OutlinedBox.ExposedDropdownMenu"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_margin="10dp"
        android:hint="@string/game_genre"
        app:helperTextEnabled="true"
        app:helperTextTextColor="@color/design_default_color_error"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toBottomOf="parent">

        <AutoCompleteTextView
            android:id="@+id/genre_spinner"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:inputType="none" />

    </com.google.android.material.textfield.TextInputLayout>

    <Button
        android:id="@+id/edit"
        style="@style/Widget.Material3.Button.OutlinedButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/edit"
        android:layout_gravity="center_horizontal"
        android:layout_marginTop="10dp"

        />
</LinearLayout>
</ScrollView>

Activity xml:
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".ui.BaseActivity"
android:background="@color/main_color">

<TextView
    android:id="@+id/label"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_marginTop="16dp"
    android:layout_weight="1"
    android:gravity="center"
    android:text="@string/game_list"
    android:textColor="@color/white"
    android:textSize="35sp"
    android:textStyle="bold"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent" />

<fragment
    android:id="@+id/nav_host_fragment"
    android:name="androidx.navigation.fragment.NavHostFragment"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    android:layout_marginTop="16dp"
    app:defaultNavHost="true"
    app:layout_constraintBottom_toTopOf="@+id/navigation_bar"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@+id/label"
    app:navGraph="@navigation/navigation_bar" />

<com.google.android.material.bottomnavigation.BottomNavigationView
    android:id="@+id/navigation_bar"
    style="@style/navigationBar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_gravity="bottom"
    android:background="@color/main_color"
    app:itemIconTint="@color/icons_color"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toEndOf="parent"
    app:menu="@menu/menu_material" />

</androidx.constraintlayout.widget.ConstraintLayout>

Пробывал вставлять android:isScrollContainer="false" не помогло
Как это можно пофиксить?


text:
Q: Simple Unity3d app get stucked on Android I have a rather simple game in Unity3d. The game has about 300 3D objects - all of them have physics, some use cloth.
I am able to open the game on my Android phone, but the app get sucked after 2-3 minutes. The game works fine on my PC.
What am I doing wrong and what can I do to solve this issue?

A: You could use shared material technique, static or dynamic batching, GC.Collect() method and other techniques to improve the performance (you may find them by googling or here: https://unity3d.com/learn/tutorials/topics/performance-optimization). Anyway, I would suggest taking a look at Unity's profiler (biult-in) to find the bottlenecks of the app.


text:
Q: Thumbnail handler not called for embedded thumbnail I wrote a thumbnail extension handler for jpeg files for windows 10. I registered the handler to handle ".jpg" files. Thumbnails for ".jpg" files are displayed correctly. However, I noticed that on some ".jpg" files my handler is being called and on others it doesn't.
I understand now that the reason my handler is not being called is because the non-working jpeg files contain an embedded thumbnail inside them. I tried to remove the embedded thumbnail using exiftool:
exiftool.exe -thumbnailimage= c:\test\test.jpg
exiftool.exe -photoshopthumbnail= c:\test\test.jpg
Once the embedded thumbnail is removed, my handler is being successfully called by explorer. If explorer is not using the thumbnail handler to extract embedded thumbnails, how does it do it? Which handler retrieves it?


text:
Q: Select 2 tables with one select query I have 2 tables on my database. One table has categories and the other one has posts. In the category table I have a column called "active".
What I'm trying to do, is to select all posts which have category=0.
Here's the select that I got so far:
SELECT tb_posts.*, tb_categories.active
FROM tb_posts, tb_categories
WHERE tb_categories.active='0'
ORDER BY datapub DESC

The above query doesn't work as it loads all posts not matter the category status. :(

A: You need a left join:
SELECT tp.*, tc.active
FROM tb_posts tp
LEFT JOIN tb_categories tc ON tb.category_id = tc.id
WHERE tc.active='0'
ORDER BY datapub DESC

The join is done on the category column (replace with proper column name - this was my guess) which is (probably) referencing the id in the tb_categories (again, replace the name).
For an exact query, please show your table structures.


text:
Q: Symfony2 Overriding Controllers I use the FOSUserBundle and I want to override his registerAction controller.
I read the documentation related to overriding controllers of FOSUserBundle but it doesn't work. By echoing a little message in the controller, it is not print in the template.
Here is the way I chose :
I inherit my bundle from FOSUserBundle :
namespace Jheberg\MembersBundle;

use Symfony\Component\HttpKernel\Bundle\Bundle;

class JhebergMembersBundle extends Bundle
{
    public function getParent()
    {
        return 'FOSUserBundle';
    }
}

And I override registerAction in the file named RegistrationController.php in the controller directory of my bundle :
namespace Jheberg\MembersBundle\Controller;

use FOS\UserBundle\Controller\RegistrationController as BaseController;

class RegistrationController extends BaseController
{
    public function registerAction()
    {
        echo 'foo';
        $response = parent::registerAction();

        // do custom stuff

        return $response;
    }
}

Have you got any solution ?

A: Just spent hours trying to get this working and finally figured it out. The part I was missing was extending my User class with a User entity from within MyUserBundle. For instance:
namespace MyNamespace\MyMainBundle\Entity;

use MyNamespace\MyUserBundle\Entity\User as BaseUser;

class User extends BaseUser
{
}

The User entity is identical to the one in the FOSUserBundle (just with a different namespace).
namespace MyNamespace\MyUserBundle\Entity;

use FOS\UserBundle\Model\User as AbstractUser;

abstract class User extends AbstractUser
{
}

If I didn't do this, as Jeffrey mentioned, MyUserBundle wasn't used at all (as if it didn't exist). Now all my overridden views, controllers etc. are being used. Hope this helps.

A: It doesnt work for me. i try to do your solution. Finally i just clear the cache runnig the php bin/console cache:clear inside of my proyect of course. And func like a charm.
So.. try to clear the cache.
And sorry for my bad english.


text:
Q: Python selenium. How do I tell selenium to wait until a key is clickable? for example:
driver.find_element_by_css_selector('#yes')
# wait until it's done loading and then it'll be available to click again
driver.find_element_by_css_selector('#yes')

this is the loading element when it's not loading. When it's loading display: block
<div id="loading" style="display: none;">

A: There is a method built into the selenium library to do just that:
element = WebDriverWait(driver, [TimeToWait]).until(
EC.presence_of_element_located((By.ID, "ElementName"))


text:
Q: Behavior of the integral of products of probability densities Assume $z \in \mathbb{R}^m$ and $x \in \mathbb{R}^n$. Assume we have proper density function $P(z)$ and proper conditional density function $P(x|z)$. We give the definition
$$
T(x_1,\ldots,x_n) := \int_{\mathbb{R}^m}P(z)\prod_{i=1}^nP(x_i|z)dz
$$
Therefore we have a group of functions $T(x_1),T(x_1,x_2),\ldots$.
What are the behaviors of such a group of functions? I mean, if we only have a group of functions $T(x_1),T(x_1,x_2),\ldots$ without knowing $P(z)$ and $P(x|z)$, can we judge if these functions can be obtained by some $P(z)$ and $P(x|z)$?
Are there any papers that can help?

A: I believe this can be answered using de Finetti's Theorem about infinite sequences of independent exchangeable random variables.  The theorem states that such sequences are conditionally independent given "the sigma field at infinity".  Suppose we construct a sequence of random variables $X_1,X_2,\dots$ having as their joint distribution the integral representations above.   This implies  exchangeability of the $X$'s and and the sigma field at infinity then captures the conditioning information represented by $z$ in the integral.  Conversely, given not the integral form itself but the functions $T(x_1,x_2,\dots,x_n)$, if and only if they are symmetric in their arguments and they satisfy the "marginal consistency condition" that when you integrate out one of the variables the result is consistent with the joint distribution with one fewer arguments, then an exchangeable sequence of random variables $X_1,X_2,\dots$ having finite-dimensional marginals given by $T$  may be constructed.  De Finetti's theorem says that the $X$'s are conditionally independent given the sigma field at infinity.  This would give an integral representation of the form you describe, where the integral is over the sigma field at infinity.


text:
Q: c# HttpWebRequest and HttpWebResponse generic stuff I am playing around with an app using HttpWebRequest to dialog with a web server.
I followed standard instructions I found on the web to build my request function that I tried to make as generic as possible (I try to get a unique method regardless of the method:  PUT, POST, DELETE, REPORT, ...)
When I submit a "REPORT" request, I get two access logs on my server:
1) I get response 401 after following line is launched in debugger
reqStream.Write(Encoding.UTF8.GetBytes(body), 0, body.Length);

2) I get response 207 (multi-get, which is what I expect) after passing the line calling Request.GetResponse();
Actually, it seems to be the Request.GetRequestStream() line that is querying the server the first time, but the request is only committed once passing the reqStream.Write(...) line...
Same for PUT and DELETE, the Request.GetRequestStream() again generates a 401 access log on my server whereas the Request.GetResponse(); returns code 204.
I don't understand why for a unique request I have two server access logs, especially one that seems to be doing nothing as it always returns code 401... Could anybody explain what is going on? Is it a flaw in my code or a bad design due to my attempt to get a generic code for multiple methods?
Here is my full code:
public static HttpWebResponse getHttpWebRequest(string url, string usrname, string pwd, string method, string contentType,
                                       string[] headers, string body) {
  // Variables.
  HttpWebRequest Request;
  HttpWebResponse Response;
  //
  string strSrcURI = url.Trim();
  string strBody = body.Trim();
  try {
    // Create the HttpWebRequest object.
    Request = (HttpWebRequest)HttpWebRequest.Create(strSrcURI);

    // Add the network credentials to the request.
    Request.Credentials = new NetworkCredential(usrname.Trim(), pwd);

    // Specify the method.
    Request.Method = method.Trim();

    // request headers
    foreach (string s in headers) {
      Request.Headers.Add(s);
    }

    // Set the content type header.
    Request.ContentType = contentType.Trim();

    // set the body of the request...
    Request.ContentLength = body.Length;
    using (Stream reqStream = Request.GetRequestStream()) {
      // Write the string to the destination as a text file.
      reqStream.Write(Encoding.UTF8.GetBytes(body), 0, body.Length);
      reqStream.Close();
    }

    // Send the method request and get the response from the server.
    Response = (HttpWebResponse)Request.GetResponse();

    // return the response to be handled by calling method...
    return Response;
  }
  catch (Exception e) {
    throw new Exception("Web API error: " + e.Message, e);
  }


text:
Q: Flow with SharePoint Online I have a list where I'm running a workflow created on MS Flow.
I am using "start and wait for approval action" for an approval process.
But with the approval, I also want to give the feature of adding an attachment along with the comments to the approver who approves the task.
Can some one please help me with it.

A: It is currently not achievable with OOB Flow since we cannot modify the approval progress to accept "Add attachment" action.
Plus, if the item is approved, it will trigger another content approval request when the approver modify the list item. If it is not approved, the approver won't even have the ability to modify the item.
There are certain posts with similar suggestion in the Power Automate feedback forum. You can vote for the post below to help improving this product:
Add attachment in FLOW Approval notification.


text:
Q: Changing config and loading Hugging Face model fine-tuned on a downstream task I am using HuggingFace models for TokenClassification task. I have the following label2id mapping. I am using version 3.3.0 of the library
label2id = {
    "B-ADD": 4,
    "B-ARRESTED": 7,
    "B-CRIME": 2,
    "B-INCIDENT_DATE": 3,
    "B-SUSPECT": 9,
    "B-VICTIMS": 1,
    "B-WPN": 5,
    "I-ADD": 8,
    "I-ARRESTED": 13,
    "I-CRIME": 11,
    "I-INCIDENT_DATE": 10,
    "I-SUSPECT": 14,
    "I-VICTIMS": 12,
    "I-WPN": 6,
    "O": 0
  }

The following scenario works well and the model gets loaded correctly.
from transformers import AutoModelForTokenClassification, AutoTokenizer, AutoConfig

pretrained_model_name = "bert-base-cased"
config = AutoConfig.from_pretrained(pretrained_model_name)

id2label = {y:x for x,y in label2id.items()}
config.label2id = label2id
config.id2label = id2label
config._num_labels = len(label2id)

model = AutoModelForTokenClassification.from_pretrained(pretrained_model_name, config=config)

model

I get the following output. The last layer have been correctly initialized with 15 neurons (numer of token category to predict).
.....................
      (dropout): Dropout(p=0.1, inplace=False)
      (classifier): Linear(in_features=768, out_features=15, bias=True)
    )

but if I changed the pretrained_model_name to "dbmdz/bert-large-cased-finetuned-conll03-english", I am getting the following error
loading weights file https://cdn.huggingface.co/dbmdz/bert-large-cased-finetuned-conll03-english/pytorch_model.bin from cache at C:\Users\anu10961/.cache\torch\transformers\4b02c1fe04cf7f7e6972536150e9fb329c7b3d5720b82afdac509bd750c705d2.6dcb154688bb97608a563afbf68ba07ae6f7beafd9bd98b5a043cd269fcc02b4
All model checkpoint weights were used when initializing BertForTokenClassification.

All the weights of BertForTokenClassification were initialized from the model checkpoint at dbmdz/bert-large-cased-finetuned-conll03-english.
If your task is similar to the task the model of the checkpoint was trained on, you can already use BertForTokenClassification for predictions without further training.

---------------------------------------------------------------------------
RuntimeError                              Traceback (most recent call last)
<ipython-input-15-2969a8092bf4> in <module>
----> 1 model = AutoModelForTokenClassification.from_pretrained(pretrained_model_name, config=config)

C:\ProgramData\Anaconda3\envs\arcgis183\lib\site-packages\transformers\modeling_auto.py in from_pretrained(cls, pretrained_model_name_or_path, *model_args, **kwargs)
   1372         if type(config) in MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING.keys():
   1373             return MODEL_FOR_TOKEN_CLASSIFICATION_MAPPING[type(config)].from_pretrained(
-> 1374                 pretrained_model_name_or_path, *model_args, config=config, **kwargs
   1375             )
   1376

C:\ProgramData\Anaconda3\envs\arcgis183\lib\site-packages\transformers\modeling_utils.py in from_pretrained(cls, pretrained_model_name_or_path, *model_args, **kwargs)
   1047                 raise RuntimeError(
   1048                     "Error(s) in loading state_dict for {}:\n\t{}".format(
-> 1049                         model.__class__.__name__, "\n\t".join(error_msgs)
   1050                     )
   1051                 )

RuntimeError: Error(s) in loading state_dict for BertForTokenClassification:
    size mismatch for classifier.weight: copying a param with shape torch.Size([9, 1024]) from checkpoint, the shape in current model is torch.Size([15, 1024]).
    size mismatch for classifier.bias: copying a param with shape torch.Size([9]) from checkpoint, the shape in current model is torch.Size([15]).

The only difference I could see is the model dbmdz/bert-large-cased-finetuned-conll03-english is already finetuned on TokenClassification task and it model config has these label2id mappings
label2id = {
    "B-LOC": 7,
    "B-MISC": 1,
    "B-ORG": 5,
    "B-PER": 3,
    "I-LOC": 8,
    "I-MISC": 2,
    "I-ORG": 6,
    "I-PER": 4,
    "O": 0
  }

But still I feel that we can change the last layer of this model and use it for my specific task (although I need to train the model first before using it for inferencing)

A: Once a part of the model is in the saved pre-trained model, you cannot change its hyperparameters. By setting the pre-trained model and the config, you are saying that you want a model that classifies into 15 classes and that you want to initialize with a model that uses 9 classes and that does not work.
If I understand correctly you want to initialize the underlying BERT from a different classifier. A workaround that can do it is:

*

*Load only the underlying BERT without the classification layer;

*Initialize a classification model from scratch;

*Replace the randomly initialized BERT in the new classifier with the pre-trained one.

from Transformers import AutoModel, AutoModelForTokenClassification
bert = AutoModel.from_pretrained('dbmdz/bert-large-cased-finetuned-conll03-english')
classifier = AutoModelForTokenClassification.from_config(config)
classifier.bert = bert

A: I believe the problem that you faced can be solved by passing this argument ignore_mismatched_sizes=True like below
model = AutoModelForTokenClassification.from_pretrained(pretrained_model_name, config=config, ignore_mismatched_sizes=True)

more information can be found here and here
I also checked your code in colab and had a similar issue and then when I added ignore_mismatched_sizes=True, it solved the issue I think. Also, the RuntimeError message has included a new line (which I believe was no available before)
You may consider adding `ignore_mismatched_sizes=True` in the model `from_pretrained` method.

I hope it solves the issue to a certain degree, but I am quite new to transformers and still exploring this library.
Thanks :)


text:
Q: How not close application after driver.quit() I am using Appium to install an application. After installation the application should work in the background. Another test should use Chrome to check Internet connectivity while the application is working in the background.
The issue is that driver.quit() or even initiating a new instance of a AndroidDriver kills the application and it does not work in the background any more.
Is there a way to test Chrome while the installed application is still working in the background?
public class test {

    public static void main(String[] args) throws MalformedURLException, InterruptedException {

        AndroidDriver<MobileElement> driver;
        DesiredCapabilities capabilities = new DesiredCapabilities();
        capabilities.setCapability(MobileCapabilityType.BROWSER_NAME, "");

        capabilities.setCapability(MobileCapabilityType.DEVICE_NAME, "Xiaomi A2 Lite");
        capabilities.setCapability(MobileCapabilityType.PLATFORM_VERSION, "9");
        capabilities.setCapability(MobileCapabilityType.APPLICATION_NAME, "Android");
        capabilities.setCapability(MobileCapabilityType.CLEAR_SYSTEM_FILES, "false");
        capabilities.setCapability(MobileCapabilityType.NO_RESET, "true");
        capabilities.setCapability(MobileCapabilityType.FULL_RESET, "false");
        capabilities.setCapability("appPackage", "com.waze");
        capabilities.setCapability("appActivity", "com.waze.FreeMapAppActivity");

        driver = new AndroidDriver<MobileElement>(new URL("http://127.0.0.1:4723/wd/hub"), capabilities);
        driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
        Thread.sleep(5000);

        DesiredCapabilities capabilities2 = new DesiredCapabilities();
        capabilities2.setCapability(MobileCapabilityType.BROWSER_NAME, "Chrome");
        capabilities2.setCapability(MobileCapabilityType.DEVICE_NAME, "Xiaomi A2 Lite");
        capabilities2.setCapability(MobileCapabilityType.PLATFORM_VERSION, "9");
        capabilities2.setCapability(MobileCapabilityType.APPLICATION_NAME, "Android");
        AndroidDriver<MobileElement> driver2;

        driver2 = new AndroidDriver<MobileElement>(new URL("http://127.0.0.1:4723/wd/hub"), capabilities2);
        driver2.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
        driver2.get("http://google.com");

        MobileElement googleLogo=(MobileElement) driver2.findElement(MobileBy.id("hplogo"));
        Assert.assertEquals(googleLogo.isDisplayed(), true);

    }

}

A: You could come up with a sample class implementing Callable interface:
import io.appium.java_client.AppiumDriver;

import java.time.Duration;
import java.util.concurrent.Callable;

public class BackgroundThread implements Callable {

    AppiumDriver driver;
    Duration duration;

    public BackgroundThread(AppiumDriver driver, Duration duration) {
        this.driver = driver;
        this.duration = duration;
    }

    @Override
    public Object call() {
        driver.runAppInBackground(duration);
        return "Slept for " + duration.toString();
    }
}

When you need to send your application to the background and do something else while it is there - call it with the ExecutorService:
ExecutorService executorService = Executors.newSingleThreadExecutor();
Future<Object> result = executorService.submit(new BackgroundThread(driver, Duration.ofSeconds(60)));

You might also find DeviceAction command useful, for instance you can mimic "Home" button click which will send the app to the background and return the context immediately.

A: Found a way to keep application in the background while opening another application by using
Activity activity = new Activity(appPackage, appActivity);
driver.startActivity(activity);

However this solution do not work if driver was initiated while app capability is set -for installing apk file
capabilities.setCapability(MobileCapabilityType.APP, apkPath);


text:
Q: Jacoco: jacocoTestResport working ok but jacocoTestCoverageVerification always shows 0 coverage I wanted to make some simple Unit Tests plus its coverage report: Actually everything works ok but the code coverage tasks always responds that there is 0% coverage
Actually I'm using Gradle 5.6; Jacoco 0.8.4
I tried verifying if the test coverage isn't reading the .exec file, but it does.
I excluded all the beans because they uses lombok notations, to avoid synthetic code and coverage problems (anyway the problem persists)
/*Especificación de cobertura de código para test unitarios
-Qué clases incluir y excluir en la cobertura
-De las clases incluidas
    --Mínimo de % de cobertura ok

Además agregamos rutina de jacocoTestReport en tarea de tests
*/

jacocoTestReport {

    getClassDirectories().setFrom(classDirectories.files.collect {
            fileTree(dir: it,
                    exclude: ['example/config/*',
                    'example/dto/*',
                    'example/model/configuration/*'])
        })

    getSourceDirectories().setFrom(sourceSets.main.java.srcDirs)

    getExecutionData().setFrom(
        fileTree(dir: "${buildDir}/jacoco", include:["**/*.exec"]))

    reports {
        xml.enabled false
        csv.enabled false
        html.destination file("${buildDir}/jacocoHtml")
    }
}

jacocoTestCoverageVerification {

    getClassDirectories().setFrom(classDirectories.files.collect {
            fileTree(dir: it,
                    exclude: ['example/config/*',
                    'example/dto/*',
                    'example/model/configuration/*'])
        })

    getSourceDirectories().setFrom(sourceSets.main.java.srcDirs)

    getExecutionData().setFrom(
        fileTree(dir: "${buildDir}/jacoco", include:["**/*.exec"]))

    violationRules {

        rule {
            enabled = true
            limit {
                counter = 'INSTRUCTION'
                value = 'COVEREDRATIO'
                //minimum = 0.05
                /*Los test actuales cubren el 6% del código
                Este requisito debería fallar*/
                minimum = 0.1
            }
        }

    }
}

Actually i want to reproduce the behavior to fail the coverage test because JacocoTestReport in the htmlReport shows that the total of Instructions coverage is 6%, but the console's message always shows that the value is zero
"[ant:jacocoReport] Rule violated for bundle example-ms: instructions covered ratio is 0.0, but expected minimum is 0.1
FAILURE: Build failed with an exception.

*

*What went wrong:
Execution failed for task ':jacocoTestCoverageVerification'.

Rule violated for bundle example-ms: instructions covered ratio is 0.0, but expected minimum is 0.1"

I'm adding JacocoTestReport in the test task (using finalize)...it works ok
After that if i execute the gradle jacocoTestCoverageVerification it always shows the mesagge described above


text:
Q: Appending a list in Prolog I'm just starting logic programming(in Prolog), and it's very different from procedure/OO. Please help out:
male(a).
male(b).
male(c).

female(x).
female(y).

append([],X,X).
append([X|Y],Z,[X|W]):- append(Y,Z,W).

partners(X,Y):- male(X), female(Y).

I'm trying to write a predicate getAllPartners(MyList, Output) that outputs a list including all possible combinations of partners. I don't mind having 0s in the list, but if anyone figure out a way of not having 0s in the output list, that'll be awesome.
Here's my 'buggy, crappy' code, please help:
getAllPartners(MyList, Output):-
append([],0,MyList),
partners(X,Y),
append(MyList,X,Output),
append(Output,Y,MyList),
append(MyList,0,Output).

A: Instead of manually appending such lists, Prolog has a builtin findall:
getAllPartners(L) :-
  findall((M,F),(male(M),female(F)),L).

Or even more compact:
getAllPartners(L) :-
  findall((M,F),partners(M,F),L).

When you call:
getAllPartners(L).

It will respond with:
L = [ (a, x), (a, y), (b, x), (b, y), (c, x), (c, y)].

You can generate your list manually, as well, but the problem with your approach is that partners(X,Y) will always bind with the same people first. Your list is thus [ a, x, 0, a, x, 0, a, x, 0, ...]. Another problem you should resolve is the fact that you append "lists" and not a "list" with an "element".


text:
Q: How to submit assumptions defined in master kernel to subkernels Consider an example:
$Assumptions = m > 0 && m \[Element] Integers;
ParallelDo[Print[{$Assumptions, Simplify[Sin[2*Pi*m]]}], {ik, 1, 2}, DistributedContexts -> All]

I expect it to produce:
{m > 0 && m \[Element] Integers,0}

But instead of it, Wolfram Mathematica gives:
{True,Sin[2 Notebook$$44$996424`m \[Pi]]}

A: $Assumptions cannot be distributed because it is in the System` context and because it is a symbol with special behaviour.
The correct way to handle this is to set it explicitly on all subkernels.
ParallelEvaluate[$Assumptions = m > 0 && m \[Element] Integers]


text:
Q: How to get Title, cookies, and post data for all tabs in IE I need a way to get Following data for all Tabs of IE :

*

*Titles of all Tab instances.

*Post Data when a form is submitted.

*All Cookies

Actually my client wants to keep tab on his employees surfing behaviors, he has this requirement. I am not sure how i can do this.I guess it will be done in VC++/Delphi,Any technology will do as long as its able to produce a single executable for this.
Any help would be appreciated.
Regards
Gaurav Verma

A: I don't think this is a good method to observe the employee's (besides the privacy issues). I would suggest to get logging from either the proxy server or the firewall.

A: Going after a specific browser has some limitations.  First, you will have to stay on top of every change that the vendor makes to the browser...since the web is so dynamic and is still evolving, expect to have your program break often with every release.  Second, its easy to bypass security by installing a different browser, and there are even some that will run completely off of a USB stick without any "footprint" on the local machine.
That said, I'm not sure going after cookies and post data is worth the effort, but the best solution would be to use a proxy service of some type (could even be on the workstation itself).  You could also use a traffic monitoring program (for instance Wireshark) to track specific requests based on filters, but this will not "crack open" any HTTPS/FTPS streams as they are encrypted.
A Browser Helper Object would work, but again is limited to a specific browser.


text:
Q: Why text editors deforms indentation of pasted code? This seems to be very generic issue related with many different text editors (or maybe copy-paste mechanism in Windows?). Often when I copy-paste fragments of indented code I end up with the first line indented correctly and the rest of lines shifted right by one level and needing manual correction (which is irritating).
For example when I paste code:
int i = 0;
for(; i < 5; ++i){
     System.out.println(i);
}

The effect often looks like:
int i = 0;
    for(; i < 5; ++i){
         System.out.println(i);
    }

This problems occurs even when using ultra-advanced IDEs like Eclipse. What is the cause of that problem and why have I had to deal with it for so many years?

A:
What is the cause of that problem

The IDE is probably trying to do some sort of smart indenting on your behalf, but in this case it does look like a bug.
The Zeus editor does something very similar.
As an example of what I mean assume you copy this text to the clipboard:
System.out.println(i+1);
System.out.println(i+2);
System.out.println(i+3);

If you then paste that code into into your example in the location shown below:
int i = 0;
for(; i < 5; ++i){
    System.out.println(i);
} <-- place cursor on this line

You should end up with this code (that is what Zeus does):
int i = 0;
for(; i < 5; ++i){
    System.out.println(i); < place cursor on this line
    System.out.println(i+1);
    System.out.println(i+2);
    System.out.println(i+3);
}

As you can see this is different from what you may have expected which is this:
int i = 0;
for(; i < 5; ++i){
    System.out.println(i); < place cursor on this line
System.out.println(i+1);
System.out.println(i+2);
System.out.println(i+3);
}

That is smart indenting .

why have I had to deal with it for so many years?

There should be an option in the IDE to turn off this feature. Zeus certainly has such an option.


text:
Q: J2me db option, jmesql Is jmesql better option than rms for j2me environment, Is there any limitaions using jmesql. Is rms is better when using large volume of data. What is better to use.

A: Comparing a RDBMS to the RMS is a fairly complicated topic but in short, J2ME applications can only use the RMS for internal storage of data so any RDBMS is going to use the RMS to store the data. So you won't get around any of the technical limitations of the RMS but it could make it easier to work with your data, particularly if it contains complicated relationships between distinct groups of data.
A RDBMS may give you some performance benefits but it will be impacted by the limitations of the RMS, e.g. you can't partially load a record store in the RMS so the RDBMS must load an entire record store before selecting only the data you have requested.
JMESQL is in pre-alpha and doesn't appear to have had any active development for almost 2 years so unless you're willing to fix bugs/add new features yourself you would be better looking for a different library.
In most situations you are better using the RMS as it is simpler to work with and has less overhead but it will depend on the data you need to store.


text:
Q: Understanding the eval function used to define combinators and expression (Lambda) in Haskell I find the use of pattern matching for eval (App x y) redundant since both cases would return App x y. I wonder if eval (App x y) is needed at all because we have eval x = x at the end, which should also include eval (App x y)
data Expr = App Expr Expr | S | K | I | Var String | Lam String Expr deriving (Show,Eq)
eval :: Exp -> Exp
eval (App I x) = eval x
eval (App (App K x) y) = eval x
eval (App (App (App S f) g) x) = eval (App (App f x) (App g x))
eval (App x y)
 | evalx == x  = (App evalx (eval y)) --test if x is a Lam (not other possible values of Exp)
 | otherwise = eval (App evalx y)
     where evalx = eval x
eval (Var x) = (Var x)
eval x = x


text:
Q: How do I generate a hash values of 3 arrays in Ruby? Given I have 3 arrays that are mapped to each other.
fruit = ['apple', 'avocado', 'banana']
color = ['red', 'purple', 'yellow']
price = [30, 20, 50]

How do create an array of hashes with the following value
[
 {fruit: 'apple', color: 'red', price: 30},
 {fruit: 'avocado', color: 'purple', price: 20},
 {fruit: 'banana', color: 'yellow', price: 50}
]

A: You can use zip to interleave the arrays, and then map them into an array of hashes:
fruit.zip(color, price).map { |f, c, p| { fruit: f, color: c, price: p } }
# => [{:fruit=>"apple", :color=>"red", :price=>30},
# =>  {:fruit=>"avocado", :color=>"purple", :price=>20},
# =>  {:fruit=>"banana", :color=>"yellow", :price=>50}
# => ]


text:
Q: Button for downloading SVG in JavaScript & HTML? There's an SVG image that's rendered in the browser. I want a button below to download the SVG. Looks like download with proper mimetype is the way to go.
Attempt:

<button id="download">Download SVG</button>

function downloadSVG() {
    const svg = document.getElementById('container').innerHTML;
    /*console.info(btoa(svg));

    document.getElementById('svg').src = `data:image/svg+xml;utf8,${document.createTextNode(svg).textContent}`;
    console.info('src:', document.getElementById('svg').src, ';');*/

    const element = document.createElement('a');
    const mimeType = 'image/svg+xml'; // 'image/svg+xml;utf8';
    element.href = `${mimeType},${document.createTextNode(svg).textContent}`;
    element.target = '_blank';
    element.mimeType = mimeType;
    element.download = 'w3c.svg';
    element.id = 'downloader';
    document.body.appendChild(element);
    element.click();
    document.getElementById('downloader').remove();
}

Runnable example: https://stackblitz.com/edit/typescript-mpk8ui
But I get a broken SVG file. Similar issue with my real code (I get an empty SVG).

A: The downloading data must be a blob raw data.
function downloadSVG() {
  const svg = document.getElementById('container').innerHTML;
  const blob = new Blob([svg.toString()]);
  const element = document.createElement("a");
  element.download = "w3c.svg";
  element.href = window.URL.createObjectURL(blob);
  element.click();
  element.remove();
}

This should do the trick.


text:
Q: Web Scraping XML file that's Downloaded After Submitting Form (Python) How do you scrape an xml file that automatically downloads to your computer after submitting a form? I haven't seen any examples that contain a file that is from submitted data. I haven't been able to find it in the python documentation. https://docs.python.org/3/library/xml.etree.elementtree.html . Any suggestions, or links would be very much appreciated.
   from selenium import webdriver
   from webdriver_manager.chrome import ChromeDriverManager
   from selenium.webdriver.support.select import Select
   from selenium.webdriver.common.action_chains import ActionChains

   url = 'https://oui.doleta.gov/unemploy/claims.asp'
   driver = webdriver.Chrome(executable_path=r"C:\Program Files (x86)\chromedriver.exe")

   driver.implicitly_wait(10)
   driver.get(url)
   driver.find_element_by_css_selector('input[name="level"][value="state"]').click()
   Select(driver.find_element_by_name('strtdate')).select_by_value('2020')
   Select(driver.find_element_by_name('enddate')).select_by_value('2022')
   driver.find_element_by_css_selector('input[name="filetype"][value="xml"]').click()
   select = Select(driver.find_element_by_id('states'))

   # Iterate through and select all states
   for opt in select.options:
       opt.click()
   input('Press ENTER to submit the form')
   driver.find_element_by_css_selector('input[name="submit"][value="Submit"]').click()

A: This post on stackoverflow seems to be in the direction of what I'm looking for; How to download XML files avoiding the popup This type of file may harm your computer through ChromeDriver and Chrome using Selenium in Python
This link helped the most for my needs, so I'll add it here, however, the first link is very helpful as well so I want to leave it.
How to control the download of files with Selenium + Python bindings in Chrome


text:
Q: What is wrong with my code? Combining Operators I have been working on this for hours but I couldn't get it to work correctly. My code is below.
I need to write a code using boolean variables. The code should print True if hungry is True, and either coworkers_going is True or brought_lunch is False.
Here is my code:
hungry = True
coworkers_going = False
brought_lunch = False

print(((hungry) and  coworkers_going) or  brought_lunch)

A: Since "either coworkers_going is True or brought_lunch is False" is considered together and the or operator has a lower precedence than the and operator, you should use parentheses to group the two expressions so that the or operation is evaluated before the and operation. Also, use the not operator to return True when an expression is False:
hungry and (coworkers_going or not brought_lunch)

A: From what I understood, you want to print True if hungry == True and at the same time coworkers_going == True or brought_lunch == False, it would be like this:
print((hungry and (coworkers_going or not brought_lunch)))


text:
Q: How to automate git push processes using python? I'm trying to automate the git push processes using python.
I've succeeded automating all except entering the username and password after the git push command.
This is my code so far:
import subprocess
import sys

add: str = sys.argv[1]
commit: str = sys.argv[2]
branch: str = sys.argv[3]

def run_command(command: str):
    print(command)
    process = subprocess.Popen(command.split(), stdout=subprocess.PIPE)
    print(str(process.args))
    if command.startswith("git push"):
        output, error = process.communicate()
    else:
        output, error = process.communicate()
    try:
        output = bytes(output).decode()
        error = bytes(error).decode()
        if not output:
            print("output: " + output)
        print("error: " + error)
    except TypeError:
        print()

def main():
    global add
    global commit
    global branch
    if add == "" or add == " ":
        add = "."
    if branch == "":
        branch = "master"
    print("add: '" + add + "' commit: '" + commit + "' branch: '" + branch + "'")

    command = "git add " + add
    run_command(command)

    commit = commit.replace(" ", "''")
    command = 'git commit -m "' + commit + '"'
    run_command(command)

    command = "git push origin " + branch
    run_command(command)

if __name__ == '__main__':
    main()

Is there any way to send the information to the command?

A: If possible, use a credential helper in order to cache that information (credentials associated to a remote URL).
Check the gitcredential section and "Git Tools - Credential Storage".
git config --global credential.helper

That way, you won't have to enter that information at all.

A: This is how I solved it:
# make sure to cd into the git repo foler

import subprocess
import sys
import os

msg = input('Type the commit message (+ ENTER):')
repo_directory = os.getcwd()

subprocess.run(["git", "add", "."], cwd=repo_directory)
# commit file
subprocess.run(["git", "commit", "-m", msg], cwd=repo_directory)
# push
subprocess.run(["git", "push"], cwd=repo_directory)


text:
Q: Volume using spherical coordinates-finding theta! Let $V$ be the region in $\mathbb{R}^3$ defined by the inequalities $z^2\ge x^2+y^2$, $x^2+y^2+z^2\leq 1$, and $z\ge 0$. Sketch the region $V$ and find its volume?
I have sketched $V$ but to find the volume I have  written the region in spherical coordinates but I don't understand how to determine the value of theta or phi? I know what theta and phi are for a point in space but don't how to find it for a region in space.
Also how do you know when to use spherical coordinates and when to use cylindrical ones?

A: The restriction of $\theta$ to the interval $[0,\frac{\pi}{2}]$ comes from the third inequality, $0\leq z$. The further restriction of $\theta$ to the interval $[0,\frac{\pi}{4}]$ comes from the first inequality, $x^2+y^2\leq z^2$. In spherical coordinates this becomes,
$$r^2\sin^2{\theta}\cos^2{\phi}+r^2\sin^2{\theta}\sin^2{\phi}\leq r^2\cos^2{\theta}\\
\iff r^2\sin^2{\theta}\leq r^2\cos^2{\theta}\\
\iff 0\leq r^2\left(\cos^2{\theta}-\sin^2{\theta}\right)\\
\iff 0\leq r^2\cos{(2\theta)}\\
\iff \theta\in[0,\frac{\pi}{4}]\cup[\frac{3\pi}{4},\pi]~\lor~r=0.$$


text:
Q: What does "Host application code" refer to in this context? I'm lookin at a job description that lists this as a responsibility:

Design, develop, and test software for analytical scientific instruments with an emphasis on Host application code

This is a software engineer job in the electronics manufacturing field so i imagine there will be a heavy emphasis on embedded software and drivers as well as electronics test fixturing code.
So what specifically does host application code refer to? I did some googling and found this link which suggests it has to do with windows powershell. This would make sense because they also ask for experience with C# or VB.net and visual studio. It looks like they are very windows oriented. But I'm still not entirely sure about what they're looking for.

A: I'm guessing it just means code for the scientific instruments - the instruments will 'host' the embedded code.

A: On its own it does not mean anything, and almost certainly nothing to do with Powershell.
Whoever wrote it knew what it meant to them, but it has lost all meaning without context.  You simply need to ask the recruiter to elaborate - there is no shame in that, and in fact it would probably be to your credit to show that initiative.
Try:

"Sounds interesting; can you give me more information?

If I had to guess from the other information you have given, I would imagine that it refers to software running on a PC connected to a number of instruments (perhaps via GPIB, Ethernet, USB, Serial or other interfaced or PCI cards plugged directly into the PC).
Many companies use National Instruments' LabView for this for this sort of application.  I can think of many reasons not to use LabView, but it might be a question for you to bring up in an interview.

A: I would assume that host application software refers to PC-based windows applications that interface to the instruments (via serial, usb, ethernet, or other interface) and are used to configure the instruments, analyze and store data from the instruments, and/or test the instruments.


text:
Q: Saving Static Tableview Cell Check Marks using NSUserDefaults **New to iOS dev and programming in general. Patience please.
I have looked everywhere for something that I can understand and implement that will allow me to save and retrieve check marks for static tableview cells.
I have tried:
saving checkmark accessory value in nsuserdefaults and then retreving them
how to save the state in userdefaults of accessory checkmark-iphone
and countless others.
It is probably my lack of knowledge that is causing the problems.
I have a tableview with static cells. I have implemented the check mark for multiselection, per Apple's instructions as follows:
- (void)tableView:(UITableView *)theTableView
didSelectRowAtIndexPath:(NSIndexPath *)newIndexPath {

    [theTableView deselectRowAtIndexPath:[theTableView indexPathForSelectedRow] animated:NO];
    UITableViewCell *cell = [theTableView cellForRowAtIndexPath:newIndexPath];
    if (cell.accessoryType == UITableViewCellAccessoryNone) {
        cell.accessoryType = UITableViewCellAccessoryCheckmark;

    } else if (cell.accessoryType == UITableViewCellAccessoryCheckmark) {
        cell.accessoryType = UITableViewCellAccessoryNone;

    }
}

This works fine for selecting and unselecting multiple rows, which then display the checkmark.
How do I save those checkmarks to user defaults so that they reload everytime for that tableview?
When I try to set the object for the NSUserDefaults, I get an error that says "Implicit conversion of NSInteger to 'id' is disallowed with ARC" and "Incompatible integer to pointer conversion sending NSInteger to parameter type of 'id'".
Any help is much appreciated, even if it is just pointing me to a resource that is understandable for a rookie.
Thank you!

A: I think you might be approaching this from the wrong direction. Your table view is data driven so you should be modifying your data, not your views, in response to cell selection. Then you cause your views to be updated either by doing [tableView reloadData]
or for more fine grained control (i.e. modifying one at a time) using reloadRowsAtIndexPaths:withRowAnimation:. The idea is that you update the underlying data and you cause iOS to update the cell, which you configure according to that data, in cellForRowAtIndexPath:.

A: In general, you should be looking to modify the underlying data represented by the table view, and then persist that, rather than modify and persist the state of the table view's representation of the data.
However, if there's no clear way to do that, then to fix your current error you must remember that NSUserDefaults only stores objects, not primitive types. So to convert an integer expression to an NSNumber box it with @(...expr...), and then get the integer value for the object that you retrieve from NSUserDefaults by calling the integerValue method on it. You don't show any of the code actually causing the error, though, so that's as far as I can comment.


text:
Q: Django Aggregation: highest sum in categories Hy Guys
I was wondering how I can get the highest sum of one category.
So i have a model with my categories and a model with my costs which contains a cost category.
My models.py
from django.db import models

class CostCat(models.Model):
    name = models.CharField(max_length=50, default=None, null=True, blank=True)

class Cost(models.Model):
    name = models.CharField(max_length=50, default=None, null=True, blank=True)
    cost_category = models.ForeignKey(CostCat, on_delete=models.CASCADE)
    amount = models.DecimalField(max_digits=12, decimal_places=2,null=True, blank=True)

The result should be that I can show the category with  the highest sum of costs.
I have been stuck on that for hours now. The closest i got was with my tests as shown below.
I can print out all the sums and its respective category but now I now need to find out how to get the category and the value of the highest sum. And i'm really in a spiral right now.
views.py
def metrics(request):

    tests = CostCat.objects.annotate(sum=Sum('cost__amount'))

    for test in tests:

        print(test, test.sum)

    return render(request, 'metrics.html', "topcostcat":test, "topcostcatsum":test.sum )

Much appreciated if you could me a bit out!
Thanks in advance

A: You can order by the cost and obtain the last one, so:
def metrics(request):
    topcat = CostCat.objects.annotate(sum=Sum('cost__amount')).latest('sum')
    return render(request, 'metrics.html', {'topcat': topcat})
or if it is possible that there are categories without a Cost, you can use nulls_last=True [Django-doc]:
from django.db.models import F

def metrics(request):
    topcat = CostCat.objects.annotate(sum=Sum('cost__amount')).earliest(
        F('sum').desc(nulls_last=True)
    )
    return render(request, 'metrics.html', {'topcat': topcat})


text:
Q: How do I run git update-index skip-worktree from nodeJS sccript I know that git update-index skip-worktree can be used to ignore a file from any changes. I don't want to run this command manually on every system, how can I write a node js script to do this with a npm command.

A: You have approaches for formatting code (here or in okonet/lint-staged issue 170 which takes advantages of a script section of a package.json
You could use that for instance in the prepare step, which is run both before the package is packed and published, on local npm install without any arguments, and when installing git dependencies.
{
  "scripts": {
    "prepare": "git update-index --skip-worktree -- afile",
  }
}


text:
Q: How to add new line into txt file I'd like to add new line with text to my date.txt file, but instead of adding it into existing date.txt, app is creating new date.txt file..
TextWriter tw = new StreamWriter("date.txt");

// write a line of text to the file
tw.WriteLine(DateTime.Now);

// close the stream
tw.Close();

I'd like to open txt file, add some text, close it, and later after clicking something: open date.txt, add text, and close it again.
So i can get:
Button pressed: txt opened -> added current time, then close it. Another button pressed, txt opened -> added text "OK", or "NOT OK" in the same line, then close it again.
So my txt file will look like that:
2011-11-24 10:00:00 OK
2011-11-25 11:00:00 NOT OK

How can i do this? Thanks!

A: var Line = textBox1.Text + "," + textBox2.Text;

File.AppendAllText(@"C:\Documents\m2.txt", Line + Environment.NewLine);

A: You could do it easily using
File.AppendAllText("date.txt", DateTime.Now.ToString());

If you need newline
File.AppendAllText("date.txt",
                   DateTime.Now.ToString() + Environment.NewLine);

Anyway if you need your code do this:
TextWriter tw = new StreamWriter("date.txt", true);

with second parameter telling to append to file.
Check here StreamWriter syntax.

A: No new line:
File.AppendAllText("file.txt", DateTime.Now.ToString());

and then to get a new line after OK:
File.AppendAllText("file.txt", string.Format("{0}{1}", "OK", Environment.NewLine));

A: Why not do it with one method call:
File.AppendAllLines("file.txt", new[] { DateTime.Now.ToString() });

which will do the newline for you, and allow you to insert multiple lines at once if you want.

A: Try the following code to create and write content to a text file in Unity3D.
void CreateLog() {
        string timestamp = DateTime.Now.ToString("dd-mm-yyyy_hh-mm-ss");
        PlayerPrefs.SetString("timestamp", timestamp);
        string path = Application.persistentDataPath + "/" + "log_" + timestamp + ".txt";
        // This text is added only once to the file.
        if (!File.Exists(path)) {
            // Create a file to write to.
            using (StreamWriter sw = File.CreateText(path))
            {
                sw.WriteLine(DateTime.Now.ToString() + ": " + "App initialised");
            }
        } else {
            // This text is always added, making the file longer over time
            // if it is not deleted.
            using (StreamWriter sw = File.AppendText(path)) {
                sw.WriteLine(DateTime.Now.ToString() + ": " + "App initialised");
            }
        }

        // Open the file to read from.
        using (StreamReader sr = File.OpenText(path)) {
            string line = "";
            while ((line = sr.ReadLine()) != null)
            {
                Debug.Log(line);
            }
        }
}


text:
Q: What is needed to use Cloud Firestore from Google App Engine Standard Environment I read many GCP documents relating to credentials for using Cloud Firestore from Google App Engine Standard Environment, but I'm very confused now.
According to the following pages, I assume there can be two service accounts from Google App Engine and Firebase. So there are two credentials from each of them, right?
https://firebase.google.com/docs/admin/setup#initialize_the_sdk
https://cloud.google.com/docs/authentication/production
The documentation recommends to use the environment variable for a credential like the following,
export GOOGLE_APPLICATION_CREDENTIALS="[PATH]"

but which credential should I use in my case?


text:
Q: DataFrame object is not callable with AIF360 I encounter TypeError: 'DataFrame' object is not callable with the following. Anyone can help? Thanks.
%cd -
dataset_orig = df_data_1(protected_attribute_names=['Gender'],
privileged_classes=['Male'],
features_to_drop=[])

dataset_orig_train, dataset_orig_test = dataset_orig.split([0.7], shuffle=True)

privileged_groups = [{'Gender': 1}]
unprivileged_groups = [{'Gender': 0}]

/home/wsuser/work

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-59-8c624cfec261> in <module>
      5 # consider in this evaluation
      6 privileged_classes=['Male'],      # male is considered privileged
----> 7 features_to_drop=[]) # ignore all other attributes
      8
      9 dataset_orig_train, dataset_orig_test = dataset_orig.split([0.7], shuffle=True)

TypeError: 'DataFrame' object is not callable

A: It appears that df_data_1 is your dataset dataframe, right? If it is, you would need to update your script to convert it to StandardDataset:
from aif360.datasets import StandardDataset

dataset_orig = StandardDataset(df_data_1,
                               protected_attribute_names=['Gender'],
                               privileged_classes=['Male'],
                               features_to_drop=[],
                               favorable_classes=[1]  # Update this with label values which are considered favorable in your dataset
                              )

I am not sure how your dataset looks like, but you can adapt the complete reproducible example here to do this process for your dataset.


text:
Q: is it better to Use to store the Function libraries, repositories in QC itself? I 'm planning to use QC as a place for Repositories for Libraries, Object repositories , other data files. I'll be executing the all the test cases from QC. If i use QC for these,  Will that be a better opinion? Will the execution be more faster than usually?
Note: usual Method is functions, repo on local and just updating the Driver script in QC and running it from QC.

A: Whatever is stored on QC will have to be downloaded to the machine on which the QTP test run is executed. Increasing the number of items to be downloaded from QC will not increase performance.

A: After thinking about it for a while, I decided to come up with my own answer:
If you

*

*work with more than one people on the QTP tests,

*AND/OR execute the tests on more than one or two machines,

*AND/OR use QC's workflow scripting features to keep track of tests' stati (or other attributes)

*AND/OR want to do more than execute tests directly ("interactively") from QTP using Run/F5

*AND/OR want to use QC's version control for QTP tests (urgh..)

then it is highly recommended to put the tests into QC because

*

*a central repository is useful in such situations

*it is the only way to use QC's requirements tree, test lab and defect manager with automated test integration, including the graphing/reporting facilities.

The biggest disadvantages of having them in QC is that you

*

*never will see a usable hierarchical file system of those tests again (but hey! Does QTP without QC create a useful file system for every test? No!),

*thus must do all operations via the QC interface (forget about deleting or copying while trees with Windows Explorer)

*Will pay a performance penalty since upon every open or save operation, the test must be  transferred to/from the local file system from/to QC. (Once it is there, you have full local performance, though, at least in most cases.)

*heavily increase the dependency on stability of your local network

*should always have the most current QTP & QC releases (especially in terms of patches/SRs),

*will see some rare cases where the QTP IDE crashes when it would not have crashed if the test was in the local file system (there still seem to be some bugs in the interface implementation between both)

So only put the stuff into QC if you can live with the disadvantages.

A: In the past ive used a tool called StarTeam which contains a working folder with all your repositories in. This is version controlled and means that any one of the engineers can access it or check it out to make changes to it.
Execution is quick because your own personal version of the working folder is held on your local drive, giving you speedy access.
However it may be better having it in QC to increase visibility to the other testers. Its personal preference really each solution has good and bad points.


text:
Q: How to perform checks on data type construction For a data type constructor, is there any way to limit the creation of the "object" (I don't know the proper term) based on criteria other than the types of the arguments to the constructor?
For instance:
data UInt = UInt Int --the int must be >= 0

Truly, I would like to create a data type for rectangular multidimensional lists (in which all the sublists have the same length). Would a class or some other technique be better suited for this?

A: No, there is no way to enforce what values a user passes to a constructor.
However, there is a common practice in the community and standard library of creating smart constructors.  You see these in modules like Data.Map, Data.Ratio, and many more.  Simply put, you don't export the constructor itself, just the type, and you export a function which vets the arguments:
module UInt
    ( UInt
    , uint
    ) where

data UInt = UInt Int

uint :: Int -> Maybe UInt
uint x | x >= 0 = Just (UInt x)
       | otherwise = Nothing


text:
Q: How can I differentiate between push notifications received in app and touched from outside the app? I have push notifications setup in my app.  I have the method:
 - (void)application:(UIApplication *)application didReceiveRemoteNotification:     (NSDictionary *)userInfo
 {
      if()
      {
           //app is in foreground to get here
      }
      else if()
      {
           //app is in background and then the notification is clicked, to get here
      }
 }

I need to differentiate between touches of the notification outside the app, and simply receiving the notification in the app.  Any help?

A: - (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{
    if ( application.applicationState == UIApplicationStateActive )
        // app was already in the foreground
    else
        // app was just brought from background to foreground
    ...
}

A: Use Following methods for receiving Push Notification in Foreground as well as Background. In Backgound, You can show Default Alert / Banner But In Foreground, You Can't show Alert / Banner but You can manage it by UIAlertView.
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{
    if ( application.applicationState == UIApplicationStateBackground | application.applicationState == UIApplicationStateInactive )
    {
        // Application is in Background
    }
    else
    {
        // Application is in Foreground
    }
}

It's Works Fine...!!!

A:     - (void)applicationWillResignActive:(UIApplication *)application
    {
        applicationIsActive = NO;
    }
    - (void)applicationDidBecomeActive:(UIApplication *)application
    {
       applicationIsActive = YES;
     }

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{
if (applicationIsActive)
{
 }
  else
 {
  }
}

A: This is better handled with UNUserNotificationCenter.
UNUserNotificationCenter.current().delegate = self

func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
    // a notification arrived while the app was in the foreground and has a value for badge, alert, or sound
    // if the notification also has content-available=1 then didReceiveRemoteNotification will also be called.

    // we can have iOS to display the alert normally
    completionHandler([.alert, .sound, .badge])
}

func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
    // the user took an action (i.e. tapped) on a notification
    // unless you support custom notification action that run in the background the app is now in the foreground. The tap may have caused the app to launch OR brought it to the foreground OR the app may have already been in the foreground
    completionHandler()
}

func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
    // a notification arrived with content-available = 1
    // the application may be in the background or foreground
    // note: if the app is in the foreground AND the notification also has a value for badge, alert, or sound then the userNotificationCenter(willPresent) method will also be called
    completionHandler(.newData)
}


text:
Q: How do you transfer large amounts of content to a new WordPress theme without down time? I'm working on a non-profit's website and social media presence. They are currently using an outdated website built on WordPress and we're working on a limited budget to improve it. I have suggested we go with a more up-to-date WordPress theme as this would keep costs as low as possible.
The question that remains is how easy/cost-effective (in terms of labor) is it to take a large amount of content (mostly text) and transfer it to a new WordPress theme? Would this mean the website would be down for an extended period of time while we implement existing content? or would we be able to backup the content, apply a new theme, and upload the content from the backup? Is this a simple process or an extended process? I'm going to estimate there are about 150-200 pages worth of content. At a rate of $30/hour for labor, how much would this end up costing us?

A: Changing theme does not affect website availability. Before changing the theme permanently, check it in live preview for any incompatibility.
There many backup plug-ins out there. UpdraftPlus is a good one and you can use it to backup locally/and on Google drive for free (other cloud storages are not supported in free version AFAIK).


text:
Q: Can one use Hölder's inequality or some other method for this? Suppose that $\sum_{i=1}^{n}\lambda_{i}=1$, where $\lambda_{i}>0$,
and $\sum_{i=1}^{n}b_{i}^{2}=1$, where $b_{i}>0$. Does one have $\sqrt{n}\sum_{i=1}^{n}\lambda_{i}b_{i}\le B$
for some constant $B$ (independent of $n$)? Thanks.

A: The question changed, here is an answer to the new question:
No. Choose $\lambda_1 = 1, b_1 = 1$. Let $\lambda_k=b_k=0$ for all $k\neq 1$. Then you have $\sum_i \lambda_i b_i = 1$. Hence $\sqrt{n} \sum_i \lambda_i b_i = \sqrt{n}$. So you cannot have a bound independent of $n$.
Old answer:
Yes. The Cauchy-Schwarz-Bunyakovsky-$\cdots$ inequality gives $|\lambda^T b | \leq \|\lambda\| \|b\| = \|\lambda\| \leq 1$.
More simply, since $\sum_i b_i^2 = 1$ we have $|b_i| \leq 1$, and then $\sum_i \lambda_i b_i \leq \sum_i \lambda_i |b_i| \leq \sum_i \lambda_i =1$.
It follows that $\sqrt{n} \sum_i \lambda_i b_i \leq \sqrt{n}$, so take $B=\sqrt{n}$.


text:
Q: SOAP message on Java SE Using JAX-WS on Java SE 7.
The guides on Soap Handlers seem to assume a Java EE server. Is this essential for SOAP handlers or can they also work in Java SE?

A: You can implement web services in Java SE.
You just need to start up an Endpoint and publish it.
This is a simple example.
Java EE and servlet containers handle the publishing part for you. Outside of that, they're pretty much the same thing and handled the same way.

A: A web service gets deployed either on a Servlet container (like Tomcat) or any Java EE application server (like JBoss AS, WebLogic etc).
So Java SE is not enough for deploying your web service.


text:
Q: Data Structure Parallel Add Serial Remove Needed I'm working on a dynamically branching particle system on the GPU.  I need a parallel data structure with the following properties:

*

*One thread must be able to remove elements one by one, in constant time.  The element returned isn't important to the algorithm--just so long as some element is returned when nonempty.  For extra awesomeness, change to any number of threads.

*Any number of threads must be able to add elements to the data structure in constant time.  Note that some locking is allowed, (and necessary) but it must still scale with no relation on the number of threads.  I.e., more threads shouldn't slow it down.

Basic synchronization primitives (mutexes, semaphores), and anything that can be implemented using them, are available.
I had toyed with the idea of a linked list, but this violates condition two (since adding would be O(m) for m threads, since locking must be taken into consideration).  I'm not sure such a data structure exists--but I thought I would ask.

A: Without knowing more about how you want your data organized (sorted? FIFO? LIFO?) I'm. Or sure whether I can give you an exact answer.  However, what you're describing sounds like the definition of a lock-free structure.  Lock-free implementations of stacks and queues exist, which do support O(1) insertions and deletions even when there are a lot of threads modifying the structure concurrently.  They're usually based on atomic test-and-set operations.
If locks are okay and you just want a highly-concurrent data structure that's sorted, consider looking into concurrent skip lists, which provide O(log n) sorted insertion and deletion with multiple active threads.
Hope this helps!


text:
Q: Difference between localhost and the ip address If bind a socket in Python to localhost,8200 this is accessible via http://localhost:8200/. but not http://x.x.x.x:8200/
If bind a socket in Python to x.x.x.x,8200, machinename,8200 this is accessible via http://x.x.x.x:8200/ and http://machinename:8200/, but not http://localhost:8200/
I thought localhost meant 'this machine', and that using it would 'loop back' to the machine's ip address, but it appears to be different ips.
Is 127.0.0.1 always a different ip address to the machines ip address?
update:
I understand that the actual numbers are different, but what does the loopback do?
For example wikepedia says that
'pointing a web browser to the URLs http://127.0.0.1/ or http://localhost/ will access that computer's own web site'
but that web site will also be accessible on x.x.x.x, and presumably be set up with a single socket on x.x.x.x. So how do both references work then?
conclusion:
I think I finally understand that 127.0.0.1 and x.x.x.x work like this
--127.0.0.1 ==\
               >- Computer
--x.x.x.x   ==/

and not
--127.0.0.1 ==\
--------------- x.x.x.x >- Computer

or
--x.x.x.x ==\
--------------- 127.0.0.1 >- Computer

Thanks all for the help

A:
For example wikepedia says that
  'pointing a web browser to the URLs http://127.0.0.1/ or http://localhost/ will access that computer's own web site'

Slightly inaccurate. It may do so. Equally well it may not bring up any website and it is even possible to display an different internal website from what you get when you use your x.x.x.x address.
127.0.0.1 points to your own machine, but that doesn't mean it will behave the same way once it reaches your machine
If you want a non-technical analogy, your can consider them different doors into your house.
There are both pointing to the same house but they are not the same thing.
It is possible for each door to take you into the same room or they could take you into a different room. It is also possible to lock one door and not the other.
When you configure a website, you specify which addresses to bind to and quite often the answer is all addresses. (That is equivalent to have all doors taking you into the one room)
You can also specify the website to bind to one address only. (That is equivalent to locking all doors except one.)
If you have two (or more) websites you can bind them to separate addresses. (That is equivalent to having each door going into separate rooms).
An example of how both references work,  my Windows 7 computer has IIS installed, when I go into IIS Manager and right click on Default Web Site, it gives me a 'Edit Bindings' menu option. Selecting that bring up a list of bindings. I have only one, but for IP Address it has * which means IIS listens on all my ip addresses.

A: To answer your question.
127.0.0.1 is not just a different ip address to the machine ip address, it's a different
interface as well.  127.0.0.1 should not be seen on the local network.  It's a special
internal IP address for the loopback adapter.
x.x.x.x will be your ethernet card.
by the way 'localhost' is simply an entry in your hosts file that points to 127.0.0.1
If you bind a socket to 127.0.0.1:8200 then only clients running locally will be able to access it and only with http://127.0.0.1:8200 or http://localhost:8200 (or a dns or hosts file entry that points to 127.0.0.1).
A socket bound to x.x.x.x:8200 will only be available through http://x.x.x.x:8200 or a dns or hosts file entry that points to that.
Binding a socket to 127.0.0.1 does not automatically make it available on the ethernet interface as well.
Thats why you can't connect to x.x.x.x:8200
You can bind port 8200 to all available interfaces (0.0.0.0) then it should work.
Other features of the loopback adapter:
The loopback interface is a virtual interface. It's often used to allow programs to talk to each other on the same machine. It is not a way to reference the machine IP address. 127.0.0.1 IS the IP address of the loopback virtual adaptor.
The other thing about the loopback adapter is that because it's virtual it doesn't actually pass any packets through to the network card.

A: Every IP address on the system is independent and can be bound to by sockets separately, with the exception of the special address 0.0.0.0 which indicates to the OS to bind the socket to all interfaces.


text:
Q: Group by and add values in cypher I did this query on neo4j (Cypher):
match (Person)-[KNOWS]->(Comp)
WHERE Comp.name='EN' OR Comp.name='FR' OR Comp.name='CUI'
RETURN Person.fname,
CASE Comp.name
    WHEN 'EN'
    THEN 5
    WHEN 'FR'
    THEN 3
    WHEN 'CUI'
    THEN 1
    ELSE 0 END AS Points_Candidat

My result is:
Yves 3

Yves 1

Alina 3

Alina 1

David 5

David 3

But I want to group my result and sum the Points_Candidate for every person. I want to get an answer like this:
Yves 4

Alina 4

David 8

How do I have to modify my query?

A: You can get the sum of a collection of numeric values with SUM, for instance you can run it on your CASE clause,
MATCH (Person)-[KNOWS]->(Comp)
WHERE Comp.name='EN' OR Comp.name='FR' OR Comp.name='CUI'
RETURN Person.fname, SUM(
    CASE Comp.name
        WHEN 'EN'  THEN 5
        WHEN 'FR'  THEN 3
        WHEN 'CUI'  THEN 1
        ELSE 0
    END
) AS Points_Candidat

I don't know the context, but I think of two minor changes that would give you an equivalent but slightly trimmed down query: 1) since the three tests in the WHERE clause are identical except for the value tested for, you can use the IN operator with a collection of values instead of a three term disjunction, and 2) since the three CASE ... WHEN values exhaust the possibilities of what is bound in the WHERE clause, all bound nodes will test true for one of the cases, so you don't need the ELSE.
MATCH (Person)-[KNOWS]->(Comp)
WHERE Comp.name IN ['EN' ,'FR','CUI']
RETURN Person.fname, SUM(
    CASE Comp.name
        WHEN 'EN'  THEN 5
        WHEN 'FR'  THEN 3
        WHEN 'CUI'  THEN 1
    END
) AS Points_Candidat

You may also benefit from using labels and indices, and unless the mapping of Comp.name to a value is different from query to query you might consider adding it as a property on Comp and RETURN Person.fname, SUM(Comp.Points_Candidat).


text:
Q: Cast de array al filtrar con stream falla Tengo 3 arrays de una clase llamada TangerMedObject. Al filtrar con Arrays.stream y pasar el resultado a un Array, si intento hacer un cast del array devuelto al tipo TangerMedObject[] (que es lo que realmente se devuelve), obtengo un error:

" java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to
[Les.portel.serviciosportuarios.entity.TangerMedObject;"

Sin embargo, si guardo el array que devuelve el stream de java en un Object[], funciona y veo que en el Object[] es un array compuesto de objetos TangerMedObject.
Falla:
// listaCamiones y listaContenedores son variables del tipo TangerMedObject[]
// Dentro de los camiones nos quedamos con los registros que tambien tengan
// contenedores
listaCamiones = (TangerMedObject[]) Arrays.stream(listaCamiones)
                                    .filter(x -> x.getPlateauNo() != null).toArray();

// Dentro de los contenedores nos quedamos con los registros que tambien tengan
// camiones
listaContenedores = (TangerMedObject[]) Arrays.stream(listaContenedores)
                                    .filter(x -> x.getTrackNo() != null).toArray();

// Unimos el resultado en un solo array
listaCompleta = ArrayUtils.addAll(listaCamiones, listaContenedores);

Funciona:
// Dentro de los camiones nos quedamos con los registros que tambien tengan
// remolque
Object[] camionesTemporal = Arrays.stream(listaCamiones)
                                    .filter(x -> x.getUnitNo() != null).toArray();

// Dentro de los remolques nos quedamos con los registros que tambien tengan
// camiones
Object[] remolquesTemporal = (TangerMedObject[]) Arrays.stream(listaRemolques)
                                    .filter(x -> x.getTrackNo() != null).toArray();

// Unimos el resultado en un solo array
listaCompleta = ArrayUtils.addAll(camionesTemporal, remolquesTemporal);

Me gustaría saber si hay manera de guardar el resultado del stream en un array del objeto que yo quiero, en lugar de en un Object[].

A: Sí hay manera, pasándole el arreglo en el que quieres guardarlo en el proceso antes de regresarlo.
// listaCamiones y listaContenedores son variables del tipo TangerMedObject[]
// Dentro de los camiones nos quedamos con los registros que tambien tengan
// contenedores
        listaCamiones = Arrays.stream(listaCamiones)
                .filter(x -> x.getPlateauNo() != null).toArray(TangerMedObject[]::new);

// Dentro de los contenedores nos quedamos con los registros que tambien tengan
// camiones
        listaContenedores = (TangerMedObject[]) Arrays.stream(listaContenedores)
                .filter(x -> x.getTrackNo() != null).toArray(TangerMedObject[]::new);

// Unimos el resultado en un solo array
        listaCompleta = ArrayUtils.addAll(listaCamiones, listaContenedores);

lo que ves que dice ::new es una referencia estática para la creación de un objeto


text:
Q: Where can I download a xyz bathymetry file of the Northwest Atlantic? I'm looking to download the bathymetry of the Northwest Atlantic ocean as a txt file or any other file format that I can easily upload and use in R.
I once used the Global topography - Scripps Institution of Oceanography but it looks like I'm running into an error message this time...?
I have been looking at other websites, but I'm having a hard time to locate a new site where I could download a xyz file of my area of interest.
I would appreciate any recommendations.
Thank you very much in advance,

A: Upon requesting "topography" for longitudes between -30 and -24 degrees and latitudes between 54 and 60 degrees, I noticed the file contained three columns, for longitude, latitude, and elevation, apparently in an XYZ ASCII output arrangement (totaling 239,704 lines).  After the page was saved in ASCII text format, it could be read and processed in R:
x <- read.table("f:/temp/bathy.txt", header=FALSE)   # Read the data into an array
names(x) <- c("lon", "lat", "z")                     # Provide meaningful column names
nrows <- length(levels(as.factor(x$lon)))            # Count distinct longitudes
library(raster)                                      # Load the 'raster' library
z <- raster(matrix(x$z, nrow=nrows), xmn=min(x$lon),
    xmx=max(x$lon), ymn=min(x$lat), ymx=max(x$lat))  # Create a raster from the array
plot(z)                                              # Plot it

That's the Reykjanes Ridge in the upper left and part of the Eriador Seamount near the lower right, where they should be.


text:
Q: Getting the last inserted messages from ajax chat I'm building a chat application and having some issues. First of all I want the chat starts loading from database  once the the user logs in.
function that gets the whole chat from db which is called by ajax
function getChatData(){
    global $mysqli;
    //echo $lastinseted= $mysqli->insert_id();
    $sql = "SELECT `chat`.`message`,
        `users`. `username`,
        `chat`.`timestamp`
        from `chat` JOIN `users` ON (`chat`.`user_id`=`users`.`user_id`)
        ORDER BY `chat`.`timestamp` DESC limit 15";
    try{
        if($stmt=$mysqli->prepare($sql)){
            echo returnJson($stmt);
            $stmt->close();
            $mysqli->close();
        }else{
            throw new Exception("An error occured while fetching record data");
        }
    }catch(Exception $e){
        log_error($e, $sql, null);
        echo 'fail';
    }
}

here is the callback function:
function getChatCallback(data){
    var h='';
    for(var i=0, l=data.length;i<l;i++){
        h+=data[i].username+' says: '+data[i].message+' at the time '+data[i].timestamp+'
';
    }
    $('.messages').html(h);
    setTimeout(getChat,1500);
 }

this is the function that will insert the new messages to the database which is called once the user hits enter and it is called also by ajax call:
function putChatData($message,$room,$user_id){
    global $mysqli;
    $sql = "INSERT INTO `chat`
    (`message`,`timestamp`,`room`,`user_id`)
    VALUES (?,?,?,?)";
    $timestamp = gmdate("Y-m-d H:i:s");

    try{
        if($stmt=$mysqli->prepare($sql)){
             $stmt->bind_param('ssii',$message,$timestamp,$room,$user_id);

            $stmt->execute();

            $stmt->close();
            $mysqli->close();

        }else{
            throw new Exception("An error occured while fetching record data");
        }
    }catch(Exception $e){
        log_error($e, $sql, null);
        echo 'fail';
    }

}

the problem now is that I could insert the new messages to the db, but the first function the gets the chat, brings all that chat including the old ones before the user logs in.  I tried to use timestamp or the last insert id but didn't work with me.

A: For this usecase you need to know the reg time and add a WHERE condition to your query
$sql = "SELECT `chat`.`message`,
    `users`. `username`,
    `chat`.`timestamp`
    from `chat` JOIN `users` ON (`chat`.`user_id`=`users`.`user_id`)
    WHERE `chat`.`timestamp` > $userRegDate
    ORDER BY `chat`.`timestamp` DESC limit 15";


text:
Q: Unity3D application - the SonarScanner for MSBuild integration failed: SonarQube was unable to collect the required information about your projects I have a Unity3D application, for which I have configured a build pipeline in Azure DevOps by following this documentation.
In the same build pipeline, I have integrated SonarQube tasks (prepare, run code, publish).
Whenever I run this build pipeline, I get the following error:

##[error]12:18:51.144  The SonarScanner for MSBuild integration failed: SonarQube was unable to collect the required information about your projects.
Possible causes:
1. The project has not been built - the project must be built in between the begin and end steps
2. An unsupported version of MSBuild has been used to build the project. Currently MSBuild 14.0.25420.1 and higher are supported.
3. The begin, build and end steps have not all been launched from the same folder
4. None of the analyzed projects have a valid ProjectGuid and you have not used a solution (.sln)


text:
Q: BETWEEN and LIKE on VarChar Field? I have a query that has the follow WHERE criteria condition:
or ((code between 'T71.112' and 'T72') and code like 'T__.__2%')

I was unaware that this could be a valid SQL statement and would think that it would require substringing and recasting parts of the field to handle the BETWEEN.
Is this something unique to SQL Server's implementation and in fact valid?
EDIT:
It sounds like this is valid under most situations/systems one would ever expect to encounter.  How numbers are evaluated in Varchar for the BETWEEN was my primary concern, but it seems to produce expected results.  I have done some testing which seems to confirm it as well.


text:
Q: Javascript: Extract data from option list I am trying to get data from a php sub-page.
Using javascript, I have tried to use :

var items = document.querySelectorAll('option');
console.log("length : "+items.length);
  <option value="75">item-127 ( 120127 )</option>
  <option value="74">item-163 ( 0 )</option>
  <option value="94">item-139 ( 0 )</option>
  <option value="89">item-135 ( 0 )</option>
  <option value="369">Item-AC95 ( AC95 )</option>
  <option value="63">item-159 ( 120159 )</option>

But it does not return the expected length:
length : 0
How could I do it?
The final expectation is having a table with values and items
thanks

A: First, don't forget that <options> tend to appear only within a <select> tag.
Your code works fine. checkout the snippet below.

var items = document.querySelectorAll('option');

console.log('There are ' + items.length + ' options');

items.forEach(function(option,i){
   console.log('option #' + i + '  has value ' + option.value + ' and html:' + option.innerHTML);
});
<html>

<head>
</head>

<body>
  <select>
<option value="75">item-127 ( 120127 )</option>
<option value="74">item-163 ( 0 )</option>
<option value="94">item-139 ( 0 )</option>
<option value="89">item-135 ( 0 )</option>
<option value="369">Item-AC95 ( AC95 )</option>
<option value="63">item-159 ( 120159 )</option>
</select>
</body>

</html>

A: Ideally, <option> tag must be enclosed by <select>.Here is the code to retrieve the value from the option

var items = document.querySelectorAll('option');
for(i = 0; i < items.length; i++) {
       item = items[i];
       if (item.value != "") {

           alert(item.value);
       }
     }
<option value="75">item-127 ( 120127 )</option>
<option value="74">item-163 ( 0 )</option>
<option value="94">item-139 ( 0 )</option>
<option value="89">item-135 ( 0 )</option>
<option value="369">Item-AC95 ( AC95 )</option>
<option value="63">item-159 ( 120159 )</option>

A: I'm not sure if you aware but assigning a variable doesn't output things, you could use console.log() by example.

const values = document.querySelectorAll('option');

console.log(values);
<html>
<head>
</head>
<body>
<option value="75">item-127 ( 120127 )</option>
<option value="74">item-163 ( 0 )</option>
<option value="94">item-139 ( 0 )</option>
<option value="89">item-135 ( 0 )</option>
<option value="369">Item-AC95 ( AC95 )</option>
<option value="63">item-159 ( 120159 )</option>
</body>
</html>

A: Firstly you should wrap your <option> elements in a <select>.
Secondly the code you provided gives you a HTMLNodeList object with <option> as elements of it. Their values are under items[0].value and the item itself is under items[0].innerHTML or items[0].textContent
let options = items.map((option) => {
  console.log(`Item: ${option.textContent}, value: ${option.value}`);
})


text:
Q: Disconnected from Neo4j. Please check if the cord is unplugged I am running simple queries on neo4j 2.1.7
I am trying to execute that query:
MATCH (a:Caller)-[:MADE_CALL]-(c:Call)-[:RECEIVED_CALL]-(b:Receiver) CREATE(a)-[:CALLED]->(b) RETURN a,b
While the query is executing, I am getting the following error
Disconnected from Neo4j. Please check if the cord is unplugged.
Then another error:
GC overhead limit exceeded
I'm working on windows server 2012 with 16G of RAM and here is my nodes.properties file:
**
`neostore.nodestore.db.mapped_memory=1800M
neostore.relationshipstore.db.mapped_memory=1G
#neostore.relationshipgroupstore.db.mapped_memory=10M
neostore.propertystore.db.mapped_memory=500M
neostore.propertystore.db.strings.mapped_memory=250M
neostore.propertystore.db.arrays.mapped_memory=10M

cache_type=weak
keep_logical_logs=100M size**`

and my neo4j-community.vmoption file:
 **
-Xmx8192
-Xms4098
-Xmn1G
-include-options ${APPDATA}\Neo4j Community\neo4j-community.vmoptions**

I have 6 128 644 Nodes, 6 506 355 Relationships and 10 488 435 properties
Any solution?

A: TL;DR: Neo4j disconnected because your query is too inefficient. The solution is to improve the query.
Your Neo4j instance appears to have timed out and undergone a GC dump due to the computational intensiveness of your query. When you initialize the Neo4j database using the bash shell, you have the option of configuring certain JVM variables, of which include the amount of memory and heap size available to Neo4j. Should a query exceed these computational limitations, Neo4j automatically terminates the query, undergoes a GC dump, and disconnects.
Looking at the information you gave on the database, there are 6M nodes with 6M relationships. Considering that your query essentially looks for all pathways from Callers to Receivers across 6M nodes, then tries to perform bulk write operations, it's not surprising that Neo4j crashes/disconnects. I would suggest finding a way to limit the query (even with a simple LIMIT keyword) and running multiple smaller queries to get the job done.


text:
Q: page.evaluate() Как Передать несколько параметров в функцию?) Получаю вот такую ошибку при использовании этой функции

Error: Too many arguments. If you need to pass more than 1 argument to the function wrap them in an object

  async waitForValue(page, selector, value) {
    const result = await page.evaluate(
      (selector, value) =>
        document.querySelector(selector).getAttribute('value').includes(value),
      selector,
      value,
    )
    console.log(result)
  },

A: Внезапно, нужно просто передать несколько аргументов.
Чуть-чуть изменённый пример из документации:
const puppeteer = require('puppeteer');

(async () => {
    const browser = await puppeteer.launch();
    const page = await browser.newPage();

    // (x, y, z) - приняли три аргумента
    const result = await page.evaluate((x, y, z) => {
        return Promise.resolve(x * y * z);
    // 7, 8, 9 - передали три аргумента
    }, 7, 8, 9);
    console.log(result);

    await browser.close();
})();

Что касается предстваленного вами кода, то он наводит на предположение о том, что присутсвует проблема XY, т.к. он отвечает на вопрос из заголовка. Но если на странице не окажется элемента подходяшего под передаваемый селектор, то document.querySelector(selector) вернёт null что в даст ошибку, т.к. null не имеет метода getAttribute.
Если передавать одним аргументом, как предлагается в ошибке:
const puppeteer = require('puppeteer');

(async () => {
    const browser = await puppeteer.launch();
    const page = await browser.newPage();

    // Теперь всё внутри args
    const result = await page.evaluate((args) => {
        return Promise.resolve(args.x * args.y * args.z);

    // Передали объектом
    }, {x:7, y:8, z:9});
    console.log(result);

    await browser.close();
})();


text:
Q: What is the reason of using two sets of parentheses on object method call I'm currently learning and educating myself on javascript, i just found one simple code which is using this '()();' what is this called, didnt find much information about it, what is it and how it is used, here the code i found :

  'use strict';
    let obj, method;

    obj = {
      go: function() { alert(this); }
    };

    obj.go();

    (obj.go)();

    (method = obj.go)();

    (obj.go || obj.stop)();

sory english is not my mother language if some mistake.

A: Used on their own, parenthesis are grouping operators. They group expressions to control the order or precedence of the evaluation. You can read MDN here about it.
// example                 // is the same as

(obj.go)();                 obj.go();

(method = obj.go)();        method = obj.go; method();

(obj.go || obj.stop)();     // calling go or stop after assinging to a temp variable

A: That piece of code is demonstrating how this is bound within a function execution content (in this case in go). It shows that simply putting parentheses around a method does not alter that behaviour: this is still bound to obj.
As soon as the parentheses surround an expression involving operator(s) the situation changes, and the method that results from the expression is called without a specific this binding: the default applies (undefined).
Another variant is the following:
(0,obj.go)();

Here the comma-operator kicks in, and so we are in the expression case: this is no longer bound to obj in the method call.

A: It just controls the order of the execution. You could write everything like this too, to make it more clear:
// (obj.go)();
obj.go();

// (method = obj.go)();
method = obj.go;
method();

// (obj.go || obj.stop)();
var method = obj.go || obj.stop;
method();


text:
Q: I cannot read second internal HD I reformatted my Win "C" drive and loaded Ubuntu 11.04. The second internal HD of course is not read.  It is shown in 'disk utility'.  I try to mount it in disk utility but I get an error message
error mounting: mount exited with exit code 1: helper failed with:
mount: according to mtab, /dev/sda1 is already mounted on /

One problem I see is the error relates to sda1, but I am trying to mount sdb.
Unfortunately, I am windows literate and ignorant of the coding for linux.
Can someone help me with the code to mount my second drive (sdb)
Nathan

A: Before you can mount a disk, you need to have a mountpoint (which is a directory). The general command for mounting a partition is:
sudo mount /dev/sdb1 /mnt

Here, /dev/sdb1 is the first (1) partition on the second disk (b). If the command was succesful, the filesystem wil be available at /mnt. Only the superuser can mount new filesystems, therefore sudo is prepended on the command. If you're mounting multiple partitions, you might want to create a folder before use:
sudo mkdir /media/mountp
sudo mount /dev/sdb1 /media/mountp

Do not forget to remove the directory after unmounting it:
sudo umount /media/mountp
sudo rmdir /media/mountp