text:
Q: How do I run a directory compare operation from TortoiseGit? The diff program BeyondCompare has a directory compare feature where you can select two folders and have it run a side-by-side comparison on all files within those folders that have the same filenames, and then look at individual files that it flags as showing differences.  TortoiseSVN has a way to run this directory comparison between two versions of a directory, or an older version and the working copy, which is really awesome at times.
Unfortunately, not everything is in SVN.  I've got a Git-versioned project that contains a large folder with well over 100 auto-generated files.  They got regenerated recently, and TortoiseGit is telling me that every last one of them has been changed.  When I diff a few of them, though, all I see are harmless and irrelevant whitespace changes.  It's not impossible that a very few changes might exist somewhere in there, but I'd prefer not to have to go over every single one of them manually.
Is there any way I can get TortoiseGit to send a directory compare to BC for me, so I can have it compare the old version with my working copy while ignoring whitespace (it can do that) and then I can know for sure whether there are any relevant changes in this folder or if I can just revert the whole thing?

A: I ran into this same problem. Unfortunately, as Yue Lin Ho stated, TortoiseGit does not have this available directly in the GUI. However, if you have TortoiseGit, you have some version of command line Git installed. Therefore, you can invoke BeyondCompare from the command line.
The following instructions assume you have Git version 2.2.0 or later
First, you have to setup BC as your diff tool:
  git config --global merge.tool bc
  git config --global mergetool.bc.path "c:/Program Files (x86)/Beyond Compare 4/bcomp.exe"

(Note that the default Windows path is shown. The path may be different if using a different OS or if you have a Portable version of BC installed on Windows, for example. Make sure you use the actual path to your copy of BC)
Then you can invoke BC folder compare in Git by running the following inside the folder for your Git project:
git difftool --dir-diff

A: There is no way to send a directory compare to BC/external diff tool.
But, you still can compare two commits/revisions of a directory in TortoiseGit and there are some "ignore" options:

A: You could try another approach with a temporary checkout:
Checkout your old version to a new directory.
Then use the standard folder comparison of beyond compare to compare the new directory with the working dirctory.
You can define unimportant text to filter the irrelevant whitespace changes.
When you finished your comparison you can delete the directory with the old version.


text:
Q: Top hits aggregation group by I am using top_hits_aggregation to get my users last visited document. I want to group by the results of top_hits_aggregation.
Sample Rows Returned:
{
  "lastvisited_users": {
   "buckets": [
     {
      "top_user_hits": {
        "hits": {
           "hits": [
              { _source: {"c": "s"}},
              { _source: {"c": "s,b"}},
              { _source: {"c": "s"}},
           ]
         }
       }
     }
   ]
 }
}

I want to group by the results by field "c".
Expected output:
{
"s": 2,
"s,b": 1
}

I am using elasticsearch version 1.7 in production. How to do this?

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to remove the gap between two components in JDialog I have following(snippet) JDialog box with gridbag and having multiple components in it.
I want to remove the gap between the "search" textfield and the bottom Jlist. How to do that?
My code snippet is
textField_1 = new JTextField(TEXTFIELD_INPUT_PROMPT);
    GridBagConstraints gbc_textField_1 = new GridBagConstraints();
     gbc_textField_1.insets = new Insets(0, 0, 5, 5);
    gbc_textField_1.fill = GridBagConstraints.BOTH;
    gbc_textField_1.gridx = 6;
    gbc_textField_1.gridy = 5;
    getContentPane().add(textField_1, gbc_textField_1);
    textField_1.setColumns(10);
    textField_1.addFocusListener(new MyFocusListener(textField_1));

    DefaultListModel<String> model_list = new DefaultListModel<>();
    list = new JList<String>(model_list);
    GridBagConstraints gbc_list = new GridBagConstraints();
     gbc_list.insets = new Insets(0, 0, 5, 5);
    gbc_list.fill = GridBagConstraints.BOTH;
    gbc_list.gridx = 2;
    gbc_list.gridy = 6;
    sp = new JScrollPane(list);
    getContentPane().add(sp, gbc_list);
    list.setVisibleRowCount(10);
    list.setFixedCellWidth(14);


text:
Q: Prevent elements from wrapping when resizing the window How can I prevent my squares from wrapping when resizing the window?
I want the squares to stay at their positions, but every time I resize the window, they get pushed down and are hidden.
This example is currently working, but the solution, which makes this possible, is just ridiculous.
Is there a "cleaner" way or how can I make it look more professional?
My JSFiddle Example
.content {
    width: 100000000px;
}

A: Remove position:absolute and overflow:hidden from the parent element.
Since the elements are inline-block, you could use white-space:nowrap to prevent them from wrapping. If that's not the desired effect, just remove it though.
jsFiddle example
#container {
    width: 100%;
    height: 100px;
    white-space:nowrap;
}
.square {
    display: inline-block;
    width: 100px;
    height: 100px;
}

A: http://jsfiddle.net/CLErY/2/
/* The following rule can be romoved, is just to give a smooth overflow hidden visibility */
.content {
    width: 200%; /* Always bigger than the real value, so 200% is the double and it should work. */
}

.content should have at least the size of the whole element plus the size of one children (100px), so 200% is the double and it should work.
In case we have 4 squares the size should be (width x 4 + width) in case the width of the square is 100 the result is 500px.
Also this is to give a smoother overflow dissapear but not necesary.
Hope it helps.


text:
Q: Problem with function parametrs i cant refer to this function let confirmed = {};
let deaths = {};
let recovered = {};
const objectWithParams = (param) =>
  getCountryInfo.map((item) => {
    let year, month, day;
    const formatDate = ([year, month, day] = item.date
      .split("-")
      .map((element) => parseInt(element)));
    for (var i = 0; i < getCountryInfo.length; i++) {
      param = { x: new Date(formatDate), y: item.param };
    }
    return param;
  });

confirmed = objectWithParams(`confirmed`);
console.log(confirmed);

how i can refer to the function parametr during it is mapping
this code in console.log show me that "y" is undefined, how i can do that it will be good?

A: You don't need to iterate again. You are already iterating in map.
Sample:

let confirmed = {};
let deaths = {};
let recovered = {};
const objectWithParams = (param) =>
  param.map(({ date, ...rest }) => {
    const formatDate = date.split("-").map((element) => parseInt(element));
    return { x: new Date(formatDate), ...rest };
  });

confirmed = objectWithParams([
  {
    date: "03-04-2020",
    death: 10,
    active: 12,
    recovered: 10,
  },
  {
    date: "03-01-2020",
    death: 10,
    active: 12,
    recovered: 10,
  },
  {
    date: "03-02-2020",
    death: 10,
    active: 12,
    recovered: 10,
  },
  {
    date: "03-04-2020",
    death: 10,
    active: 12,
    recovered: 10,
  },
]);
console.log(confirmed);

Mapper Function:

let confirmed = {};
let deaths = {};
let recovered = {};
class Mapper {
  constructor(array, key) {
    this.map = array.reduce((map, item) => {
      const val = item[key];
      if (!map[val]) {
        map[val] = [];
      }
      map[val].push(item);
      return map;
    }, {});
  }

  find(key) {
    return this.map[key] && this.map[key][Mapper.FIRST_INDEX]; //return blank array
  }

  findAll(key, returnUndefined) {
    //return blank array
    return this.map[key] ? this.map[key] : returnUndefined ? undefined : [];
  }
}

Mapper.FIRST_INDEX = 0;
const data = [
  {
    date: "03-04-2020",
    death: 10,
    confirmed: 12,
    recovered: 12,
  },
  {
    date: "03-01-2020",
    death: 10,
    confirmed: 12,
    recovered: 10,
  },
  {
    date: "03-02-2020",
    death: 10,
    confirmed: 12,
    recovered: 23,
  },
  {
    date: "03-04-2020",
    death: 10,
    confirmed: 21,
    recovered: 10,
  },
]

var userMapper = new Mapper(data, "confirmed"); // create a map on names
console.log(JSON.stringify(userMapper.map, null, 4)); //will return only user with name 'Schmidt'
userMapper = new Mapper(data, "recovered"); // create a map on names
console.log(JSON.stringify(userMapper.map, null, 4)); //will return only user with name 'Schmidt'

A: Is this what you were looking for (xdeepakv almost had it the first time I think)

const data = [
  {
    date: "03-04-2020",
    death: 10,
    active: 12,
    recovered: 10,
  },
  {
    date: "03-01-2020",
    death: 10,
    active: 12,
    recovered: 10,
  },
  {
    date: "03-02-2020",
    death: 10,
    active: 12,
    recovered: 10,
  },
  {
    date: "03-04-2020",
    death: 10,
    active: 12,
    recovered: 10,
  },
]

const objectWithParams = (param) =>
  data.map(({ date, [param]:y }) => {
    const formatDate = date.split("-").map((element) => parseInt(element));
    return { x: new Date(formatDate), y };
  });

confirmed = objectWithParams('death');
console.log(confirmed);


text:
Q: Is it good practice to use appropriate data types? This might be a stupid question but here goes:
I'm unsure whether it's habit, laziness, or the correct thing to do. But I find myself using data types that I simply don't need to use, for the sake of consistency, and making things a little bit easier to code later on (i.e casting data types).
Let me show you an example:
public int Number1 { get; set; }

Number1 is just a regular whole number, but imagine the scenario where it will always (or has to be) be a positive number, so I could in fact use uint instead of an int.
However, one of the problems with using lots of different data types is the risk of having to use explicit casting, so I would have lots of noisy code. Using common data types such as int helps to reduce the noise but would this have any effect on the overall performance of an application compared to casting?
int one = 2;
uint two = 1;

one = (int)two;

This noise isn't necessarily bad, but it can be frustrating. There could also be an issue where the uint could be higher than the maximum value of an int.
I find that in many examples, int seems to be a very commonly used data type for working with whole numbers, I very rarely see other data types being used. Why is this?
Is there anything wrong with using 'incorrect' data types, is it more efficient to use an int, rather than a uint, or a short ect?
Thanks in advance.

A: The best practice is to not simply use signed or unsigned numbers based on the nature of the entities that you want to represent, but to actually declare an entirely new data type for each different type of entity that you are dealing with.
So, for example, a temperature requires a signed number, but the best practice is to declare a new "Temperature" value type. (struct Temperature)
The beauty of C# is that:

*

*If your struct Temperature contains nothing but a float, it will occupy exactly as much memory as a float would, and it will be as efficient as a float. (The entire struct will be passed around in a register just as a float would.)

*You can overload operators, including type cast operators, including implicit type cast operators, so if your temperature needs to be freely interchangeable with some other kind of entity, you can overload the appropriate operators and achieve this without any type casts.  (See https://msdn.microsoft.com/en-us/library/85w54y0a.aspx)
It should be noted, however, that free interchangeability between data types defeats the purpose of declaring them as separate data types in the first place. What you should do instead is encapsulate as many operations as possible within the type itself, so as to minimize the situations where the type needs to be converted to something else.
Amendment
The practice of defining a special data type for every different type of quantity you are dealing with is derived from, and in accordance with, the practice of Physicists to always follow every single term of an equation with the units of that term.  So, length is never just a plain 5 value, it is always a 5 metres value (in SI), and also acceleration is never just a plain 9.8 value, it is always a 9.8 metres per second squared value. This tends to make it very evident when a mistake is being made, and therefore minimizes the chances of it happening.  For example, attempting to use a value in centimeters in an equation which expects meters, and also (even more importantly) attempting to use a velocity value in an equation which expects an acceleration value.  For more information about this, see, for example, this: https://physics.stackexchange.com/q/138841
Making mistakes evident was also the original intention of Hungarian notation (see https://en.wikipedia.org/wiki/Hungarian_notation) though at the time it was not really possible with the C language to define a different data type for each kind of value and maintain performance.  So, they just fiddled with the names of the variables.
With modern languages like C# we can finally declare our own efficient types, so that data type substitution mistakes are not just easier to catch, but actually impossible to make.

A: Before looking at the performance, see if the correctness of your program is compromised by this assignment:
one = (int)two;

it has a potential of overflowing int, which is much worse than a simple loss of a few CPU cycles.
If you know that there will be no overflow, because you have sanitized the values of unsigned variables (in this case, two is less than or equal to int.MaxValue) then you might as well use int. The reasons to go for an unsigned data type would be to gain the extra bit, or to make all operations treat the number as unsigned, not to gain performance or to make an implicit validation.

A: In .NET Framework, even for positive or zero values, Microsoft choosed to use int or long in place of uint or ulong. Why : because it's easier to avoid type casts between signed and unsigned types and potential exception on sign change on substractions that unsigned integers may imply.
So, what does using only posivite or zero values on an int mean: Using only 31 of the 32 bits. Not a problem : we have a lot of memory.
This may become a problem if you want to store binary data, in that case you will generaly use byte that is unsigned. Data size can also become important for very large data storage and in communications on slow medias. Some optimized algorithms will be written to minimize memory usage and will also use unsigned values.
What is the good practice : If you use values between 0 and 2 000 000 000, use an int, if you want to be easy to use, use ints or longs. If memory usage impact, media bandwith usage is crucial, data are of binary nature (images bits, sounds, ...) or algorithm efficiency requires use of uint or ulong, use them but be carefull during substractions : substracting a number higher than the first operand will throw an ArithmeticOverflowException.


text:
Q: Why can't a range be sorted in range-v3? Using the Range-v3 (release 0.10.0) library I was trying to construct a range from a std::vector, transform it into another range and finally sort that range. I expected the sort step to produce another range that I could consume later. But the best I could come up with was this:
std::vector<std::string> const input { "2", "3", "1" };
using namespace ranges;
std::vector<int> output = input
    | views::transform([](std::string s) { return std::stoi(s); })
    | to<std::vector>()
    | actions::sort

Notice the use of to<std::vector>() after the transform step and before the sort step. This seems to allocate a new std::vector when all I wanted was to sort the range that the transform step had produced.
Why is there no view::sort ? It would fit nicely in the above composition of ranges.

A: The transformed range is only a view, the elements are generated one at a time as the view is iterated. It can't be sorted as there is nowhere to store the sorted elements. A hypothetical implementation would also be inefficient as it would have to transform each element every time it needed to do a comparison for the sort.
Your solution is correct to store the transformed elements in a vector then sort them.


text:
Q: Kubernetes Fake Client doesn't handle GenerateName in ObjectMeta When using the Kubernetes Fake Client to write unit tests, I noticed that it fails to create two identical objects which have their ObjectMeta.GenerateName field set to some string. A real cluster accepts this specification and generates a unique name for each object.
Running the following test code:
package main

import (
    "context"
    "testing"

    "github.com/stretchr/testify/assert"
    corev1 "k8s.io/api/core/v1"
    metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
    "k8s.io/client-go/kubernetes/fake"
)

func TestFake(t *testing.T) {
    ctx := context.Background()
    client := fake.NewSimpleClientset()

    _, err := client.CoreV1().Secrets("default").Create(ctx, &corev1.Secret{
        ObjectMeta: metav1.ObjectMeta{
            GenerateName: "generated",
        },
        StringData: map[string]string{"foo": "bar"},
    }, metav1.CreateOptions{})
    assert.NoError(t, err)

    _, err = client.CoreV1().Secrets("default").Create(ctx, &corev1.Secret{
        ObjectMeta: metav1.ObjectMeta{
            GenerateName: "generated",
        },
        StringData: map[string]string{"foo": "bar"},
    }, metav1.CreateOptions{})
    assert.NoError(t, err)
}

fails with
--- FAIL: TestFake (0.00s)
    /Users/mihaitodor/Projects/kubernetes/main_test.go:44:
            Error Trace:    main_test.go:44
            Error:          Received unexpected error:
                            secrets "" already exists
            Test:           TestFake
FAIL
FAIL    kubernetes  0.401s
FAIL

A: According to this GitHub issue comment:

the fake clientset doesn't attempt to duplicate server-side behavior
like validation, name generation, uid assignment, etc. if you want to
test things like that, you can add reactors to mock that behavior.

To add the required reactor, we can insert the following code before creating the corev1.Secret objects:
client.PrependReactor(
    "create", "*",
    func(action k8sTesting.Action) (handled bool, ret runtime.Object, err error) {
        ret = action.(k8sTesting.CreateAction).GetObject()
        meta, ok := ret.(metav1.Object)
        if !ok {
            return
        }

        if meta.GetName() == "" && meta.GetGenerateName() != "" {
            meta.SetName(names.SimpleNameGenerator.GenerateName(meta.GetGenerateName()))
        }

        return
    },
)

There are a few gotchas in there:

*

*The Clientset contains an embedded Fake structure which has the PrependReactor method we need to call for this use case (there are a few others). This code here is invoked when creating such objects.

*The PrependReactor method has 3 parameters: verb, resource and reaction. For verb, resource, I couldn't find any named constants, so, in this case, "create" and "secrets" (strange that it's not "secret") seem to be the correct values for them if we want to be super-specific, but setting resource to "*" should be acceptable in this case.

*The reaction parameter is of type ReactionFunc, which takes an Action as a parameter and returns handled, ret and err. After some digging, I noticed that the action parameter will be cast to CreateAction, which has the GetObject() method that returns a runtime.Object instance, which can be cast to metav1.Object. This interface allows us to get and set the various metadata fields of the underlying object. After setting the object Name field as needed, we have to return handled = false, ret = mutatedObject and err = nil to instruct the calling code to execute the remaining reactors.

*Digging through the apiserver code, I noticed that the ObjectMeta.Name field is generated from the ObjectMeta.GenerateName field using the names.SimpleNameGenerator.GenerateName utility.


text:
Q: Assign spotlight short cut to different keys By default in Yosemite Spotlight shortcut is assigned to ⌘SPACE, but change language is also ⌘SPACE so for a multilingual person it turns out to be a tough choice which one to use. I am wondering if there is a way of assigning a different short cut as ⌥SPACE for a spotlight or the language switch?
I know I can disable language switch and only use 'next language' as ⌥⌘Space, but I am looking for an easy 2 keys solution

A: just go to Preferences -> Keyboard. There you select the Shortcut tab and on the left Spotlight. Here you can enable/disable shortcuts and also customize them. Just click on the Shortcut on the right so it becomes selected and then press the new combination of keys you want to assign to it.

Hope that resolves your problem.
Best regards


text:
Q: Creating multiple unnested records A controller action invokes the quantity of records to create as
@guests = []
@quantity.times do
  @guests << Guest.new

which in the form is presented as follows.
<%= form_tag multiple_guests_path do %>
  <% @guests.each_with_index do |guest,index| %>
    <%= fields_for 'guests[]', guest do |f| %>

the parameters are submitted and look like:
  Parameters: {"utf8"=>"✓", "guests"=>[{"name"=>"f1", "lastname"=>"l1", [...]}, {"name"=>"f2", "lastname"=>"l2",[...]}], "commit"=>" Send "}

However the multiple controller action does not process these parameters as guest parameters
 params[:guests].each do |guest|
   @guest = Guest.new(guest_params)

returning error  param is missing or the value is empty: guest for the strong_params setter
def guest_params
  params.require(:guest).permit(:name, :lastname,

How can this action process the parameters correctly?

A: When you use require on params it looks for the key you asked for in the params hash and if it can't find it - it raises an error.
In your case:
def guest_params
  params.require(:guest).permit(:name, :lastname....

you required a key named guest and since the params hash you get from the page doesn't have that key you get that error:
param is missing or the value is empty: guest
You can see that the passed key is guests - in the plural form.
so you should require the correct key:
def guest_params
  params.require(:guests).permit( ... )
end

I think you can also not require any key, and just use permit:
params.permit( ... )

but you should require what you need!


text:
Q: Delete the content between HTML tags including the tags themselves in Perl There are about 100 files and I need to go through each of them and delete all the data which is between <style> and </style> + delete these tags too.
For example
<html>
<head> <title> Example </title> </head>
<style>
p{color: red;
background-color: #FFFF;
}
div {......
...
}
</style>
<body>
<p> hi I'm a paragraph. </p>
</body>
</html>

should become
<html>
<head> <title> Example </title> </head>
<body>
<p> hi I'm a paragraph. </p>
</body>
</html>

Also, in some files the style pattern is like
<style type="text/css"> blah </style>

or
<link rel="stylesheet" type="text/css" href="$url_path/gridsorting.css">

I need to remove all 3 patterns. How do I do this in Perl?

A: use strict;
use warnings;

use XML::LibXML qw( );

my $qfn = 'a.html';

my $doc  = XML::LibXML->load_html( location => $qfn );
my $root = $doc->documentElement();

for my $style_node ($root->findnodes('//style')) {
   $style_node->parentNode()->removeChild($style_node);
}

{
   open(my $fh, '>', $qfn)
      or die;
   print($fh $doc->toStringHTML());
}

It correctly handles:

*

*style elements with attributes or spaces in the tag,

*style elements that span more than one line,

*style tags that span more than one line,

*lines that contain part of a style element and something else,

*documents with multiple style elements,

*something that looks like a style tags in attribute values,

*something that looks like a style tags in CDATA blocks, and

*something that looks like a style tags in comments.

As of this update, the other solutions only handle 2 or 3 of these.

A: Ikegami is right, you really should use at least an HTML/XML parser to do this task. Personally I like using the Mojo::DOM parser. This is a Document-Object Model interface to your HTML and it supports CSS3 selectors, making it really flexible when you need it. This is a pretty easy one for it however:
#!/usr/bin/env perl

use strict;
use warnings;

use Mojo::DOM;

my $content = <<'END';
<html>
<head> <title> Example </title> </head>
<style>
p{color: red;
background-color: #FFFF;
}
div {......
...
}
</style>
<body>
<p> hi I'm a paragraph. </p>
</body>
</html>
END

my $dom = Mojo::DOM->new( $content );
$dom->find('style')->pluck('remove');

print $dom;

The pluck method is a little confusing, but its really just a shorthand for the doing a method on each resultant object. The analogous line could be
$dom->find('style')->each(sub{ $_->remove });

which is a little more understandable but less cute.

After reading your edit that you have to deal with more that just your basic form, I have to stress even further that this is why you use a parser for modifying HTML rather than let your regex grow to ridiculous proportions.
Now lets say that the $content variable also contained these lines
<link rel="stylesheet" type="text/css" href="$url_path/gridsorting.css">
<link rel="icon" href="somefile.jpg">

where you want to remove the first one, and not the second. You can do this in one of two ways.
$dom->find('link')->each( sub{ $_->remove if $_->{rel} eq 'stylesheet' } );

This mechanism uses the object methods (and Mojo::DOM exposes attributes as hash keys) to remove only the link tags which have rel=stylesheet. You can however use CSS3 selectors to only find those elements, however, and since Mojo::DOM has full CSS3 selector support you can do
$dom->find('link[rel=stylesheet]')->pluck('remove');

CSS3 selector statements can be joined with a comma to find all tags matching either selector, so we can simply include the line
$dom->find('style, link[rel=stylesheet]')->pluck('remove');

and get rid of all your offensive stylesheets in one fell swoop!

A: One more possible solution is to use HTML::TreeBuilder.
#!/usr/bin/perl

use strict;
use warnings;
use HTML::TreeBuilder 5; # Ensure weak references in use

foreach my $file_name (@ARGV) {
  my $tree = HTML::TreeBuilder->new; # empty tree
  $tree->parse_file($file_name);
  # print "Hey, here's a dump of the parse tree of $file_name:\n";
  # $tree->dump; # a method we inherit from HTML::Element
  foreach my $e ($tree->look_down(_tag => "style")) {
      $e->delete();
  }
  foreach my $e ($tree->look_down(_tag => "link", rel => "stylesheet")) {
      $e->delete();
  }
  print "And here it is, bizarrely rerendered as HTML:\n",
    $tree->as_HTML, "\n";

  # Now that we're done with it, we must destroy it.
  $tree = $tree->delete; # Not required with weak references
}

A: One way using sed:
sed '/<style>/,/<\/style>/d' file.txt

Results:
<html>
<head> <title> Example </title> </head>
<body>
<p> hi I'm a paragraph. </p>
</body>
</html>

A: perl -lne 'print unless(/<style>/.../<\/style>/)' your_file

tested below:
> cat temp
<html>
<head> <title> Example </title> </head>
<style>
p{color: red;
background-color: #FFFF;
}
div {......
...
}
</style>
<body>
<p> hi I'm a paragraph. </p>
</body>
</html>

> perl -lne 'print unless(/<style>/.../<\/style>/)' temp
<html>
<head> <title> Example </title> </head>
<body>
<p> hi I'm a paragraph. </p>
</body>
</html>
>

if you want to do it inplace,then:
perl -i -lne 'print unless(/<style>/.../<\/style>/)' your_file

A: I figured out one way, you can try the following:
#! /usr/bin/perl -w
use strict;
my $line = << 'END';
<html>
<head> <title> Example </title> </head>
<style>
p{color: red;
background-color: #FFFF;
}
div {......
...
}
</style>
<body>
<p> hi I'm a paragraph. </p>
</body>
</html>
END

$line =~ s{<style[^>]*.*?</style>.}{}gs;
print $line;


text:
Q: Vue-select not loading more when searching So I made a simple v-select where i put an infinite scroll. This works good I can load all the users and when i scroll down 10 more users are added to the array. When I typ i can filter in the select and i get to see 10 users filtered but when I scroll down there are no 10 users added. I only see loading more options. I have been searching for this quit some time but haven't found an answer for this problem so I thought I try to ask it here...
The only thing I noticed debugging is when I  console.log(this.$refs.load)
I see :

 Loading more options...

But when i search nothing is logged so i guess it must be something with the observer or so...
If u need more info please ask.
my code
vue component:
<template>
    <v-select
        :options="users"
        label="name"
        :filterable="false"
        @open="onOpen"
        @close="onClose"
        @search="inputSearch"
        class="form-control"
        :loading="loading"

    >
        <template #list-footer>

                Loading more options...

        </template>
    </v-select>
</template>

UserController :
  public function users(Request $request){

        return User::query()

            ->when($request->search,function ($q) use ($request) {

                $q->where('name', 'like', '%' . $request->search . '%');

            })
            ->orderBy('name', 'ASC')->paginate(10);

    }

A: I've fixed the issue with adding two code lines simply.
...
inputSearch: _.debounce(   async function (search, loading) {
    if (search.length) {
        this.users = []
        this.loading = true
        this.page = 0
        this.getUsers(search, loading)
        //await this.$nextTick()
        // Add following code lines for reloading the infiniteScroll observer
        this.onClose()
        await this.onOpen()
     }
}, 500),
...


text:
Q: Xcode6: What does faded (grey) check button in Connections Inspector mean? In the process of debugging the application I'm working on, I read some other threads here that posted with the same error message I had received and one of the recommendations was to look at the connections inspector and fix anything broken there.
So in the process of doing this, I've noticed something I don't understand.
While there are no exclamation marks in the connection inspector to warn me of broken links here, I noticed that some outlet and segue connections had a black button next to them (to show they are active) but the view outlet has a grey/faded/half-checked button, while the others are all unchecked (blank).
What does this faded, grey, status of the view outlet mean?


text:
Q: Send message to all servers in wazure web farm I have a number of Asp.Net Core 2.x AppService WebApp instances running in Azure.  They all keep a copy of a data object in a local memory cache.
Assume in this scenario that distributed cache is not a feasibility.  As such, I'm looking for a mechanism to send a message/signal to all relevant instances to refresh their memory objects in the local cache.
I can call a rest endpoint to flush the local memory cache, but I'm not sure if there is a way of directing the handling of the call to specific instances.  Is this possible?  If not, is there a workout to letting each instance in the farm know that it's time to expire their cache?

A: Firstly, Azure App Service content is stored on Azure Storage and is surfaced up in a durable manner as a content share and the content is shared across multiple virtual machine (VM) instances of the app.
Would the Local cache feature work fine for your requirement: - The Azure App Service Local Cache feature provides a web role view of your content. This content is a write-but-discard cache of your storage content that is created asynchronously on-site startup. When the cache is ready, the site is switched to run against the cached content
If you're just looking at restart a specific instance in pool, you could leverage Auto-healing feature -  where you could define the triggers in the root web.config file of your web site and configure the actions to be performed when these triggers are hit.
If you have multiple instances of your web site, it will only log an event for the instance that has hit this trigger and not all instances. Take a look at this blog  for details.
As a side note, In Azure Portal, navigate to your Azure web app under Diagnose and Solve Problems, search for  -Advanced Application Restart- and you will get an option that allows you to pick just the instance you want. Kindly let me know if this helps or you need further assistance.


text:
Q: Concatenate values from a table then update a field in a different table with those values I need to populate a field in Table1 with concatenated data from Table2 based on the AuthorIDs in Table 1. The IDs in table 1 are a string separated by a ;. for example '234;242;54'
I found a function that will turn CSV into a table, I can then use those values to grab the GUIDs associated with those IDs and concatenate them
SELECT TOP 100 *,
  stuff((
        select ';' + convert(varchar(200),AuthorGuid)
        from
            (select t.AuthorGuid
            from Table2 t
            where t.AuthorID in (select * from dbo.CSVToTable(REPLACE(w.Authors,';',',')))
            ) auths
        for xml path('')), 1, 1, '') as AuthorGUIDStemp
  FROM Table1 w

The above query puts the GUIDS in a temporary field in Table1 but I need to update Table1
update Table1 w set AuthorGUIDs =
    stuff((
        select ';' + convert(varchar(200),AuthorGuid)
        from
            (select t.AuthorGuid
            from Table2 t
            where t.AuthorID in (select * from dbo.CSVToTable(REPLACE(Authors,';',',')))
            ) auths
        for xml path('')), 1, 1, '')

This does not work to update the field & throws errors.

Msg 102, Level 15, State 1, Line 15
Incorrect syntax near 'w'.
Msg 156, Level 15, State 1, Line 23
Incorrect syntax near the keyword 'for'.

How do I make this update work?

A: It looks like your update syntax may be off.  I believe you're attempting to update AuthorGuids with an type XML.
Try this assuming the results you want are text:
 UPDATE  w
  SET   AuthorGUIDs = STUFF((   SELECT  ';' + CONVERT(VARCHAR(200), AuthorGuid)
                                  FROM
                                    (   SELECT  t.AuthorGuid
                                          FROM  Table2 t
                                          WHERE t.AuthorID IN(SELECT    * FROM  dbo.CSVToTable(REPLACE(Authors, ';', ',')) ))auths
                                FOR XML PATH(''), TYPE).value('.', 'varchar(max'), 1, 1, '')

  FROM  Table1 w


text:
Q: Android kill service when app relauch and close? I have to run a task in background when reach the scheduled time.i assigned the task of waking up my service to Alarm Manager and it does well if the app is background/running.service keep running fine on app's background as well as foreground states if am not changing the state of app after beginning the service.for the purpose of well understanding the scenario's given below.
Case 1:

1.Setting up the schedule and sending the time to alarm manager and keep the app running.
2.Alarm manager calls the service when the time is reaching.
3.Service start running
4.when i close my app service get stopped

Case 2:

1.Setting up the schedule and sending the time to alarm manager and closing the app.now app in background.
2.Alarm manager calls the service when the time is reaching.
3.Service start running
4.Relaunching the app.service continuing running/working fine.
5.Now closing the app and the result is service dead.

I have to call the service only by Alarm Manager , not on every time when app launches for that purpose in service onStartCommand method i returned START_NOT_STICKY and i don't want to use START_STICKY.if i goes to START_STICKY it won't consider the scheduled time.and the thing is i don't want to check the time again as it's doing well by Alarm Manager.
When app running on low memory the services get destroyed.is the solution using startForeground instead of startService ?
How can i make my service running stable without bothering about the app opening/closing states ?

Setting schedule

public void setAction(View v) {
        Calendar calendar = Calendar.getInstance();
        int hour = Integer.parseInt(HH.getText().toString());
        int minute = Integer.parseInt(MM.getText().toString());
        int second = Integer.parseInt(SS.getText().toString());
        String peried = PP.getText().toString();
        calendar.set(Calendar.HOUR_OF_DAY, hour);
        calendar.set(Calendar.MINUTE, minute);
        calendar.set(Calendar.SECOND, second);
        calendar.set(Calendar.AM_PM, peried.equalsIgnoreCase("AM") ? Calendar.AM : Calendar.PM);
        Intent myIntent = new Intent(MainActivity.this, MyReceiver.class);
        myIntent.putExtra(ACTION,
                ACTION_SC_1);
        pendingIntent = PendingIntent.getBroadcast(MainActivity.this, REQUEST_CODE_SC_1, myIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
        alarmManager.set(AlarmManager.RTC, calendar.getTimeInMillis(), pendingIntent);
    }

Service class

public class MyService extends Service {

    @Override
    public IBinder onBind(Intent arg0) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public void onCreate() {
        // TODO Auto-generated method stub
        super.onCreate();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        try {
            final String action = intent.getStringExtra(ACTION);
            final Handler handler = new Handler();
            final Timer timer = new Timer();
            final TimerTask doAsynchronousTask = new TimerTask() {
                @Override
                public void run() {
                    handler.post(new Runnable() {
                        public void run() {
                            try {
                                Toast.makeText(MyAlarmService.this, "Running....", Toast.LENGTH_LONG).show();

                            } catch (Exception e) {
                                // TODO Auto-generated catch block
                            }
                        }
                    });
                }
            };
            timer.schedule(doAsynchronousTask, 1000, 5000); //execute in every 5000 msdo

          //  this.stopSelf();
        } catch (Exception e) {
           //TODO
        }

        return START_NOT_STICKY;
    }

    @Override
    public void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
        Toast.makeText(this, "Killed", Toast.LENGTH_LONG).show();
    }

A: There are many ways to avoid killing of service...but we can not guarantee it. In low memory situations the service will be killed by the os. At this situation if you return START_STICKY this will restart the service with null intent. If you want the intent to be not null return START_REDELIVER_INTENT
See the android docs here


text:
Q: Interface equivalent for a union type I have a Typescript type defined as:
export type IStepFunctionOperand =
  | IStepFunctionOperand_StringEquals
  | IStepFunctionOperand_StringGreaterThan
  | IStepFunctionOperand_StringGreaterThanEquals
  | IStepFunctionOperand_StringLessThan
  | IStepFunctionOperand_StringLessThanEquals
  | IStepFunctionOperand_NumericEquals
  | IStepFunctionOperand_NumericGreaterThan
  | IStepFunctionOperand_NumericGreaterThanEquals
  | IStepFunctionOperand_NumericLessThan
  | IStepFunctionOperand_NumericLessThanEquals;

Where each of the conditionals looks something like the following:
export interface IStepFunctionOperand_NumericLessThanEquals
  extends IStepFunctionBaseLogicalOperand {
  /** compare the value passed in -- and scoped by "Variable" -- to be numerically equal to a stated number */
  NumericLessThanEquals?: number;
}

export interface IStepFunctionBaseLogicalOperand {
  /** points to the specific area of context which is being evaluated in the choice */
  Variable: string;
}

This does what I want it to as a type but it would be super convenient to have this type be made into an interface. If I were able to do this I could then define an interface like so:
export interface IStepFunctionChoiceItem<T> extends Partial<IStepFunctionOperand> {
  // simple operands leverage inheritance but are optional

  // complex operators
  And?: IStepFunctionOperand[];
  Or?: IStepFunctionOperand[];
  Not?: IStepFunctionOperand;

  // State machine
  Next?: keyof T;
  End?: true;
}

Is this possible?

A: While you cannot use an interface to represent a union, for example to extend from it, you can use intersection types with type aliases to reuse or parameterize a union type
From your example:
export type StepFunctionChoiceItem<T> =
  & Partial<StepFunctionOperand>
  & {
  // simple operands leverage inheritance but are optional

  // complex operators
  and?: StepFunctionOperand[];
  or?: StepFunctionOperand[];
  not?: StepFunctionOperand;

  // State machine
  next?: keyof T;
  end?: true;
};

export type StepFunctionOperand =
  | StepFunctionOperand_StringEquals
  | StepFunctionOperand_StringGreaterThan
  | StepFunctionOperand_StringGreaterThanEquals
  | StepFunctionOperand_StringLessThan
  | StepFunctionOperand_StringLessThanEquals
  | StepFunctionOperand_NumericEquals
  | StepFunctionOperand_NumericGreaterThan
  | StepFunctionOperand_NumericGreaterThanEquals
  | StepFunctionOperand_NumericLessThan
  | StepFunctionOperand_NumericLessThanEquals;

This isn't the same as interface extension because, among other differences, members with. matching names are neither overridden nor overloaded and instead are themselves intersected. However, intersection types will get you the essentially desired behavior.


text:
Q: Fundamental polygon square $abab$ What is the most convenient description of the space with fundamental polygon a square, with all vertices identified, glued by $abab$? If we were to identify only opposite vertices, we would get $\mathbb{R}P^2$. So I believe one description is $\mathbb{R}P^2$ with two points identified, which is homotopy equivalent to $\mathbb{R}P^2 \vee S^1$. Is this the best we can do, or is it something else in disguise?
This answer suggests that it should be a surface, but I'm having a hard time seeing how it is. There is no neighborhood of the glued point homeomorphic to $\mathbb{R}^2$, is there? If so, how?

A: I'm putting what I have wrote in the comments together in this answer :
Claim The polygon $abab$ with all the vertices identified is homotopy equivalent $\Bbb RP^2 \vee S^1$.
First consider the polygon $abab$ with diagonally opposite pair of vertices identified, which is homeomorphic to $\Bbb RP^2$. Since all of the vertices must be identified, attach a $1$-cell to the resulting space along the disjoint union of the unidentified vertices; nullhomotoping the attaching map along the surface of $\Bbb RP^2$ gives you the desired homotopy type.
You can see that this is not a surface by looking at the wedged point. Any neighborhood of the wedge point looks like an open disk wedge $(0, 1)$, which is certainly not homeomorphic to $\Bbb R^2$.
As for the polygon in the MO question, the standard convention for identification on the polygon of $abab$ is that you identify diagonally opposite pairs of vertices, so that's just the usual $\Bbb RP^2$.


text:
Q: Why can't I upload a theme to my WordPress site running on Windows? I'm running WordPress on Windows 2008 / IIS 7 and I get a non-descript error when I try to upload a theme. It just says "Are you sure you want to do this?" and then a line below that says "Server error"

A: Here are a number of steps I had to take to resolve the issue:

*

*First, make sure that the IUSR account has access to write to the WordPress site Themes directory

*Second, locate your PHP.ini config file. Mine was in Program Files\PHP\<version> Make a backup and open the original file in notepad to edit it.

*Change the upload_tmp_dir value to a directory that the IUSR account has write access to. (Beware, values can be set multiple times in the config file so look for duplicate entries.)

*Change upload_max_filesize and post_max_size to a file size appropriate for the kind of themes you are uploading. I went with 20 megabytes.

*Change max_execution_time and max_input_time to durations appropriate to the size of the theme and bandwidth of your server. 300 seconds for both settings works well for me.

*Reset IIS

If you're still having trouble create a PHP script with the following code:
<?php phpinfo(); ?>

Run this script and use it to verify that the above settings have been applied. If not, check for duplicate entries in the config file that may be overwriting your settings and verify you've edited the file listed in the output under Loaded Configuration File
It took me a while to gather up all these pieces so hopefully anyone else having the same issue will end up here first. :)


text:
Q: You cannot call a method on a null-valued expression when adding to array of System.Collections I have a Function (powershell 5.1) that is using regular expressions to get info out of 3 separate files/strings using the same regex.  I want to process all 3 in the same Function and return it as an array of System.Collections(maybe Hashtable ...not sure if that's needed). But I'm getting the above error. It makes sense for me to do it this way because otherwise I will have separate functions doing the exact same thing, with the same regex.  So I'm trying to re-use functionality to do the same regex on 3 different strings/files.
I looked up the error and it says something isn't assigned.  not assigned I'm not seeing what isn't assigned in my case.
Function ProcessOmAlarmXml{
[cmdletbinding()]
  Param ()
  Process
  {
   $OMs = [System.Collections]::new() #this will store the 3 hashtables from the regex

   $pathViewBase = 'C:\EndToEnd_view\'
   $XML_OmMap_Dirs = @('\OmAlarmMap.xml')   #will add the other 2 later
   $XML_OmMap_Names = @('Config1','Config2','Config3')
   $i = 0

   #get each one from array
   foreach($omFile in $XML_OmMap_Dirs)
   {
      $pathToXml = Join-Path -Path $pathViewBase -ChildPath $omFile
      if(Test-Path $pathToXml)
      {
          #get file contents to parse as string
          $fileContent = Get-MethodContents -codePath $pathToXml -methodNameToReturn "<Configuration>" -followingMethodName "</Configuration>"

          #get the Mapping from omMap xml file
          $errorMap = @{}
          # create array to collect keys that are grouped together
          $keys = @()

          #regex works perfectly
          switch -Regex ($fileContent -split '\r?\n') {  #test regex with https://regex101.com/
            'Name=\"(\w+-\w+)' { #12-5704
                # add relevant key to key collection
                $keys = $Matches[1] } #only match once
                '^[\s]+<Value Name="MsgTag[">]+(\w+[.\w]*)<\/Value' { # gets the word after MsgTag, before closing tag      (\w+)<\/Value                MsgTag[">]+(\w+)<\/Value    ([?:<!\s\S]?"MsgTag[">]+)(\w+[.\w]*)<\/Value #fails if line commented out..still captures line
                # we've reached the relevant error, set it for all relevant keys
                foreach($key in $keys){
                    #Write-Host "om key: $key"
                    $errorMap[$key] = $Matches[1]
                    Write-Host "om key: $key ... value: $($errorMap[$key])"
                }
            }
            'break' {
                # reset/clear key collection
                $keys = @()
            }
          }#switch

          #I'm trying to add each $errorMap with the name in the array $XML_OmMap_Names so I can pull them out and use them later meaningfully
          [void]$OMs.Add({$XML_OmMap_Names[$i]=$errorMap})  #gives error message
          Write-Host $OMs.Count
          Write-Host $OMs -ForegroundColor Cyan
          $i++
       }#test-Path
       else
       {
          Write-Host "No such path $pathToXml"
       }

      } #foreach
   return $errorMap #will return $OMs later instead
  } #end Process
}# End of Function

I'm also trying to store my objects in the array like this seems to be using: arrays.
Note that I'm trying to provide a minimal amount of info here, and want to show enough of what the function does so it makes sense of why I need to store the hashtables in an array to return without re-writing complex code which would still be pretty complex. It would be great if someone has more info on how to store the hashtables in the array to return all 3 in the array.
More info on the error:
You cannot call a method on a null-valued expression.
At C:\Users\2021\temp endToEnd folder while network down\EndToEndParser.ps1:329 char:11
+           [void]$OMs.Add({$XML_OmMap_Names[$i]=$errorMap})  #[System. ...
+           ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : InvalidOperation: (:) [], RuntimeException
    + FullyQualifiedErrorId : InvokeMethodOnNull

A: Answer
You want
using namespace system.collections.generic
$OMs = [list[object]]::new() #this will store the 3 hashtables from the regex

[object[]]$XML_OmMap_Names = @('Config1','Config2','Config3')

$OMs.Add({$XML_OmMap_Names[$i]=$errorMap})
$OMs.Add( $somethingElse )

[System.Collections] isn't a valid type. That's why this is null.
$OMs = [System.Collections]::new()
$null -eq $OMs # returns True

Note, @() is not an array constructor
 @('\OmAlarmMap.xml')

To declare those as lists, and not accidentally become scalars, what you want is to give it a type.
$XML_OmMap_Names = @('Config1','Config2','Config3')

# becomes
[object[]]$XML_OmMap_Names = @('Config1','Config2','Config3')

*

*Types on Left Hand Side will declare types, they are strongly typed.

*Types on the Right Hand Side coerce values, but doesn't declare them to be any type.

By Left or Right hand side, that means which side of the assignment = operator it is.
using namespace system.collections.generic
$OMs = [list[object]]::new() #this will store the 3 hashtables from the regex

$OMs.Add({$XML_OmMap_Names[$i]=$errorMap})
$OMs.Add( $somethingElse )

Creating arrays: What to Avoid
What you want to avoid is
1] [System.Collections.ArrayList] and [System.Collections.Generic[Type]]::new()
This is explained in why generics are better? : microsoft docs
2] addition like $s = @(), the $s += stuff, because that allocates new memory every addition. It gets exponentially worse as the size increases.
What you should do
1] The docs say for objects that have mixed types, use [list[object]]
using namespace System.Collections.Generic

$items = [list[object]]::new()
$items.Add( '1' )
$items.Add( (Get-Item . ))

2] for objects of one specific type use  [list[type]]
$nums = [list[Int64]]::new()
$nums.add( '1' )

$nums[0] -is [Int64]  # True
$nums[0] -is [string] # False

3] Implicit arrays are okay if you're not += ing
# now the type is an array, regardless if nothing, or single value return
[object[]]$ArrayOfAnything = FunctionMightReturnNothing # 0-tomany items

[object[]]$AlwaysArray = Get-ChildItem . | Select -first 1
$AlwaysArray.GetType() # type is object[] arrray

$sometimesArray = Get-ChildItem . | select -first 1
$sometimesArray.GetType() # type is a scalar of type [filesysteminfo]

Implicit arrays are fine.
# often in powershell it's more natural to emit output to the pipeline, instead of manually adding arrays.

$results = @(
    Get-ChildItem c:\ -depth 3 | Sort-Object LastWriteTime | Select-Object -top 3
    if($IncludeProfile) {
         Get-ChildItem -file "$Env:UserProfile" -depth 3 | Sort-Object Length | Select-Object -top 3
    }
)

Links

*

*https://vexx32.github.io/2020/02/15/Building-Arrays-Collections/#using-an-expandable-list

*https://learn.microsoft.com/en-us/dotnet/api/system.collections.arraylist?view=net-6.0#remarks

A: It sounds like what you're looking for is a (potentially ordered) nested hashtable:
# Initialize an ordered hashtable.
$OMs = [ordered] @{ } # This will later store 3 nested hashtables.

# The (top-level) keys
$XML_OmMap_Names = @('Config1','Config2','Config3')

$i = 0
foreach($someFile in 'foo', 'bar', 'baz') {
  # Construct the nested hashtable
  $errorMap = [ordered] @{ nested = $someFile }
  # Add it to the top-level hashtable.
  $OMS.Add($XML_OmMap_Names[$i], $errorMap)
  ++$i
}

Note how the key, $XML_OmMap_Names[$i], and the value, $errorMap are passed as separate arguments to the .Add() method.
(By contrast, in your attempt, [void]$OMs.Add({$XML_OmMap_Names[$i]=$errorMap}), you mistakenly passed a single argument as a script block ({ ... }).)
Alternatively, index syntax - $OMS[$XML_OmMap_Names[$i]] = $errorMap - could be used to add the entries; note that this method quietly replaces any preexisting value with the same key, whereas the .Add() method would throw an exception.
Now you can get entries by name; e.g.:
$OMs.Config1  # Same as: $OMs['Config1']

Note: Since [ordered] was used, you can also use positional indices:
$OMs[0] # Same as : $OMs.Config1

Direct access to the nested hashtable's entries is also possible:
$OMs.Config1.nested  # Same as: $OMs['Config1']['nested'] -> 'foo'


text:
Q: how to passing these data return into other pages react navigation page? import React from 'react';
import { View, Text, Button, Alert } from 'react-native';
import Expo from 'expo';

export default class LoginScreen extends React.Component{
async signInWithGoogleAsync() {
    try {
      const result = await Expo.Google.logInAsync({
        androidClientId: '768673945897-ftrhehlg3io4v2fohdbpacio1vghos8v.apps.googleusercontent.com',
        //iosClientId: YOUR_CLIENT_ID_HERE,
        scopes: ['profile', 'email'],
      });

      if (result.type === 'success') {
            console.log(result);
            //this.props.navigation.navigate('Profile');
            return result.accessToken;
            return result.user.name;
            return result.user.photoUrl;
      } else {
        return {cancelled: true};
      }
    } catch(e) {
      return {error: true};
    }
  }

render() {
    return(
        <View>
            <Button
                onPress={this.signInWithGoogleAsync.bind(this)}
                title='Google Sign in'
            />
        </View>
    );
}
}

A: Well if you want to access data in some other component or page than you should use redux store. You can store the data obtained or generated in the current page to the redux store which will be accessible to any component or page which requires it.

A: You can try passing parameters to routes like this
class HomeScreen extends React.Component {
  render() {
    return (
      <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
        <Text>Home Screen</Text>
        <Button
          title="Go to Details"
          onPress={() => {
            /* 1. Navigate to the Details route with params */
            this.props.navigation.navigate('Details', {
              itemId: 86,
              otherParam: 'anything you want here',
            });
          }}
        />
      </View>
    );
  }
}

and retrieve the data like this...
class DetailsScreen extends React.Component {
  render() {
    /* 2. Get the param, provide a fallback value if not available */
    const { navigation } = this.props;
    const itemId = navigation.getParam('itemId', 'NO-ID');
    const otherParam = navigation.getParam('otherParam', 'some default value');

    return (
      <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
        <Text>Details Screen</Text>
        <Text>itemId: {JSON.stringify(itemId)}</Text>
        <Text>otherParam: {JSON.stringify(otherParam)}</Text>
        <Button
          title="Go to Details... again"
          onPress={() =>
            this.props.navigation.push('Details', {
              itemId: Math.floor(Math.random() * 100),
            })}
        />
        <Button
          title="Go to Home"
          onPress={() => this.props.navigation.navigate('Home')}
        />
        <Button
          title="Go back"
          onPress={() => this.props.navigation.goBack()}
        />
      </View>
    );
  }
}

A: *

*it solved already, thanks for helping :))
btw i just passing this array data into navigator :)

result = [object]
this.props.navigation.navigate('Profile', { result: result.user });

*and then in other pages let say Profile, i make contrsuctor for new state

this.state = {
        result: this.props.navigation.state.params.result, };

*and then i call that state in each section like this

{ this.state.result.email }


text:
Q: How to add a CSS class to an XML item? Is it possible to add a CSS class to an item in a XML file? The reason for adding a class is because i want to be able to change the color of the item from the XML file by switching between 3 classes. So I would just style the 3 classes and then switch between them.
<?xml version="1.0" encoding="utf-8"?>
<?xml-stylesheet href="main.css" media="screen" type="text/css"?>
   <root>
      <item row="1" span="4" name="Develop">
         <item name="Idea" row="2" classname="test">
             <item shape="arrow" span="8" name="Project Management"></item>
             <item name="Concept, Technology & Layout"></item>
             <item name="Consent" span="6" shape="arrow"></item>
             <item shape="arrow" span="8" name="Engineering"></item>
             <item shape="arrow" name="Commercial"></item>
             <item name="Operation Preparation"></item>
          </item>

A: Try adding the below code and check.
item {
  color: red;
}

A: Where the xml rendered in? If you render it on browser then regular styling will work. Example:

plist {
  display: block;
  width: 100%;
}

item {
  display: block;
  width: 100%;
}

.yellow {
  color: yellow;
}
<plist>
  <item class="yellow">One</item>
  <item>Two</item>
</plist>


text:
Q: How to set cookie from the backend hosted in the cloud to the frontend running on the localhost When both backend and frontend run on the localhost then cookies are being set properly,
but when i deploy the backend in the cloud then cookies are not getting set in the browser


text: Q: Explicit matrix representation of an algebraic extension This may be considered an extension of this question. Let $\mathbb{F}$ be a field, and let $p(X)\in\mathbb{F}[X]$ be an irreducible polynomial. Let $\mathbb{F}_p$ be the extension of $\mathbb{F}$ by adding the roots of $p$. Can we find an explicit matrix representation of $\mathbb{F}_p$ in $\mbox{End}_\mathbb{F}\mathbb{F}_p\simeq\mbox{gl}(\mathbb{F},[\mathbb{F}_p:\mathbb{F}])$ in terms of coefficients or roots of $p(X)$? I think $[\mathbb{F}_p:\mathbb{F}]=(\deg p-1)!$ can be shown by induction, but I find it hard to establish a tractable representation similar to the well known one for $\mathbb{C}$ over $\mathbb{R}$. I am much afraid of clever things like Galois or so, and I would appreciate an answer in simpler terms. Thank you.


text:
Q: Parse Math Expression as "3 + 2 * temp + humidity", where replace alpha values from payload Math Expression can be anything. The variable or alpha character here in expression are also not fixed "3 + 2 * temp + humidity". The variable must look for json and get replaced by it's value from json.
environment = {"temp": 23, "humidity": 12, "airpressure":21.12}
expression = '3 + 2 * temp + humidity'

the response I am looking is as '3 + 2 * 23 + 12'.
as I just started exploring  pyparsing I  couldn't find the solution.

A: You could just use a regex to look for the variables, and use re.sub to replace each matched variable by its value:
import re

environment = {"temp": 23, "humidity": 12, "airpressure":21.12}
expression = '3 + 2 * temp + humidity'

def replace_var(m):
    return str(environment[m.group(0)])

def replace_vars(expression):
    return re.sub(r'[a-z]+', replace_var, expression)  # assuming your variables are all lowercase

print(replace_vars(expression))
# 3 + 2 * 23 + 12

This will raise a KeyError in case a variable doesn't exist in environment.

A: You can transform the keys of your environment dictionary to a regular expression, and then replace them with the corresponding value:
def resolve_vars(expression, environment):
    regex = r"\b({})\b".format("|".join([re.escape(k) for k in environment]))
    repl = lambda s: str(environment.get(s.group(), s.group()))
    return re.sub(regex, repl, expression)


text:
Q: NSDictionary load information of 18 key-value pairs always read as nil instead     - (instancetype)initWithDestinationIndex:(NSUInteger)levelsIndex {
          NSString* filepath = [[NSBundle mainBundle]
                          pathForResource:@"Levels" ofType:@"plist"];
          NSDictionary *levels = [NSDictionary dictionaryWithContentsOfFile:filepath];
          NSArray *levelsArray = levels[@"LevelsData"];
          _data = levelsArray[levelsIndex];
          [_verticalB setToInitialStateVertical];
          return self;
    }

I have a plist that is supposed to load information of 18 key-value pairs.  The _data of type NSDictionary instance variable (when I run the program and put a breakpoint at that line _data = levelsArray[levelsIndex];) is almost always null, except on one occasion where it is actually had the 18 key-value pairs loaded.  Any thoughts as to why it pretty much always is null?
I pass in 0 for my levelsIndex, and the 'LevelsData' is the NSArray that holds the 18 key-value pair dictionaries.

A: if your _data is NSMutableDictionary use the below code,
NSMutableDictionary *_data = [[NSMutableDictionary alloc] init];
[_data setObject:[levelsArray objectAtIndex: levelsIndex] forKey:[NSString stringWithFormat:@"%d", levelsIndex]];

or
for(int i=0; i<[levelsArray count]; i++){
    [_data setObject:[levelsArray objectAtIndex:i] forKey:[NSString stringWithFormat:@"%d",i]];
}

hope its helpful

A: It may possible that, you are running app in a "release" scheme. Have you double check? As long as you're getting the result.
To check,

Click on Project Name next to [Run] button. > Edit Scheme > Run > Build Configuration > Debug/Release


text:
Q: Parsing repeated characters I'm new to parsing (obviously). I am using LEPL library to parse some markup language.
I have a problem with this code (I've omitted details for the sake of clarity).
from lepl import *

a = Literal('a')[0:,...] # 0 or more, join the result
b = Literal('b')

c = (a | b)[0:]

print c.parse("abaabaaab")

The last line should give me ['a','b','aa','b','aaa','b']
There is no error but it hangs (infinite recursion maybe?). Could anyone point me in the right direction?
Edit
I could do this like this
from lepl import *

a = Literal('a')
b = Literal('b')

c = (a | b)[0:]

print c.parse("abaabaaab")

But the a will not be grouped.

A: I am pretty sure that, in your first example, you want
a = Literal('a')[1:]

With two [0:] repeats in your grammar, the parser will indeed run into effectively infinite backtracking.


text:
Q: Magento-Custom shopping cart price rule - Buy 2 different products and get those for flate rate? I want to set up different kind of price rules(shopping cart price rules) for my client. I tried default magento's extension, but I couldn't. when I searched in the net, some solutions told that using observer can solve my problem. But those weren't enough for me. Let me explain one of my problem.
Buy 2 different products and get those for flat rate.
Say, Product X is 700 and Product Y is 500. When customer buys those 2 products (Total 1200), he can get both products for 1000.
is there any straight way to do this or should need to create custom module with database table and observer?

A:

*

*First Specified Your X and Y SKU and put this condition and action and apply discount amount.

*If you don't found SKU in condition, then change in the SKU attribute to apply shopping rule to YES


text:
Q: How can I change this function in R so that it changes the data frame in x? The code below is my attempt at a function to change the data table in x.
The data table x has columns named MutationStatus and disease. When I plug x as the data table and y as the string within the disease column manually, the function works, however plugging it as a function does not.
diseaseMutation <- function(x,y) {
  x$MutationStatus[x$disease != y] = "WT"
  x$disease[x$disease != y] = y
}

A: We need to return the 'x'
diseaseMutation <- function(x,y) {
  x$MutationStatus[x$disease != y] = "WT"
   x$disease[x$disease != y] = y
   x
 }


text:
Q: Why does getchar wait after one character is entered? Here is my code:
#include <stdio.h>

int main()
{
        char a = getchar();
        printf("char: %c", a);
}

I'm compiling this with gcc.
When running, the program waits for input even after one character is entered on console. Shouldn't it immediately exit and print the character? I'm running this on Ubuntu for Windows, if that can make any difference.

A: stdin is your default input stream. The default buffering mode of stdin is line buffered. So it waits for the \n to be entered. Then only there is something to read from the input stream and then getchar gets the input and works with it.

A: The operating system often buffers console input until a new line is entered, such that your program will not even receive the single character before. Probably nothing you can do about that.


text:
Q: How do I recover production data in App Engine that I accidentally deleted? I deleted some data from my production App Engine app. Unfortunately I had the wrong table name in mind when I did so because I have two tables that have very similar names. I know the deployed code is versioned so you can roll back to a previous version of your code. What about for your data? And, going forward, what's the best data backup strategy to use for production data?

A: Sorry Keith your data is lost. Backups are the responsibility of the user.
There is a feature request Datastore archive which you should star if you think something like this should be part of the service and an improved Import/Export is on the roadmap.
For now your best options are:

*

*Use the Bulkloader to fetch all your entities

*Write a custom offsite backup script that fetches important parts of your data via remote_api

*Periodically copy all your entities into a different namespace in the datastore (this can be trickier that it sounds)


text:
Q: Angular  links - odd behaviour Folks I have real odd situation that doesn't seem to make sense to me at all. Here's my setup:

    blah

        Profile

<blah>

The header has it's own controller, then I use ngRoute to define various paths, including the profile:
.when('/profile', {
    templateUrl: 'views/profile.html',
    controller: 'profileController'
})

For some reason, clicking in the a href link in the header does nothing. No error, no activity. It does show the correct URL when you hover over the link, and, right-clicking and opening in new tab DOES work just fine.
Why does a normal left click not work? Bearing in mind that either:

*

*Typing that route in directly into address bar &

*Right click - open in new window

both work, what's stopping angular from loading that view into the  div?
Any help much appreciated!

A: I think problem is that you do not specify  base url. Try it.


text:
Q: Can I convert kernel density plots to raster and then overlay them using map algebra? I am currently exploring three shapefiles, each with point data, and all confined to the same window. I also have them in ppp format which I've used to create kernel density maps.
plot(density.ppp(smktppp, 0.5, edge=T), main="Supermarket Density")
plot(density.ppp(tptppp, 0.5, edge=T), main="Transport Density")
plot(density.ppp(farmppp, 0.5, edge=T), main="Urban Farm Density")

I would like to overlay these plots, using map algebra, or fuzzy logic, etc, to create one output map showing the density of the three combined. How would I go about doing this in R?

A: If you simply want to estimate the overall density (usually called intensity since it doesn't integrate to one) of points disregarding whether it is "Supermarket", "Transport" or "Urban Farm" you just combine all the points and do as before:
library(spatstat)
combined <- superimpose(smktppp, tptppp, farmppp)
plot(density(combined), main="Density of all points.")

Of course you can choose the smoothing bandwidth to be 0.5 as before or any other value you like.
You can also do normal algebra with the raster images produced by density.ppp (object of class im). If you saved these as smktim, tptim and farmim you can do something like rslt <- smktim + tptim + farmim to get the sum of the three estimates.

A: Alternatively, if you combine the three point patterns into a single object
library(spatstat)
X <- superimpose(Supermarket=smktppp, Transport=tptppp, Farm=farmppp)

then you can display both the original data and the intensity estimates, with or without identifying the kind of point:
# original data:
plot(X)  # single plot with 3 different plot characters for 3 types
plot(split(X)) # three plot panels, one for each type of point
plot(unmark(X)) # single plot without distinguishing types of points

# intensity images:
plot(density(X, 0.5)) # single plot: intensity regardless of type
plot(density(split(X), 0.5)) # three panels: intensity for each type
plot(relrisk(X), 0.5) # three panels: relative probabilities of each type

See the spatstat book for details.


text:
Q: Taking in a string from a txt file that has prices in double format separated by a tab and putting them into a double array having a parse issue here on bottom line can someone please help!
   FileIO io = new FileIO();
            String[] original = io.load("C:\\sharePrice.txt");
            int numcols=original[0].split("\t").length;
            double[]sharePriceArray = new double[numcols];
            for(int i=0;i<numcols;i++)
            { //load in the data
                sharePriceArray[i] = Double.parseDouble(original[i].split("\t"));
            }

A: AFAIK, .split splits a string into a string array. Your code is trying to assign a double to a string array, so that's the reason of your parse issue.
To fix, I would reccomend splitting the string into an array using .split(), and then traversing that array to assign to the double.

A: I suppose this should be like original[i].split("\t")[0]   or original[i].split("\t")[1]  in this case you are taking first or second value and then do parsing.


text:
Q: SQL Server Remove double quotes SQL Server 2008 R2
I'm creating an XML file from SQL Server and one column is causing me problems because of " inside the varchar.
The XML looks like this after export,
<variantValue name="marketingInfo" value="random text.

 random text.

"random text""/>

which of course breaks the xml file.
It turned out i mistook the " for a " (U+201D RIGHT DOUBLE QUOTATION MARK) which is why replace didnt work. It does however still export as a regular " to XML.
How do you deal with text fields when exporting from SQL to XML in order to escape any characters that can break the XML?
SQL procedure looks something like this,
declare @pricat xml

set @Pricat = (
    --Pricat HEAD
    select ..some attributes
        --Pricat ROWS
        ,(select ..sone attributes

            -- PriceBracket 1 (PRE)
            ,(select ..some attributes
            for xml path ('priceBracket'), type)

            -- PriceBracket 2 (Supp)
            ,(select ..some attributes
            for xml path ('priceBracket'), type)

            -- VariantValue 01
            ,(select ..some attributes
            for xml path ('variantValue'), type)

            -- VariantValue 02
            ,(select ..some attributes
            for xml path ('variantValue'), type)

        for xml path ('sprProduct'), type)
from prh
FOR XML PATH ('Pricat')
)

-- Not sure if this is a good way to add verion and encoding tag.
--select '<?xml version="1.0" encoding="ISO-8859-1"?>' + cast(@Pricat as varchar(max)) as xml
select @b24Pricat

XML file is created as below,
declare @filename varchar(100)
declare @cmd varchar(256)
declare @date datetime

set @date = getdate()
set @filename = cast(datepart(year,@date) as varchar)+cast(LEFT(CONVERT(CHAR(20), @date, 101), 2) as varchar)+cast(datepart(day,@date) as varchar)
set @filename = @filename + '_' + cast(datepart(minute,@date) as varchar )+ cast(datepart(second,@date) as varchar)
set @filename = 'blabla_' + @filename + '.xml'
-- -C 28591
set @cmd = 'bcp "exec db..procedure 1,2,3,4" queryout "c:\export\'+ @filename +'" -T -c -C 28591'

EXEC xp_cmdshell @cmd

A: I'm not sure if its the whole answer but changing the BCP command as below solved my problem.
set @cmd = 'bcp "exec db..procedure 1,2,3,4" queryout "c:\export\'+ @filename +'" -T -w


text:
Q: Transforming queries in a URL I'm trying to use a REST API apparently constructed with LoopBack and it requires that my filter parameters be encoded in a specific way.
What is this sort of transformation called?
# this is a JSON type encoding
...?filter={"where": {"StartDate": {"gte": "2021-01-01T00:00:00.000Z"}}, "offset": 0, "limit": 100, "order": "id DESC" }

which needs to be encoded as some sort of HTTP query string

...?filter=%7B%22where%22%3A%20%7B%22StartDate%22%3A%20%7B%22gte%22%3A%20%222021-06-01T00%3A00%3A00.000Z%22%7D%7D%2C%20%22offset%22%3A%200%2C%20%22limit%22%3A%20100%2C%20%22order%22%3A%20%22id%20DESC%22%20%7D

Is there a python function to do this?

A: This is URL encoding.
URLs cannot contain a lot of different special characters, such as spaces (a space would be %20 in URL encoding).
Note that URL encoding is quite easy to recognize once you know it exists, due to the %xx pattern.
The urllib has functions to deal with encoding/decoding this.
To create an URL encoded string use urllib.parse.quote(string). Relevant docs here...
Example
from urllib.parse import quote
jsonstring = '{"where": {"StartDate": {"gte": "2021-01-01T00:00:00.000Z"}}, "offset": 0, "limit": 100, "order": "id DESC" }'
urlencoded = quote(jsonstring)

print(urlencoded)

# output
# %7B%22where%22%3A%20%7B%22StartDate%22%3A%20%7B%22gte%22%3A%20%222021-01-01T00%3A00%3A00.000Z%22%7D%7D%2C%20%22offset%22%3A%200%2C%20%22limit%22%3A%20100%2C%20%22order%22%3A%20%22id%20DESC%22%20%7D

A: You are looking for URL encoding. If you already have the JSON encoded in a variable as such, then just encode it to the filter parameter:
from urllib.parse import urlencode, quote

base_url = "..."
filter_string = """{"where": {"StartDate": {"gte": "2021-01-01T00:00:00.000Z"}}, "offset": 0, "limit": 100, "order": "id DESC" }"""
query = urlencode({"filter": filter_string}, quote_via=quote)
url = f"{base_url}?{query}"

Now, I expect that the JSON is probably coming from a Python data structure. You can use the dumps function from json to handle that encoding:
from urllib.parse import urlencode, quote
import json

base_url = "..."
data = {
    "where": {
        "StartDate": {
            "gte": "2021-01-01T00:00:00.000Z"
        }
    },
    "offset": 0,
    "limit": 100,
    "order": "id DESC"
}
filter_string = json.dumps(data)
query = urlencode({"filter": filter_string}, quote_via=quote)
url = f"{base_url}?{query}"

And you have the URL to call to in the variable url.


text:
Q: Should 404 pages retain the URL or be redirected? Some websites retain the URL path when a path is accessed that isn't found and when the page loads they simply display an error title, message and also set the HTTP status code to 404.
Other pages redirect it to a fixed 404 URL path which displays both the content and the header.
My questions are:

*

*Should the URL not change so that the URL path is categorized as 404 for as long until the http response expires?

*Should there ALWAYS be a 404 status code?

*And even when a redirection occurs, then should the resulting page contain a 404 status code?

Or is it better to return a 404 response and include a location header pointing to the dedicated 404 URL (I'm not sure if its possible to mix redirections and 400-series status codes)?

A: If the page that your server is returning is a "File Not Found", it should return a 404 error. Adding in a redirect seems pointless and confusing to web-crawlers and people alike.
With Apache you can retain the original URL, return a 404 and have a custom error message if you add this to your .htaccess file in the root of your webserver:
ErrorDocument 404 /notfound.html

Where notfound.html is your custom error page.


text:
Q: Adding reply-to header for simple postfix mailing list I have a postfix with the following in /etc/postfix/main.cf:
virtual_alias_domains = hash:/etc/postfix/mydomains
virtual_alias_maps = hash:/etc/postfix/virtual

These specify the domains set up for mail forwarding, and the mail forwarding mappings.
I would like to set up a simple mailing list, which can easily be achieved by adding to the mapping file. However, I would like to add a "reply-to" header to the messages so that replies get sent back to the list rather than the original sender. I'm fairly sure this is possible with a regular expression, but I'm not quite sure where to put it.
Secondly, I wonder is it possible to make Postfix reject messages if they don't come from one of the members of the mailing list? This would be nice to have, but not essential.
The list will have about ten members, and will change very rarely, so hard coding the member addresses into regular expressions wouldn't be a big problem.
Any help would be appreciated.

A: The Reply-To header can be added using the smtp_header_checks option:
smtp_header_checks = pcre:/etc/postfix/header_checks.pcre

where header_checks.pcre contains something like
/^To: your-mailing-list@example.net/  PREPEND Reply-To: <your-mailing-list@example.net>

The first part (between the slashed) is the regex matching a header.  PREPEND says that an additional line should be added to the mail.  The rest is the content of the added line.  If you want to experiment a little with that setup, take a look at man 5 header_checks, it explains that kind of processing in greater detail.
Rejecting messages would work similarly to the above, just add a few more rules to header_checks.pcre.  It should contain something like this:
if /^To: .*<your-mailing-list@example.net>/
/^From: .*your-friend1@example.org/     OK
/^From: .*your-other-friend@exmple.net/ OK
/.*/  REJECT
endif

and so on.
The above config should cause postfix to accept mail to your mailing list only if it appears to be by one of your friends.  It's untested, so please proceed with care.


text:
Q: How to store data inside mongodb js and mongodb.I have created a model file named models like the one given below
 User = new Schema({
        username : String
      , password : String
      , created_at : Date
 });
 mongoose.model('User', User);
 exports.defineModels = defineModels;

In app.js i have called the defineModels like this:
var models = require('./models'),

models.defineModels(mongoose, function() {
  app.User = User = mongoose.model('User');
  db = mongoose.connect(app.set('db-uri'));
})

I can't call save method directly on User or can I?
i want to save data in User what could be the function for the same.any answer will be appriciated

A: To do what you want, you should have something like this:
var user = new User({username: 'Name', password: 'unsecure'});
user.save();

There are a few things odd with your code, so I highly suggest going over a tutorial that uses express and mongoose to create a sample site (most likely you can find a blog).
Here is one I made: https://github.com/mathrawka/node-express-starter
Good luck!


text:
Q: How can I force magnified mode on a retina display? As the "High Resolution Explained: Features and Benefits" article describes, on a retina display, an "Open in Low Resolution" checkbox is available for the user to open an app if it has problems on a high-res display.
One of our apps apparently has performance issues on retina displays, and we don't have the bandwidth to find and fix the problem immediately. In the mean time, is there a way to automatically disable scaling for the app, so that users don't have to select the checkbox to make the app work properly?

A: There is an NSHighResolutionCapable Boolean defined for Info.plist.  I've only seen references in documentation that set this to true, but perhaps the default can also be hard-coded if you set it to false.


text:
Q: Change the text on spinners created by a CustomAdapter (extends BaseAdapter) My app creates a ListView that creates list items based on the number of strings in my array. However, I would like each Spinner item to have the appropriate item selected.
Example:
String[] items = {"item1", "item2", "item3"}
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    String[] items = {"item1", "item2", "item3"}

    adapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_item, items);
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    ListView listView = (ListView) findViewById(R.id.requestItems_listView);
    listView.setAdapter(new CustomAdapter(this));
}

    private class CustomAdapter extends BaseAdapter {
        LayoutInflater inflater;

        public CustomAdapter(Context context) {
            inflater = LayoutInflater.from(context);
        }

        public int getCount() {
            // TODO Auto-generated method stub
            return items.length;
        }

        public Object getItem(int position) {
            // TODO Auto-generated method stub
            return position;
        }

        public long getItemId(int position) {
            // TODO Auto-generated method stub
            return position;
        }

        public View getView(int arg0, View convertview, ViewGroup arg2) {
            ViewHolder viewHolder;
            if (convertview == null) {
                convertview = inflater.inflate(R.layout.request_item_list_item, null);
                viewHolder = new ViewHolder();
                viewHolder.spinner = (Spinner) convertview.findViewById(R.id.itemSpinner);
                viewHolder.spinner.setAdapter(adapter);
                convertview.setTag(viewHolder);
            } else {
                viewHolder = (ViewHolder) convertview.getTag();
            }
            return convertview;
        }

        public class ViewHolder {
            Spinner spinner;
        }
    }
}

So this should create 3 (because there are 3 items in the String[] "items") "request_item_list_item" items within the ListView.
And it has each spinner (1 part of request_item_list_item) in position 0 so:
"item1"
"item1"
"item1"
I would like it to do the following though:
"item1"
"item2"
"item3"
Would this be accomplished in the CustomAdapter?
BONUS Question:
If I wanted the user to be able to press an "Add Button" to increase the number of list items by 1 (so that there would be 4 request_item_list_items, 5, 6, etc.) is there a .add method I should be using? or do I just change the getCount and refresh the list (this wouldn't be ideal... if the user had already filled out information in the request_item_list_items, they would then lose all of their inputs when it refreshes)?

A: For the first question you just need to change getView like this: (as I_A_Mok commented)
public View getView(int arg0, View convertview, ViewGroup arg2) {
    ViewHolder viewHolder;
    if (convertview == null) {
        convertview = inflater.inflate(R.layout.request_item_list_item, null);
        viewHolder = new ViewHolder();
        viewHolder.spinner = (Spinner) convertview.findViewById(R.id.itemSpinner);
        viewHolder.spinner.setAdapter(adapter);
        convertview.setTag(viewHolder);
        viewHolder.spinner.setSelection(arg0);
    } else {
        viewHolder = (ViewHolder) convertview.getTag();
    }
    return convertview;
}

and for second question:
CustomAdapter myAdapter;
ArrayList<String> items;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    items = new ArrayList<>();
    items.add("item1");
    items.add("item2");
    items.add("item3");

    ListView listView = (ListView) findViewById(R.id.requestItems_listView);
    myAdapter = new CustomAdapter(this, items);
    listView.setAdapter(myAdapter);

    Button bt_add_new = (Button)findViewById(R.id.bt_add_new);
    bt_add_new.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            items.add("item" + items.size() + 1);
            myAdapter.setItems(items);
            myAdapter.notifyDataSetChanged();
        }
    });
}

private class CustomAdapter extends BaseAdapter {
    LayoutInflater inflater;

    private ArrayList<String> items;

    public CustomAdapter(Context context, ArrayList<String> items) {
        inflater = LayoutInflater.from(context);
        this.items = items;
    }

    public int getCount() {
        // TODO Auto-generated method stub
        return items.size();
    }

    public Object getItem(int position) {
        // TODO Auto-generated method stub
        return position;
    }

    public long getItemId(int position) {
        // TODO Auto-generated method stub
        return position;
    }

    public View getView(int arg0, View convertview, ViewGroup arg2) {
        ViewHolder viewHolder;

        convertview = inflater.inflate(R.layout.request_item_list_item, null);
        viewHolder = new ViewHolder();
        viewHolder.spinner = (Spinner) convertview.findViewById(R.id.itemSpinner);

        ArrayAdapter<String> adapter = new ArrayAdapter<>(getApplicationContext(), android.R.layout.simple_spinner_item, items);
        adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        viewHolder.spinner.setAdapter(adapter);
        convertview.setTag(viewHolder);

        return convertview;
    }

    public ArrayList<String> getItems() {
        return items;
    }

    public void setItems(ArrayList<String> items) {
        this.items = items;
    }

    public class ViewHolder {
        Spinner spinner;
    }
}


text:
Q: Install rgdal and rgeos on Azure Databricks I cannot install rgdal and rgeos on Databricks, any suggestions?
configure: error: gdal-config not found or not executable.
ERROR: configuration failed for package 'rgdal'
* removing '/databricks/spark/R/lib/rgdal'

configure: error: geos-config not found or not executable.
ERROR: configuration failed for package 'rgeos'
* removing '/databricks/spark/R/lib/rgeos'

A: Here is one way to install rgdal and rgeos on R on Azure Databricks. Step 1 and 2 needs to be done each time you start the cluster. Step 1 can be automated (see below) but step 2 needs to be executed manually in a separate script or be added to the top of your R script.
Step 1
You need to first install gdal and geos on the linux machines in your cluster. This can be done with bash script in a databricks notebook. The %s is the magic command that allows this cell to run a shell script.
%sh
#!/bin/bash

#Start by updating everything
sudo apt-get update

##############
#### rgdal

#This installs gdal on the linux machine but not the R library (done in R script)
#See https://databricks.com/notebooks/rasterframes-notebook.html
sudo apt-get install -y gdal-bin libgdal-dev

#To be able to install the R library, you also need libproj-dev
#See https://philmikejones.me/tutorials/2014-07-14-installing-rgdal-in-r-on-linux/
sudo apt-get install -y libproj-dev

##############
#### rgeos

#This installs geos on the linux machine but not the R library (done in R script)
#See https://philmikejones.me/tutorials/2014-07-14-installing-rgdal-in-r-on-linux/
sudo apt install libgeos++dev

However, that is annoying to have to run manually each time, so you can create an init script that runs each time on startup of the cluster. So in a databricks python notebook, copy this code into a cell. Scripts in dbfs:/databricks/init/<name_of_cluster> will run on start-up for clusters with that name.
#This file creates a bash script called install_packages.sh. The cluster run this file on each startup.
# The bash script will be anything inside the variable script

clusterName = "RStudioCluster"
script = """#!/bin/bash

#Start by updating everything
sudo apt-get update

##############
#### rgdal

#This installs gdal on the linux machine but not the R library (done in R script)
#See https://databricks.com/notebooks/rasterframes-notebook.html
sudo apt-get install -y gdal-bin libgdal-dev

#To be able to install the R library, you also need libproj-dev
#See https://philmikejones.me/tutorials/2014-07-14-installing-rgdal-in-r-on-linux/
sudo apt-get install -y libproj-dev

##############
#### rgeos

#This installs geos on the linux machine but not the R library (done in R script)
#See https://philmikejones.me/tutorials/2014-07-14-installing-rgdal-in-r-on-linux/
sudo apt install libgeos++dev

"""
dbutils.fs.put("dbfs:/databricks/init/%s/install_packages.sh" % clusterName, script, True)

Step 2
So far you have just installed gdal and geos on the linux machines in the cluster. In this step you will install the R package rgdal. Recent versions of rgdal however, are not compatible with the most recent version of gdal available with apt-get. See here for more details and alternative ways to solve this, but if you are ok with an older version of rgdal then the easiest workaround is to install version 1.2-20 of rgdal.  You do that in an databricks R notebook or in the Rstudio databricks app like this:
require(devtools)
install_version("rgdal", version="1.2-20")
install.packages("rgeos")

Setup done
Then you can import these libraries like usual:
library(rgdal)
library(rgeos)


text:
Q: This WebKit bug is fixed in Chrome 18, right? I am sorry to ask such an elementary question especially when I am almost certain I already have the answer.... but it seems like I am hitting the following WebKit bug:
https://bugs.webkit.org/show_bug.cgi?id=71053
And yet I am using Chrome 18.0.1025.142, and as near as I can tell it is using WebKit 535.19, and if I'm reading that bug report page correctly, this bug was patched several WebKit versions ago... right?
Does Chrome have like a really weird CORS implementation or something?  I am getting "Cross-origin image load denied by Cross-Origin Resource Sharing policy", but ONLY in Chrome (it works in Firefox, Safari, and IE w/ Chrome Frame), and even then only when the website is hosted in a particular way (the details of which are beyond the scope of this question).

A: I get the same Chrome error when I am serving from localhost, but not when I am serving from my Sonic server.
I recall there being a cross-origin setting in the header. I test webGL stuff in Firefox when serving from localhost to avoid this issue.


text:
Q: Android rtl stopped working My app does specify supportRtl = true in the manifest
But all of a sudden, I don't know what caused this, but my app layout in Hebrew in still ltr.
I can't explain this, has anyone have experienced that before?


text:
Q: Why json can be imported easily where as csv cannot in Nodejs Typescript javascript? I was trying to import data from csv file. I tried the following statement:
import * as c from './t.csv';

I got the error:

TypeScript error: src/dataset.ts(18,20): Error TS2307: Cannot find module './training.csv'.

Then I converted the file into a json file and tried the following code:
import * as c from './t.json';

It worked.
I wonder why the csv file was not loaded where as json file loaded without any issues.

A: Probably because Any JSON text is a valid JavaScript expression and CSV is absolutely not.


text:
Q: Is the tensor product of two real numbers a real number? I am on a physics course where they've introduced the tensor product as if it was something that I would have seen before, and they don't tell me any of its properties. However, I am trying to work them out on my own.
My question is: suppose $f(x)$ and $g(x)$ are two $\mathbb{R}^d \to \mathbb{R}$ functions. Does that mean that $f(x)\otimes g(x)
$ is the real number obtained by $ f(x)\cdot g(x)$, where $\cdot$ is ordinary multiplication on the reals, for all $x \in \mathbb{R}^d$?

A: In general $f\otimes g$ is a bilinear map $\Bbb R^d\times\Bbb R^d\to\Bbb R$ which is defined by $$f\otimes g(x,y)=f(x)g(y)$$
and in particular it can be evaluated at $(x,x)$.