text:
Q: Proving a convex function I'm given a function  $f:A \to \mathbb{R}$ which is twice continuously differentiable on $A \subseteq \mathbb{R}^n$. $A$ is a convex set. Show that $f$ is convex.
Any ideas on how to prove this?

A: People have commented, but this deserves an answer.
Problem statement:  "I'm given a function $f:A\rightarrow\mathbb{R}$ which is twice continuously differentiable on $A\subseteq\mathbb{R}^{n}$. $A$ is a convex set. Show that $f$ is convex."
The statement is false as written. Consider the function $f(x) = -x * x$ , defined on the convex set $\mathbb{R}$. $f(x)$ is twice continuously differentiable on $A$, and indeed, continuously differentiable of all orders.  Yet, $f(x)$ is not convex.
The statement is false, as should be immediately and overwhelmingly apparent to anyone with any capability at all in mathematics.  Nevertheless, to be charitable, one can suppose the possibility of a "typo" in which some other condition was accidentally omitted from the problem statement.  The hypothesis would need to be strengthened in some way in order for the statement to become true, for instance, by adding the hypothesis that the Hessian of $f$ is positive semi-definite at every point in the domain $A$.
Edit: Proof of the statement, with the hypothesis added that the Hessian of $f$ is positive semi-definite at every point in the domain $A$, can be found in numerous textbooks.


text:
Q: Win Forms combo box combination issue I have a windows application where in one of the forms, I have two combo boxes.
Both the combo boxes are filled with the same data. (e.g. A, B, and C as data items). The data comes from the database and is the bound to these combo boxes.
What I want is that if I select A in combo box 1, 'A' can not be selected in combo box 2 and vice versa. That is, same item can not be selected in both combo boxes unless there is only one item in the combo boxes.
Can anyone please guide me on how to achieve this ?
A pseudo code or a direction would be greatly appreciated.
Thanks.

A: Maybe what you really want is to load the items into a list and keep that in memory instead of binding directly to the controls.  Then you can use that list to dynamically (re)populate the ComboBox controls as selection events fire.  Just wire up a SelectionChangeCommitted event to each one, and as they fire, (re)load the other ComboBox controls with the items that they should contain, either in complete or filtered by the item just selected.

redpajama_set_name: RedPajamaStackExchange


text: Q: Django: View-related functionality, specific for the Model, where to put? I.e. I have the Model (actually abstract one, used in many other classes) with two ImageField rendered and preview and it's commonly used operation in views to redirect to rendered or preview depending on request. So I'd like to put some method in my model, which returns desired HttpResponseRedirect, but I feel that it's definitely bad practice to mix Model and View functionality. What is best practice, where to put View-related functionality, specific for the Model?


text:
Q: MLCP Import with custom transform module Could not able to Import documents with custom transform module option.
I am trying to Import through mlcp as a gradle task over SSL. When I try to Run task , it is building successfully but not importing any modules.
Code:
task DeployPatterns(type: com.marklogic.gradle.task.MlcpTask) {
classpath = configurations.mlcp
command = "IMPORT"
ssl = true
port = project.mlRestPort.toInteger()
database = mlAppConfig.contentDatabaseName
input_file_type = "documents"
document_type = "xml"
input_file_path = "data/patterns/"
transform_param = "template temp"
transform_module = "/ext/mlcp/transform.xqy"
transform_namespace = "http://transform-test"
output_collections = "config, patterns"
output_permissions = "rest-reader,read,rest-writer,update"
output_uri_replace = ".*data/,'/'"

}
The Task is running successfully but not performing any import.
MarkLogic - 8.0.6-6
Gradle - 3.9.0
mlcp - 9.0.5

A: When you use mlcp, you supply the name of a user(s) with which to interact with MarkLogic Server. If the user does not have admin privileges, then the user must have at least the privileges as below

*

*import - hadoop-user-write

*export - hadoop-user-read

*copy - hadoop-user-read (input) , hadoop-user-write (output)


text:
Q: Slack bot - registering to a message-event not getting triggered We created a Slack app using Bolt and Javascript.
We wanted to listen to messages coming from the Slack app. We went to the api.slack.com and added message.app_home event

According to the documentation we should add an event to the Bot for message and check if the the event.type is app_home
We did it as follow:

We add a new message in the Slack app:

The listener function just logs the message, but it never gets called:

Is it something with the Bolt or I am not implementing it correctly?

A: We figured it out.
We had to add message.im event to the 'Subscribe to bot events' section.
The message.app_home is deprecated and won't work for new apps created after 2021.


text:
Q: Keras: expected dense_5 to have shape (None, 1) but got array with shape (60000, 10) I'm running the following code on python 3.6:
(train_images, train_labels), (test_images, test_labels) = mnist.load_data()
train_images = train_images.reshape((60000, 28, 28, 1)).astype('float')/255
test_images = test_images.reshape((10000, 28, 28, 1)).astype('float')/255
train_labels = ku.to_categorical(train_labels)
test_labels = ku.to_categorical(test_labels)
filepath = 'my_model_file.hdf5' # define where the model is saved
callbacks_list = [
        keras.callbacks.EarlyStopping(
            monitor = 'val_loss', # Use accuracy to monitor the model
            patience = 1 # Stop after one step with lower accuracy
        ),
        keras.callbacks.ModelCheckpoint(
            filepath = filepath, # file where the checkpoint is saved
            monitor = 'val_loss', # Don't overwrite the saved model unless val_loss is worse
            save_best_only = True # Only save model if it is the best
        )
]
model = models.Sequential()
model.add(layers.Conv2D(32, (3, 3), activation='relu', input_shape=(28, 28, 1)))
model.add(layers.MaxPooling2D((2, 2)))
model.add(layers.Conv2D(64, (3, 3), activation='relu'))
model.add(layers.MaxPooling2D((2, 2)))
model.add(layers.Conv2D(64, (3, 3), activation='relu'))
model.add(layers.Flatten())
model.add(layers.Dense(64, activation='relu', kernel_regularizer=l2(0.001)))
model.add(Dropout(0.5))
model.add(layers.Dense(10, activation='softmax'))
model.summary()
## Compile the model
model.compile(optimizer='adam',loss='sparse_categorical_crossentropy',metrics=['accuracy'])

## Now fit the model
nr.seed(2356)
set_random_seed(2333)
history = model.fit(train_images, train_labels, epochs=40, batch_size = 128, callbacks = callbacks_list, validation_data = (test_images, test_labels))  # Call backs argument here)

and get the following error:
ValueError: Error when checking target: expected dense_5 to have shape (None, 1) but got array with shape (60000, 10)

The previous posts I look talk about datalabel should be convert to categorical data but this is done. Actually most of the code is copy and past from tensor flow tutorial so it's little bit hard to see where things where wrong.

A: Use loss functions categorical_crossentropy

loss='categorical_crossentropy'

beacause your label was encoded at

train_labels = ku.to_categorical(train_labels)

PS.
If your label are endcoded(one-hot encoded) use categorical_crossentropy
ex:

[1,0,0]
  [0,1,0]
  [0,0,1]

But if your targets are integers, use sparse_categorical_crossentropy
ex:

[1,2,3]


text:
Q: Include .npmrc while creating a new angular project I am creating a command line application using node.js. The application wraps the ng new command from angular CLI. While creating a new angular project, dependencies are installed automatically.
The problem here is we are using a private npmjs repository which at times may not have some specified dependencies in it. To avoid this situation, I thought to have a .npmrc file in which I can define to fetch the organization specific node modules from the private repository and rest of the node modules from the npm repository.
Is there any way, using which I can add a .npmrc file during angular project creation with the command ng new?
Thanks in advance

A: You can do this to avoid using global config:

*

*Make a project directory

*Add a .yarnrc file to your project directory with your desired registry like:
registry=https://registry.npmjs.org/

*Then yarn init in the directory

*Then yarn add ng so it adds ng from the repository you listed

*Continue with ng new ${yourprojectname} to use the local ng you just created

*After ng new creates the angular directory, you may want to also copy the .npmrc and .yarnrc inside the project and configure them with your desired registry and run npm install just to be sure.


text:
Q: Android thread class reuse I have multiple levels each with their own activity and surfaceview. I'm have a difficult time figuring out how I could use just one thread extended class for all the levels without explicitly setting each surfaceview to the thread. In the thread I'm going to have to use a set method to get the surfaceview class and call its onDraw method in the loop, but I want to use this thread again with all the other levels. Can someone help me on this matter?

A: I recommend creating a separate class for each level and an interface that all levels implement (maybe each level has an onDraw() method). Then, just advance through the levels by switching out the classes (this could be done within that thread). You can use handlers to communicate between threads the UI layer.


text:
Q: How to write a "from" and "to" function for "Add Void a === a"? From the document: http://chris-taylor.github.io/blog/2013/02/10/the-algebra-of-algebraic-data-types/, it says:

Bool and Add () () are equivalent, because we can define a "from" and "to" function:
to :: Bool -> Add () ()
to False = AddL ()
to True  = AddR ()

from :: Add () () -> Bool
from (AddL _) = False
from (AddR _) = True

That:
from (to a) == a
to (from a) == a

Then he gives another two:
 Add Void a === a
 Add a b === Add b a

How to write "from" and "to" functions for these two?

A: For

Add a b === Add b a

you need to swap the AddL/AddR constructors as follows:
to :: Add a b -> Add b a
to (AddL x) = AddR x
to (AddR x) = AddL x

-- from = to

For

Add Void a === a

you need a polymorphic function void : Void -> a
to :: Add Void a -> a
to (AddL impossible) = void impossible
to (AddR x) = x

from :: a -> Add Void a
from x = AddR x

The variable impossible stands for a "non-existent" value of type Void. There is indeed no such value (apart from bottom/undefinedness). This is why the line
to (AddL impossible) = ...

is actually unreachable code -- it will never be executed.
Function void exploits the fact that it requires an impossible argument to produce a value a out of thin air. Sadly, in Haskell, void can not be defined unless exploiting undefinedness, e.g.
void :: Void -> a
void _ = error "This will never be reached"

A more elegant and correct solution would have been
void :: Void -> a
void x = case x of
           -- no constructors for Void, hence no branches here to do!
           -- since all these (zero) branches have type `a`, the whole
           -- case has type `a` (!!!)

but, alas, Haskell forbids empty case constructs. (In GHC 7.8 empty cases are allowed through the EmptyCase extension, as bheklilr points out).
By comparison, in a dependently typed language such as Coq or agda the code above (with minor changes) would have been fine. Here's it in Coq:
Inductive Void : Set := .   (* No constructors for Void *)

Definition void (A : Set) (x : Void) : A :=
      match x with
      end .

And in Agda
data Void : Set where
   -- no constructors

void : (A : Set) -> Void -> A
void A ()
-- () is an "impossible" pattern in Agda, telling the compiler that this argument
-- has no values in its type, so one can omit the definition entirely.

A: The void library has an absurd function with type Void -> a. It captures the "from false, everything follows" logical principle.
It can be used to remove a Void branch from sum types. Intuitively, if your type is either a or something impossible, then it is pretty much the same as a.
import Data.Void

foo :: Either Void a -> a
foo x = either absurd id x


text:
Q: Meaning of "I'll send you this check *for more*, if you can refund me *the difference*" Below is an excerpt from a podcast script I came across, which talks about how you can fall for scam through emails and messages, and I don't understand the "check" reference they mentioned.

This is something I would say to my mom. "Beware there's this scam out there. Don't fall for it." I actually tested my parents once. Because they were selling something on craigslist, I sent them an email that said, "hey, I wanna buy it, I'll send you this check for more, if you can refund me the difference"... and my parents fell for it!

I'm having difficulty understanding the part in bold, especially "for more", and "the difference." I want to write more specific questions, but I'm not sure how to elaborate it. "for more" (what)? What does "difference" indicate? Maybe it's not about the words but about how checks work in the US that I'm not familiar of, but I'm completely lost interpreting this sentence.

A: A cheque (or check in American English) is a written instruction telling your bank to pay someone the amount of money specified. The idea of the scam here is that the parents were selling an item; let's say that they had listed the item as costing £100. The buyer says I will pay for the item with a £200 cheque (i.e. a cheque that is "for more" money than the item is listed at), but please refund me the difference. So, the buyer gives the parents the £200 cheque, they give the buyer both the item and an extra £100 (the "difference" between the listed price of the item, and the amount on the cheque). However, and this is where the scam part comes in, after the parents have put the cheque into the bank, the cheque will "bounce" (that is, there won't be enough funds in the buyer's bank account to pay the amount on the cheque), so the parents will be left without the money from the cheque, and also down the £100 they gave to the buyer.

A: As @Stuart_F has mentioned in the comments, it is an overpayment scam, where the scammer gives your a generous amount of money, and will later ask you to refund the excess money back to them, but you won't get it back! So the narrator's parents fell for this scam.


text:
Q: bold header text for rails and html i want to make create an account button to be bold as the login button.
The create an account button is made like this:
<%= f.submit "Create an account", class: "btn-submit" %>

With additional CSS:
.btn-submit {
color: #FFFFFF;
font-size: 18px;
text-transform: uppercase;
text-decoration: none;
background: #c91717;
padding: 11px 20px;
border: 0;
margin-top: 6px;
}

And the Log In button is already bold link-to like:
<%= link_to("Register", {:controller => 'users', :action => 'new'}, :class => 'tosignup') %>

The CSS for this:
.tologin {

color: #FFFFFF;
font-size: 18px;
text-transform: uppercase;
text-decoration: none;
background: #c91717;
padding: 11px 20px;
border: 0;
margin-top: 6px;
margin-left: 905px;
}

I don't know how to make the Create and Account button to be bold as the login link-to button is? Can you help me out? Thank you

A: The Element tool helped me! I've deleted in the general html and body brackets the font-weight: bold. And now the login link-to is like the create an account unbolded. Thank you


text:
Q: Antlr setText not working in the way I expected I have a requirement to convert an identifier into a beanutil string for retrieving an item from an object. The the identifiers to string conversions look like:
name                                        ==> name
attribute.name                              ==> attributes(name)[0].value
attribute.name[2]                           ==> attributes(name)[2].value
address.attribute.postalcode                ==> contactDetails.addresses[0].attributes(postalcode)[0].value
address[2].attribute.postalcode             ==> contactDetails.addresses[2].attributes(postalcode)[0].value
address[2].attribute.postalcode[3]          ==> contactDetails.addresses[2].attributes(postalcode)[3].value

Now I have decided to do this using antlr as I feel its probably going to be just as quick as using a set of 'if' statements. Feel free to tell me I'm wrong.
Right now, I've got this partial working using antlr, however once I start doing the 'address' ones, the setText part seems to stop working for Attribute.
Am I doing this the correct way or is there a better way of using antlr to get the result I want?
grammar AttributeParser;

parse returns [ String result ]
:  Address EOF { $result = $Address.text; }
|  Attribute EOF { $result = $Attribute.text; }
|  Varname EOF { $result = $Varname.text; }
;

Address
: 'address' (Arraypos)* '.' Attribute { setText("contactDetails.addresses" + ($Arraypos == null ? "[0]" : $Arraypos.text ) + "." + $Attribute.text); }
;

Attribute
:  'attribute.' Varname (Arraypos)* { setText("attributes(" + $Varname.text + ")" + ($Arraypos == null ? "[0]" : $Arraypos.text ) + ".value"); }
;

Arraypos
: '[' Number+ ']'
;

Varname
:  ('a'..'z'|'A'..'Z')+
;

Number
: '0'..'9'+
;

Spaces
:  (' ' | '\t' | '\r' | '\n')+ { setText(" "); }
;

Below are two unit tests, the first returns what I expect, the second doesn't.
@Test
public void testSimpleAttributeWithArrayRef() throws Exception {

    String source = "attribute.name[2]";
    ANTLRStringStream in = new ANTLRStringStream(source);
    AttributeParserLexer lexer = new AttributeParserLexer(in);
    CommonTokenStream tokens = new CommonTokenStream(lexer);
    AttributeParserParser parser = new AttributeParserParser(tokens);
    String result = parser.parse();
    assertEquals("attributes(name)[2].value", result);
}

@Test
public void testAddress() throws Exception {

    String source = "address.attribute.postalcode";
    ANTLRStringStream in = new ANTLRStringStream(source);
    AttributeParserLexer lexer = new AttributeParserLexer(in);
    CommonTokenStream tokens = new CommonTokenStream(lexer);
    AttributeParserParser parser = new AttributeParserParser(tokens);
    String result = parser.parse();
    System.out.println("Result: " + result);
    assertEquals("contactDetails.addresses[0].attributes(postalcode)[0].value", result);
}

A: No, you can't do (Arraypos)* and then refer to the contents as this: $Arraypos.text.
I wouldn't go changing the inner text of the tokens, but create a couple of parser rules and let them return the appropriate text.
A little demo:
grammar AttributeParser;

parse returns [String s]
  :  input EOF {$s = $input.s;}
  ;

input returns [String s]
  :  address   {$s = $address.s;}
  |  attribute {$s = $attribute.s;}
  |  Varname   {$s = $Varname.text;}
  ;

address returns [String s]
  :  Address arrayPos '.' attribute
     {$s = "contactDetails.addresses" + $arrayPos.s + "." + $attribute.s;}
  ;

attribute returns [String s]
  :  Attribute '.' Varname arrayPos
     {$s = "attributes(" + $Varname.text + ")" + $arrayPos.s + ".value" ;}
  ;

arrayPos returns [String s]
  :  Arraypos      {$s = $Arraypos.text;}
  |  /* nothing */ {$s = "[0]";}
  ;

Attribute : 'attribute';
Address   : 'address';
Arraypos  : '[' '0'..'9'+ ']';
Varname   : ('a'..'z' | 'A'..'Z')+;

which can be tested with:
import org.antlr.runtime.*;

public class Main {
  public static void main(String[] args) throws Exception {
    String[][] tests = {
      {"name",                                "name"},
      {"attribute.name",                      "attributes(name)[0].value"},
      {"attribute.name[2]",                   "attributes(name)[2].value"},
      {"address.attribute.postalcode",        "contactDetails.addresses[0].attributes(postalcode)[0].value"},
      {"address[2].attribute.postalcode",     "contactDetails.addresses[2].attributes(postalcode)[0].value"},
      {"address[2].attribute.postalcode[3]",  "contactDetails.addresses[2].attributes(postalcode)[3].value"}
    };
    for(String[] test : tests) {
      String input = test[0];
      String expected = test[1];
      AttributeParserLexer lexer = new AttributeParserLexer(new ANTLRStringStream(input));
      AttributeParserParser parser = new AttributeParserParser(new CommonTokenStream(lexer));
      String output = parser.parse();
      if(!output.equals(expected)) {
        throw new RuntimeException(output + " != " + expected);
      }
      System.out.printf("in  = %s\nout = %s\n\n", input, output, expected);
    }
  }
}

And to run the demo do:
java -cp antlr-3.3.jar org.antlr.Tool AttributeParser.g
javac -cp antlr-3.3.jar *.java
java -cp .:antlr-3.3.jar Main

which will print the following to the console:
in  = name
out = name

in  = attribute.name
out = attributes(name)[0].value

in  = attribute.name[2]
out = attributes(name)[2].value

in  = address.attribute.postalcode
out = contactDetails.addresses[0].attributes(postalcode)[0].value

in  = address[2].attribute.postalcode
out = contactDetails.addresses[2].attributes(postalcode)[0].value

in  = address[2].attribute.postalcode[3]
out = contactDetails.addresses[2].attributes(postalcode)[3].value

EDIT
Note that you can also let parser rules return more than just one object like this:
bar
  :  foo {System.out.println($foo.text + ", " + $foo.number);}
  ;

foo returns [String text, int number]
  :  'FOO' {$text = "a"; $number = 1;}
  |  'foo' {$text = "b"; $number = 2;}
  ;


text: Q: Fedora and Windows dual-boot boots to grub command line I'm trying to dual boot fedora34 and windows 10, but ran into some issues installing fedora. I followed this tutorial to install fedora34 to dual-boot with win10 which was already installed on my pc. https://www.youtube.com/watch?v=Ln8z3pBOpN0 After the installation when I rebooted it boots into the grub command line and not fedora. ls shows (proc) and 4 (hd0,gpt) partitions. (my pc is uefi btw) doing ls on gpt1 says its formatted in Fat, ls on proc says the pc is running procfs or something I forgot but its not important. ls on any other partition says it's an unknown file system. if I type exit it takes me to the windows bootloader where I can boot into win10, or "linux" which is the grub command line. If that part sounds weird I messed with the boot loader previously. This would seem easier if it weren't for the partitions saying unknown file system. By the way, fedora is on an sd card but the boot partition is on the computers hard drive. Thanks,


text:
Q: How do I change objects inside an array in CloudFirestore? I need to add / change / delete objects inside an array that is inside a document, I would like to know if I have to update all the data that will be sent, or if I can only change the specific object that is inside the array.
I have a form with many fields, I would just like to update a specific object ... Do I have to send the entire object or can I only update the specific object?

Is it possible to add / change / delete only objects that are within plans? Or do I need to send every object in the image to update plans together?

A: You can't update individual items in an array.  You have to send the entire array with each update.
On that note, sometimes it's better to use an object if you just want to change individual elements if you already know their names.


text:
Q: How to submit a form with AJAX/JSON? Currently my AJAX is working like this:
index.php
One

workspace

one.php
$arr = array ( "workspace" => "One" );
echo json_encode( $arr );

ajax.js
jQuery(document).ready(function(){
    jQuery('.ajax').live('click', function(event) {
        event.preventDefault();
        jQuery.getJSON(this.href, function(snippets) {
            for(var id in snippets) {
                jQuery('#' + id).html(snippets[id]);
            }
        });
    });
});

Above code is working perfectly. When I click link 'One' then one.php is executed and String "One" is loaded into workspace DIV.
Question:
Now I want to submit a form with AJAX. For example I have a form in index.php like this.
<form id='myForm' action='one.php' method='post'>
 <input type='text' name='myText'>
 <input type='submit' name='myButton' value='Submit'>
</form>

When I submit the form then one.php should print the textbox value in workspace DIV.
$arr = array ( "workspace" => $_POST['myText'] );
echo json_encode( $arr );

How to code js to submit the form with AJAX/JSON.
Thanks

A: Here is my complete solution:
jQuery('#myForm').live('submit',function(event) {
    $.ajax({
        url: 'one.php',
        type: 'POST',
        dataType: 'json',
        data: $('#myForm').serialize(),
        success: function( data ) {
            for(var id in data) {
                jQuery('#' + id).html(data[id]);
            }
        }
    });
    return false;
});

A: Submitting the form is easy:
$j('#myForm').submit();

However that will post back the entire page.
A post via an Ajax call is easy too:
$j.ajax({
    type: 'POST',
    url: 'one.php',
    data: {
        myText: $j('#myText').val(),
        myButton: $j('#myButton').val()
    },
    success: function(response, textStatus, XMLHttpRequest) {
        $j('div.ajax').html(response);
    }
});

If you then want to do something with the result you have two options - you can either explicitly set the success function (which I've done above) or you can use the load helper method:
$j('div.ajax').load('one.php', data);

Unfortunately there's one messy bit that you're stuck with: populating that data object with the form variables to post.
However it should be a fairly simple loop.

A: Have a look at the $.ajaxSubmit function in the jQuery Form Plugin. Should be as simple as
 $('#myForm').ajaxSubmit();

You may also want to bind to the form submit event so that all submissions go via AJAX, as the example on the linked page shows.

A: You can submit the form with jQuery's $.ajax method like this:
$.ajax({
 url: 'one.php',
 type: 'POST',
 data: $('#myForm').serialize(),
 success:function(data){
   alert(data);
 }
});


text:
Q: Fundamental solution for 1D nonhomogeneous wave equation I want to get the fundamental solution for the following 1D nonhomogeneous wave equation:\begin{align}\left\{
\begin{aligned}
&\frac{\partial^2u}{\partial^2t}-\frac{\partial^2u}{\partial^2x}-au=0,x\in R^1,t>0,a\ is\ a\ constant.\\& u(x,0)=0,u_t(x,0)=\phi(x)
\end{aligned}
\right.\end{align}
I know the fundamental solution should statisfy the following equation:\begin{align}\left\{
\begin{aligned}
&\frac{\partial^2E}{\partial^2t}-\frac{\partial^2E}{\partial^2x}-aE=0,x\in R^1,t>0,a\ is\ a\ constant.\\& E(x,0)=0,E_t(x,0)=\delta(x)
\end{aligned}
\right.\end{align}Use the fourier transform and then:
\begin{align}\left\{
\begin{aligned}
&\frac{\partial^2\hat{E}}{\partial^2t}+(\xi^2-a)\hat{E}=0,\xi\in R^1,t>0,a\ is\ a\ constant.\\& \hat{E}(\xi,0)=0,\hat{E}_t(\xi,0)=1
\end{aligned}
\right.\end{align}
Solve the equation then we got:$$\hat{E}(\xi,t)=\frac{sin(\sqrt{\xi^2-a}t)}{\sqrt{\xi^2-a}}$$Using the  inverse Fourier transform:$$E(x,t)=\frac{1}{2\pi}\int_R\frac{sin(\sqrt{\xi^2-a}t)}{\sqrt{\xi^2-a}}e^{-ix\xi}d\xi=\frac{1}{\pi}\int_{0}^{\infty}\frac{sin(\sqrt{\xi^2-a}t)}{\sqrt{\xi^2-a}}cos(x\xi)d\xi$$I don't know how to compute this integration,or maybe I shouldn't use the fourier transform to solve this problem? Appreciate anybody who answer this question first

A: If you replace $au$ and $aE$ with $k(x,t)$ then you will have the non homogeneous wave equation as its normally given.
If you then set $E(x,0)=E_t(x,0)=0$ you will have the purely non homogeneous equation with a forcing function and no initial conditions.
Then setting $E(x,0)=0, E_t(x,0)=g(x,t)$ and $k(x,t)=0$ will give you the non homogeneous wave equation with a velocity initial condition.
Finally, setting $E(x,0)=f(x,t), E_t(x,0)=0$ and $k(x,t)=0$ will give you the non homogeneous wave equation with a displacement initial condition.
So you can get three separate solutions, and the final solution is their sum.
If when used, $k,f,g$ are set to $\delta$ then the sum of the solutions will be the fundamental solution.
The homogeneous solutions can be found from D'Alemberts formula.  The non homogeneous solution is a little more work--Google it.
Bottom line: I think your wave equation may be wrong, and you do not need the Fourier transform.


text:
Q: Same author same year bibliography issue So I want to submit a paper to Biostatistics journal, which has its own Latex template and \bibliographystyle{biorefs}. The problem arises when I try to cite two different papers of the same author and the same year. Such references are:
@article{kwok1999moderating,
  title={Moderating the outputs of support vector machine classifiers},
  author={Kwok,  James Tin-Yau},
  journal={IEEE Transactions on Neural Networks},
  volume={10},
  number={5},
  pages={1018--1031},
  year={1999},
  publisher={IEEE}
}
@inproceedings{kwok1999integrating,
  title={Integrating the evidence framework and the support vector machine.},
  author={Kwok, James Tin-Yau},
  booktitle={ESANN},
  volume={99},
  pages={177--182},
  year={1999}
}

I have tried using \cite and \citep, but both of them produce (Kwok, 1999,?) as a result, instead of (Kwok, 1999a,1999b) or (Kwok, 1999a,b), which is what I want to obtain.
Any idea of how to solve it? Thanks a lot.
Edit: Here you can find an example in Overleaf (link).

A: This seems to be a bug in biorefs.bst.
Since it is usually a very bad idea to modify files without renaming them, do rename biorefs.bst (e.g. newbiorefs.bst) and change line 1079 from
label.year write$

to
sort.year write$

Like this:
FUNCTION {output.bibitem}
{ newline$
  "\bibitem[" write$
  make.abbr.label write$
  "(" write$
  sort.year write$          % <-- here!!!
  ")" write$
  make.full.label write$
  "]{" write$
  cite$ write$
  "}" write$
  newline$
  ""
  before.all 'output.state :=
}

Now the output looks like this:

You should absolutely contact the maintainers about this.


text:
Q: Google Map not Updating By Onchange Event In Dynamics 365 In Dynamics 365(version:8.2), I am loading google map using web resource and then trying to initiate google map by onchange event from CRM input field but it is showing error alert message:

ReferenceError: google is not defined at initMap

I got the solution by finding iframe and then call google map.like this:
var description = Xrm.Page.getAttribute('new_street').getValue();
// Get the HTML iFrame object.
var iFrame = Xrm.Page.ui.controls.get('WebResource_Map').getObject();
// Get the element from the iFrame.
var element = iFrame.contentWindow.document.getElementById('addr_line1');
var ifr = iFrame.contentWindow;
// Set the element's value.
element.value = description+' ';

I need help on this.

A: Here's how I would suggest you do it:

*

*From your script that loads the google maps (Web Resource), get the form attribute values (address fields).

*Whenever you need to refresh the map in case of any field change, just reload the web resource that's embedded on your form and it should automatically call the google maps again resulting in your new location being set.
You can call the reloadMapOnFieldChange() on change of the fields for which you want the map to be refreshed
function refreshWebResource(name) {

    var _webResourceControl = Xrm.Page.getControl(name);

    if(_webResourceControl!=null && _webResourceControl!="" && _webResourceControl!=undefined)
    {
        var _src = _webResourceControl.getSrc();
        _webResourceControl.setSrc(null);
        _webResourceControl.setSrc(_src);
    }
}

function reloadMapOnFieldChange(){

    refreshWebResource(<Name of your Map Web Resource>);
}


text:
Q: ActiveMQ and Client identity through certificate authentication Is there a way to determine the identity of a Message sender in ActiveMQ (JMS in general) that successfully connected to a broker via SSL using a client certificate?
I am planning on using JMs for communications between a remote terminal and a perimeter server within my network simply because of the extensive work that's been done internally to support JMS in the internal network. The terminal application uses a client certificate to authenticate to the ActiveMQ JMS broker, nevertheless, i'm trying to find out if there's a way to determine the certificate used by the remote terminal to connect to JMS at the perimeter server in order to pass that information to the authentication service.
Any thoughts or ideas are greatly appreciated..

A: I figured I asked this question about a year ago and since then I have manged to successfully capture the SSL connection's user.
The answer is quite simple, add populateJMSXUserID="true" to the broker definition.
If you need help configuring SSL client authentication, I have found Fuse Source to have by far some of the most well rounded and detailed documentation on ActiveMQ (Fuse Message Broker). You can find more details about JAAS Certificate Authentication Plug-In here.


text:
Q: Can't hide  item programmaticaly Android Studio 3.6
in app/build.gradle:
android {
viewBinding.enabled = true

In my activity:
 override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = QrBluetoothSwipeActivityBinding.inflate(layoutInflater)
}

in my qr_bluetooth_swipe_activity.xml
      <include
            android:id="@+id/blueToothBottonContainer"
            layout="@layout/bluetooth_bottom_container"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:visibility="gone"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent" />

I want to hide blueToothBottonContainer programmaticaly.
So I try this:
private fun setBottomContainreViewMode(isQrScreenVisible: Boolean) {
        if (isQrScreenVisible) {
            binding.qrBottonContainer.
        }
}

but not found method smt like setVisible
why?

A: setVisibility method belongs to a View class. <include> tag is not really a layout(View + ViewGroups). That's why you won't find setVisibility method on it.
To hide the included layout, you can give id to parent layout in your bluetooth_bottom_container layout and then change it's visiblity from binding.blueToothBottonContainer.{parent_layout_id}.


text:
Q: Watson Machine Translation in Node Red Flow It seems there have been some changes in the usage of the Machine Translation service from within a Node Red flow. There was the capability to configure from within the node from which into which other language to translate. This has been changed. Can you help me in understanding where to set exactly this when having identified the language already before (msg.lang)
Thanks

A: There are two ways to set the translation language for the Machine Translation node.
You can either...

*

*Select the language from the dropdown menu in the node configuration dialog.

*

*Pass the language translation type as the "lang" parameter on the "msg" object.

Supported language types for the Machine Translation node are automatically registered at runtime. You must have the Watson Machine Translation Service bound to your Node-RED instance running on Bluemix.


text:
Q: Should I use non- standard Windows Azure Port Mappings? When I configured Windows Azure VM last night I had to Edit Mappings in Azure Management portal. This is a process of opening a public port and mapping that to a private port. Its very simple but I noticed Azure by default maps private RDP 3389 to some random high port number say 51460.
I need to open http so mapped private 80 >> public 80. Could I have benefited in some way from mapping random public port number to private port 80?? Seems to me this would would simply block all traffic as http is going to be REQUESTED on 80 anyway.
So why do they do it?
Is it simply a matter of RDP being a high value target that should legitimately be called only  from private admin requests?

A: So... for something like a web server, you'd typically have more than one VM (for scale), and you'd typically want the load balancer to do its job and spread the traffic across all of your VMs. In that case, you'd use a load-balanced endpoint and map port 80 (external) to port 80 (internal) - it makes no sense to pick some random input port. Of course, if you have a non-standard web site (e.g. management site), maybe you'd place that on something else (like maybe port 8000). At that point, you can decide to map it to port 80 or leave it at port 8000.
Where the fun begins: something like RDP. If you just used port 3389, and you had more than one VM, all mapping external 3389 to internal 3389, how would you choose which VM to RDP to? The answer: You wouldn't - you'd have a load-balanced endpoint and you'd have luck-of-the-draw and only be able to guess which VM you attached to.
Therefore, you use port-forwarded endpoints, one endpoint per VM, each with its own dedicated port. From the outside world, you'd now have a bank of ports: maybe 55000, 56000, etc. Each of these would then map to internal port 3389 on their respective VM. And... voila - you have direct RDP access to every single VM.
This port-mapping also applies to ssh (when using Linux) or any other scenario where you have a service running independently on multiple VMs, where you need direct access to a specific VM for some reason.


text:
Q: Bounded discrepancy multiplicative functions A rather specific question, concerning the second remark of Tao in
http://www.michaelnielsen.org/polymath1/index.php?title=Bounded_discrepancy_multiplicative_functions_do_not_correlate_with_characters
As I interpret it, the second remark states that the Theorem which begins the note may alternatively be derived by an application of two other results used as black boxes, although the alternative proof occupying the note has the advantage of being more flexible. I have not been able to construct an argument deducing the Theorem from the results quoted in this second remark (the 'Fourier reduction lemma' and Halasz's theorem): might someone be able to say what I'm missing?
Let me give a little of the background. This note by Tao was written during the Polymath project some five years ago on the Erdos discrepancy problem. The special case -- showing that a completely multiplicative $\{\pm 1\}$-valued function has unbounded partial sums -- is still interesting, and still unknown. The main theorem of the note states that were such a function $g$ to exist it would not correlate with a non-principal Dirichlet character $\chi$, in the sense that $$\sum\limits_{p}\dfrac{\vert 1-g(p)\overline{\chi(p)}\vert}{p}=\infty$$
The 'Fourier reduction lemma' to which he refers is from here:
http://michaelnielsen.org/polymath1/index.php?title=Fourier_reduction
-- another ingenious argument of Tao reducing the general Erdos discrepancy problem to a similar statement about completely multiplicative $S^1$-valued functions. 'Theorem 2.3' from Balog, Granville and Soundararajan  is just a version of Halasz's Theorem on sums of multiplicative functions.
I've read what I believe to be the corresponding discussion on the original blog post (EDP4 on Gowers' blog), but have not been able to reconstruct an appropriate argument. No doubt this is due to my own innate stupidity.


text:
Q: How to design a position absolute child div placed within overflow hidden div in bootstrap carousel I am trying to place a badge (position absolute) on a parent div in a bootstrap carousel. Due to overflow hidden in the .carousel-inner class of bootstrap, the top part of the badge hides.
If I try to remove the overflow hiiden it works, but I need the overflow hidden as well.
Can some one pls help me to find a way out.
Thanks in advance
My Code
http://jsfiddle.net/JPais/jqkg4t1p/6/
[1]: http://ttps://jsfiddle.net/JPais/jqkg4t1p/fiddle link

A: Use margin top
.txtpic{position: absolute;
    background: #f69165;
    padding: 20px;
    top: -15%;left:15px;
    margin-top:10%}

A: Add a 15px white top border for the .item
And move the carousel-inner up with negative margin
.carousel-inner>.item {
           border-top: 15px solid #fff;
    }
.carousel-inner {
          margin-top: -15px;
    }

http://jsfiddle.net/afelixj/53u0otns/


text:
Q: How to remove "image_picker" mark when select image using Image Picker flutter I have this image picker But when picked the image It shows the "image_pick" mark in front of the image file Like this image_picker5431631000176511341.jpg But I want to remove it How can I do that is it possible?
code:
//Pick image
ElevatedButton(
         onPressed: () => selectFile(),
         child: const Text(
         'Select Image /Gallery'),
        ),

//Show fileName
Text('$fileName')

//To pick image
  void selectFile() async {
    final XFile? results = await picker.pickImage(source: ImageSource.gallery);

    if (results != null) {
      path = results.path;

      fileName = results.name;
      setState(() {});
      print(fileName);
    } else {
      print('No image picked');
    }
    setState(() {
      imageFile = File(results!.path);
    });
  }

Image:

remove the "image_picker" mark in front of the actual file name

A: change to this
fileName = results.name.replaceFirst ("image_picker","");


text:
Q: MySQL. Блокировка строк Всем привет!
Есть таблица, содержащая 2 миллиона записей. Каждый раз показывает 50 новый записей. Сейчас sql выглядит таким образом(к сожаление нельзя исправить, т.к. генерируется CRM-кой): SELECT * FROM table order by ID LIMIT 50 OFFSET 0.
Видно узкое место - мы вначале вытаскиваем все записи,сортируем их, а потом только берем 50. Худо-бедно запрос отрабатывает.
А теперь вопрос: каждый определенный интервал времени мы обновляем последовательно каждую запись. И пока происходит обновление - мы не можем выполнить наш главный запрос на отображение последних 50 строк. Как сделать так, что бы и обновление и выборка работали не конфликтуя?
Дабы усложнить задачу - при выборке 50 записей мы join-ним пару таблиц.
Пробовал использовать HIGH/LOW_PRIORITY - не помогает.
Подсистема хранения - InnoDB.


text:
Q: SqlAlchemy changes in Model description not applied in DB I am currently developing a server using Flask/SqlAlchemy. It occurs that when an ORM model is not present as a table in the database, it is created by default by SqlAlchemy.
However when an ORM class is changed with for instance an extra column is added, these changes do not get saved in the database. So the extra column will be missing, every time I query. I have to adjust my DB manually every time there is a change in the models that I use.
Is there a better way to apply changes in the models during development? I hardly think manual MySql manipulation is the best solution.

A: you can proceed as the following:
new_column = Column('new_column', String, default='some_default_value')
new_column.create(my_table, populate_default=True)

you can find more details about sqlalchemy migration in: https://sqlalchemy-migrate.readthedocs.org/en/latest/changeset.html


text:
Q: Avoiding redundant work when matching and parsing I'm using match to see if string input is a position, and if it does, convert it to a tuple. For example, "B6" would become (1, 5). I have the functions is_pos to math the right input and parse_pos to transform it, so each match needs to perform string parsing twice.
fn main() {
    let input = ""
    match input {
        "exit" => return,
        _ if is_pos(input) => parse_pos(input),
        _ => (0, 0),
    };
}

fn is_pos(str: &str) -> bool {
    // string processing
    true
}

fn parse_pos(str: &str) -> u32 {
    // the same string processing
    5
}

I'd to have one function that returns an Option. Then the match would select the Option if it wasn't none, and I could unwrap it without needing to redo the string parsing.
Is this possible with match, or should I go back to using if statements?

A: There is no elegant way to save the intermediate result of the if clause. Yes you could go back to an if statement.
if input == "exit" {
    return;
}
let pos = parse_pos(input).unwrap_or((0, 0));

You could still use a match like this:
let pos = match input {
    "exit" => return,
    _ => parse_pos(input).unwrap_or((0, 0)),
};

(Note that the early-return here does not really stand out. Could be a problem for future readers.)


text:
Q: Why isn't the The Least Upper Bound axiom derivable from the order axioms? Apostol, in his Calculus book, has this as one of the axioms before he starts fleshing out rest of the subject. The axiom states that any non-empty set of real numbers that has an upper bound necessarily has a least upper bound.
I fail to understand why we need to state this as axiom. Isn't this obvious from the order axioms? If a non-empty set has an upper bound, then there must exist the least one. Sorry if I'm unable to articulate it any better, but that could also mean I don't really know what I'm asking.
The necessity of the Least Upper Bound axiom is not obvious to me. Why is it needed?

A: It is not obvious from the order axioms because it does not follow from the order axioms. For example, the rationals $\mathbb Q$ with the usual addition and multiplication is a field that satisfies the order axioms but does not have the least upper bound property. For example since $\frac{\pi^2}{6} = \sum_{k=1}^\infty \frac{1}{k^2}$, the set $\{\sum_{k=1}^n \frac{1}{k^2} : n \in \mathbb N\}$ is a bounded subset of $\mathbb Q$ with no least rational upper bound.

A: Think about the rationals in the interval $(-\sqrt{2},\sqrt{2})$. In general rational numbers satisfy the order axioms. However, this set fails to satisfy LUB axiom simply because $\sqrt{2}$ is not a member of rational.

A: The rational numbers also satisfy the field axioms and the order axioms, but they do not satisfy the Least Upper Bound axiom. For example, consider the set of all rational numbers $q$ such that $q^2 \leq 2$. This is bounded from above, but the least upper bound is $\sqrt{2}$ which is not rational.
The Least Upper Bound Axiom is necessary to make sure that the real line doesn't have any "gaps".

A: The Least Upper property is not a consequence of the partial ordering on the reals. The same ordering exists on the rationals and the LUB property fails for them.For example, the set $\{ x\in\mathbb{Q} : x^2 <2 \} $ does not have a least upper bound in $\mathbb{Q} .$ (Fairly easy to prove,do it yourself.)  The LUB property rests on the completeness of the real numbers, which can be formulated several different ways. What it basically means is that there are no gaps in the real numbers: in between any 2 rational numbers there exists an irrational and in between any 2 irrationals,there's a rational. As a result,all Cauchy sequences converge in the reals and this is what gives the real numbers their unique analytic properties that makes them so paramount in analysis.

A: If this was true, the rationals would also satisfy it.
In $\mathbb Q$, does the following have a least upper bound / supremum?
$$\{3,3.1,3.14,3.141,3.1415,3.14159,\dots\}$$


text:
Q: why are commits being duplicated in gitk --all? In my app that has a Git repo I noticed in the gitk --all viewer that there are some commits with the same description and datestamp, though they have different hashes.  There are 3 pairs of duplications, all dated 2022-06-21 with paired timestamps.

Interestingly enough, in the VS Code Source Control panel, the Commits section does not display the duplicated commits -

I'm thinking the fix for this is probably to move the state-2 tag to the commit hash for the description "Add scenario module" that's on the main branch (topmost one in screenshot) but I'm wondering why/how this happened in the first place?


text:
Q: Spark - extracting numeric values from an alphanumeric string using regex I have an alphanumeric column named "Result" that I'd like to parse into 4 different columns: prefix, suffix, value, and pure_text.
I'd like to solve this using Spark SQL using RLIKE and REGEX, but also open to PySpark/Scala
pure_text: contains only alphabets (or) if there are numbers present, then they should either have a special character "-" or multiple decimals (i.e. 9.9.0) or number followed by an alphabet and then a number again (i.e. 3x4u)
prefix: anything that can't be categorized into "pure_text" will be taken into consideration. any character(s) before the 1st digit [0-9] needs to be extracted.
suffix: anything that can't be categorized into "pure_text" will be taken into consideration. any character(s) after the last digit [0-9] needs to be extracted.
value: anything that can't be categorized into "pure_text" will be taken into consideration. extract all numerical values including the decimal point.
Result

11 H
111L
<.004
>= 0.78
val<=0.6
xyz 100 abc
1-9
aaa 100.3.4
a1q1

Expected Output:
Result         Prefix     Suffix   Value    Pure_Text

11 H                           H      11
111L                           L     111
.9                                   0.9
<.004               <              0.004
>= 0.78            >=               0.78
val<=0.6        val<=                0.6
xyz 100 abc      xyz         abc     100
1-9                                              1-9
aaa 100.3.4                              aaa 100.3.4
a1q1                                            a1q1

A: Here's one approach using a UDF that applies pattern matching to extract the string content into a case class.  The pattern matching centers around the numeric value with Regex pattern [+-]?(?:\d*\.)?\d+ to extract the first occurrence of numbers like "1.23", ".99", "-100", etc.  A subsequent check of numbers in the remaining substring captured in suffix determines whether the numeric substring in the original string is legitimate.
import org.apache.spark.sql.functions._
import spark.implicits._

case class RegexRes(prefix: String, suffix: String, value: Option[Double], pure_text: String)

val regexExtract = udf{ (s: String) =>
  val pattern = """(.*?)([+-]?(?:\d*\.)?\d+)(.*)""".r
  s match {
    case pattern(pfx, num, sfx) =>
      if (sfx.exists(_.isDigit))
        RegexRes("", "", None, s)
      else
        RegexRes(pfx, sfx, Some(num.toDouble), "")
    case _ =>
      RegexRes("", "", None, s)
  }
}

val df = Seq(
  "11 H", "111L", ".9", "<.004", ">= 0.78", "val<=0.6", "xyz 100 abc", "1-9", "aaa 100.3.4", "a1q1"
).toDF("result")

df.
  withColumn("regex_res", regexExtract($"result")).
  select($"result", $"regex_res.prefix", $"regex_res.suffix", $"regex_res.value", $"regex_res.pure_text").
  show
// +-----------+------+------+-----+-----------+
// |     result|prefix|suffix|value|  pure_text|
// +-----------+------+------+-----+-----------+
// |       11 H|      |     H| 11.0|           |
// |       111L|      |     L|111.0|           |
// |         .9|      |      |  0.9|           |
// |      <.004|     <|      |0.004|           |
// |    >= 0.78|   >= |      | 0.78|           |
// |   val<=0.6| val<=|      |  0.6|           |
// |xyz 100 abc|  xyz |   abc|100.0|           |
// |        1-9|      |      | null|        1-9|
// |aaa 100.3.4|      |      | null|aaa 100.3.4|
// |       a1q1|      |      | null|       a1q1|
// +-----------+------+------+-----+-----------+


text:
Q: How can I find elements from a Perl array that match elements in a second array? I have two arrays
@one = ("1|1|the|dog|ran", "1|2|a|x|b", "2|8|e|s|e");
@two = ("1|2|a|x|b", "1|1|down|the|street", "2|8|e|s|e");

I need to match them by the first two "|" separated elements. So that when on $one[0] the search would return $two[1].
There are millions of lines in each array so I need the fastest way to do this.
EDIT:
Sorry for the confusion. I want to treat the first 2 "|" separated elements (ie. 1|2, 2|1) as a key for the array, loop through the first array and search the second array using that key to get the values in the second array. Does that help?

A: - For each record in the second array,
  - Parse the record
  - Add it to a hash keyed by the first two fields.

- For each record in the first array,
  - Parse the record
  - Look in the hash for a record with the appropriate key.
  - If there is one,
    - Do something with it.


text:
Q: Get duplicates in collection list of dataframes in the same row in Apache Spark (pyspark 2.4) In Spark, with pyspark, I have a data frame with duplicates. I want to deduplicate them with multiples rules like email and mobile_phone.
This is my code in python 3 :
from pyspark.sql import Row

from pyspark.sql.functions import collect_list

df = sc.parallelize(
    [
        Row(raw_id='1001', first_name='adam', mobile_phone='0644556677', email='adam@gmail.fr'),
        Row(raw_id='2002', first_name='adam', mobile_phone='0644556688', email='adam@gmail.fr'),
        Row(raw_id='3003', first_name='momo', mobile_phone='0644556699', email='momo@gmail.fr'),
        Row(raw_id='4004', first_name='momo', mobile_phone='0644556600', email='mouma@gmail.fr'),
        Row(raw_id='5005', first_name='adam', mobile_phone='0644556688', email='adama@gmail.fr'),
        Row(raw_id='6006', first_name='rida', mobile_phone='0644556688', email='rida@gmail.fr')
    ]
).toDF()

My original dataframe is :
+--------------+----------+------------+------+
|         email|first_name|mobile_phone|raw_id|
+--------------+----------+------------+------+
| adam@gmail.fr|      adam|  0644556677|  1001|
| adam@gmail.fr|      adam|  0644556688|  2002|
| momo@gmail.fr|      momo|  0644556699|  3003|
|mouma@gmail.fr|      momo|  0644556600|  4004|
|adama@gmail.fr|      adam|  0644556688|  5005|
| rida@gmail.fr|      rida|  0644556688|  6006|
+--------------+----------+------------+------+

Then, i apply my deduplication rules :
df_mobile = df \
   .groupBy('mobile_phone') \
   .agg(collect_list('raw_id').alias('raws'))

df_email = df \
   .groupBy('email') \
   .agg(collect_list('raw_id').alias('raws'))

This is the result i have :
df_mobile.select('raws').show(10, False)
+------------------+
|raws              |
+------------------+
|[2002, 5005, 6006]|
|[1001]            |
|[4004]            |
|[3003]            |
+------------------+

df_email.select('raws').show(10, False)
+------------+
|raws        |
+------------+
|[3003]      |
|[4004]      |
|[1001, 2002]|
|[5005]      |
|[6006]      |
+------------+

So, the final result I want is to regroup common elements of the raws column like this :
+------------------------+
|raws                    |
+------------------------+
|[3003]                  |
|[4004]                  |
|[2002, 5005, 6006, 1001]|
+------------------------+

Do you know how I can do it with pyspark ?
Thank you very much!

A: So it seems as @pault is hinting at you could model this as a graph where your original dataframe df is a list of vertices and df_email and df_mobile are lists of connected vertices. Now unfortunately GraphX is not available for python, but GraphFrames is!
GrameFrames has a function called Connected Components that will return the list of connected raw_ids or vertices. To use it we must do two things, raw_id must be just called id and the edge must be source (src) and destination (dst) pairs not simply lists of vertices.
from pyspark.sql import SparkSession
from pyspark.sql.functions import *
from pyspark.sql.types import *
from graphframes import GraphFrame

spark = SparkSession \
    .builder \
    .appName("example") \
    .getOrCreate()

spark.sparkContext.setCheckpointDir("checkpoints")
    # graphframes requires a checkpoint dir since v0.3.0
    # https://graphframes.github.io/user-guide.html#connected-components

spark.sparkContext.setLogLevel("WARN") # make it easier to see our output

vertices = spark.createDataFrame([
    ('1001', 'adam', '0644556677', 'adam@gmail.fr'),
    ('2002', 'adam', '0644556688', 'adam@gmail.fr'),
    ('3003', 'momo', '0644556699', 'momo@gmail.fr'),
    ('4004', 'momo', '0644556600', 'mouma@gmail.fr'),
    ('5005', 'adam', '0644556688', 'adama@gmail.fr'),
    ('6006', 'rida', '0644556688', 'rida@gmail.fr')
]).toDF("id", "first_name", "mobile_phone", "email")

mk_edges = udf(
    lambda a: [{'src': src, 'dst': dst} for (src, dst) in zip(a, a[-1:] + a[:-1])],
    returnType=ArrayType(StructType([
        StructField('src', StringType(), nullable=False),
        StructField('dst', StringType(), nullable=False)])))

def edges_by_group_key(df, group_key):
    return df.groupBy(group_key) \
        .agg(collect_list('id').alias('ids')) \
        .select(mk_edges('ids').alias('edges')) \
        .select(explode('edges').alias('edge')) \
        .select("edge.*")

mobileEdges = edges_by_group_key(vertices, 'mobile_phone')
print('mobile edges')
mobileEdges.show(truncate=False)

# mobile edges
# +----+----+
# |src |dst |
# +----+----+
# |2002|6006|
# |5005|2002|
# |6006|5005|
# |1001|1001|
# |4004|4004|
# |3003|3003|
# +----+----+

emailEdges = edges_by_group_key(vertices, 'email')
print('email edges')
emailEdges.show(truncate=False)

# email edges
# +----+----+
# |src |dst |
# +----+----+
# |3003|3003|
# |4004|4004|
# |1001|2002|
# |2002|1001|
# |5005|5005|
# |6006|6006|
# +----+----+

g = GraphFrame(vertices, mobileEdges.union(emailEdges))

result = g.connectedComponents()
print('connectedComponents')
result.select("id", "component") \
    .groupBy("component") \
    .agg(collect_list('id').alias('ids')) \
    .select('ids').show(truncate=False)

# connectedComponents
# +------------------------+
# |ids                     |
# +------------------------+
# |[1001, 2002, 5005, 6006]|
# |[4004]                  |
# |[3003]                  |
# +------------------------+

There might be a cleverer way to do the union between the mobile and email dataframes, maybe deduplicate with distinct, but you get the idea.


text:
Q: How to remove the parentheses and the text in between them in a string in Python? I want to remove the brackets and text in between them using regular expression.
Example strings are :
string = "Hello (World)"
string = "Hello (World) I am here"

Expected output string after using regular expression is as follows:
output ="Hello "
output ="Hello  I am here"

A: Taking the question very literally the following regex would remove ' (republic)'  from your sample string.
 *\(.*\)

(Note the space at the start of the regex)

A: Use this example and try. (In python 2.7)
variable "text" should be a String.
text = " aaa) bbb( "
filteredtext = filter(lambda z: z not in ")(", text)
print filteredtext

Output :
*** Remote Interpreter Reinitialized  ***
>>>
 aaa bbb
>>>


text:
Q: Get Notifications from Phone - React Native Can someone please help? I am trying to create an app that gets the notifications list similar to the upper drawer of an android phone, but this time I want those notifications to be displayed in a View. Can someone point me a solution or perhaps a repository or dependency I can use.
Thanks!


text:
Q: Smoothness of distributions I've reached an impasse in reading some texts on distribution theory, as several of them mention smooth distributions, but none of them actually define what it means.
Therefore I'd like to know if anyone could give me the definition of a smooth distribution.
EDIT:
After reading a bit more, I've realized that I am thinking about distributions which are locally given by smooth functions. Where is it possible to read about these


text:
Q: Distribution MSR We have $Y_i = \beta_0 +\beta_1(X_i -\bar X )+\epsilon_i$ for i=1,...,n
$$\epsilon_i \sim N(0,\sigma^2)$$
We know that $SSR= Y^T P_xY - n\bar Y^2=Y^T (P_x -n^{-1} J_nJ_n^T)Y$
$$J_n=\big[\begin{matrix}1 \\ ... \\ 1\end{matrix}\big]_{nxn}$$
$$MSR=SSR/(r-1)$$
How can I find the distribution of MSR?
Suppose $Y\sim N_p(\mu, V)$ and Rank(V)=p
If AV is idempotent of ranks then $Y^TAY \sim \chi_s^2(\lambda)$ where $\lambda =1/2 (\mu^TA\mu)$
Will I use this result?
I have done for $SSR=Y^TP_xY$ Uncorrected model.
By using this result and find
$$\frac{Y^TP_xY}{\sigma^2}=Y^TBY\sim \chi_s^2(\lambda)$$
where $\lambda =1/2 (\mu^TB\mu)$ and$B= \sigma^{-2 }P_x$
But I couldn't find for corrected model MSR.


text:
Q: getting a error oledbexception was unhandled Additional information: No value given for one or more required parameters I am getting this error while trying to select data from a database and I am lost on how to fix it. My query works in my database but I am not sure what is happening
randomget = "SELECT top 1 id, Department, Team, Process,  SubProcess, SubTask, LastUpdatedBy from workload where stepstatus = 'complete' and agent is null or agent = 0  ";
OleDbConnection MyConn = new OleDbConnection();
MyConn.ConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=.......;Persist Security Info=False";;
MyConn.Open();
OleDbCommand cmd = MyConn.CreateCommand();
cmd.CommandText = randomget;
OleDbDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
int id = 0;

while (reader.Read())
{
    id = int.Parse(reader[0].ToString());
    textBox8.Text = reader[6].ToString();
    textBox5.Text = reader[1].ToString();
    textBox6.Text = reader[2].ToString();
    textBox7.Text = reader[3].ToString();
    textBox9.Text = reader[4].ToString();
    textBox11.Text = reader[5].ToString();
    break;
}

// input table name here
textBox2.Text = agentsrf.ToString();
string sqlupdate = "Update workload set agent = '" + agent + "',  where ID = "  + id + " ' ";
}

public OleDbConnection connection { get; set; }

A: You have one stray , after set agent = '" + agent + "' just remove it and then it works fine. Also you should use parameterized queries because this kind of string concatenations are open for SQL Injection:
string sqlupdate = "Update workload set agent = @agent where ID = @id ";
cmd.Parameters.AddWithValue("@agent", agent );
cmd.Parameters.AddWithValue("@id", id);

A: I solved it. One of my field names had a space in it, which I did not spot.


text:
Q: How to use variable variables in class variables and function arguments This is what I want to do:
class Contacts {

    private $_plural = 'contacts';
    private $_single = 'contact';
    private $_factory = 'contactfactory';
    private $_model = 'contact_model';

    private $_idname = $_plural . "Id";

    function a($$_idname = 0) {

    }
}

These two lines:
private $_idname = $_plural . "Id";

and
function a ($$_idname = 0) {

aren't working. Why? And how can I fix this?
EDIT
About the function argument:
If $_idname = "contactId" I want the argument to be $contactId. That's why I have two dollar signs there. This might be not the correct way to handle this, but this is what I want to accomplish.

A: According to PHP's documentation, you must initialize a class attribute with a constant value:

This declaration may include an initialization, but this initialization must be a constant value--that is, it must be able to be evaluated at compile time and must not depend on run-time information in order to be evaluated.

A fix for this would be using a class constructor:
function __construct() {
    $this->_idname = $this->_plural . "Id";
}

Also, you can't use dynamic variable names on functions or methods:

Please note that variable variables cannot be used with PHP's Superglobal arrays within functions or class methods. The variable $this is also a special variable that cannot be referenced dynamically.

A: You could change
private $_idname = $_plural . "Id";

to
private $_idname;
public function __construct(){
  $this->_idname = $this->_plural.'Id';
}

first.
Not seeing enough in function a. Probably more like:
public function a($really = 'What is the point of those underscores?'){
  ${$this->_idname} = $really; // local $contacts var holds $really
}

I'm really guessing that you want to have a method that will automatically change your instantiated Object property. You don't need a variable variable for that. If you want to affect a variable which you are passing as an argument it's &$yourVar. There is no need to pass a property of an instantiated Object to its own method, since you already have access to it within the method with $this->yourVar.


text:
Q: Cómo podría adaptar los selectores de este Modal para poder apuntar a varias imágenes de una misma página? He encontrado este Modal propuesto por la W3C y parece una solución sencilla; pero está pensada para utilizarlo en una imagen por página, ya que los selectores son IDs. He probado a cambiar a clases y cambiar el selector, pero sigue sin funcionar.
https://www.w3schools.com/howto/tryit.asp?filename=tryhow_css_modal_img
Habría 3 o 4 imágenes por página que me gustaría que se pudieran ampliar. Las imágenes se meterían directamente desde el HTML, o sea que se podría cambiar una cifra a cada clase para cada imagen de forma sencilla.
Como apunte: Habeís podido observar que mi nivel de Javascript es mínimo. Así que, por favor, intentad no ser demasiado técnicos en la explicación. En cuanto al HTML, CSS, selectores, etc ningún problema.
Gracias de antemano.

A: En realidad es muy sencillo con jquery, mira el ejemplo:

// Get the modal
var modal = document.getElementById('myModal');

// Get the image and insert it inside the modal - use its "alt" text as a caption
var img = document.getElementById('myImg');
//var modalImg = document.getElementById("img01");
var captionText = document.getElementById("caption");
$("img").click(function(){
    //modal.style.display = "block";
    $("#myModal").css("display","block");
    $("#img01").attr("src",$(this).attr('src'));
    $("#caption").text( $(this).attr('alt'));

    //console.log($(this).attr('src'));
});

// Get the  element that closes the modal
var span = document.getElementsByClassName("close")[0];

// When the user clicks on  (x), close the modal
span.onclick = function() {
    modal.style.display = "none";
}
img {
   border-radius: 5px;
    cursor: pointer;
    transition: 0.3s;
}

img:hover {opacity: 0.7;}

/* The Modal (background) */
.modal {
    display: none; /* Hidden by default */
    position: fixed; /* Stay in place */
    z-index: 1; /* Sit on top */
    padding-top: 100px; /* Location of the box */
    left: 0;
    top: 0;
    width: 100%; /* Full width */
    height: 100%; /* Full height */
    overflow: auto; /* Enable scroll if needed */
    background-color: rgb(0,0,0); /* Fallback color */
    background-color: rgba(0,0,0,0.9); /* Black w/ opacity */
}

/* Modal Content (image) */
.modal-content {
    margin: auto;
    display: block;
    width: 80%;
    max-width: 700px;
}

/* Caption of Modal Image */
#caption {
    margin: auto;
    display: block;
    width: 80%;
    max-width: 700px;
    text-align: center;
    color: #ccc;
    padding: 10px 0;
    height: 150px;
}

/* Add Animation */
.modal-content, #caption {
    -webkit-animation-name: zoom;
    -webkit-animation-duration: 0.6s;
    animation-name: zoom;
    animation-duration: 0.6s;
}

@-webkit-keyframes zoom {
    from {-webkit-transform:scale(0)}
    to {-webkit-transform:scale(1)}
}

@keyframes zoom {
    from {transform:scale(0)}
    to {transform:scale(1)}
}

/* The Close Button */
.close {
    position: absolute;
    top: 15px;
    right: 35px;
    color: #f1f1f1;
    font-size: 40px;
    font-weight: bold;
    transition: 0.3s;
}

.close:hover,
.close:focus {
    color: #bbb;
    text-decoration: none;
    cursor: pointer;
}

/* 100% Image Width on Smaller Screens */
@media only screen and (max-width: 700px){
    .modal-content {
        width: 100%;
    }
}

<!DOCTYPE html>

Image Modal

In this example, we use CSS to create a modal (dialog box) that is hidden by default.

We use JavaScript to trigger the modal and to display the current image inside the modal when it is clicked on. Also note that we use the value from the image's "alt" attribute as an image caption text inside the modal.

  ×

Lo que hace el código es:
 $("img").click(function(){//Asigna el click a TODAS LAS imagenes de la pagina
        //modal.style.display = "block";
        $("#myModal").css("display","block");//Muestro el modal
        $("#img01").attr("src",$(this).attr('src'));//Paso la imagen al modal
        $("#caption").text( $(this).attr('alt'));//Paso la informacion al caption

        //console.log($(this).attr('src'));
    });

A: Antes de hacer un manejo tan en crudo del DOM en HTML recomendaría usar algo como JQuery para que no sea tan engorroso el manejo.
La idea de la solución es en ves de utilizar ID que son único, seleccionar todas las imágenes de la galería por un selector de clase, o agregarle un evento OnClick en base a ello la siguiente solución es mas sencilla.
Te dejo un ejemplo funcional del mismo

function mostrarModal(obj) {
  var imgSrc = $(obj).attr('src');
  $("#img01").attr('src', imgSrc);
  $("#myModal").show();
}

function ocultarModal() {
    $("#myModal").hide();
}
.image {
    border-radius: 5px;
    cursor: pointer;
    transition: 0.3s;
}

.image:hover {opacity: 0.7;}

/* The Modal (background) */
.modal {
    display: none; /* Hidden by default */
    position: fixed; /* Stay in place */
    z-index: 1; /* Sit on top */
    padding-top: 100px; /* Location of the box */
    left: 0;
    top: 0;
    width: 100%; /* Full width */
    height: 100%; /* Full height */
    overflow: auto; /* Enable scroll if needed */
    background-color: rgb(0,0,0); /* Fallback color */
    background-color: rgba(0,0,0,0.9); /* Black w/ opacity */
}

/* Modal Content (image) */
.modal-content {
    margin: auto;
    display: block;
    width: 80%;
    max-width: 700px;
}

/* Caption of Modal Image */
#caption {
    margin: auto;
    display: block;
    width: 80%;
    max-width: 700px;
    text-align: center;
    color: #ccc;
    padding: 10px 0;
    height: 150px;
}

/* Add Animation */
.modal-content, #caption {
    -webkit-animation-name: zoom;
    -webkit-animation-duration: 0.6s;
    animation-name: zoom;
    animation-duration: 0.6s;
}

@-webkit-keyframes zoom {
    from {-webkit-transform:scale(0)}
    to {-webkit-transform:scale(1)}
}

@keyframes zoom {
    from {transform:scale(0)}
    to {transform:scale(1)}
}

/* The Close Button */
.close {
    position: absolute;
    top: 15px;
    right: 35px;
    color: #f1f1f1;
    font-size: 40px;
    font-weight: bold;
    transition: 0.3s;
}

.close:hover,
.close:focus {
    color: #bbb;
    text-decoration: none;
    cursor: pointer;
}

/* 100% Image Width on Smaller Screens */
@media only screen and (max-width: 700px){
    .modal-content {
        width: 100%;
    }
}

  ×

A: Sin jquery, ocupando tu mismo código.
No encuentro engorroso usar javascript y lo menos de librerías posible, aunque ya es como cada uno se acomode mejor.
En CSS, cambié la consulta al modal a id pues es único para todas las imágenes que quieras. Y el de la imagen la cambié a class para indicar que pueden ser varias imágenes a seleccionar en el mismo archivo.
Agregué una lista de ids de imagen, pero puede reemplazarse por una búsqueda de clase, solo que no se me ocurrió en ese momento.
Incluí las cuatro imágenes de donde viene la que usaste en tu ejemplo.
Te dejo el link para ver la solución en TryIt de W3Schools
Usé la misma estructura de tu código, pero como muchos, te recomiendo que uses archivos independientes para estilo y scripts.


text:
Q: Create an array made of imported arrays I have stored multiple arrays in an archive.py file, which will increase in number as I add more arrays.
#in archive.py

array1 = [a, b, c]
array2 = [x, y, z]
array3 = [1, 2, 3]

In my main.py file, I want a for loop that calls a function with each array in archive.py as argument per iteration.
To do that, I would like to import archive.py, and then create a container array in main.py which contains all the arrays in archive. How do I do that?
# in main.py
import archive

container = []

for x in archive:
    container.append(x)

This one does not seem to work, as 'archive' does not seem to be iterable.

A: Method 1
Use inspect.getmembers:
# main.py

from inspect import getmembers
import archive

arrays = [value for name, value in getmembers(archive) if not name.startswith("_")]

Explanation
getmembers(archive) will return all the members of archive in a list of (name, value) pairs:
# getmembers(archive)
[
    ("__builtins__", ...),
    ("__cached__", ...),
    ("__doc__", None),
    ("__file__", ...),
    ("__loader__", ...),
    ("__name__", "archive"),
    ("__package__", ""),
    ("__spec__", ...),
    ("array1", ["a", "b", "c"]),
    ("array2", ["x", "y", "z"]),
    ("array3", [1, 2, 3]),
]

The names beginning with an _ should not be imported, so we use not name.startswith("_") as a filter:
# [(name, value) for name, value in getmembers(archive) if not name.startswith("_")]
[
    ("array1", ["a", "b", "c"]),
    ("array2", ["x", "y", "z"]),
    ("array3", [1, 2, 3]),
]

We need only the values:
# [value for name, value in getmembers(archive) if not name.startswith("_")]
[
    ["a", "b", "c"],
    ["x", "y", "z"],
    [1, 2, 3],
]

Method 2
Define arrays in archive.py:
# archive.py

arrays = [
    ["a", "b", "c"],  # array1
    ["x", "y", "z"],  # array2
    [1, 2, 3],  # array3
]

# main.py

from archive import arrays


text:
Q: BotFramework User's Culture from IEventActivity I am trying to figure out how to get user's culture from my chatbot during the OnEventActivityAsync. Our webchat posts an activity that would trigger welcome message from the bot. This welcome message must come in user's language.
Ordinarily, we would look at IMessageActivity locale attribute.
IMessageActivity msg = context.Activity.AsMessageActivity();
string locale = msg.Locale;

However, in the OnEventActivityAsync the parameter is of type IEventActivity, and it does not have locale attribute. Any ideas on how to get culture in OnEventActivityAsync?

A: The BotFramework-WebChat 04.api/a.welcome-event sample demonstrates sending the user's language (locale) as the event value.
const store = window.WebChat.createStore({}, ({ dispatch }) => next => action => {
  if (action.type === 'DIRECT_LINE/CONNECT_FULFILLED') {
  // When we receive DIRECT_LINE/CONNECT_FULFILLED action, we will send an event activity using WEB_CHAT/SEND_EVENT
    dispatch({
      type: 'WEB_CHAT/SEND_EVENT',
      payload: {
        name: 'webchat/join',
        value: { language: window.navigator.language }
      }
    });
  }

  return next(action);
});

If you read the event value first, setting the locale to be used, then you will be able to send the welcome message in the user's language, as desired.
Hope of help!


text:
Q: Repeating partitioner steps causing huge performance delay Below is my job flow.
Step 1 : Download large files – more than 5 GB
Step 2 :Split file in small file
Step 3 : process file – process split files using partitioner and taskExecutor
Repeat step 1 to 3  till some condition is satisfied – normally  more than 10k repetitions
When batch start performances is very good. But as time progress  performances degrades.
Note – processing of data is not bottleneck
I am suspecting  Repeating partitioner steps is creating new threads for each repetition.
Below are my config
@Bean
public Job myjob(JobBuilderFactory jobs) throws Exception {
    return jobs.get("myjob")
            .start(DownloadStep())
            .next(master()).on(CONTINUE_CONDITION .next(DownloadStep())
            .next(master()).on(STOP_CONDITION).to(cleanUpStep())
            .build();
}

@Bean
@StepScope
public Partitioner partitioner() {
    MultiResourcePartitioner multiResourcePartitioner = new MultiResourcePartitioner();
    ClassLoader cl = this.getClass().getClassLoader();
    ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver(cl);
    Resource[] resources = resolver.getResources("file:" some file path);
    multiResourcePartitioner.setResources(resources);
    multiResourcePartitioner.partition(10);
    return multiResourcePartitioner;
}

@Bean
public TaskExecutor taskExecutor() {
    ThreadPoolTaskExecutor taskExecutor = new ThreadPoolTaskExecutor();
    taskExecutor.setMaxPoolSize(30);
    return taskExecutor;
}

@Bean
@Qualifier("master")
public Step master() {
    return stepBuilderFactory.get("master")
            .partitioner(process())
            .partitioner("process",partitioner)
            .taskExecutor(taskExecutor())
            .build();
}

Update  As suggested by  Michael Minella  I updated Spring Batch version to 4.0.0.RC1 But there is no improvement in performance
After 150+ repetitions batch is taking more than 15+ minutes to created partition steps. I am creating 16 partition for each file.
2017-12-05 17:00:51,660  INFO  [THREAD ID=main] XXXXXConfiguration. - Resource files: 16
2017-12-05 17:11:20,923  INFO   [THREAD ID=taskExecutor-17]  XXXProcessor. - XXXXListener beforeStep StepExecution: id=841, version=1, name=XXXStep:partition14, st
atus=STARTED, exitStatus=EXECUTING, readCount=0, filterCount=0, writeCount=0 readSkipCount=0, writeSkipCount=0, processSkipCount=0, commitCount=0, rollbackCount=0


text:
Q: How does Aion differentiate itself from Everquest? Is Aion another Everquest clone?

A: Although I haven't played recently, I played for several months after the initial release.  Aion does have some features that set it apart:

*

*Flight: all characters can "fly" from an early level.  In many places, you are only allowed to glide, and your flight time is limited (and can be increased with equipment and potions). This can still make getting around much faster, or at least more entertaining.  No mounts are required, but there are "wing" upgrades that get pretty pricey.

*Flying combat: you can fight in the air, and attack others from ground or sky.  This gets interesting when you take into account limited flight time - not only do you have to try and win the fight, but you may have to pop potions or maneuver to avoid falling to your death when your wings get tired.

*Crafting system: the addition of NPC work-orders allows you to trade money and craft time for leveling up, and there is always a work-order recipe available for your current level.  This avoids the problem of having to find a new recipe and adequate ingredients every time a certain craft skill goes up a few levels.  The system also allows any player to reach very high levels in all crafting skills, if they're persistent enough and willing to spend the money.  There is also an interesting mechanic that causes random craft attempts to create improved items (but crafting can also fail, depending on skill level).  The main downside of the crafting system is that it's very grindy.  If you want to max a skill, prepare to spend a lot of time and money.

One of the strongest aspects of Aion is the PvP gameplay.  Some things worth mentioning on that topic:

*

*Fighting in the air, as described above.

*A large, 3-level, dedicated PvP zone, essentially a bunch of floating rocks in space.

*In the PvP zone, there are several fortresses (on each level) that become attackable at semi-random times.  The two player factions can own fortresses, and a third, NPC faction (that swoops in in a giant spaceship) will sometimes attack as well.  Attacking the fortress involves coordinated groups capturing artifacts that bestow advantages, breaking down fortress defenses and killing NPC defenders, and finally defeating a powerful boss to complete the capture.  The faction that captures a fortress gets to use the NPCs there and the dungeon.  When I was playing, there were some lag problems due to the quantity of players participating, but this may have improved since then.  Even with the lag, it was still a lot of fun.

*A PvP currency used for buying PvP equipment and consumables.  This can be gained from defeating enemy players (anywhere) and completing quests and killing monsters in the PvP zone.

*Portals: Each faction has several zones geared more toward PvE and leveling, and these are mostly separated.  However, portals appear randomly, but pretty frequently, and these allow players to cross over to the enemy zones and attack.  There are a few quests that specifically require the player to go through portals and mess around with the opposing side.  Personally, I found this mechanic more interesting than just having shared zones where the factions clash (although that is also present in the PvP zone.

Overall, Aion had some interesting features, and I felt like it did stand out from the crowd more than most games.  Castle defense/capture is a great mechanic, and I had missed it from my days playing Ragnarok Online.
What ultimately caused me to stop playing was the level grind.  Like many (most?) games originally from Asia, grinding monsters is the main activity, and leveling is pretty slow.  There are quests, but the effort to reward ratios get pretty unimpressive as you get closer to the level cap.  The PvP zone was fun, but not fast leveling.  Organized dungeon raids may be the way to go, I never really got into that while I was playing.  I have also seen announcements that say the exp grind has been improved, so my info may be out of date.


text:
Q: Cache Angular Component I have two angular components. The first component has a list with picture items requested from a server. When the user selects one picture he is forwarded to the second page, the detail view, where more information is displayed. Now when he is hitting the browser's back button component 1 loads again and fires some heavy request for getting the pictures.
Is there a way I can cache component 1 so when the user hits the browser's back button component 1 is restored and the server request are not sendend again? I have read about Angular Route Reuse Strategy but I guess this applies not for browser navigation?

A: Just store the items in a variable inside a service


text:
Q: Why my multi thread execution is single threaded mode package indi.JavaLearn;

public class MultiThread {
    private static int shared;
    public static void main(String[] args) {
        for (int i = 0; i < 5; i++) {
            (new Thread() {
                public void run() {
                    write2();
                }
            }).start();
        }
    }
    public synchronized static void write2() {
        int i = 0;
        while (i < 2) {
            shared++;
            System.out.println("write," + Thread.currentThread().getId() + "," + String.valueOf(shared));
            i++;
        }
    }
}

Result
write,12,1
write,12,2
write,15,3
write,15,4
write,16,5
write,16,6
write,14,7
write,14,8
write,13,9
write,13,10

A: The synchronized modifier in write2 allows the method to only be run by one thread at a time - you need to remove it for it to be run on multiple threads at the same time.
If what you actually want to do is lock the shared variable, use a synchronized block:
synchronized(shared){
  shared++;
  System.out.println("write," + Thread.currentThread().getId() + "," + String.valueOf(shared));
}

A: public synchronized static void write2() is a static synchronized method implies lock/monitor is maintained at Class level instead of Object level.
static synchronized methods are synchronized on the Class object. If one thread is executing a static synchronized method, all other threads trying to execute any static synchronized methods will be blocked unless the lock is released by locked thread.
Non-static synchronized methods synchronize on this(means Object, which is an instance of the class). If one thread is executing a synchronized method, all other threads trying to execute any synchronized methods on that Object (but not the class) will be blocked.
Have a look at related SE questions:
Static versus non-static lock object in synchronized block
What is the difference between synchronized and static synchronized?
You can find good documentation about the concepts at this link

You might wonder what happens when a static synchronized method is invoked, since a static method is associated with a class, not an object. In this case, the thread acquires the intrinsic lock for the Class object associated with the class. Thus access to class's static fields is controlled by a lock that's distinct from the lock for any instance of the class.

A: You should read about concurrency in Java, specifically what the synchronized keyword means.
Now, on to what is going on with your code ...
When one thread (ex. the thread with the id 12) calls the write2() method it obtains a lock (mutex) on the object. Then it performs the code within the method body (i.e. the loop and print statement). Finally, it releases the lock on the object to allow another thread that is waiting to perform the method. Therefore, you always see the print statements occurring in segments of two.


text:
Q: Delphi XE8 error FMX.ListView I'm trying delphi XE 8 and I found that if I declare to use the library FMX.ListView gives me error (no load) when run on the iOS simulator. I have updated to the latest version XCode.
no problem:
   unit Unit2;

  interface

  uses
    System.SysUtils, System.Types, System.UITypes, System.Classes, System.Variants,
    FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs;

 type
  TForm2 = class(TForm)
  private
   { Private declarations }
  public
   { Public declarations }
 end;

var
 Form2: TForm2;

 implementation

{$R *.fmx}

end.

error:
 unit Unit2;

 interface

uses
 System.SysUtils, System.Types, System.UITypes, System.Classes,  System.Variants,
 FMX.Types, FMX.Controls, FMX.Forms, FMX.Graphics, FMX.Dialogs, FMX.ListView;

type
 TForm2 = class(TForm)
  private
   { Private declarations }
  public
   { Public declarations }
 end;

var
 Form2: TForm2;

implementation

{$R *.fmx}

 end.

Does it happen to someone else this error?


text:
Q: is there any way to iterate two lists parallely in sightly? Consider this code in java
for(int i=0,j=0;i<list1.size() && j<list2.size();i++,j++){

//do something

}

Can we do the similar thing in sightly? I tried best on my level but I couldn't find a way to do it. Please help on this.

A: There is no support for this kind of iteration and this is intended (in order to avoid putting your business logic in the HTL/Sightly template). You should instead invoke an Use-Api object which applies this logic and returns a collection of tuples from the two lists.

A: Adding to the answer posted by Vlad, You could either use

*

*Sling Models

*WCMUse class

*server side javascript to perform such business logic

I would say it is better to use nodejs for such simple problems as it is more productive, easy to write and lives in the same folder as the sightly/HTL code.
For example, if your component name is 'componentA'
your HTL/sightly code is componentA.html residing inside componentA folder
and your business logic can be componentA.js residing in the same folder.
use(function() {
    /*
        Business logic
    */
    return {
        name: valueName,
        list: listObject
    };
});

Sling Models are very effective when you need to perform business logic using injected properties and resources. For example, a component that has several primitive and derived (from resource) properties.


text:
Q: How to connect to an ftp server from a web site? I would need to connect to my FTP server from my website. I'll explain. What I need is for my website to show a login form with username and password to the FTP server and when you log in it will automatically show the content of it. Something similar to what browsers do when you enter ftp:\name servers that ask you for username and password and show the contents of the server.

A: There would be a lot of work involved to do this from scratch, your best bet would be to use a package like https://github.com/Nicolab/php-ftp-client


text:
Q: greatest-n-per-group comparing geometry Postgis I'm working on a query that I think could fit under the greatest-n-per-group category.
So here's a simplified version of the table:

So these are samples taken with a ~10 year span. So I have the exact same geometry stored in two or more rows.
I'd like to fetch only one row for each unique geometry, and the hard part is that I only want the latest taken samples (according to year column) and the data on that row.
I have tried something like this:
SELECT *
 FROM samples s
 INNER JOIN (
SELECT geom, MAX(year) as year
FROM samples
GROUP BY geom
) b ON ST_EQUALS(s.geom, b.geom) AND s.year = b.year

WHERE customer_id = 38330
ORDER BY provnr ASC;

This seems to give me a pretty good result, but it takes a lot of time. This specific customer has ~850 rows in a table of ~400k rows. That query takes about 7 seconds.
I have the geom and year columns indexed.
Is there a better way to write the query?
The query will be used in a real time app, so 7 seconds is way to long.
Really thankful for your'e help!

A: I would say that it is the order of the filtering that is causing the issues.  It would appear that you are doing a GROUP BY geom over the entire table before filtering to the customer.  This may also cause other issues if other customers have a geometry at that point as well.
Another performance issue may be that you are joining the reduced group back onto samples using year and geom.  I can't imagine this using indexes.
Assuming that there is a primary key type field or some unique identifier on the samples table I would use that against a sub query.  The subquery makes use of the first_value windowed function to return the IDs of the latest years for a geom.
SELECT *
FROM SAMPLES
WHERE ID IN (
    SELECT FIRST_VALUE(ID) OVER (PARTITION BY GEOM ORDER BY YEAR DESC) ID
    FROM SAMPLES
    WHERE CUSTOMER = 38330
    )
ORDER BY PROVNR ASC;


text:
Q: Why does this always result in try? Im writing this java code for school.  I need to see if the data is a palindrome or not and then let the user know the results.  My eyes are bleeding.  I can't figure this out!
import javax.swing.JOptionPane;
import helpers.*;

public class Palindrome {
    public static boolean check(String dataInput) {
        boolean test = false;
        String reverseDataInput = new StringBuffer(dataInput).reverse().toString();
        if (dataInput == reverseDataInput){
            test=true;
            return test;
        }
        return test;
    }

    public static void main(String[] args) {

        String inputString = "";
        int number = 0;
        boolean isPalindrome = false;

        number = helpers.InputUtilities.getIntegerInput(inputString, -99999, 99999);

        String str = Integer.toString(number);
        isPalindrome = check(str);
        if (isPalindrome = true){
            JOptionPane.showMessageDialog(null, str + " is a palindrome!", "Area", JOptionPane.PLAIN_MESSAGE);
        }
        else {
            JOptionPane.showMessageDialog(null, str + " is not a palindrome!", "Area", JOptionPane.PLAIN_MESSAGE);
        }
    }
}

A: First java Strings are compared with .equals() not == because they are objects (see this).
if (dataInput.equals(reverseDataInput))

Second your if statement is a bit wrong.
if (isPalindrome = true){

Instead
if (isPalindrome == true){

or (this looks better to some people)
if (isPalindrome){

A: I've seen this question before (here: Local variable not used).
The problem is simply the if: statement. Replace
if (isPalindrome = true)

with
if (isPalindrome)

You also need to modify your first if:
if (dataInput == reverseDataInput)

by
if (dataInput.equals(reverseDataInput))

Because == checks for pointer equality and since you generate a new string, the two strings are not the same, they are equal, but not the same...


text:
Q: inequalities of the product of sum and difference of two terms I'm aware of the product of sum and difference of two terms but I'm poor in proving inequalities...all I can do is to verify the claim... please somebody help me...$$H(t) >\frac {t^{n–1} (1 + t)}{2}$$
$$1 - H^2(t)<[1-\frac{t^{n-1} (1+t)}{2}][1+\frac{t^{n-1} (1+t)}{2}]<  2 – t^{n-1} (1 + t)$$
How did this happen?

A: Put $a=H(t)$, $b=\frac {t^{n–1} (1 + t)}{2}$. Then we can rewrite the initial inequalities as $a>b$ and $1-a^2<(1-b)(1+b)<2-2b.$ The implication $a>b$ $\Rightarrow$ $1-a^2<(1-b)(1+b)=1-b^2$ holds, for instance, when $b\ge 0$.
The inequality $(1-b)(1+b)<2-2b$ holds for each real $b\ne 1$ because it is equivalent to an inequality $0<(b-1)^2$.


text:
Q: Question about grid and data type conversion I am making a 12* 12 grid with numbers leading the columns and rows, leftover place placed by '.'.
void creatGrid(){
    char theGrid[SizeX][SizeY];
    for(int b = 0; b<SizeY;b++){
            theGrid[0][b] = b + 0;
            for(int i =0;i<SizeX;i++){
                if(b==0){
                    char t = i+0;
                    theGrid[i][b] = t;
                }else if(i==0){
                    char e = b+0;
                    theGrid[i][b] = e;
                }else{
                    theGrid[i][b] = '.';
                }
            }
        }
    for(int i = 0;i<SizeY;i++){
        for(int a =0; a<SizeX;a++){
            printf("%c ",theGrid[a][i]);
        }
        printf("\n");
    }
}

I am using a char-type two-dimensional array to create the grid, I convert the int to char by adding 0 behind them, but it is not working as the output is gibberish at the position of int.


text:
Q: Quitar el simbolo € de NumberFormat JavaScript estoy formateando la moneda, pero quisiera que no me imprimiese el simbolo €.
const formatterEuro = new Intl.NumberFormat('de-DE', {
  style: 'currency',
  currency: 'EUR'
})

Es posible quitarlo??
Estoy probando así:
let ofertaFormateado = formatterEuro.format(data.oferta);
var ofertaFormat = ofertaFormateado.replace(/[€]/g,'');

Me quita el simbolo € pero deja el espacio en blanco que hay entre el importe y el simbolo, al sacar el valor console.log me devuelve esto 1,50

A: Una forma que funciona pero quizá un poco enrevesada sería:

const formatterEuro = new Intl.NumberFormat('de-DE', {
  style: 'currency',
  currency: 'EUR'
});

const amount = formatterEuro.formatToParts(232).filter((p) => p.type !== 'currency').map((p) => p.value).join('').trim();

console.log(amount);

EDITADO:
La solución que estás utilizando sólo funcionaría con € y la lista de posibles monedas puede ser grande. La solución que te propongo funcionaría con cualquier moneda.
Si aun así prefieres hacerlo como dices simplemente bastaría con que añadas un espacio a la expresión regular del replace (fíjate que he añadido un espacio):
var ofertaFormat = ofertaFormateado.replace(/ [€]/g,'');

A: Si solo necesitas el número formateado en el idioma sin agregar el símbolo de la moneda, entonces podrías hacerlo así:

const formatterEuro = new Intl.NumberFormat('de-DE', {
  style: 'decimal',
  minimumFractionDigits: 2,
  maximumFractionDigits: 2
});

console.log(formatterEuro.format(232));
console.log(formatterEuro.format(1.5));
console.log(formatterEuro.format(1.126));

A: solamente necitas usar el siguiente código después de tu variable
.replace('€' , '')

quedaria así
let laVariableConNumero = 654554

        const formatterEuro = new Intl.NumberFormat('en.US', {
      style: 'currency',
      currency: 'USD'
    }).format(laVariableConNumero).replace('$' , '');

console.log(formatterEuro )


text:
Q: One or more of the items in this list is not Comparable error when sorting I am trying to sort a wrapper class list. But I am getting an error of "One or more of the items in this list is not Comparable".  My sorting function is right and there is no issue but    not understanding how this error coming. Any help is appreciated.
public Integer compareTo(Object compareTo)
         {
                 importantWrapper appdata = (importantWrapper) compareTo;
                 if (   this.duedateSorter  ==   appdata.duedateSorter   )
                 {
                    if( this.cardType  ==   appdata.cardType )
                    return 0;
                    else
                    {
                          if (  this.cardType   >   appdata.cardType  )
                          return 1;
                          return -1;
                    }
                 }

                 if (  this.duedateSorter   >   appdata.duedateSorter  )
                  return 1;
                  return -1;
         }

A: This error occurs because one or more of them items in your list is not comparable (a key requirement for the sort feature). It is likely an instance of an Apex Class of your own or someone else's creation does not implement the Comparable interface. Or one of the Apex system classes that don't support it. Fortunatly you can implement this interface yourself and/or wrap the unsupported type.
Without being able to compare items being sorted the platform cannot perform the sorting for you and gives this error. Some but not all of the standard Apex classes support this, so you may not have encountered this until now. Take a look at the documentation for the sort method.

Using this method, you can sort primitive types, SelectOption elements, and sObjects (standard objects and custom objects). For more information on the sort order used for sObjects, see Sorting Lists of sObjects. You can also sort custom types (your Apex classes) if they implement the Comparable Interface interface.

This topic provides a good example of implementing this interface....
public class Employee implements Comparable {

    public Long id;
    public String name;
    public String phone;

    // Constructor
    public Employee(Long i, String n, String p) {
        id = i;
        name = n;
        phone = p;
    }

    // Implement the compareTo() method
    public Integer compareTo(Object compareTo) {
        Employee compareToEmp = (Employee)compareTo;
        if (id == compareToEmp.id) return 0;
        if (id > compareToEmp.id) return 1;
        return -1;
    }
}

NOTE: global is not required, i've changed my copy of the code above to use public.

A: I know its not the answer to this issue, but I ran into the same error and found out that "Comparable" need to be on the class implementation and not only on the Interface.
You can't do this:
public interface IEmployee extends Comparable {}

public class Employee implements IEmployee {
  public Integer compareTo(Object compareTo) {...}
}

But you need to do this:
public interface IEmployee {}

public class Employee implements IEmployee, Comparable {
  public Integer compareTo(Object compareTo) {...}
}

A: I have this error
One or more of the items in this list is not Comparable.

when I had actually all the items in the list implementing Comparable interface. However, in some cases the compare function wasn't returning 1, -1 or 0.
So we need implement the Comparable interface method in such a way that it always return at least 0.


text:
Q: Postgresql, hibernate "is not distinct" Is there easy way to write is not distinct using CriteriaBuilder without Disjunction?
SQL condition
where field1 is not distinct from field2

A: I found the solution as creating own function which will check 2 fields using native is not distinct.
Then I could use my function in CriteriaBuilder via method function.