text:
Q: Title of Message box not setting up I am writing some code in Visual Basic 6. It also uses the Msgbox funtion. Now I searched this and I got to know that if you want to set the title of the Message box then this is the syntax:
Msgbox(<Prompt>,<Title>)

For example, I write this:
MsgBox ("Incorrect Answer!","QM")

It says:
Compile Error
Expected: =
Can someone tell me what is the problem?

A: With VB6, you can either request a response, and do something based on the answer, or you can simply display a message.
If you want to know what button was clicked, you need to use the function format - that is, you must use the brackets.
If you simply want to display a message, then you don't use the brackets.
So if  you want to just display the message, then continue, do this:
MsgBox "Incorrect Answer!", , "QM"

But if you want to know which button the user clicked (e.g. to offer them a try again, cancel, then you need a variable, and you use the brackets to signifify that it's a function:
Dim response = MsgBox("Try again?", MsgBoxStyle.YesNo, "QM")

You can then look at the response variable to find out which button the user clicked.
A couple of pages for reference:
http://vb6reference.tomswebdesign.net/msgbox.html
https://msdn.microsoft.com/en-us/library/139z2azd(v=vs.90).aspx


text:
Q: Workaround for casting concrete to base generic abstract class I have a generic base abstract class:
public abstract class Generator<T>
{
    public abstract void Start(T config);
}

Then, I have many concrete classes that inherit from base class and expect certain parameter type. Some of them:
public class AGenerator : Generator<AGeneratorConfig>
{
    public override void Start(AGeneratorConfig Config) { /* some code*/ }
}

public class BGenerator : Generator<BGeneratorConfig>
{
    public override void Start(BGeneratorConfig Config) { /* some code*/ }
}

Their Start() method parameters are defined as follows:
public abstract class GeneratorConfig
{
    public int CommonProperty {get; set;}
}

public class AGeneratorConfig : GeneratorConfig
{
    // Some props specific for AGenerator
}

public class BGeneratorConfig : GeneratorConfig
{
    // Some props specific for BGenerator
}

At last, I have a client/manager/factory-like class that handles actual generator start process with provided config,
but is uses casting concrete to abstract generic class:
public class GeneratorClient
{
    public static void StartGenerator<T>(T config)
    {
        Generator<T> generator = null;

        if (config is AGeneratorConfig)
        {
            generator = new AGenerator() as Generator<T>; // casting to abstract base class
        }
        else if (config is BGeneratorConfig)
        {
            generator = new BGenerator() as Generator<T>; // casting to abstract base class
        }
        else
        {
            throw new NotImplementedException();
        }

        generator.Start(config);
    }
}

My question: is there any workaround to eliminate the need of casting concrete to abstract base classes?
The most simple solution would be this:
public static void StartGenerator<T>(T config)
{
    if (config is AGeneratorConfig)
    {
        var generator = new AGenerator();
        generator.Start(config);
    }
    else if (config is BGeneratorConfig)
    {
        var generator = new BGenerator();
        generator.Start(config);
    }
    else
    {
        throw new NotImplementedException();
    }
}

but for each newly created concrete Generator object generator.Start(config); needs to be repeated.

A: Define the generator just as object and cast it to Generator<T> only at the last call:
public static void StartGenerator<T>(T config)
{
    object generator = null;

    if (config is AGeneratorConfig)
    {
        generator = new AGenerator();
    }
    else if (config is BGeneratorConfig)
    {
        generator = new BGenerator();
    }
    else
    {
        throw new NotImplementedException();
    }

    ((Generator<T>)generator).Start(config);
}

A: You can use Reflection to call the constructor, and maybe improve you Factory in order to remove those if's.
You can use a dictionary like this:
    private Dictionary<Type, Type> Diccionary;
    public void CreateDicionary()
    {
        Diccionary = new Dictionary<Type, Type>();
        Diccionary.Add(typeof(AGeneratorConfig), typeof(AGenerator));
        Diccionary.Add(typeof(BGeneratorConfig), typeof(BGenerator));
    }

then you can have the concrete instance with something like this:
   public Generator<T> GetGenerator<T>()
    {
        var type = typeof(T);
        if (!Diccionary.ContainsKey(type))
            throw new Exception("Not found");

        var typeInstance = Diccionary[type];

        return (Generator<T>) Activator.CreateInstance(typeInstance);
    }

And you use the code above with something similar to this:
 public  void StartGenerator<T>(T config)
    {
        var generator = GetGenerator<T>();
        generator.Start(config);
    }

    public static void Main()
    {
        var gen = new GeneratorClient();
        gen.CreateDicionary();
        gen.StartGenerator<AGeneratorConfig>(new AGeneratorConfig());
    }

redpajama_set_name: RedPajamaStackExchange


text:
Q: A Tale of Urns and Balls I got the following situation:

2 urns with 2 whites and 3 blacks
2 urns with 1 white  and 4 blacks
1 urn  with 4 whites and 1 blacks

A ball is drawn from an urn (and this urn is selected at random). The ball is white.
Now, a second ball is drawn from the same urn. What is the probability of getting a black?
ATTEMPT: The urn is selected at random, and we have no further informations about it, so it smells of deception. I think we got to consider only the general set of 10 whites and 15 blacks.
So, having independent trials, we calculate $\frac{10}{25} \times \frac{15}{24}$. (Alternatively, using conditional probability formula).
Is this correct?

A: These things can be tricky, and unless one has a very well developed intuition, I would advise a formal conditional probability calculation.
The probability of white on the first pick turns out to simplify to $\frac{2}{5}$. You got that a quick way. It can also be done more slowly.
Next we compute the conditional probabilities, given white on first pick, that it came from the various urns.
The conditional probabilities turn out to be $\frac{1}{5}, \frac{1}{5},\frac{1}{10},\frac{1}{10},\frac{2}{5}$. Thus the probability that the second is black is
$$\frac{1}{5}\cdot \frac{3}{4}+ \frac{1}{5}\cdot \frac{3}{4} +\frac{1}{10}\cdot \frac{4}{4} + \frac{1}{10}\cdot \frac{4}{4}+\frac{2}{5}\cdot \frac{1}{4}.$$
We leave it to you to verify that the conditional probabilities are what they are, and to fill in any missing details.


text:
Q: How to update form with errors in Django? I'm trying to write an is_valid method for my forms and I'm using this general strategy:
def is_valid(self):
    form = super(UserCreateForm, self).is_valid()
    for f, error in self.errors.iteritems():
        if f!= '__all__':
            self.fields[f].widget.attrs.update({'class': 'error', 'value': strip_tags(error)})
    return form

I want to update the form fields' attributes if I get an error with helpful attributes. But I already have class attributes for the fields (using Bootstrap, so something like 'class':'form-control'); I want the error to replace them. However, when I fail the validation and actually get an error, Django complains saying can't concatenate str and errorList. I'm a bit new to Django, so I'm not sure what is going on here.

A: The way i do this is, have the the errors checked at all the individual divs and display bootstrap's .error class if i find a error.
Eg:{% if form.error %}
Like that you check it with every filed name.
Note: There might be better ways to do it, but i have been using this for a long time now and has worked fine.


text:
Q: CSS: 3D flip of a single letter What I'm trying to achieve is to 3D flip a single letter inside a text.

WebNαme

In this particular case i want to horizontally flip α when it's hovered with the mouse.
I tried doing the same by putting the α in an outside div and it works fine, but it doesn't when I try doing the same with the span inside h1.
This is my CSS:
#logo-alpha {

    -webkit-transition: all 0.5s;
    -moz-transition: all 0.5s;
    -o-transition: all 0.5s;
    transition: all 0.5s;
    -webkit-transform: rotateY(0deg);
    -moz-transform: rotateY(0deg);
    -o-transform: rotateY(0deg);
    -ms-transform: rotateY(0deg);
    transform: rotateY(0deg);
}

#logo-alpha:hover {

    -webkit-transform: rotateY(180deg);
    -moz-transform: rotateY(180deg);
    -o-transform: rotateY(180deg);
    -ms-transform: rotateY(180deg);
    transform: rotateY(180deg);
}

A: You are facing this issue : CSS tranform can't apply on inline elements see here : dev.w3.org transformable elements so you need to change the default display property of the  element to inline-block.
FIDDLE
CSS :
#logo-alpha{
    display:inline-block;
    -webkit-transition: -webkit-transform 1s;
    -moz-transition: -moz-transform 1s;
    transition: transform 1s;
}

h1:hover #logo-alpha{
    -moz-transform: rotateY(-180deg);
    -webkit-transform: rotateY(-180deg);
    transform: rotateY(-180deg);
}

A: Below is some code for both X and Y flips - the important thing is your span needs display:inline-block in order for any 3d transformation to be applied.
Demo Fiddle
HTML

WebNαme

WebNαme

CSS
span {
    -webkit-transition: all 1s ease;
    transition: all 1s ease;
    -webkit-transform: perspective(250px) rotateX(0deg) rotateY(0deg) rotateZ(0deg);
    transform: perspective(250px) rotateX(0deg) rotateY(0deg) rotateZ(0deg);
    display:inline-block;
}
span.flipX:hover {
    -webkit-transform: perspective(250px) rotateX(360deg) rotateY(0deg) rotateZ(0deg);
    transform: perspective(250px) rotateX(360deg) rotateY(0deg) rotateZ(0deg);
}
span.flipY:hover {
    -webkit-transform: perspective(250px) rotateX(0deg) rotateY(360deg) rotateZ(0deg);
    transform: perspective(250px) rotateX(0deg) rotateY(360deg) rotateZ(0deg);
}

A: user hover pseudo class,
.text-muted{font-zise:12px;}
.text-muted:hover{font-size:20px; /* opr what ever you want to do when mouse hover*/ }

or may be you want something this http://css3playground.com/3d-flip-cards/
try it


text:
Q: Creating an AddRegistration method that returns a boolean value with data validation in C# I really need help. I can't seem to figure out how to get this AddRegistration Method to work or how to call it to test it. It's supposed to add a row to a table and display a message box saying whether the operation was a success or not. I'll display the code I've written for it.it is supposed to accept a Registration object and return a boolean value that indicates if the operation was successful. I also need to know how I can call it from a Register Product button.
public static bool AddRegistration(Registration registration)
{
    SqlConnection connection = TechSupportDB.GetConnection();
    string insertStatement = "INSERT INTO Registrations (CustomerID, ProductCode, RegistrationDate) " +
        "VALUES (@CustomerID, @ProductCode, @RegistrationDate)";
    SqlCommand insertCommand = new SqlCommand(insertStatement, connection);
    insertCommand.Parameters.AddWithValue("@CustomerID", registration.CustomerID);
    insertCommand.Parameters.AddWithValue("@ProductCode", registration.ProductCode);
    insertCommand.Parameters.AddWithValue("@RegistrationDate", registration.RegistrationDate);
    try
    {
        connection.Open();
        int count = insertCommand.ExecuteNonQuery();
        if (count > 0)
            return true;
        else
            return false;
    }
    catch (SqlException ex)
    {
        throw ex;
    }
    finally
    {
        connection.Close();
    }


text:
Q: Why is Google Chrome emptying my search bar in MediaWiki? This is a saga that begun with

*

*Adding extra search text to a MediaWiki search query using InputBox and continued with

*PHP function is not defined error and syntax error of misplaced </p> in generated HTML.
I have created a JavaScript to enter text into a MediaWiki search box depending on check box selections. This now works in Firefox and Internet Explorer. But not in Google Chrome.
In Chrome, the search box is correctly filled (with the aforementioned JavaScript) but the search box blanks (empties) when the search button is pressed. This means that the search URL is also blanked which in turn means that only the default MediaWiki search page is shown.
What is Chrome doing with the code that FF and IE are not - and how can I fix this?

A: In my PHP code, I embedded this JavaScript:
<script type="text/javascript">function appendAndSubmit(){var platform1 = document.getElementById('p1').checked;var platform2 = document.getElementById('p2').checked;var text = document.getElementById('searchboxInput').value;if (platform1 * platform2 >0) text = text + ' "Applies to=Platform 1.0" "Applies to=Platform 2.0"';else if (platform1) text = text + ' "Applies to=Platform 1.0"';else if (platform2) text = text + ' "Applies to=Platform 2.0"';document.getElementById('searchboxInput').value = text;document.forms['searchform'].submit();}</script>

The variable text was defined as what was in the search form. So I simply changed the last part:
document.forms['searchform'].submit();

to
text.submit();

It works, but I don't know why.


text:
Q: How to test Angular component's observable error? I want to test a component will render a ErrorComponent if one of the service or Gql fails, but I'm having trouble mocking the error where it triggers the catchError() block.
Where do I mock that error? Inside the providers array? Using spyOn ? I tried both but not getting the results I want.
Component's ngOnInit() will set this.loading = isLoading and this.data$ = this.getData()
Inside getData()
combineLatest([
serviceA.get(),
serviceB.get(),
GqlC.fetch(),
GqlD.fetch(),
]).pipe(
      map(
        ([a,b,c,d]) => ({
            a,
         name: b[c],
         age : d
        })
      ),
      tap(() => {
        this.loading = isSuccess;
      }),
      catchError((e) => {
        this.loading = isFailure;
        return throwError(() => e);
      })
)

How do I mock an error returned from service or GQL to trigger the catchError block ?
Inside Spec
describe('aComponent error state', () => {
  let component;
  let fixture;
  let controller: ApolloTestingController;

  beforeEach(async () => {
    await TestBed.configureTestingModule({
      declarations: [aComponent],
      providers: [
        { provide: serviceA,
          useValue: new mockServiceA({ mock }),},
        { provide: serviceB,
          useValue: new mockServiceB(mock), },
        { provide: APOLLO_TESTING_CACHE,
          useValue: new InMemoryCache({ addTypename: true }),},
      ],
      imports: [Module....],
    }).compileComponents();

    fixture = TestBed.createComponent(aComponent);
    component = fixture.componentInstance;
    controller = TestBed.inject(ApolloTestingController);
    fixture.detectChanges()
  });
  it('should render ERROR_COMPONENT', () => {

  });
});

I tried spyOn(component['GqlC'],'fetch').and.returnValue(throwError(()=>new Error('mockError')))
but I'm not getting any error component rendered at all.
Thank you for any inputs, I'm very new to angular and testing in general any help would be much appreciated.

A: Your mocks need to return appropriate Observables. For this particular test, have the service get methods and GqlC's fetch method return of(null) to make sure they emit, and have GqlD's fetch method return an Observable which errors out with throwError().


text:
Q: Self-referential use of unordered_map causes problems for gcc 5.3 but not clang The following code fails to compile under gcc 5.3 (it's a reduced version taken from a larger piece of code):
#include <unordered_map>
#include <string>

class Foo {
    std::unordered_map<std::string, Foo> m;  //"self-referential"
};

int main()
{
    Foo f;
    return 0;
}

with the following errors:
g++ --std=c++1y  -c rh.cpp

In file included from /usr/local/include/c++/5.3.0/utility:70:0,
                 from /usr/local/include/c++/5.3.0/unordered_map:38,
                 from rh.cpp:1:
/usr/local/include/c++/5.3.0/bits/stl_pair.h: In instantiation of 'struct std::pair<const int, Foo>':
/usr/local/include/c++/5.3.0/ext/aligned_buffer.h:85:34:   required from 'struct __gnu_cxx::__aligned_buffer<std::pair<const int, Foo> >'
/usr/local/include/c++/5.3.0/bits/hashtable_policy.h:246:43:   required from 'struct std::__detail::_Hash_node_value_base<std::pair<const int, Foo> >'
/usr/local/include/c++/5.3.0/bits/hashtable_policy.h:292:12:   required from 'struct std::__detail::_Hash_node<std::pair<const int, Foo>, false>'
/usr/local/include/c++/5.3.0/bits/hashtable_policy.h:1896:60:   required from 'struct std::__detail::_Hashtable_alloc<std::allocator<std::__detail::_Hash_node<std::pair<const int, Foo>, false> > >'
/usr/local/include/c++/5.3.0/bits/hashtable.h:170:11:   required from 'class std::_Hashtable<int, std::pair<const int, Foo>, std::allocator<std::pair<const int, Foo> >, std::__detail::_Select1st, std::equal_to<int>, std::hash<int>, std::__detail::_Mod_range_hashing, std::__detail::_Default_ranged_hash, std::__detail::_Prime_rehash_policy, std::__detail::_Hashtable_traits<false, false, true> >'
/usr/local/include/c++/5.3.0/bits/unordered_map.h:101:18:   required from 'class std::unordered_map<int, Foo>'
rh.cpp:4:32:   required from here
/usr/local/include/c++/5.3.0/bits/stl_pair.h:102:11: error: 'std::pair<_T1, _T2>::second' has incomplete type
       _T2 second;                /// @c second is a copy of the second object
           ^
rh.cpp:3:7: note: forward declaration of 'class Foo'
 class Foo {

There is no issue with the code using clang (I tested 3.8 on Linux, and 3.9 on OSX):
clang++ --std=c++1y --stdlib=libc++ -c rh.cpp
On linux, using clang + libstdc++ also fails.
The issue seems to come down to libstdc++ using an __gnu_cxx::__aligned_buffer in its hash map implementation, which needs a complete type.
Both standard libraries work fine when a std::map is used, but that is not a solution I can accept. Nor is having the value type of the map be a pointer to Foo.
Is there any other change that I can make to have the code work on gcc/libstdc++?
Thanks!

A: I suggest you to modify Foo class in the next manner:
class Foo {
public:
    Foo();
private:
    using MapType = std::unordered_map<std::string, Foo>;
    std::shared_ptr<MapType> m_ptr;
};

// Here Foo is already defined.
Foo::Foo() {
    m_ptr = std::make_shared<MapType>();
}

This code compiles fine with both clang 3.9 and gcc 6.2.


text:
Q: Unable to get the IF condition in AWS CLI commands in Jenkins to work I am trying to run a series for commands for aws through a Jenkins job but whenever it comes to the if condition, it throws an error
Here are the list of commands
echo '****** Updating ASG ********'
aws autoscaling update-auto-scaling-group --auto-scaling-group-name test-asg --desired-capacity 2 --min-size 2 --max-size 6
sleep 200
echo '****** Initiating Instance Refresh ********'
aws autoscaling start-instance-refresh --auto-scaling-group-name test-asg --preferences '{"InstanceWarmup": 300, "MinHealthyPercentage": 100}'
while true;
do
    instance_refresh_status=$(aws autoscaling describe-instance-refreshes --auto-scaling-group-name test-asg --query "InstanceRefreshes[0].Status" --output text --region us-east-1)
    if (( "$instance_refresh_status" == "Successful" )); then
        break
    fi
    sleep 10
done

echo '****** Finished Instance Refresh ********'

echo '****** Updating ASG back to normal ********'
aws autoscaling update-auto-scaling-group --auto-scaling-group-name test-asg --desired-capacity 1 --min-size 1

The error I get is this in the Jenkins output
+ instance_refresh_status=InProgress
+ InProgress == Successful
/tmp/jenkins8251579523029552853.sh: 10: /tmp/jenkins8251579523029552853.sh: InProgress: not found

No matter what I try to wrap the if condition in, (), (()), [], [[]] I get the same error as above.
Can you please help me solve this?

A: Use if [ "$instance_refresh_status" = "Successful" ]; then (note the single square brackets and single equal sign).
There are two problems in your version: first, (( )) is a bashism, and your script is not running under bash. In any POSIX-compliant shell, ( ) runs its contents (as normal shell commands) in a subshell. bash (and some other shells) treat (( )) differently, but in a basic POSIX shell like dash (which I suspect you're running under), it just runs its contents in two layers of subshell. So it's running "InProgress" == "Successful" in a double-sub-shell, which treats InProgress as a command and == and Successful as arguments to it, and gets a "not found" error looking for the command.
If you want to use bash features (or don't know which features are bashisms and which will work in other shells), you should start the script with a proper bash-specific shebang line, like #!/bin/bash or #!/usr/bin/env bash (and don't override it by running the script with the sh command).
The second problem is that in bash, (( )) does integer arithmetic evaluation. Given (( "InProgress" == "Successful" )), it will try to evaluate InProgress and Successful as integers. The details aren't important here, but essentially they'll both evaluate as 0, so since 0 == 0 is true, the test will come out as true even though they're completely different strings.
To do string comparisons, use [ ] or [[ ]], and since [[ ]] is another bashism (as is == inside them), I'd recommend using [ = ] at least until you're certain of which shell your script is running under.


text:
Q: strangeness , psql use trim() and replace() Can't remove spaces Is it a format encoding problem?
enter image description here
select length(replace('  1221A7', ' ', '')),
       length(replace(' 1221A7', ' ', '')),
       btrim(' 1221A7'),length(btrim(' 1221A7'));

A:
Save this and check under hex editor.
It looks like in second string there is 0x80 instead of 0x20


text:
Q: image url with physical path? In application I have physical path (OS path of image) and requirement is to assign this path to an image control. Image control imageUrl requires application path. Please advice how to do this.
THANKS

A: Like millimoose said, your file should be in the same folder or sub-folder of your deployed application. If but any chance they are (deployed with your app or copied manually) you could translate it to a relative path using something like this:
        string phicalPath = @"C:\WebSite\Images\myimg.png";
        String desiredRelativePath = phicalPath.Replace(Request.ServerVariables["APPL_PHYSICAL_PATH"], String.Empty);

Hope that helps.


text:
Q: Efficient way to store user records in a file in java I need to store user details in a file, efficiently. Should I use different file for every record , or I should append all records in a single file.
which extension is best among these , .txt , .bin , .csv.
Or any other suggestion?

A:
Should I use different file for every record:

No, usually not

or I should append all records in a single file

Yes, in most cases

which extension is best among these , .txt , .bin , .csv. ?

*

*bin for binary files

*csv for text based comma separated file which have one record in each line (like excell tabel)

*txt only when human readable

otherwise any extension you want, eg. ".dat"

A: I have created one an app in FX that needs to store locally user inputs and details. I used XML file with JAXB (you can use JAXP too but it is somewhat outdated). Consider your details as a database. After that, with JAXB it is very easy and fast to store/load data from a local XML file


text:
Q: What fires 'touchmove' event? I've been debugging a touchmove event and 'console.logging it', yet I still don't get and still haven't found any information on how does this event actually get fired.
So is this event fired based on distance/time, both?, When is this fired?

A: The exact implementation depends on the user agent, as can be read in the specification on here in section 5.5 the touchmove event


text:
Q: Meaning of "I've never taken anything on a journey that I'd have been less sorry to lose on the way" I have just finished reading this sentence in Tolkien's Lord of the Rings:

In fact, I've never taken anything on a journey that I'd have been less sorry to lose on the way.

Samwise says that of Gollum.
I know from broader context that Sam is implying he'd be happy to have lost Gollum on the way. But I'm struggling to understand the double negatives. How do the double negatives compound to result in the implication? Is it better phrased as, never have I taken anything on a journey which I'd be sorry to lose? But how does 'less sorry' make sense here?
I hope you can see or understand my difficulty here, I'm having trouble expressing it.

A: Breaking it down in steps:

In fact, I've never taken anything on a journey that I'd have been less sorry to lose on the way.

Remove non-essential bits

I've never taken anything on a journey that I'd have been less sorry to lose

Add in the implicit object of comparison

I've never taken anything on a journey that I'd have been less sorry to lose than Gollum

"less sorry" = "happier"

I've never taken anything on a journey that I'd have been happier to lose than Gollum

"There is nothing more X than Y" = "Y is the most X"

Of all the things I've ever taken on a journey, I'm happiest about losing Gollum.


text:
Q: Why is there a limitation on the number of points a polygon can have on ST_WITHIN? We are at a cross roads where we need to decide if we are going to store our GeoSpatial data in DocumentDB or SQL Azure. According to this article, the polygon parameter of the ST_WITHIN function in a query can contain a maximum of 256 points. Our data will potentially contain polygons with millions of points as we are mapping continents, countries, states/provinces, etc. We need to be able to use ST_WITHIN against all of these polygons. The article also mentions that we can adjust that limitation by contacting Azure Support.
Why is this limitation in the first place? If Support does remove the limitation, are we going to bring DocumentDB down with so many points?

A: If you want to do it all in DocumentDB (as opposed to adding something like SQL Azure), you can use an approach of narrowing down the list by using ST_DISTANCE to get candidates and then running the equivalent to ST_WITHIN client side (ray casting algorithm is simple and fast). The trick involves storing denormalized meta-data about each polygon, namely a center point (accuracy of center point not critical) and the maximum radius using that center point. Then if the distance between your point and the center minus the maximum radius is less than zero, it's in the candidate list. It works like a charm and is performant with some careful index design.
One thing to worry about is the condition where the polygon intersects itself. Do you treat the intersecting space as outside the polygon or within it? We had a nasty bug that took forever to figure out and it boiled down to a self-intersecting polygon. This problem exists whether you implement your own algorithm or use the database's native "within" function.

A: The short answer to your question is yes, they are worried you will bring DocumentDB down with more than 256 points.  It used to be limited to just 16 points, but they changed it to 256 recently. Perhaps they will raise it again in the future. We ran into a similar problem with polygons having more than 1,000 points. In the end, we decided to use Sql Server for our polygon searches and then use the data refined from Sql Server to pull the related data from DocumentDB.
The problem is that DocumentDB resources are shared between customers so all of the operations that you run against DocumentDB have to be governed by request units. That way, no one customer can bring the system down with massive queries. I don't know how to calculate the request units from using ST_WITHIN on millions of points, but my guess is that even on the S3 tier, it would probably push the limit of the allowable 2500 Request Units.  So even if they lifted the 256 points to a one million points, your query might not be able to finish because it would be too expensive.  So I suggest you go with Sql Azure. That is what we settled on and it performs great.


text:
Q: Allowing users to network SO is an excellent platform for techincal questions, ranging from newbies to . Would it be possible for SO to add a feature "Add as a friend" so that like minded people can also chat toget

A: You can chat right now. Just click "chat". Rooms can be topic based, site based, or whatever you want as long as they are broadly on-topic (related in some way to the site), and is reasonably behaved.

A: No, please no!
I can already see Jon drowning in friend and support requests.


text:
Q: Rails: render text gives missingtemplate error I am trying to do an AJAX call with Rails.  The call is to the change_profile action in my controller.  The contents of this action are as follows:
def change_profile
    @test = params[:test]
    puts "AAAAAAA #{@test}"
    respond_to do |format|
       format.html
       format.js
    end
    render(:text => "FINISHED THE AJAX REQUEST")
end

When I call this, however, the Rails console says:
ActionView::MissingTemplate (Missing template main/change_profile  ....

I don't understand why this is happening.  Since I'm rendering text, shouldn't it know not to try to find the template and just render the text?

A: When left without a {}, the respond_to block looks for a file called change_profile.erb.js or some other change_profile.xxx.js. Add your code within the respond_to block
def change_profile
    @test = params[:test]
    puts "AAAAAAA #{@test}"
    respond_to do |format|
       format.html
       format.js {
         render :text => "FINISHED THE AJAX REQUEST"
       }
    end
end


text:
Q: C# .NET - How can I create a new Bitmap instance for a bitmap from native resources? I tried many times to load a Bitmap from native resources but I failed big time.
The image I'm trying to load is like this into the native resources:
http://i.stack.imgur.com/x7Jr8.jpg
The code I wrote the image with is this:
    [DllImport("kernel32.dll")]
public static extern int UpdateResource(uint hUpdate, SqlDbType lpStructure, uint lpName, ushort wLanguage, int lpData, UIntPtr cbData);
[DllImport("kernel32.dll")]
public static extern UIntPtr BeginUpdateResource(string pFileName, bool bDeleteExistingResources);
[DllImport("kernel32.dll")]
public static extern bool EndUpdateResource(UIntPtr hUpdate, bool fDiscard);
public static bool WriteResource(string FileName, byte[] data, uint Name)
{
    UIntPtr ptr = BeginUpdateResource(FileName, false);
    GCHandle Handle = GCHandle.Alloc(data, GCHandleType.Pinned);
    uint size = Convert.ToUInt32(Convert.ToUInt64(data.Length));
    UIntPtr pt = new UIntPtr(size);
    UpdateResource(ptr.ToUInt32(), SqlDbType.Bit, Name, 0, Handle.AddrOfPinnedObject().ToInt32(), (UIntPtr)Convert.ToUInt64(data.Length));
    EndUpdateResource(ptr, false);
    return true;
}

I tried to use LoadImage and LoadBitmap API calls but I failed big time.
Can you provide me with a snippet on how I can do this conversion? I want to fetch it from the native resources and store it into a Bitmap class (the common System.Drawing.Bitmap class of .NET framework). I'd appreciate any help.

A: I'm not sure if I've understood you correctly. But I could imagine you are searching for something like this:
System.Reflection.Assembly thisExe;
thisExe = System.Reflection.Assembly.GetExecutingAssembly();
System.IO.Stream file =
thisExe.GetManifestResourceStream("AssemblyName.ImageFile.jpg");
this.pictureBox1.Image = Image.FromStream(file);


text:
Q: Element implicitly has an 'any' type because index expression is not of type 'number'. - Index Signature error I am new to TypeScript and I am getting

Element implicitly has an 'any' type because index expression is not of type 'number'

on this line -->
const { status, msg } = codes[err.code];
I am not too sure how to fix it.
Here is the code:
    export const handlePSQLErrors = (
    err: { status: number; msg: string; code: string | number },
    req: Request,
    res: Response,
    next: NextFunction
) => {
    const codes: any = {
        '22P02': { status: 400, msg: 'Bad Request' },
        42703: { status: 400, msg: 'Bad Request' },
        23502: { status: 400, msg: 'Bad Request' },
        23503: { status: 404, msg: 'Bad Request' },
    };

    function hasKey<O>(obj: O, key: keyof any): key is keyof O {
        return key in obj;
    }

    if (hasKey(err.code, codes)) {
        const { status, msg } = codes[err.code];

        res.status(status).send({ msg });
    } else next(err);
};

Help to explain what is going on and how to fix it would be much appreciated.
Thanks

A: There is not an typing issue, but there is a wrong call.
You get this error on the line:
const { status, msg } = codes[err.code];

But there real error is this:
if (hasKey(err.code, codes)) {

should be (swap the arguments)
if (hasKey(codes, err.code)) {

As hasKey is defined that the key is send as 2nd argument

*

*Demo with this error

*Demo with fix


text:
Q: I need to send this value to a php variable "c:\" but php guees I close a \" I need to send this value to a php variable "c:\" but php guees I closed a \" and return an error. If I change to 'c:\' is the same.

A: You must escape the \, i.e. "c:\"
\ is an escape character, hence \" means use the next " as is and not as a closing "


text:
Q: log4j2 and syslog, using RFC5424 format does not show varargs part of log message I have this syslog appender configured:
    <Syslog name="syslog" format="RFC5424" host="localhost" port="514"
            protocol="UDP" appName="" includeMDC="true"
            facility="LOCAL0" enterpriseNumber="" newLine="true"
            messageId="" id="">
        <LoggerFields>
            <KeyValuePair key="c" value="%c{1}" />
            <KeyValuePair key="l" value="%p" />
            <KeyValuePair key="t" value="%t" />
        </LoggerFields>
    </Syslog>

The log messages in local0 do not get the varargs part of the log4j2 output. For example, this log statement in the code:
log.info("commit(). Query {}", query.getQuery());

will result in this output in local0.log (not the curly braces at the end):
Mar  3 20:09:22 127.0.0.1 1 2015-03-03T20:09:22.431Z app-03-prod.lax.projone.net  -  [mdc@18060 c="c.c.p.p.TransactionHelper" l="INFO" t="qtp812765588-375 - /id/1.0/credential?appKey=867ac7681942fb3ee5453b95378f155e"] commit(). Query {}

But in the application log file, I do get the varargs part of the statement:
2015-03-03 20:04:25,374 INFO c.c.p.p.TransactionHelper [qtp380256045-442 - /id/1.0/session/start?appKey=940d52aac10af731c83176e65a763f87] commit(). Query INSERT INTO oid_identity (oid, app_id, app_uid, platform_id, platform_uid, creation_time) VALUES ( UNHEX( ? ), ? , ?, ? , ? , ? ) ON DUPLICATE KEY UPDATE creation_time=creation_time

I must be missing something in the log4j2.xml config?

A: In the pattern layout, %t stands for the thread name, and you would use %m to get the message.
If that does not answer your question, can you clarify your expected result? (You explained the steps to reproduce and the actual result, but it would be helpful if you can make explicit what output you expect/want to achieve.)


text:
Q: Power Point 2007 won't automatically advance to linked presentation I'm using PPt 2007.  I've successfully linked 3 PPt presentations; however, I can't advance from the last slide in, for example, presentation #1 unless I click.  I would like PPt to simply advance from the last slide on the 1st presentation to the 1st slide on the 2nd presentation and continue on.

A: Unfortunately, that's the nature of links ... you have to click them to activate them.
Is there some reason you can't combine both presentations into one?


text:
Q: Open multiple files using fileopendlg() function I want to open multiple files using fileopendlg() function, when I code it selects only one file at a time. Is there any function or procedure to select multiple files at a time?

A: Unfortunately, MapBasic does not provide the means to open multiple files through the FileOpenDlg function. However, as described in the link posted by Joseph in the comments, you can use a .NET assembly to give you that functionality. A few years back I wrote an assembly to handle a bunch of file and folder functions, including a multi-file version of the FileOpenDlg, and uploaded it to the community downloads site including code examples on how to use it. You can find it here. You may find some of the other functions it provides useful as well!


text:
Q: given array find all combinations of elements that give sum I've been asked the following question in an interview. Although I've answered it using an n-ary tree, I've been told it wasn't "good enough". So, I'm curious, what's the optimal solution for it.
Input: array of integers: [2, 3, 7]  and sum: 10
Output: all combinations of array elements that add up to sum (e.g. 2+2+2+2+2, 2+2+3+3, 3+7, etc.)
Thanks,
T

A: This problem can be solved using dynamic programming. You have two dimensional dp. Lets say you do the dp in an array called mem. mem[i][j] will store the number of ways you can achieve sum i with the elements of indexes j, j + 1... n(here n is the size of the array).
You have the following relation mem[i][j] = mem[i][j+1] + mem[i - a[j]][j+1](of course you need to check if i is not less than a[j]). And now you can find the number of ways in which you can achieve sum S by getting the value of mem[S][j]. reconstructing the solutions is not very hard once you have the array. I suggest you try to do that on your own and write a comment if you can't figure it out.


text:
Q: handling ampersand(&) in an sql statement
Possible Duplicate:
How do I ignore ampersands in a SQL script running from SQL Plus?

I have an using an sql statement where there is an ampersand(&) explicitly used in the WHERE clause.
e.g. select * from table1 where column1 IN('abc',"'a & b',''def')
In this statement I am getting the values for the IN clause as a comma separated string e.g.string1="'abc',"'a & b',''def'"
which I directly use it to build my sql query.
Now when I try to run this query I am unable to execute this query as when I execute it during run time it is asking for a replacement character for ampersand .
how do I change or alter my query so that I can get to use the ampersand
Should I use a regex on the string which I get to manipulate to make it work.As the string(comma seperated value) I am using in the sql query is coming from a text box.
the database I am using is Oracle
please help

A: This Oracle Technology Network forum discussion offers various workarounds for this problem. The simplest, in my opinion, is one of the first suggestions, which is to replace this:
'a & b'

with this:
'a &' || ' b'

but you can look through that page to see if any of the other ideas sounds better to you.
(Though I have to say — I'm a bit worried that you're getting this error. It makes it sound almost as though you were just plugging the user-submitted text right into SQL*Plus . . . which, if it were the case, would be really bad. What would happen if the user submitted '; \n DROP TABLE users;?)

A: if 'a&b' is a Column name, you can use like below.
'A&B'

it will solve the recognizing ampersand problem.
and as @ruakh told using ||, that trick will do work.
These Question1 and Question2 will help You.
for more information check this forum


text:
Q: Serialize LocalDate as TimeStamp using Spring Boot 2.3.4.RELEASE Jackson2ObjectMapper I tried several ways to change the default jackson configuration within the spring boot and it doesn't work.
it simply ignores all configuration
@SpringBootApplication
public class AvaliacaoairtonApplication {

public static final String URL = "*";

public static void main(String[] args) {
    SpringApplication.run(AvaliacaoairtonApplication.class, args);
}

@Bean
@Primary
public ObjectMapper objectMapper(Jackson2ObjectMapperBuilder builder) {

    ObjectMapper objectMapper = builder.build();

    objectMapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);

    JavaTimeModule javaTimeModule = new JavaTimeModule();
    javaTimeModule.addSerializer(LocalDate.class, new StdScalarSerializer<LocalDate>(LocalDate.class) {

        @Override
        public void serialize(LocalDate localDate, JsonGenerator jsonGenerator,
                              SerializerProvider serializerProvider) throws IOException {

            jsonGenerator.writeString(localDate.format(DateTimeFormatter.ofPattern("yyyy-MM-dd")));
        }
    });

    objectMapper.registerModule(javaTimeModule);

    return objectMapper;
}

}
application.properties
spring.jackson.serialization.write-dates-as-timestamps=false
POM
<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.3.4.RELEASE</version>
    <relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>br.com.softplan</groupId>
<artifactId>avaliacaoairton</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<name>avaliacaoairton</name>
<description>Demo project for Spring Boot</description>

<properties>
    <java.version>11</java.version>
</properties>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

    <dependency>
        <groupId>org.projectlombok</groupId>
        <artifactId>lombok</artifactId>
        <optional>true</optional>
    </dependency>
    <dependency>
        <groupId>org.hibernate.validator</groupId>
        <artifactId>hibernate-validator</artifactId>
        <version>6.0.2.Final</version>
    </dependency>
    <dependency>
        <groupId>org.hibernate.validator</groupId>
        <artifactId>hibernate-validator-annotation-processor</artifactId>
        <version>6.0.2.Final</version>
    </dependency>

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-data-jpa</artifactId>
    </dependency>

    <dependency>
        <groupId>org.postgresql</groupId>
        <artifactId>postgresql</artifactId>
        <scope>runtime</scope>
    </dependency>
    <dependency>
        <groupId>com.fasterxml.jackson.datatype</groupId>
        <artifactId>jackson-datatype-jsr310</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-tomcat</artifactId>
        <scope>provided</scope>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-test</artifactId>
        <scope>test</scope>
        <exclusions>
            <exclusion>
                <groupId>org.junit.vintage</groupId>
                <artifactId>junit-vintage-engine</artifactId>
            </exclusion>
        </exclusions>
    </dependency>
</dependencies>

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
    </plugins>
</build>

result
enter image description here


text:
Q: three level page table in linux I know that linux uses three level page tables in memory management.

I got confused on the content of the page table.Does page table
  contains next level page tables base address or it contains page frame
  number?
If it contains page frame number then how base address for that
  particular page table is got?Where is it stored?

Would be greatful if someone clarified this to me.

A: If you're talking about x86(/64), then every page table entry (except the terminal one) contains the physical address of the next page table, and the terminal PTE contains the physical address of the actual code/data page.
Since page tables are organized as pages themselves, their physical addresses are naturally multiples of the page size.
It makes little sense to store full physical addresses in PTEs with the 12 least significant bits being always zero (in case the page size is 4KB), and so they aren't stored in the PTEs (and the recovered space in the PTEs is used for control flags such as kernel/user, read-only/writable, executable, present, dirty, accessed, etc). Addresses truncated like that are commonly called page frame numbers because they are nothing else but page numbers (if you count all pages from 0 for the page at address 0, 1 for the page at address 4096 and so on).
The ultimate answer to your question with all the gory details is in the relevant CPU manual.


text:
Q: Uno application run on MacOS - problem with elements accessibility I have the MacOS application developped using UNO Platform whitch i would like to test using appium.  Application was is fully fucntional for manual usage.
Then i encountered an issue with accessibility inspector that default MacOS window buttons like "close application", "maximalize", and "minimalize" can be accessed wia UIElementInspector but almost all of the application connetnt cannot be accessed(they are not listed at all) as a children of the main window. Only images are accessible but none of the buttons neither texts.
I checked other applications like calculator, visual studio etc and hadn't simillar problems - every element was listed, so in my opinion problem is not coming form system but the application or uno platrorm  itself. Remark - on windows this application hadn't such inssue with contetnt acessibility.
Also found example application developed in uno platform and this applicacion  also does not share the elements in inspector.

https://github.com/unoplatform/Uno.Ch9

Have anyone had faced similar problem and was able to solve it?


text:
Q: Cover of vertices - NP Algorithm analysis, correctness and execution time Introduction
Given a graph $G = (V, E)$, we call a set $T \subseteq V$ a cover if any edge $e \in E$ has one extremity in T.
Decision Problem: Given $G = (V, E)$ with n nodes and a $k \le n$, return Yes if there exists a set T which is a cover in G, with $|T| \le k$, No otherwise.
Ok, so far so good. I'm given the following algorithm(it returns Yes/No & the set T):
$R-COV(G,k)$
$if(E = \emptyset$ then return ("Yes", $\emptyset$)
$if(|E| \gt k * (|V| - 1)$ then return ("No")
Let ${u, v} \in E$
$if( R-COV(G - u, k - 1) == ("Yes", T) )$ then return("Yes", $T \cup\{u\}$)
else $if( R-COV(G - v, k - 1) == ("Yes", T)$ then return ("Yes", $T \cup \{v\}$)
else return ("No")
I shall prove that this algorithm does exactly what's asked to do (so it is correct) and find out it's $T(n, k)$ (execution time).
What I know by now
Guessing right, this decision problem is NP-complete.
To prove it is correct, I thought of analyzing every condition in this algorithm and proving that it returns "Yes" only for T-covers.. Visually it looks right, but I don't know how to write it down mathematically..
For the execution time, should I use the Master Theorem? Is it apropriate? Also I think that when k is constant, the algorithm is, obviously, running in polynomial time. But how should I write this down mathematically?
Thanks for your time.


text:
Q: Relative Fluctuations in volume at thermodynamic limit Volume fluctuation of a pressure ensemble is given by
$$\langle(\Delta V)^2\rangle = k_BT\langle V\rangle\kappa_T$$
where $\kappa_T$ is the isothermal compressibility.
In the book, it is said that in the thermodynamic limit, the relative fluctuations vanish in the thermodynamic limit, which I don't seem to understand why?
$$\frac{\sqrt{\langle(\Delta V)^2\rangle}}{\langle V\rangle} = \frac{\sqrt{k_BT\kappa_T}}{\sqrt{\langle V\rangle}}$$
Both $\kappa_T$ and $V$ are finite in the thermodynamic limit. So, how are the relative fluctuations vanishing?

A: The thermodynamic limit (TL) is a theoretical tool necessary to justify the connection between Statistical Mechanics and Thermodynamics. Indeed, for interacting finite systems, the logarithm of the partition functions in different ensembles fails to have some key properties like additivity, convexity, and the possible presence of non-analytic behavior (aka phase transitions). The thermodynamic limit restores the expected thermodynamic behavior of macroscopic systems.
However, the exact statement about how to perform the TL changes in each statistical ensemble. The general recipe is that the limit that should exist is the limit of the logarithm of the partition function divided by one extensive independent variable; all the extensive independent variables must go to infinity by keeping fixed their ratios.
To list a few well-known and some less well-known cases, the way to implement the TL in different ensembles is the following.
microcanonical ensemble
$$
\lim_{{{E\rightarrow \infty} \atop {V \rightarrow \infty}} \atop {N \rightarrow \infty }} \frac{1}{V} \log W(E,V,N)~~~~~~~~~~~~~~~~~~~~~~{\mathrm {by~keeping~constant}}~~~~~~ \frac{E}{V}= e ~~~~ {\mathrm {and}}~~~~~~~~  \frac{N}{V}= \rho
$$
canonical ensemble
$$
\lim_{{ {V \rightarrow \infty}} \atop {N \rightarrow \infty }} \frac{1}{V} \log Z(\beta,V,N)~~~~~~~~~~~~~~~~~~~~~~{\mathrm {by~keeping~constant}}~~~~~~ ~~~~~  \frac{N}{V}= \rho
$$
grand canonical ensemble
$$
\lim_{V \rightarrow \infty} \frac{1}{V} \log \Xi(\beta,V,z=e^{\beta \mu})
$$
isothermal-isobaric ensemble
$$
\lim_{N \rightarrow \infty} \frac{1}{N} \log X(\beta,\beta P,N)
$$
Notice that there is only one extensive independent variable in the last two cases.
The previous TLs, if they exist, correspond respectively to

*

*entropy density $s(e,\rho)$  (microcanonical);

*$-\beta f(\beta,\rho)$, $f$ density of free energy;

*$-\beta P(\beta,z)$;

*$-\beta \mu(T,P)$
In the case of the isothermal-isobaric ensemble, the existence of TL implies the extensiveness of the Gibbs free energy $G= N \mu$. Therefore, $\langle V \rangle=\frac{\partial G}{\partial P}$ grows like $N$ and the relative fluctuation of the volume vanishes at the TL.


text:
Q: Hide an element after 5 seconds only CSS does not work on Firefox For hiding an element after 5 seconds, I have used below code.
But it does not work in Firefox.

.classname {
    -webkit-animation: cssAnimation 0s ease-in 5s forwards;
    -moz-animation: cssAnimation 0s ease-in 5s forwards;
    -o-animation: cssAnimation 0s ease-in 5s forwards;
    animation: cssAnimation 0s ease-in 5s forwards;
    -webkit-animation-fill-mode: forwards;
    animation-fill-mode: forwards;
}
@keyframes cssAnimation {
    to {
    width:0;
    height:0;
    overflow:hidden;
    }
}
@-webkit-keyframes cssAnimation {
    to {
    width:0;
    height:0;
    visibility:hidden;
    }
}

This will hide

A: There are some issues with the code above:

*

*The animation is not the same for all browsers: one is animating the visibility (webkit), the other one is animation the overflow (standard).

*The overflow property is not animatable.

*Firefox has a history of issues with the visibility property (this is not your fault but a problem of Firefox itself, you can find many questions on SO related to it).

Because of the way in which you are running the animation (with a duration of 0s), you can trick Firefox by using the from in the CSS animation. The thing is that Firefox is not animating the visibility, but it will apply the style in the from part of the animation anyway, so you'll get the desired effect.

.classname {
    -webkit-animation: cssAnimation 0s ease-in 5s forwards;
    -moz-animation: cssAnimation 0s ease-in 5s forwards;
    -o-animation: cssAnimation 0s ease-in 5s forwards;
    animation: cssAnimation 0s ease-in 5s forwards;
    -webkit-animation-fill-mode: forwards;
    animation-fill-mode: forwards;
}
@keyframes cssAnimation {
    from {
        visibility:hidden;
    }
    to {
        width:0;
        height:0;
        visibility:hidden;
    }
}
@-webkit-keyframes cssAnimation {
    from {
        visibility:hidden;
    }
    to {
        width:0;
        height:0;
        visibility:hidden;
    }
}

This will hide

If the duration of the animation was higher than 0 seconds, this solution wouldn't work; but as the change is automatic, it works fine (and it will not affect the rest of the browsers).

The advantages of this solution:

*

*The behavior is the same in all the browsers.

*The hidden text is not selectable.

The disadvantages:

*

*This is a workaround and not how things should be done.

*It does not work if the duration of the effect is higher than 0s.

A: Try to use fixed width and height for your block (in % or px) and opacity instead visibility — http://jsfiddle.net/sergdenisov/wek6x4Ln/11/:
.classname {
    width: 200px;
    height: 50px;
    -webkit-animation: css-animation 0s ease-in 5s forwards;
    animation: css-animation 0s ease-in 5s forwards;
}

@-webkit-keyframes css-animation {
    to {
        width: 0;
        height: 0;
        opacity: 0;
    }
}

@keyframes css-animation {
    to {
        width: 0;
        height: 0;
        opacity: 0;
    }
}


text:
Q: What's a non-abelian totally ordered group? Because I have heard the phrase "totally ordered abelian group", I imagine there should be non-abelian ones.  By this I mean a group with a total ordering (not to be confused with a well-ordering) which is "bi-translation invariant": a < b should imply cad < cbd.
Does anyone know any examples?
Totally ordered abelian groups are easy to come up with: any direct product of subgroups of the reals, with the lexicographic ordering, will do.  Knowing some non-abelian ones would help reveal what aspects of totally ordered abelian groups really depend on them being abelian...
Edit: Via Andy Putman's answer below, I found this great summary of results about ordered and bi-ordered groups (i.e. groups with bi-translation invariant orderings) on Dale Rolfsen's site:
Lecture notes on Ordered Groups and Topology
He shows numerous examples of non-abelian bi-orderable groups, including a bi-ordering (bi-translation invariant ordering) on the free group with two generators.  As well, he mentions, due to Rhemtulla, that a left-orderable group is abelian iff every left-ordering is a bi-ordering, which I think really highlights the relationship between ordering and abelianity.

A: What you want is to define a positive subset of the group that satisfies trichotomy (every group element is either positive, negative, or the identity), that is closed under the group law, and that is invariant under conjugation.
I think that the Heisenberg group is an example.  This is the group of matrices M = [[1,a,c],[0,1,b],[0,0,1]].  Say, integer matrices.  Then we can say that M is positive if a > 0, or if a = 0 and b > 0, or if a = b = 0 and c > 0.  I think that this works?

A: Thurston's construction of a left-order on braid groups uses hyperbolic geometry, but it doesn't have to. For the sake of argument, let S be a closed, oriented surface of non-positive Euler characteristic. The universal cover of S is homeomorphic to the plane. An essential embedded loop in S lifts to a properly embedded line in the plane. The mapping class group of S permutes the set of isotopy classes of essential embedded loops in S, and a certain extension of this group acts on the universal cover, permuting the set of embedded lines covering properly embedded curves on the surface. Any collection of proper embedded rays in the plane whose pairwise intersections are compact inherits a natural circular order from the topology of the plane; it is this circular order that gives rise to circular orders on (certain extensions of) mapping class groups, and left orders on braid groups.

A: Thompson's group $F$ is totally ordered.  See here for a description of all possible bi-orderings.  Indeed, all diagram groups are totally orderable (see here).  The pure braided Thompson group $BF$ also bi-orderable (see here).

A: This concept is usually called biorderability (there is also left- and right-orderability).  There are many examples, such as free groups and surface groups.  Most spectacularly, the pure braid groups are biorderable, while the full braid groups are left orderable but not biorderable.  The left ordering on the braid groups is usually attributed to Dehornoy, though it was discovered even earlier by Thurston (but not published).
Dale Rolfsen has several nice surveys of material related to this on his webpage here.  In particular, there is the complete text of a nice book called "Why are braids orderable?" that he wrote with Patrick Dehornoy, Ivan Dynnikov, and Bert Wiest.  I believe that a new and much expanded edition of this book was just published.
EDIT 1 : I just found the website for the much-expanded version of Rolfsen et al's book here.
EDIT 2 : Thurston's construction of a left-ordering on the braid groups (which, of course, uses hyperbolic geometry) is very beautiful.  It is explained very nicely in the first few pages of the paper "Orderings of mapping class groups after Thurston" by Short and Wiest, which is available on the arXiv here.  The intro sections of this paper also contain a brief but enlightening account of the general theory of group orderings.
Also, I have not read it, but there is a book entitled "Orderable Groups" by Rehmtulla and Mura.  However, it is from 1977 and will thus omit a lot of recent work.

A: The following should be a comment, but it's too long, and it does contain an answer in passing.  I heard the following story from Andrew Glass.  Saharon Shelah arrived in Vancouver, at a time when several ordered-group theorists were there, including Charles Holland and Alan Mekler.  The following conversation took place (SS = Saharon Shelah; OGT = ordered-group theorists):
SS: Do you have any interesting problems?
OGT: Yes, is there a linear order that is the underlying order of an ordered group but not of any ordered abelian group.
SS (after a moment's thought): Are there any non-abelian ordered groups?
OGT: Yes, free groups can be ordered.
SS: Oh; how do you do that?
OGT show him how to linearly order free groups.
SS (without further time for thought): Oh.  Then here's the answer to your question. ...
Shelah's answer at that point used the a set-theoretic principle known to be consistent but independent of ZFC (diamond, if I remember correctly), but that assumption was later eliminated in joint work.  See "Lawless Order" by Holland, Mekler, and Shelah [Order 5 (1985) pp. 383-397].

A: Not really an example (see the edit below), but somehow related to Greg Kuperberg's one: Let $\mathbb A = (A, +, \cdot, \preceq)$ be a strictly totally orderable semiring (*) and for a fixed integer $n \ge 1$ let $\mathcal M_n(A)$ denote the set of all $n$-by-$n$ matrices with entries in $A$, endowed with the usual operations of addition, say $+$, and row-by-column multiplication, say $\cdot$, induced by $\mathbb A$. Then, $(\mathcal M_n(A), +, \cdot)$ is itself a semiring. So now, let ${\rm U}_n(\mathbb A^+)$ (respectively, ${\rm L}_n(\mathbb A^+)$) be the subsemigroup of $(\mathcal M_n(A), \cdot)$ consisting of all and the only upper (respectively, lower) triangular matrices whose entries on and above (respectively, below) the main diagonal are positive in $\mathbb A$. Then, both $({\rm U}_n(\mathbb A^+), \cdot)$ and $({\rm L}_n(\mathbb A^+), \cdot)$ are strictly totally orderable semigroups.
Edit. Sorry, I've just realized that the question was focused on groups, and not on semigroups/monoids! But then let me profit from my lack of attention to turn the above into a question: Do $({\rm U}_n(\mathbb A^+), \cdot)$ and $({\rm L}_n(\mathbb A^+), \cdot)$ embed into strictly totally ordered groups in the case when $(A, +, \cdot)$ is unital and commutative?
(*) Here, a semiring is just a (possibly non-unital or non-commutative) ring whose additive monoid is not necessarily a group. A strictly totally ordered semiring is then a $4$-uple $(A, +, \cdot, \preceq)$ such that $(A, +, \cdot)$ is a semiring and $\preceq$ is a total order on $A$ such that

*

* $(A, +, \preceq)$ is a strictly totally ordered magma (in fact, a monoid), namely $x + z \prec y + z$ and $z + x \prec z + y$ for all $x,y,z \in A$ with $x \prec y$.

* $x \cdot z \prec y \cdot z$ and $z \cdot x \prec z \cdot y$ for all $x,y,z \in A$ with $x \prec y$ and $0 \prec z$, where $0$ stands for the identity of the monoid $(A,+)$.

A: As the OP was aking for examples, here is a very simple and elementary way to define a total ( bi-invariant ) ordering on the free group using the Magnus transformation which, an alphabet
$X=\{x_1,\cdots ,x_n\}$ being given, sends a reduced ( and, in fact, any ) word
$g=x_{i_1}^{\epsilon_1}x_{i_2}^{\epsilon_2}\cdots x_{i_k}^{\epsilon_k}
\in \Gamma(X)$ ( with $\epsilon_i\in \{-1,1\}$ ) to the series
$$
S=S(x_{i_1}^{\epsilon_1}x_{i_2}^{\epsilon_2}\cdots x_{i_k}^{\epsilon_k})=(1+x_{i_1})^{\epsilon_1}(1+x_{i_2})^{\epsilon_2}\cdots (1+x_{i_k})^{\epsilon_k}\in \mathbb{Z}<<X>>
$$
( it can be shown to be injective ). Then ( if $x_{i_1}^{\epsilon_1}x_{i_2}^{\epsilon_2}\cdots x_{i_k}^{\epsilon_k}\not=1$ ), develop it as
$$
(1+x_{i_1})^{\epsilon_1}(1+x_{i_2})^{\epsilon_2}\cdots (1+x_{i_k})^{\epsilon_k}=1+\cdots + \mathbf{\lambda_w\,w} +\cdots
$$
where $w\in X^{*}$ is the smallest word ( for some lexicographic ordering given by a total ordering e.g. by $x_1<\cdots <x_n$ on $X$ ) among words of smallest length in the support of $S$.
Then, if $\lambda_w\in \mathbb{N}_{\geq 1}$, say that $g$ is positive. In this way, one defines a "strictly positive cone" $P\subset \Gamma(X)$ and checks that it satisfies the three conditions ( for all $g\in \Gamma(X)$ )
$$
P.P\subset P\ ;\ gPg^{-1}\subset P \ ;\ P\cap P^{-1}=\emptyset\ ;\ P\cup P^{-1}=\Gamma(X)
\setminus \{1\}
$$
hence defining a strict total ordering on $\Gamma(X)$. This construction works mutatis mutandis when $X$ is an infinite alphabet.


text:
Q: 3D stereo, bad 3D coordinates I'm using stereo vision to obtain 3D reconstruction. I'm using opencv library.
I've implemented my code this way:
1) Stereo Calibration
2) undistort and Rectification of image pair
3) disparity map - using SGBM
4) 3D coordinates calculating depht map - unsing reprojectImageTo3D();
Results:
-Good disparity map, and good 3D reconstruction
-Bad 3D coordinates values, the distances don't corresponde to the reality.
The 3D distances, the distante between camera and object, have 10 mm error and increse with distance. I,ve used various baselines and i get always error.
When i compare the extrinsic parameter, vector T, output of "stereoRectify" the baseline match.
So i dont know where the problem is.
Can someone help me please, thanks in advance
CAlibration:
http://textuploader.com/ocxl
http://textuploader.com/ocxm

A: Ten mm error can be reasonable for stereo vision solutions, all depending of course on the sensor sensitivity, resolution, baseline and the distance to the object.
The increasing error with respect to the object's distance is also typical to the problem - the stereo correspondence essentially performs triangulation between the two video sensors to the object, and the larger the distance is the derivative of the angle between the video sensors to the object translates to larger distance on the depth axis, which means larger error. Good example is when the angle between the video sensors to the object is almost right, which means that any small positive error in estimating it will throw the estimated depth to infinity.
The architecture you selected looks good. You can try increasing the sensors resolution, or maybe dig in to the calibration process which has a lot of room for tuning in the openCV library - making sure only images taken with the chessboard being static are selected, choose higher variety of the different poses of the chessboard, adding images until the registration between the two images drops below the maximal error you can allow, etc.


text:
Q: Footer won't stay inside width of browser window This is driving me nuts, but probably very simple to sort out. I can't seem to get my footer to only be 100% width of the browser screen. At the moment there is a scroll bar at the bottom so that you can scroll to see the right end of the footer.
Do I have to wrap footer in another DIV with 100% width and then give footer 100% width?
Any pointers on how to get footer to only be 100% width of the screen, and still be stuck to the bottom of the screen, would be really helpful, without giving it a fixed px width,
http://openstrings.co.uk/contact

Thanks

A: The problem is with id 'footer' in styles.css file, line 93.
Namely, it says: width: 100% - and that's a problem.
I've managed to fix it by adding style="width:99% at line 111:
<div id="footer" class="clearfix" style="width:99%;">"

However, it's better if you can fix it in css file. In Fact, this is kind of "quick-and-dirty" solution, the proper way is box-sizing.


text:
Q: How do I create a document using the gdata gem / api? I am able to create.. something... but I can't see it in the webview of my account
require "gdata"
require "awesome_print"
require "nokogiri"

@client = GData::Client::DocList.new
@client.clientlogin('me', "mypass")

def post_doc
  # Return documents the authenticated user owns
  feed = @client.get('https://docs.google.com/feeds/documents/private/full/-/mine').to_xml
  entry = feed.elements['entry']  # first <atom:entry>

  acl_entry = <<-EOF
  <entry xmlns="http://www.w3.org/2005/Atom" xmlns:gAcl='http://schemas.google.com/acl/2007'>
    <category scheme='http://schemas.google.com/g/2005#kind'
      term='http://schemas.google.com/acl/2007#accessRule'/>
    <title>Testing Ruby GData gem</title>
    <gAcl:role value='writer'/>
    <gAcl:scope type='user' value='idk@example.com'/>
  </entry>
  EOF

  # Regex the document id out from the full <atom:id>.
  # http://docs.google.com/feeds/documents/private/full/document%3Adfrk14g25fdsdwf -> document%3Adfrk14g25fdsdwf
  ap entry.elements['id']
  doc_id = entry.elements['id'].text[/full\/(.*%3[aA].*)$/, 1]
  response = @client.post("https://docs.google.com/feeds/acl/private/full/#{doc_id}", acl_entry)

end

it seems that I can only upload documenst if I change the value of the gAcl:scope type='user' field.
On my google account, Docs are gone and replaced by google drive, would that be a problem?
also, is there a list of the fields in an entry somewhere, so I can specify the body of the document I'm trying to create?


text:
Q: Testing an HttpInterceptor My unit test for my HttpInterceptor is unfortunately not working and I have no idea how to solve this right now
Example => error.interceptor.ts
@Injectable()
export class ErrorInterceptor implements HttpInterceptor {

    public intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
        return next.handle(request).pipe(
            catchError((response) => this.handleError(response)),
        );
    }

    private handleError(response: HttpErrorResponse): Observable<HttpEvent<any>> {
        if (response.status === 500 || response.status === 501) {
            console.log('Error');
        }
        return throwError(() => response);
    }
}

Unit-Test => error.interceptor.spec.ts
let errorInterceptor: ErrorInterceptor;

beforeEach(() => {
    errorInterceptor = new ErrorInterceptor(
    );
});

it.each([500, 501])('should  ...', (statusCode) => {
    const response = new HttpErrorResponse({ status: (statusCode) });
    const request = new HttpRequest('GET', '/fakeUrl');
    const mockHandler = { handle: jest.fn(() => throwError(() => response )) };
    const result = errorInterceptor.intercept(request, mockHandler);

    result.subscribe({
        next: () => fail('error'),
        error: (err) => expect(err).toBeTruthy(),
    });
});

This test works. But if I change toBeTruthy to toBeFalsy the test works also :-(
Either the error is in result.subscribe or my beforeEach() is not correct.


text:
Q: I can't upload file to one drive using c# I get an error 400 Bad Request when I try to upload a file to my OneDrive using the Microsoft Graph API

*

*GetAccessToken method get the access token

*upload method take the file path and upload it to my OneDrive account
public class OneDrive
{

 public void Upload(string filePath)
 {

     var token = GetAccessToken();
     var url = "https://graph.microsoft.com/v1.0/drive/root:/test/test.pdf:/content";
     PostRequest(url, token, filePath).Wait();
 }
 public string GetAccessToken()
 {
     var app = ConfidentialClientApplicationBuilder.Create("client id ")
           .WithClientSecret("client secret")
             .WithAuthority("https://login.microsoftonline.com/{tenant id}/v2.0")
           .Build();
     string[] scopes = new string[] { "https://graph.microsoft.com/.default" };
     try
     {
         var result = app.AcquireTokenForClient(scopes).ExecuteAsync().Result;
         Console.WriteLine(result.TenantId);
         return result.AccessToken;
     }
     catch (MsalServiceException ex) when (ex.Message.Contains("AADSTS70011"))
     {
         Console.WriteLine(ex.Message);
         return null;
     }
 }
 public async Task PostRequest(string webApiUrl, string accessToken, string filePath)
 {

     HttpContent content = new StreamContent(new MemoryStream(File.ReadAllBytes(filePath)));
     HttpClient httpClient = new HttpClient();
     if (!string.IsNullOrEmpty(accessToken))
     {
         var defaultRequestHeaders = httpClient.DefaultRequestHeaders;
         httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/octet-stream"));

         defaultRequestHeaders.Authorization = new AuthenticationHeaderValue("bearer", accessToken);

         HttpResponseMessage response = await httpClient.PutAsync(webApiUrl, content);
         if (response.IsSuccessStatusCode)
             Console.WriteLine("File Successfuly Uploaded");
         else
             Console.WriteLine("Error Occur");
     }
 }
}

A: After removing this line :
httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/octet-stream"));
Your code works perfectly for me:

There is no need to set accpet header in request.


text:
Q: Creating Arrays of Objects With Methods I couldn't really come up with the words as to how to describe my question in the title.
What I'm trying to accomplish is something like this: (Pseudo code)
SuperClass[] superArray = new SuperClass[];
// work on superArray
// ...
SubClass[] subArray = superArray.asAnArrayOfSubClass();

`
Is something like this possible?

A: You cannot add members : methods or fields to an array. So no, it is not possible :
 SubClass[] subArray = superArray.asAnArrayOfSubClass();

To define a behavior for an array, instead create a method where you pass the array :
SubClass[] doThat(SuperClass[] superArray){
    ....
}

Even if conceptually, a type should not know its subtypes, if it is your requirement it is valid to convert manually an array of a specific type to an array of a subclass of this specific type.
For example, you can have employees stored in an array that at time are promoted as managers. This method could do this conversion :
Manager[] promote(Employee[] employees){
   Manager[] managers = new Manager[employees.length];
   for (int i=0; i<employees.length; i++){
         Employee e = employee[i];
         managers[i] = new Manager(....);
   }
   return managers;
}

A: No. Not possible. Because not every Parent is a Child. The reverse is possible as Every child is a Parent.
See the below example.
Object[] supers = new Object[5];
Integer[] childs = supers // Errrr.. No I have Strings, Doubles too

But the reverse is possible
Integer[] childs = new Integer[5];
Object[] supers = childs // Ok, I can hold any object.

A: There are restrictions that your subclass should match super class wrt properties and methods and you are only overriding those.
Below is an example of how you could do this using streams API.
 Number[] array = new Number[]{12, 20, 30, 40};

    List<Integer> list  = Arrays.stream(array)
            .map(e -> (Integer) e)
            .collect(Collectors.toList());

    System.out.println(list.toArray());

A: Casting to subclasses is a code smell, and probably you should reconsider your design. Also try to use a java collection api (Iterable, Collection, List), with generics, and not primitive arrays, which you can subclass adding your own methods like the example below:
public interface IteratorWithIndex<T> extends Iterator<T> {
    int index();
}


text:
Q: Avoid triggering Firebase functions by real-time database on special cases Sometimes we use the firebase functions triggered by real-time database (onCreate/onDelete/onUpdate ...) to do some logic (like counting, etc).
My question, would it be possible to avoid this trigger in some cases. Mainly, when I would like to allow a user to import a huge JSON to firebase?
Example:
a function E triggered on the creation of a new child in /examples. Normally, users add examples one by one to /examples and function E runs to do some logic. However, I would like to allow a user (from the front-end) to import 2000 children to /examples and the logic which is done by function E is possible at import time without the need for E. Then, I do not need E to be triggered for such a case where a high number of functions could be executed. (Note: I am aware of the 1000 limit)
Update:
based on the accepted answer, submitted my answer down.

A: As far as I know, there is no way to disable a Cloud Function programmatically without just deleting it. However this introduces an edge case where data is added to the database while the import is taking place.
A compromise would be to signal that the data you are uploading should be post-processed. Let's say you were uploading to /examples/{pushId}, instead of attaching the database trigger to /examples/{pushId}, attach it to /examples/{pushId}/needsProcessing (or something similar). Unfortunately this has the trade-off of not being able to make use of change objects for onUpdate() and onWrite().
const result = await firebase.database.ref('/examples').push({
  title: "Example 1A",
  desc: "This is an example",
  attachments: { /* ... */ },
  class: "-MTjzAKMcJzhhtxwUbFw",
  author: "johndoe1970",
  needsProcessing: true
});

async function handleExampleProcessing(snapshot, context) {
  // do post processing if needsProcessing is truthy
  if (!snapshot.exists() || !snapshot.val()) {
    console.log('No processing needed, exiting.');
    return;
  }

  const exampleRef = admin.database().ref(change.ref.parent); // /examples/{pushId}, as admin
  const data = await exampleRef.once('value');

  // do something with data, like mutate it

  // commit changes
  return exampleRef.update({
    ...data,
    needsProcessing: null /* delete needsProcessing value */
  });
}

const functionsExampleProcessingRef = functions.database.ref("examples/{pushId}/needsProcessing");

export const handleExampleNeedingProcessingOnCreate = functionsExampleProcessingRef.onCreate(handleExampleProcessing);

// this is only needed if you ever intend on writing `needsProcessing = /* some falsy value */`, I recommend just creating and deleting it, then you can use just the above trigger.
export const handleExampleNeedingProcessingOnUpdate = functionsExampleProcessingRef.onUpdate((change, context) => handleExampleProcessing(change.after, context));

A: An alternative to Sam's approach is to use feature flags to determine if a Cloud Function performs its main function. I often have this in my code:
exports.onUpload = functions.database
  .ref("/uploads/{uploadId}")
  .onWrite((event) => {
  return ifEnabled("transcribe").then(() => {
    console.log("transcription is enabled: calling Cloud Speech");
    ...
  })
});

The ifEnabled is a simple helper function that checks (also in Realtime Database) if the feature is enabled:
function ifEnabled(feature) {
  console.log("Checking if feature '"+feature+"' is enabled");
  return new Promise((resolve, reject) => {
    admin.database().ref("/config/features")
      .child(feature)
      .once('value')
      .then(snapshot => {
        if (snapshot.val()) {
          resolve(snapshot.val());
        }
        else {
          reject("No value or 'falsy' value found");
        }
      });
  });
}

Most of my usage of this is during talks at conferences, to enable the Cloud Functions at the right time (as a deploy takes a bit longer than we'd like for a demo). But the same approach should work to temporarily disable features during for example data import.

A: Okay, another solution would be
A: Add a new table in firebase like /triggers-queue where all CRUD that should fire a background function are added. In this table, we add a key for each table that should have triggers - in our example /examples table. Any key that represents a table should also have /created, /updated, and /deleted keys as follows.
/examples
.../example-id-1

/triggers-queue
.../examples
....../created
........./example-id
....../updated
........./example-id
............old-value
....../deleted
........./example-id
............old-value

Note that the old-value should be added from app (front-end, etc).
We set triggers always onCreate on
/triggers-queue/examples/created/{exampleID} (simulate onCreate)
/triggers-queue/examples/updated/{exampleID} (simulate onUpdate)
/triggers-queue/examples/deleted/{exampleID} (simulate onDelete)
The fired function can know all the necessary info to handle the logic as follows:

*

*Operation type: from the path (either: created, updated, or deleted)

*key of the object: from the path

*current data: by reading the corresponding table (i.e., /examples/id)

*old data: from the triggers table

Good Points:

*

*You can import a huge data to /examples table without firing any function as we do not add to the /triggers-queue

*you can fanout functions to pass the limit 1000/sec. That is by setting  triggers on (as an example to fanout on-create)
/triggers-queue/examples/created0/{exampleID} and
/triggers-queue/examples/created1/{exampleID}
bad-points:

*

*more difficult to implement

*need to write more data to firebase (like old-data) from the app.

B- Another way (although not an answer for this) is to move the login in the background function to an HTTP function and call it on every crud ops.


text:
Q: Ruby - UDP - How to spoof IP and Port Number I've been messing about with some sample client and server code for sending and receiving UDP packets, here's what I'm doing for the send
require 'socket'
s = UDPSocket.new
s.send("hello", 0, 'localhost', 1234)

Is it possible to somehow use a fake IP address and port number when sending? haven't come across anything online with any examples of how to do so.

A: You need to bind the socket before calling send:
require 'socket'

s = UDPSocket.new
s.bind('128.100.8.6', 1253)

s.send(...)

Keep in mind that your upstream is in no way responsible for delivering "spoofed" packets and that many providers will dump these if they're not originating in their network.


text:
Q: java HashMap not updating integer value for a specific key package cdlKata;

import java.util.HashMap;
import java.util.Map;

class Item2 {
  private String s;
  public Item2(String s) { this.s = s; }
  public String getS() { return s; }
}

class Basket2 {
  private Map<Item2, Integer> items;

  public Basket2() { items = new HashMap<>(); }

  public Map<Item2, Integer> getItems() { return items; }

  public void addItemToBasket(Item2 item) {
    items.put(item, items.getOrDefault(item,0) + 1);
  }

  public void printBasket() {
    items.entrySet().forEach(e->{ System.out.println(e.getKey().getS() + " " + e.getValue());});
  }
}

public class Main2 {

  public static void main(String[] args) {
    Basket2 basket;
    basket = new Basket2();
    basket.addItemToBasket(new Item2("A"));
    basket.addItemToBasket(new Item2("A"));
    basket.printBasket();
  }
}

Result is :
A 1
A 1
with basket size = 2. What I want is :
A 2
with basket size 1.
if I turn Item2 into a String I got no issue. Don't understans why it is not working.

A: You created two different instances as below
basket.addItemToBasket(new Item2("A"));
basket.addItemToBasket(new Item2("A"));

You are expecting it to be equal. It will not be the case.
You have to override hashcode and equals

A: According to the logic of work of HashMap, you must override your keys' hashcode() and equals() methods.
P.S. Also I would suggest you to use in this case merge method of map instead of put.
map.merge(key, 1, Integer::sum)

A: Since you are using Map of object,Integer the output :
A 1
A 1
is correct, but you are expecting output: A 2
for which you need to create Map of String,Integer ie. map of item2.getS() and Integer.
The reason it is not working is because you Mapped object and Integer, and you are adding item to basket by creating new objects each time.
So, the solution will be like this.
    package cdlKata;

    import java.util.HashMap;
    import java.util.Map;

    class Item2 {
        private String s;
        public Item2(String s) { this.s = s; }
        public String getS() { return s; }
    }

    class Basket2 {
        private Map<String, Integer> items;

        public Basket2() { items = new HashMap<>(); }

        public Map<String, Integer> getItems() { return items; }

        public void addItemToBasket(Item2 item) {
            items.put(item.getS(), items.getOrDefault(item.getS(),0) + 1);
        }

        public void printBasket() {
            items.entrySet().forEach(e->{ System.out.println(e.getKey() + " " + e.getValue());});
        }
    }

    public class Stack {

        public static void main(String[] args) {
            Basket2 basket;
            basket = new Basket2();
            basket.addItemToBasket(new Item2("A"));
            basket.addItemToBasket(new Item2("A"));
            basket.printBasket();
        }
    }

A: Well...
You are missing equals/hashCode in your class.
See this answer for more info: Why do I need to override the equals and hashCode methods in Java?
For exactly your class just define these methods:
class Item2 {
    private String s;
    public Item2(String s) { this.s = s; }
    public String getS() { return s; }

    @Override public boolean equals(Object o)
    {
        if (this == o)
            return true;
        if (o == null || getClass() != o.getClass())
            return false;

        Item2 item2 = (Item2) o;

        return s != null ? s.equals(item2.s) : item2.s == null;
    }

    @Override public int hashCode()
    {
        return s != null ? s.hashCode() : 0;
    }
}

A: Is is a common mistake of using hash.
You should implement hashCode and equals for Item class.
class Item2 {
  private String s;
  public Item2(String s) { this.s = s; }
  public String getS() { return s; }

  @Override
  public boolean equals(Object o) {
    if (this == o) return true;
    if (!(o instanceof Item2)) return false;
    Item2 item2 = (Item2) o;
    return Objects.equals(getS(), item2.getS());
  }

  @Override
  public int hashCode() {
    return Objects.hash(getS());
  }
}

Without that, HashMap will consider two objects (even the same value) are different, Therefore, it will put as a new Object.


text:
Q: What is the directory "..." when using git? During a "git pull" operation, I get a report about objects in a "..." directory. What is this directory ? I'm surprised because when trying "ls -l ..." in a shell, the response is "No such file or directory". There is obviously a difference to the git syntax. What is this difference ?
Here is an exemple of such an output:
remote: Enumerating objects: 69, done.
remote: Counting objects: 100% (69/69), done.
remote: Compressing objects: 100% (33/33), done.
remote: Total 47 (delta 27), reused 26 (delta 6), pack-reused 0
Unpacking objects: 100% (47/47), done.
From https://github.com/BaseXdb/basex
   dba88acaba..27c32529ab  master     -> origin/master
Updating dba88acaba..27c32529ab
Fast-forward
 .../java/org/basex/io/parse/json/JsonBasicConverter.java     |  4 +---
 basex-core/src/main/java/org/basex/query/func/db/DbNew.java  |  4 ++--
 .../main/java/org/basex/query/func/fn/FnAnalyzeString.java   | 12 ++++++------
 basex-core/src/test/java/org/basex/query/expr/MixedTest.java |  9 +++++++++
 4 files changed, 18 insertions(+), 11 deletions(-)

A: It's a truncated path.
Consider the full path of two of the files:
basex-core/src/main/java/org/basex/io/parse/json/JsonBasicConverter.java
basex-core/src/main/java/org/basex/query/func/db/DbNew.java

One path is simply too long to display, so it is truncated. However, cutting of the end is not a sensible choice for paths, because the most valuable information is towards the end. Hence, the start is cut off.


text: Q: Can I set a class or id for the Bearer token field in Swagger UI? I was using the Swagger UI integrated with NestJS.I was wondering if there a way to add a class or id to the Bearer token field or to set the token programmatically?


text:
Q: Best way to manage datas in an angularJS CRUD app First, i want to say that English is not my native language, so sorry by advance if i'm not 100% clear.
So let say i want to create a basic CRUD app for cars.
There would be the route "/cars" with the list of all cars.
To get those cars data, i would have to make a call to the API, which will send me all the data about all cars at once, and then display all the cars name. I think i'm right for now ?
The "problem" i have is when the user click on a specific car.
It should redirect the user to the route "cars/CAR_ID" and display this specific car's data. But how to get those data ? I mean, yes i could just make an API call "/api/car/CAR_ID", but why would i do that if i already have everything i need in the first api call with all the cars ?
I've been looking every thread, everywhere and they always make another api call, but it feel like a waste to me, i cant help it.
There got to be a reason why everyone does that and i'm missing it.
I mean, the other way would be to store the first call's data and instead of making the second api call, we could just fetch the data from the first call.
I'm new to web development so it may be better to make a request for every page than store a big set of data the first time and work with it all along the navigation.
If so, can i have some more insight on the subject, it feels like asking to the server something i already know...

A: A different answer to part of your question.

I mean, yes i could just make an API call "/api/car/CAR_ID", but why would i do that if i already have everything i need in the first api call with all the cars ?

What would happen if you didn't make the first api call? I mean, could't I directly type in my browser /api/car/12345?
Let's consider stackoverflow as an example, let's say I bookmark this question, and later on I open this page (lets assume I have no cached data) directly without going through the page with the questions list. In your scenario I would get a blank page because the creator would assume that I visit some other page first, which is unresonable (not always). Making an api call for each particular entity saves as from such a pitfall from the start because it doesn't assume anything about the browsing history of the user.

A: Here are the options I can think of.
1) Use ui-router (my preferred option). Here's an example route:
angular.module('carApp')
  .config(function ($stateProvider) {
    $stateProvider
      .state('cars', {
        url: '/cars',
        templateUrl: 'app/cars/views/index.html',
        controller: 'CarsCtrl',
        resolve: {
          cars : ['Car', function(Car) {
            return Car.list();
          }]
        }
      })
      .state('cars.show', {
        url: '/{carId}',
        views: {
          "@" : {
            templateUrl: 'app/cars/views/show.html',
            controller: 'CarCtrl'
          }
        },
        resolve: { // the cars from the parent route (cars) will be injected into this route
          car: ['$stateParams', 'cars', function($stateParams, cars) {
            // not hitting the web service, find our car using lodash
            return _.find(cars, {_id: $stateParams.carId});
          }]
        }
      })

OR
2) Use caching in your services
angular.module('carApp')
  .service('Car', function Car($http) {
    return {
      list: function() {
        return $http.get('/cars', {cache: true});
      }
    };
  });

The first time you call Car.list() it will call the web service. Subsequent calls to Car.list() will not call the web service. In your controller you can either call Car.list and find the correct car similar to the cars.show route or add another function to your service that can find a car by ID.


text:
Q: Change background popupMenu in Android I tried to change background of popupmenu, but my implementation does not work.
This is my code:
<style name="MyHoloLight" parent="android:Theme.Holo.Light">
    <item name="android:popupMenuStyle">@style/popupMenuStyle</item>
</style>
<style name="popupMenuStyle" parent="@android:style/Widget.PopupMenu">
    <item name="android:popupBackground">@color/bgPopumMenu</item>
</style>

Apply in AndroidManifest.xml
<application
        android:hardwareAccelerated="true"
        android:label="@string/app_name"
        android:icon="@drawable/ic_launcher"
        android:theme="@style/MyHoloLight">

A: If bgPopumMenu is your image then use this.
<style name="popupMenuStyle" parent="@android:style/Widget.PopupMenu">
<item name="android:popupBackground">@drawable/bgPopumMenu</item>
</style>

You need to apply your style to your AppTheme. So try this.
<style name="AppTheme" parent="android:Theme.Holo.Light">
<item name="android:popupMenuStyle">@style/popupMenuStyle</item>
</style>
<style name="popupMenuStyle" parent="@android:style/Widget.PopupMenu">
<item name="android:popupBackground">@color/bgPopumMenu</item>
</style>

A: I made some changes of @Raju`s code and the following styles working for me,
Context wrapper = new ContextThemeWrapper(context,R.style.popupMenuStyle);
PopupMenu popup = new PopupMenu(wrapper, YourView);

and this is my style,
<style name="popupMenuStyle" parent="android:Theme.Holo.Light.DarkActionBar">
    <item name="android:popupMenuStyle">@style/MyApp.PopupMenu</item>
    <item name="android:textColor">@color/White</item>
</style>

<style name="MyApp.PopupMenu" parent="android:Widget.Holo.Light.ListPopupWindow">
<item name="android:popupBackground">@color/color_semi_transparent</item>
</style>

A: the following styles working perfectly for me.
<style name="popupMenuStyle" parent="Theme.AppCompat.Light.DarkActionBar">
    <item name="android:textColor">@color/color_white</item>
    <item name="android:itemBackground">@color/color_red</item>
</style>

here, parent should be the AppTheme parent
and in your code use these lines.
Context wrapper = new ContextThemeWrapper(context, R.style.popupMenuStyle);
PopupMenu popup = new PopupMenu(wrapper, v);

i hope it will work.

A: If you are using custom theme :

*

*In Manifest : @style/MyMaterialTheme is my customized theme :
  <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/MyMaterialTheme">

*Use this code : R.style.popupMenuStyle for popup menu in java class :

Context wrapper = new ContextThemeWrapper(getContext(), R.style.popupMenuStyle);
PopupMenu popup = new PopupMenu(wrapper, v);

//Inflating the Popup using xml file
popup.getMenuInflater().inflate(R.menu.popup_menu, popup.getMenu());

MenuPopupHelper menuHelper = new MenuPopupHelper(wrapper, (MenuBuilder) popup.getMenu(), v);
menuHelper.setForceShowIcon(true);
menuHelper.setGravity(Gravity.RIGHT);

*this is custom style of popup- menu for your own background drawable

<style name="popupMenuStyle" parent="@android:style/Widget.PopupMenu">
    <item name="android:popupBackground">@drawable/dropdown_bg</item>
</style>

*then change in your own theme "popupMenuStyle"
<style name="MyMaterialTheme" parent="MyMaterialTheme.Base">

    </style>

    <style name="MyMaterialTheme.Base" parent="Theme.AppCompat.Light.DarkActionBar">
        <item name="windowNoTitle">true</item>
        <item name="windowActionBar">false</item>
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorPrimary</item>

        <item name="popupMenuStyle">@style/popupMenuStyle</item>
        <item name="android:popupMenuStyle">@style/popupMenuStyle</item>
    </style>

A: I SOLVED it,
PopupMenu popup = new PopupMenu(context, view);
In above code I used context of type Activity not of Context type.
Chill !

A: what about this :
@Override
public boolean onCreateOptionsMenu(Menu menu)
{
    MenuInflater inflater=getMenuInflater();
    inflater.inflate(R.menu.menu,menu);
    setMenuBackground();
    return true;
}

and write this in the setMenuBackground() method
protected void setMenuBackground(){
        getLayoutInflater().setFactory( new Factory() {
            public View onCreateView(String name, Context context, AttributeSet attrs) {
                if ( name.equalsIgnoreCase( "com.android.internal.view.menu.IconMenuItemView" ) ) {
                    try { // Ask our inflater to create the view
                        LayoutInflater f = getLayoutInflater();
                        final View view = f.createView( name, null, attrs );
                        /* The background gets refreshed each time a new item is added the options menu.
                        * So each time Android applies the default background we need to set our own
                        * background. This is done using a thread giving the background change as runnable
                        * object */
                        new Handler().post( new Runnable() {
                            public void run () {
                                // sets the background here
                                view.setBackgroundResource( R.drawable.bgPopumMenu);
                                // sets the text color
                                ((TextView) view).setTextColor(Color.BLACK);
                                // sets the text size
                                ((TextView) view).setTextSize(18);
                }
                        } );
                    return view;
                }
            catch ( InflateException e ) {}
            catch ( ClassNotFoundException e ) {}
        }
        return null;
    }});
}

A: You cannot give android:popupBackground as just a color. You should use or create a drawable.
You can use this link http://jgilfelt.github.io/android-actionbarstylegenerator/ to generate your desired color. And set it to that drawable.

A: Try to define android:actionBarWidgetTheme in your theme:
<style name="MyHoloLight" parent="android:Theme.Holo.Light">
    <item name="android:popupMenuStyle">@style/popupMenuStyle</item>
    <item name="android:actionBarWidgetTheme">@style/Theme.Example.Widget</item>
</style>
<style name="popupMenuStyle" parent="@android:style/Widget.PopupMenu">
    <item name="android:popupBackground">@color/bgPopumMenu</item>
</style>
<style name="Theme.Example.Widget" parent="@style/Theme.AppCompat">
    <item name="popupMenuStyle">@style/popupMenuStyle</item>
    <item name="dropDownListViewStyle">@style/DropDownListView.Example</item>
</style>
<style name="DropDownListView.Example" parent="@style/Widget.AppCompat.ListView.DropDown">
    <item name="android:listSelector">@color/bgPopumMenu_whenSelected</item>
</style>

A: If bgPopumMenu is your drawable then use this
    <item name="android:panelBackground">@drawable/bgPopumMenu</item>

You just put that directly into your AppTheme like so
<style name="AppTheme" parent="android:Theme.Holo.Light">
    <item name="android:panelBackground">@drawable/bgPopumMenu</item>
</style>

A: You can easily create a style for popup menu and apply that style to a theme and you  can assign the theme to the Activity/Parent Activity*** in the android manifest like this
<style name="MyThemePopup" parent="@style/AppTheme.NoActionBar">
    <item name="android:popupMenuStyle">@style/PopupMenu</item>
</style>

Create @style/PopupMenu like this
<style name="PopupMenu" parent="@android:style/Widget.PopupMenu">
    <item name="android:popupBackground">#000000</item>
</style>

Assign the MyThemePopup theme to your Activity/Parent Activity*** in AndroidManifest as
<activity
            android:name=".Activity"
            android:label="@string/title_activity"
            android:screenOrientation="portrait"
            android:theme="@style/MyThemePopup"/>

***When you using the fragment apply the theme for the parent activity defined in AndroidManifest

A: just add below line into Style.xml and its working :
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
    <!-- To change action bar menuItem BG -->
            <item name="android:itemBackground">@color/white</item>
 </style>


text:
Q: how to set conditions for total or cell in cross tab in fastreport for visible or width=0 I have a cross tab in Fast Report 5.
I want to set a condition for column header or cells that cells visible is off.
How to set conditions which are 'visible is off' for cells?

A: You may set column width to 0 in the cross-tab OnCalcWidth event
procedure Cross1OnCalcWidth(ColumnIndex: Integer; ColumnValues: Variant; var Width: Extended);
begin
  if ColumnValues[0] = '2000' then Width := 0;
end;


text:
Q: Python socket with PACKET_MMAP Is there a PACKET_MMAP or similar flag for python sockets? I know in C one can use a zero-copy/circular buffer with the previous mention flag to avoid having to copy buffers from kernel space to user space but I cannot find anything similar in the python documentation.
Thanks for any input on docs or code to look into.

A: So it looks like buffer or memoryview will do the trick. Although, there is some discrepancies in the sites I found regarding whether python 2.7 supported this or not, I will have to test it out to make sure


text:
Q: Vim highlight a set of words in different colors each in all files I need vim/Gvim to highlight a set of keywords each with mentioned color in all files (it may be a text file, c source file, or anything else).
For example TODO, FIXME are highlighted in C files. Like that, I want to highlight TODO and FIXME in all files each with different colors specified somewhere. This should happen as I open a vim file and do not require me to give a command for this to happen.
How can I achieve this?
Thanks in advance for the help.

A: Note this is not my answer. Points go to user Ralf, answer copied over from this stackexchange, adding it here for convenience. This is the best solution I could test (if what you want is add custom highlighted words for ALL syntaxes)
function! UpdateTodoKeywords(...)
    let newKeywords = join(a:000, " ")
    let synTodo = map(filter(split(execute("syntax list"), '\n') , { i,v -> match(v, '^\w*Todo\>') == 0}), {i,v -> substitute(v, ' .*$', '', '')})
    for synGrp in synTodo
        execute "syntax keyword " . synGrp . " contained " . newKeywords
    endfor
endfunction

augroup now
    autocmd!
    autocmd Syntax * call UpdateTodoKeywords("NOTE", "NOTES")
augroup END