text:
Q: How and when should I use variable/method declaration? I'm learning scala and I don't know how and when to use variable/method declaration in scala.
Here's the scala syntax about declaration and definition: https://www.scala-lang.org/files/archive/spec/2.11/04-basic-declarations-and-definitions.html
It show that:
Dcl         ::=  'val' ValDcl
              |  'var' VarDcl
              |  'def' FunDcl
              |  'type' {nl} TypeDcl
PatVarDef   ::=  'val' PatDef
              |  'var' VarDef
Def         ::=  PatVarDef
              |  'def' FunDef
              |  'type' {nl} TypeDef
              |  TmplDef

For example, this is declaration for variable x and method hello:
var x: Int;

class Tester {
  def hello(var x:Int):Int
}

And this is definition for variable x and method hello:
var x: Int = 1
class Tester {
  def hello(var x:Int): Int = x
}

If I want to write some application with scala, it seems that all I need is definition, I don't know how and when should I use a declaration.
Does declaration is just equal to interface ?
Please educate me.

A: In Scala, declarations are (in my experience) used for two main usages :

*

*method and variable type definitions in interfaces (whether it be traits or abstract classes)

*type "aliasing" for code clarity. This can take the form of either aliasing a single type (type UserId = Int ) or aliasing a cake of type (type Codec = Serializer with Deserializer)

As you may have noticed, you can't have variables or methods declarations in non abstract classes, since you can't have undefined behaviours at runtime. Undefined here accurately meaning "not having a definition" per the scala language meaning of definition.
So, I wouldn't say that all you need are definitions to write Scala code, since declarations are pretty useful. However, for each declaration, you'll need at least one definition to make it useful !

A:
If I want to write some application with scala, it seems that all I need is definition

It is possible to write a definition out of pure declarations. For example consider
trait Iterator[+A] {
  def hasNext: Boolean
  def next(): A
  def nextOption(): Option[A] = if (hasNext) Some(next()) else None
}

Here nextOption is defined in terms of hasNext and next even though the latter two are not defined at this point in time. Certainly, at the point when we run the program all declarations will need to be linked with fleshed out objects, but at compile-time we can proceed with writing a program even when sometimes we do not have all the details.


text:
Q: How to crop a center square in a UIImage? Sorry about this question, but I searched a lot of threads here in S.O. and I found nothing.
The question is: how to crop a center square in a UIImage?
I tried the code bellow but without success. The cropping happens, but in the upper-left corner.
-(UIImage*)imageCrop:(UIImage*)original
{
    UIImage *ret = nil;

    // This calculates the crop area.

    float originalWidth  = original.size.width;
    float originalHeight = original.size.height;

    float edge = fminf(originalWidth, originalHeight);

    float posX = (originalWidth   - edge) / 2.0f;
    float posY = (originalHeight  - edge) / 2.0f;

    CGRect cropSquare = CGRectMake(posX, posY,
                                   edge, edge);

    // This performs the image cropping.

    CGImageRef imageRef = CGImageCreateWithImageInRect([original CGImage], cropSquare);

    ret = [UIImage imageWithCGImage:imageRef
                              scale:original.scale
                        orientation:original.imageOrientation];

    CGImageRelease(imageRef);

    return ret;
}

A: Adding more information, I'm using this 'crop' after a photo capture.
After some tests, I found something that worked.
// If orientation indicates a change to portrait.
if(original.imageOrientation == UIImageOrientationLeft ||
   original.imageOrientation == UIImageOrientationRight)
{
    cropSquare = CGRectMake(posY, posX,
                            edge, edge);

}
else
{
    cropSquare = CGRectMake(posX, posY,
                            edge, edge);
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Blur page background on button Click I have been looking for a solution that will blur the CSS3 background I have in place when the user clicks a button.
At the moment the HTML is as so:

Start Now

And the CSS is:
html, body { margin:0px; padding: 0px; background: url(../assets/background.png) no-repeat center center fixed;  -webkit-background-size: cover; -moz-background-size: cover;  -o-background-size: cover; background-size: cover;}

.button {
    vertical-align: middle;
    width:150px;
    margin: 0 auto;
    margin-top:200px;
    background-color:#81DF7B;
    padding:10px;
    border-radius: 5px;
    text-decoration: none;
    color:#333;
    font-weight:300;
    font-size: 1.3em;
    -webkit-transition: background-color 0.3s ease-in-out 0s;
    -moz-transition: background-color 0.3s ease-in-out 0s;
    -o-transition: background-color 0.3s ease-in-out 0s;
    -ms-transition: background-color 0.3s ease-in-out 0s;
    transition: background-color 0.3s ease-in-out 0s;
}

.button:hover{
    background-color: #00CC33;
    cursor:pointer;
}

.button li {padding:20px; text-align:center; text-decoration: none; list-style: none; }
.button li a {text-decoration: none;}

As you can see the background image is attached to html and body as a CSS3 cover image.
What I would like is when the user clicks on the 'Start Now' button this background transitions smoothly to a blur so that hidden form fields can appear over the top clearly.
I have been looking at blur.js and Jquery blur but can't work out the best way to implement this.
Any advice would be much appreciated :)

A: you could implement css such as this for an onclick event for that button.
.background {

-webkit-filter: blur(10px);

filter: blur(10px);

}


text:
Q: Why do young witches & wizards know Voldemort's name?
*

*There is a taboo against speaking 'Voldemort' at the beginning of Book One (not the Taboo placed by the Ministry in Book Seven).

*Every student Harry meets gasps at Harry's audacity in saying 'Voldemort' instead of You-know-who.

*Point 2 means somebody told them the name, most likely their parents.

*Point 3 means there is no taboo.

Is it because logic is a branch of mathematics, and maths and JKRmagic don't mix well?
If wizarding parents were so afraid of Voldemort's memory to avoid mentioning him by name, why would they tell the name to their kids and then forbid them from using it? Makes as much sense as parents forcing children to learn the whole obscene vocabulary at the age of six, and then telling them not to use swearwords.

A: The Taboo was placed after the ministry fell in book seven. Before that there was nothing preventing people from saying the name, save general superstition.

Now they've put a Taboo on it, anyone who says it is  trackable  —  quick-and-easy way  to find Order members!  They nearly  got Kingsley —"
(Harry Potter and the Deathly Hallows - Chapter 20)

To quote Richard, We can assume that children would learn about "Voldemort" the same way they learn other "unspeakable words" such as swearwords and racial epithets.

By hearing them said by those who don't care about the consequences, by reading them in books and literature aimed at adults and by hearing them spoken by adults when they don't think children are listening.

A: First, the Taboo (as opposed to a taboo) did not exist until Book 7

"Sorry." said Ron, wrenching Harry back out of the brambles, "but the
name's been jinxed. Harry, that's how they track people! Using his
name breaks protective enchantments, it causes some kind of magical
disturbance—it's how they found us in Tottenham Court Road!"

We see that the name has been jinxed; this is a new development. The opposite would not make any sense: why would the pre-Voldemort Ministry be interested in catching people who said Voldemort's name? Voldemort, on the other hand, knows that only those who stand up to him use his name as a matter of course:

"You've got to give them credit, it makes sense. It was only people who
were serious about standing up to him like Dumbledore, who ever dared
use it. Now they've put a Taboo on it, anyone who says it is
trackable—quick-and-easy way to find Order members!"

We also see that Hagrid is willing to say the name if necessary

He sat down, stared into the fire for a few seconds, and then said,
"It begins, I suppose, with -- with a person called -- but it's
incredible yeh don't know his name, everyone in our world knows --"
"Who? "
"Well -- I don' like sayin' the name if I can help it. No one does."
"Why not?" "Gulpin' gargoyles, Harry, people are still scared. Blimey,
this is difficult. See, there was this wizard who went... bad. As bad
as you could go. Worse. Worse than worse. His name was..."
Hagrid gulped, but no words came out.
"Could you write it down?" Harry
suggested.
"Nah -can't spell it. All right -- Voldemort. " Hagrid
shuddered. "Don' make me say it again. Anyway, this -- this wizard,
about twenty years ago now, started lookin' fer followers. Got 'em,
too -- some were afraid, some just wanted a bit o' his power, 'cause
he was gettin' himself power, all right. Dark days, Harry. Didn't know
who ter trust, didn't dare get friendly with strange wizards or
witches... terrible things happened. He was takin' over. 'Course, some
stood up to him -- an' he killed 'em. Horribly. One o' the only safe
places left was Hogwarts. Reckon Dumbledore's the only one
You-Know-Who was afraid of. Didn't dare try takin' the school, not
jus' then, anyway."

I'm sure there were many other wizards, particularly when people still though Voldemort was gone, who were willing to say Voldemort's name, but simply very reluctant to do so. The setup would be very similar. Young children would wonder why, for example, their relatives were dead. (Remember that many wizarding families lost relatives in the first war in Britain). Then their parents would have to tell them, and would reluctantly hand over Voldemort's name.
Don't forget: Voldemort is a constant topic of conversation.
When a massive war happened barely a decade before, the phrase "You-Know-Who" will be on everyone's lips. Once a child has picked up a modicum of language, it would only be natural to say, "No, I don't know who." And then their parents have to explain to them in hushed voices who they are actually talking about, and not to say his name. Most people, I imagine, were not so devoted to not saying Voldemort's name that they would refuse even to whisper it to their children. I suspect that most people could write it down, to start with.
And that's really the answer: Voldemort is someone that you need to know about. People may use euphemisms, but they know his real name. It's a bit like how people often used to say "passed away" instead of died, almost uniformly, for the sake of politeness, but everyone still knew the name of death.


text:
Q: Pattern Strategy vs Switch OR How to handle a large number of different operations I want to get rid of Switch with different operations in the code. Can this be done using the Strategy pattern in this case (or is there another way?):
public interface Strategy {
    BigDecimal minus(BigDecimal a, BigDecimal b);
    BigDecimal sum(BigDecimal a, BigDecimal b);
    BigDecimal pow(BigDecimal a, int n);
}

public class Minus implements Strategy {
    public BigDecimal minus(BigDecimal a, BigDecimal b) {
        return a.subtract(b);
    }
}

public class Sum implements Strategy{
    public BigDecimal sum(BigDecimal a, BigDecimal b) {
        return a.add(b);
    }

    public BigDecimal pow(BigDecimal a, int n) {
        return a.pow(n);
    }
}

public class Calc {
    private Strategy strategy;
    private BigDecimal a;
    private BigDecimal b;
    private int n;

    public Calc(Strategy strategy, BigDecimal a, BigDecimal b, int n) {
        this.strategy = strategy;
        this.a = a;
        this.b = b;
        this.n = n;
    }

    public void calculate(String operation) {
        switch (operation) {
            case "SUM":
                strategy.sum(a, b);
                break;
            case "POW":
                strategy.pow(a, n);
                break;
            case "MINUS":
                strategy.minus(a, b);
        }
    }
}

ps: the code doesn't work, because I don't understand how to implement the Strategy interface without removing the pow method from the Sum class.

A: You have some kind of misunderstanding about the strategy pattern. Simply said, by imlementing it, you have classes, which each provides a special manifestation of a behaviour. You than select from all these possible manifestations, which one to use for your special case.
Your interface Strategy - lets better name it TwoParamOperation would then look somehow like this:
public interface TwoParamOperation {
    BigDecimal compute(BigDecimal operand1, BigDecimal operand2);
}

Your actual implementations oft it might be:
public class Minus implements TwoParamOperation{
    @Override
    public BigDecimal compute(BigDecimal operand1, BigDecimal operand2) {
        return operand1.subtract(operand2);
    }
}

public class Pow implements TwoParamOperation{
    @Override
    public BigDecimal compute(BigDecimal operand1, BigDecimal operand2) {
        return operand1.pow(operand2.intValue());
    }
}

Then you have to implement a mechanism to select from these strategies. You could simply have a map whith the operation name as key and the instance of the strategy as value:
public class Calc {
private Map<String,TwoParamOperation> operations = new HashMap<>();

public Calc(){
    add("MINUS", new Minus());
    add("POW", new Pow());
}

public void add(String opName,TwoParamOperation operation){
    operations.put(opName,operation);
}

    public Optional<BigDecimal> calculate(String opName, BigDecimal operand1, BigDecimal operand2){
    TwoParamOperation operation = operations.get(opName);
    if (operation!= null){
        return Optional.of(operation.compute(operand1,operand2));
    }
    return Optional.empty();
}

}
This way you can even add new operations. Removal is up to you..
By calling
Calc calc = new Calc();

BigDecimal x=calc.calculate("MINUS",BigDecimal.valueOf(2.3),BigDecimal.valueOf(42)).orElseThrow();

you get a result for your selected operation on the two parameters, if such an operation is implemented.
If you need operations with other parameters or result types you might add them as extra maps of other Interfaces.


text:
Q: [Openstack]most of service state is down after the hostname is changed. how can I fixed it Environment
       1 Controller node, 1 Computer node , 1 Block node; all OS is Centos7.2
       Openstack version is Queens
Cause:
      The hostname of all node  is local  localhost.localdomain;
      when I installed the three node above sucessfully, all service node state is up.
  After I change the hostname  of every host  that the hostname of Controller node is changed to controller, the hostame of Computer node is changed to computer1 and the hostname of Block node is change to block1 ,  service state is down.

this is the output of command


text:
Q: Android - onTouchListener with count I want the button to launch the settings activity after the third click. Right now it is not working at all. How can I do that?
((Button)findViewById(R.id.Einstellungen)).setOnTouchListener(new View.OnTouchListener() {
                int counter = 0;

                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    counter++;
                    if(counter==3) {
                        switch (event.getAction()) {
                            case MotionEvent.ACTION_DOWN: {
                                Button view = (Button) v;
                                view.getBackground().setColorFilter(0x77000000, PorterDuff.Mode.SRC_ATOP);
                                v.invalidate();
                                break;
                            }
                            case MotionEvent.ACTION_UP:
                                Intent intent = new Intent(FullscreenActivity.this, settings.class);
                                startActivity(intent);
                            case MotionEvent.ACTION_CANCEL: {
                                Button view = (Button) v;
                                view.getBackground().clearColorFilter();
                                view.invalidate();
                                break;
                            }
                        }
                    }
                    return true;
                }
            });

A: Currently counter is increased with every touch action. For example if you place your finger on the screen (+1) then you drag a bit (+2-5) then you move your finger off the screen (+1 ) now your counter is more than 3 and the if block is not reached.
I would advise you to use a click listener for that:
((Button)findViewById(R.id.Einstellungen)).setOnClickListener(new View.OnClickListener() {
    int counter = 0;
    @Override
    public void onClick(View view) {
        ++counter;
        if (counter == 3) {
            Intent intent = new Intent(FullscreenActivity.this, settings.class);
            startActivity(intent);
            // Reset the counter (if you want to)
            counter = 0;
        }
    }
});

That way you can keep the other functionality in onTouch and still be able to start the other activity after 3 clicks have been registered.
Note: remember to remove the counter logic from onTouch listener and also remove startActivity from Action_UP event.


text:
Q: Overwrite specific CSV partitions pyspark I have a spark dataframe named df, which is partitioned on the column date. I need to save on S3 this dataframe with the CSV format. When I write the dataframe, I need to delete the partitions (i.e. the dates) on S3 for which the dataframe has data to be written to. All the other partitions need to remain intact.
I saw here that this is exactly the job of the option spark.sql.sources.partitionoverwritemode set to dynamic.
However, it does not seem to work for me with CSV files.
If I use it on parquet with the following command it works perfectly:
df.write
.option("partitionOverwriteMode", "dynamic")
.partitionBy("date")
.format("parquet")
.mode("overwrite")
.save(output_dir)

But if I use it on CSV with the following command it does not work:
df.write
.option("partitionOverwriteMode", "dynamic")
.partitionBy("date")
.format("csv")
.mode("overwrite")
.save(output_dir)

Why is this the case? Any idea of how this behaviour could be implemented with CSV outputs?

A:
I need to delete the partitions (i.e. the dates) on S3 for which the dataframe has data to be written to

Assuming you have a convenient list of the dates you are processing you can use the replaceWhere option to determine the partitions to overwrite (delete and replace).
For example:
df.write
.partitionBy("date")
.option("replaceWhere", "date >= '2020-12-14' AND date <= '2020-12-15'")
.format("csv")
.mode("overwrite")
.save(output_dir)

A more dynamic way is if you have the start_date and end_date stored in variables:
start_date = "2022-01-01"
end_date = "2022-01-14"

condition = f"date >= '{start_date}' AND date <= '{end_date}'"

df.write
.partitionBy("date")
.option("replaceWhere", condition)
.format("csv")
.mode("overwrite")
.save(output_dir)

A: What Spark version do you use? For Spark <2.0.0 it may seem impossible to use partitioning along with the csv format

A: If you are not on EMR, and are using the s3a committers to safely commit work to s3, then the partitioned committer can be set to delete all data in the destination partitions before committing new work, leaving all other partitions alone.


text:
Q: New to React/jsx - How to make multiple fetch requests and edit the first with the second? im pretty new to programming and while this question is probably answered countless times on the internet, my google-fu was not strong enough to find an answer (i could understand)
So the problem is pretty simple, im making a first fetch request and it gives me data like :
id : j8zVO67rXu
Now in another fetch im getting data like :
"name":"Testcategory",
"id":"j8zVO67rXu",
Now I want to "translate" the id (j8zVO67rXu) to an actual name (Testcategory) in the return - how would I go about this ?
Sorry for the probably weird question, but im very new to all of this so im not even sure what/how to ask


text:
Q: Data disappears from master Data Extension We have a master DE that we use to select records and to manage subscription status for newsletters (a boolean True/False for each one)... we've seen records simply vanish from the master DE and we don't understand why.
We had one record today where the customer complained that they can't unsubscribe... we couldn't find the record in our master DE (which can sometimes happen - customer signs up from one address but they provide a different one) but the client sent us the email they received.
When we click on the unsubscribe link we're taken to our custom preference centre and the record is there... which is strange since we can't query the DE to find the record.  In any case, we change the boolean to FALSE and now we can see the record in the DE.
Anyone seen something like this before?


text:
Q: Android:Open iframe of WebView in Browser/YouTube App I have some JSON content of a blog which i am displaying using loadDataWithBaseURL in WebView. Many articles of this blog have embedded youtube/vimeo videos.
Currently, all the videos are played inside the webview itself.
What i want to achieve is, when the user clicks to Play the Video, he should get the popup "Complete Action Using" Browser or YouTube App. In short, i dont want the videos to be played inside the webview of app.
I found questions where everyone was trying to avoid this popup.. Dont' know why i am not getting it.
Here is my code
public class DetailFragment extends Fragment {

    String strTitle = null;
    String strURL = null;
    String strContent = null;

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {

        super.onActivityCreated(savedInstanceState);
        setHasOptionsMenu(true);
        AdView mAdView = (AdView) getView().findViewById(R.id.adView);
        AdRequest adRequest = new AdRequest.Builder().build();
        mAdView.loadAd(adRequest);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.detail_fragment, container, false);

        strTitle = getArguments().getString("title");
        strURL = getArguments().getString("url");
        strContent = getArguments().getString("content");

        String contToDisplay = "<meta http-equiv='Content-Type' content='text/html' charset='UTF-8' />" + strContent+"";

        TextView title = (TextView) view.findViewById(R.id.title);
        WebView desc = (WebView) view.findViewById(R.id.desc);

        WebSettings ws = desc.getSettings();
        ws.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
        ws.setJavaScriptEnabled(true);
        ws.setLoadWithOverviewMode(true);
        ws.setUseWideViewPort(true);
        ws.setLayoutAlgorithm(LayoutAlgorithm.SINGLE_COLUMN);

        ws.setUserAgentString("Mozilla/5.0 (Linux; U; Android 2.0; en-us; Droid Build/ESD20) AppleWebKit/530.17 (KHTML, like Gecko) Version/4.0 Mobile Safari/530.17");
        title.setText(strTitle);
        // desc.loadData(contToDisplay, "text/html; charset=UTF-8", null);
        desc.loadDataWithBaseURL("about:blank",strContent,"text/html", "UTF-8", null);

        return view;
    }
}

any solution that wold make the videos load in browser or YouTube App would help.
NOTE
The content i am displaying in webview is in HTML format with iframe as one of the elements. Here is the sample data:
"
Some text

some more text

This entire content is displayed in webview. What i want to achieve is when someone clicks on iframe, he should be prompted to complete action using that is, the person shd not be allowed to play the video in webview

A: I managed to achieve this using regex.
Here is what i did
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.detail_fragment, container, false);

    strTitle = getArguments().getString("title");
    strURL = getArguments().getString("url");
    strContent = getArguments().getString("content");

    contToDisplay = "<meta http-equiv='Content-Type' content='text/html' charset='UTF-8' />" + strContent+"";

    TextView title = (TextView) view.findViewById(R.id.title);
    TextView date = (TextView) view.findViewById(R.id.date);
    TextView authorName = (TextView) view.findViewById(R.id.auth);
   desc = (WebView) view.findViewById(R.id.desc);

    setHasOptionsMenu(true);

    WebSettings ws = desc.getSettings();
      ws.setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
    ws.setJavaScriptEnabled(true);
    ws.setLoadWithOverviewMode(true);
    ws.setUseWideViewPort(true);
    ws.setLayoutAlgorithm(LayoutAlgorithm.SINGLE_COLUMN);
    ws.setSupportMultipleWindows(true);

    ws.setUserAgentString("Mozilla/5.0 (Linux; U; Android 2.0; en-us; Droid Build/ESD20) AppleWebKit/530.17 (KHTML, like Gecko) Version/4.0 Mobile Safari/530.17");
    title.setText(strTitle);

    final String s = strContent;
    final String regex = "(?<=<iframe src=\")[^\"]*";
    final String regex2 = "<\\s*iframe[^>]*><\\s*/\\s*iframe>";
    p = Pattern.compile(regex);
    final Pattern p2 = Pattern.compile(regex2);
    m = p.matcher(s);
     m2 = p2.matcher(s);
    evaluate(s,contToDisplay,this);
    desc.loadData(value, "text/html; charset=UTF-8", null);
    return view;
   }

     String evaluate(String token,String defaultValue, DetailFragment context){
     value=null;
    Matcher matcher=p.matcher(token);
    if (matcher.find()) {
        iframeURL=matcher.group();
        String newURL = "Watch the Video Here";
        value = m2.replaceAll(newURL);
    }
    if (value == null) {
        value=defaultValue;
    }
    return value != null ? value : "";
}

Might help someone with similar issue.

A: This may help.we are loading a new url load in the correct native app.
desc.setWebViewClient(new WebViewClient() {

        @Override
        public boolean shouldOverrideUrlLoading(WebView view,
                                                String url)
        {

            return true;
        }

                });

A: desc.setWebViewClient(new WebViewClient() {

    @Override
    public boolean shouldOverrideUrlLoading(WebView view,
                                            String url)
    {
    if(url.contains("youtube.com")){
     // Could be cleverer and use a regex return
    return super.shouldOverrideUrlLoading(view, url);
                }
    return true;

            });

A: If the links are embedded in an iframe (as the title suggested) you have to set a WebChromeClient to your webview and override the onCreateWindow-method:
@Override
public boolean onCreateWindow (WebView view, boolean isDialog, boolean isUserGesture, Message resultMsg) {

    WebView targetWebView = new WebView(view.getContext());
    targetWebView.setWebViewClient(new WebViewClient(){

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            //simple url matching
            if (url.contains("youtube.com") == true) {

                Intent i = new Intent(Intent.ACTION_VIEW);
                i.setData(Uri.parse(url));
                view.getContex().startActivity(i);
            }
            view.stopLoading();
        }
    });
    WebView.WebViewTransport transport = (WebView.WebViewTransport) resultMsg.obj;
    transport.setWebView(targetWebView);
    resultMsg.sendToTarget();
    return true;
}

And at the websettings of your webview, you have to set:
settings.setSupportMultipleWindows(true);


text:
Q: Is there an alternative to negative margins for item overlaying other item in css? i have a markup like this:

Image caption

the p is an inline block.
I want the caption to overlay the image, rather than pushing the image to the left. Ususally I do this with margin-right -"x"px;, but as I don't know what width the image caption will have, I can't use this technique. Are there any good alternatives? (the text has a background color, so I cant' use block-elemnt)

A: Have you thought about absolute positioning the items inside a div which is relatively positioned?
For example, wrap the p and img in a div and add position:relative to the div then add position:absolute to the p and the img and left or right position those elements.

A: Put a div around it:

Image caption

Specify the width of the div and allow the img to be on top of the p. You can then use padding: 0 auto; on the div to center the image.

A: I would wrap the p and img in a div.

Image caption

then use the below styling:
div {
  position: relative;
  float:left;
}
p {
  position: absolute;
  top: 20px;
  left: 10px;
}

you can adjust the top and left values accordingly and also use bottom or right instead of top and left if you wish.

A: Another alternative would be to use a fixed-size div and use your image as it's background?  That way any text would be overlaid without any need to mess around with absolute and relative positioning.
Mat

A: The solutions written here were not possible for my site (although technically correct)
My solution was

    Image caption

and then
p{
    display:block;
    margin-right -100%;
}

some extra markup but hopefully it will help someone walking down the same path as I did!


text:
Q: On which topological spaces, can we give a group structure to make it a topological group? Let $X$ be a non-empty set. It is known that we can give a group structure on $X$. Now let $X$ be a non-empty topological space. Then can we give a group structure on $X$ so that it becomes a topological group w.r.t. its original topology ?

A: No, you cannot do that for all spaces $X$.
If $X$ has the structure of a topological group, it implies a lot of extra facts about it, and those give necessary conditions that $X$ should fulfill.
Some examples of such properties:

*

*If $X$ is $T_0$ it must also be $T_{3\frac{1}{2}}$ (Tychonoff). (it's uniformisable)

*$X$ is homogenous: for every $x, y \in X$ there is a homeomorphism $h:X \to X$ such that $h(x) = y$.

*$X$ does not have the fixed point property (any non-unit multiplication shows this)

*If $X$ is compact it is dyadic and thus ccc.

*If $X$ is first countable and $T_0$ it is metrisable. (Birkhoff metrisation theorem).

So e.g. $X= [0,1]^n$ cannot be made into a topological group, because of both 2 and 3. The Sorgenfrey line fails 5. The infinite cofinite topology fails 1.
So many spaces cannot have a structure of a topological group.
@orangeskid mentioned an algebraic topology reason of possible failure: $\pi_1(X)$ is Abelian when $X$ is a topological group. This makes the wedge sum of circles $S^1 \vee S^1$ another example, I believe.


text:
Q: C#.Запуск внешнего консольного приложения с сохранением его вывода в listbox Подскажите пожалуйста, как запустить консольное приложение с последующей записью его вывода в listbox. Я хочу сделать программу которая будет запускать tor Expert Bundle она запускается консолью в котором отображается лог подключения к сети tor,этот лог обновляется каждую секунду до подключения к сети и выглядит так:

Nov 12 14:19:07.686 [notice] Tor 0.4.4.5 (git-24e808e946e741d0) running on Windows 7 with Libevent 2.1.11-stable, OpenSSL 1.1.1g, Zlib 1.2.11, Liblzma N/A, and Libzstd N/A.
Nov 12 14:19:07.690 [notice] Tor can't help you if you use it wrong! Learn how to be safe at https://www.torproject.org/download/download#warning
Nov 12 14:19:07.713 [notice] Configuration file "C:\Users\User\AppData\Roaming\tor\torrc" not present, using reasonable defaults.
Nov 12 14:19:07.717 [warn] Path for GeoIPFile (<default>) is relative and will resolve to C:\Users\User\Documents\Visual Studio 2012\Projects\TorController\TorController\bin\Debug\Tor\<default>. Is this what you wanted?
Nov 12 14:19:07.717 [warn] Path for GeoIPv6File (<default>) is relative and will resolve to C:\Users\User\Documents\Visual Studio 2012\Projects\TorController\TorController\bin\Debug\Tor\<default>. Is this what you wanted?
Nov 12 14:19:07.728 [notice] Opening Socks listener on 127.0.0.1:9050
Nov 12 14:19:07.728 [notice] Opened Socks listener on 127.0.0.1:9050
Nov 12 14:19:07.000 [notice] Bootstrapped 0% (starting): Starting
Nov 12 14:19:12.000 [notice] Starting with guard context "default"
Nov 12 14:19:14.000 [notice] Bootstrapped 5% (conn): Connecting to a relay
Nov 12 14:19:14.000 [notice] Bootstrapped 10% (conn_done): Connected to a relay
Nov 12 14:19:14.000 [notice] Bootstrapped 14% (handshake): Handshaking with a relay
Nov 12 14:19:14.000 [notice] Bootstrapped 15% (handshake_done): Handshake with a relay done
Nov 12 14:19:14.000 [notice] Bootstrapped 75% (enough_dirinfo): Loaded enough directory info to build circuits
Nov 12 14:19:14.000 [notice] Bootstrapped 90% (ap_handshake_done): Handshake finished with a relay to build circuits
Nov 12 14:19:14.000 [notice] Bootstrapped 95% (circuit_create): Establishing a Tor circuit
Nov 12 14:19:14.000 [notice] Bootstrapped 100% (done): Done

Мне нужно чтобы когда я нажал в программе на кнопку подключиться к сети tor то в listbox выводился и синхронно построчно этот лог.Буду очень рад если напишите код.


text:
Q: How factorize equations in Matlab? I have some long equations, such as:

θ = -(Tq - Lα + CLβ_1- CLβ_2+ LTδ - Cβ_1 q- Cβ_2 q+ Lαρ + Lαδ - Tqy -
αρq - αqy + 2αρqy + 2CLβ_1^2 q+ 2CLβ_2^2 q- 2CLβ_1 δ- 3LTβ_1 q- LTβ_2
q+ Lαβ_1 q+ Lαβ_2 q- 2Lαρδ + 2Cβ_1 qy+ 4CLβ_1 β_2 q+ 2Lαβ_1 ρq)/(2δ +
2y + 2Lβ_1- Tq - 2δy - δ^2- y^2- LT + 4β_1^2 qy+ 2β_2^2 qy- 6Lβ_1 δ-
2Lβ_2 δ- 2β_1 qy- 2β_2 qy+ 4Lβ_1^2 δ+ 2Lβ_2^2 δ+ Lβ_1^2 q+ Lβ_2^2 q+
4LTβ_1 q+ 2LTβ_2 q+ 2Lβ_1 β_2 q- 1)

I want to factorize these equations, How I can do it?
can it be possible for the task in either MATLAB or other software?

A: I'd recommend the free and open source CAS Maxima:
which has a factor and ratsimp command. Ideally you'd use ASCII characters though, so here is just an example of how that would work:
expr: x^2 - y^2;
print(factor(expr));

Try it online!

A: First up: MATLAB can't handle Greek letters, so you'll have to use different variable names.
Yes, you can factor this with MATLAB, provided you have the Symbolic Toolbox. Use factor(), check its documentation for examples on usage.

A: The polynomial as written by flawr is irreducible, according to Maxima.  Perhaps what you mean by "factor" is something else.


text:
Q: Jquery - usar o "focusIn" como gatilho para adicionar uma classe Opa Galera! tudo bem? Estou fazendo um formulário que deve ser dividido em duas ou mais etapas... eu tive a ideia de usar uma classe ".hide", na segunda "div" e deixar ela como "display: none;" no css. ai eu coloquei uma outra classe com "display: block;" a minha ideia, foi colocar um gatilho no último campo da primeira div, para quando a pessoa estivesse neste campo, ele deixasse visível a segunda div.

$('#trigger').focusin(function(){
    $('.hide').addClass('isActive');

})
form{
    border: 1px solid black;
    border-radius: 5px 5px;
    padding: 80px;
}

div{
    padding: 30px;
}

.hide{
    display: none;
}

.isActive{
    display: block;
}
<form>

                Nome completo:<input type="text">
                dados:<input type="text">
                dados:<input type="text"/>
                dados:<input id="trigger" type="text"/>

                dados:<input type="text"/>
                dados:<input type="text"/>
                dados:<input type="text"/>
                dados:<input type="text"/>

</form>

Usei o addClass, sem sucesso. Tentei usar o removeClass antes de adicionar e também não deu certo. Será que teria que repensar a maneira de fazer isso?

A: Seleciona o div por outro critério, um ID por exemplo, e remove uma classe a adiciona a outra, evitando o conflito, porque se você remover a classe "hide", como funciona se seu evento é no focusin da classe "hide"?
No exemplo abaixo, usei um ID na div, para não impactar na classe que será removida/adicionada.

$('#trigger').focusin(function(){
  $('#divHide').removeClass('hide');
  $('#divHide').addClass('isActive');
})

$('#trigger').focusout(function(){
  $('#divHide').removeClass('isActive');
  $('#divHide').addClass('hide');
})
form{
    border: 1px solid black;
    border-radius: 5px 5px;
    padding: 80px;
}

div{
    padding: 30px;
}

.hide{
    display: none;
}

.isActive{
    display: block;
}

<form>

    Nome completo:<input type="text">
    dados:<input type="text">
    dados:<input type="text"/>
    dados:<input id="trigger" type="text"/>

    dados:<input type="text"/>
    dados:<input type="text"/>
    dados:<input type="text"/>
    dados:<input type="text"/>

</form>


text:
Q: How to add tabIndex to MenuItem with material UI I am using MenuItem with Material UI to display a list for a user to choose the language.
For accessibility, I need the user to be able to tab through the list and choose one, but it is skipping this list and going to the next elemend in the DOM.
    <MenuItem
        tabIndex="0"
        className="menu-item"
        key={key}
        selected={i18n.language === key}
        onClick={() => {
            handleLanguageChange(key);
                }}
            >
            <ListItemText tabIndex="0" primary={languages[key]} />
            <ListItemIcon className="icon">
                <CheckCircleIcon className={'checkmark'} fontSize="small" />
            </ListItemIcon>
    </MenuItem>

The screenshot is from the dev tools and shows that the tab index is there, but it appears that it might need to be on a child element inside of the <li>.
Is there a different way of doing this that will allow for tabIndex to work?

A: Turns out the element above the list needed tabindex="-1" added to it.


text:
Q: Does preserve-order=true affects parallelism of test cases My testng.xml file looks like -
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd">
<suite thread-count="5" name="SUITE" parallel="classes">
    <test name="TEST" preserve-order="true">
        <classes>
        <class name = "" /> ( I have around 2000 TC here)
        </classes>
        </test>
        </suite>

Does setting preserve order affects or hampers parallelism? Say I have 5 threads and 100 TC. Does it moves to 6th class after execution of one class is complete or it waits until all 5 threads finishes execution?
In my case for some classes which have multiple test methods I saw that class only getting executed. It seems as if test cases are executed sequentially and not parallely

A: see this https://testng.org/doc/documentation-main.html#parallel-tests one thread for one class. If class contains multiple methods then same thread will execute all those methods. preserve-order does not impact on parallel classes.


text:
Q: Generating Challenging plots with Matplotlib I have a data set that take the following form

The test date above may not necessarily be in chronological sequence.
I want to have 4 vertical subplots (4 rows x 1 column) representing Flow Rate, Temperature, Pressure and Concentration. Each subplot will have plots for Sample A, Sample B and Sample C.
The legend will have the Sample Names as well.
Any help in achieving this goal will greatly be appreciated.
I have tried generating the dictionary for the dataset given the constraints above without success.

A: Step by step.

*

*Import packages.
These are what I used.
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd

*We need a figure and 4 subplots stacked vertically.
This is my favourite way to do that, although there are many ways.
fig, axs = plt.subplots(4, 1, figsize=(10, 12), constrained_layout=True)

Here we are saying we want subplots in 4 rows, 1 column,
and setting the figsize to be 10 units in x and 12 units in y.
I chose the figsize by testing different sizes and choosing the best.
constrained layout is a shortcut to getting matplotlib to balance the spacing of artists ('artists' are any objects we add to a figure) it is similar to tight_layout but is a bit slower and gives better results.
this gives (half size for space here):

*I got your data by importing it into excel from image (then I cleaned up the errors):
[google drive link][2]

*get some lists to help shorten code later:
samples = [s for s in data['Sample'].unique()]
columns = [c for c in data.columns[2:]]

*This is the part I think you really needed help with. There are many ways to achieve this same result, I used a nested for loop.
1st loop : iterate the columns.
2nd loop : iterate the samples.
for i, col in enumerate(columns):
  for s in samples:

Here we enumerate the columns list because each subplot refers to a columns data, so we will index the subplots list (i.e. 'axs') using i.

*we now need to group data by sample, and pull the values from ['Test Date'] and ['col'] columns (remember 'col' is the current column we are iterating over in the columns list). Again there are many ways to do this but my usual method is of the form:
DataFrame[DataFrame['Column'] == 'category']

We are saying: from DataFrame get all rows where the value in DataFrame['Column'] is equal to category.
Then we can get the value we want from those rows by using the regular ndarray indexing, i.e. -> list[row][column].
So we have:
data[data['Sample'] == s]['Test Date']

and
data[data['Sample'] == s][col]

*We now can plot the data we grabbed. I wasn't sure which type of plot you wanted so I used the generic matplotlib.plot() function, when we use this function to plot several lists of data, it will automatically set different colors the lines.
axs[i].plot(data[data['Sample'] == s]['Test Date'],data[data['Sample'] == s][col], label=s)

So this is our nested loop to plot the data and set the legend:
fig, axs = plt.subplots(4, 1, figsize=(10, 11), constrained_layout=True)
for i, col in enumerate(columns):
    for s in samples:
        axs[i].plot(data[data['Sample'] == s]['Test Date'], data[data['Sample'] == s][col], label=s)
        axs[i].set_ylabel(col)
        axs[i].set_xlabel('Date')
        axs[i].set_title(str(col) + ' vs. Date')
        axs[i].legend(loc='center right', bbox_to_anchor=(.9655, 0.655), ncol=1)

Which Produces this set of subplots:

Here is a link to a colab  version of the python notebook where i worked through your question.
Python Notebook


text:
Q: How to incrementally update a table from SQL to HDFS I have a table imported to HDFS from RDBMS using Sqoop. After I make updates and inserts on RDBMS, how do I update the HDFS version, only transferring new and updated records? There is no timestamp or date column in this table. Can I use last modified incremental append?

A: Here last modified too required integer, timestamp,date value so last modified is not possible.
I think you can use one more column as index in mysql. And then you can import and incremental append.
MySQL index column formula:
CREATE INDEX index_name ON table_name (column_name);

This column name use as you want .it will be accepted duplicate data in row too.so don't worry.


text:
Q: android disable / enable tab in tabbedActivity I can not disable a tab in android tabbed activity.
The tabbed activity have 3 tabs and I want to disable the tab in the middle.
I tried the following code in my Fragment but the variable middleTabView  is always null!
TabLayout tabhostNew = (TabLayout) getActivity().findViewById(R.id.tabs);
TabLayout.Tab middleTabView  = tabhostNew.getTabAt(1).getCustomView();
middleTabView.setEnabled(false); //does not work, because middleTabView is null

The following code should work, but i am not able to get the variable tabwidget.
tabHost.getTabWidget().getChildTabViewAt(your_index).setEnabled(false);

Can you please help me?
Thank you in advance!

A: The method you are trying to call getTabWidget() is implemented in the TabHost class and not in TabLayout (which you are using).
Check out this answer:
TabLayout tabLayout = (TabLayout) getActivity().findViewById(R.id.tabs);
tabLayout.setupWithViewPager(viewPager); // if you are using a view pager

LinearLayout tabStrip = ((LinearLayout)mTabLayout.getChildAt(0));
for(int i = 0; i < tabStrip.getChildCount(); i++) {
    tabStrip.getChildAt(i).setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            return true;
        }
    });
}


text:
Q: Sort two dimensional table after value I'm trying to make a function to sort a table after a value inside it. Is there no functions for this already in lua? I can't seem to find one.
local table2 = {};
for i, v in pairs(table) do
   if( table[i].field > table[i+1].field ) then

this is how far I got before I thought that it wouldn't work.
Can someone help me?

A: The question is not quite clear, but if you mean to sort values in a table that may have some complex value, you can do this by using a "custom" search function:
local t = {
  {field = 2},
  {field = 1},
}
table.sort(t, function(t1, t2)
      return t1.field < t2.field
    end)
print(t[1].field, t[2].field) -- prints 1, 2

See sorting table by value for related details.


text:
Q: colour single ggplot axis item I have created a chart and am wanting to colour one of the x-axis items based on a variable. I have seen this post (How to get axis ticks labels with different colors within a single axis for a ggplot graph?), but am struggling to apply it to my dataset.

df1 <- data.frame(var=c("a","b","c","a","b","c","a","b","c"),
                  val=c(99,120,79,22,43,53,12,27,31),
                  type=c("alpha","alpha","alpha","bravo","bravo","bravo","charlie","charlie","charlie"))

myvar="a"

ggplot(df1,aes(x=reorder(var,-val), y=val,fill=type)) + geom_bar(stat="identity")

Any tips on how to make the x-axis value red when it is equal to myvar?
Update: Thanks to @ddiez for some guidance. I finally came around to the fact that i would have to reorder prior to plotting. I also should have made my original example with data.table, so am not sure if this would influenced original responses. I modified my original dataset to be a data.table and used the following code to achieve success.
df1 <- data.table(var=c("a","b","c","a","b","c","a","b","c"),
                  val=c(99,120,79,22,43,53,12,27,31),
                  type=c("alpha","alpha","alpha","bravo","bravo","bravo","charlie","charlie","charlie"))

myvar="a"

df1[,axisColour := ifelse(var==myvar,"red","black")]
df1$var <- reorder(df1$var,-df1$val,sum)

setkey(df1,var,type)

ggplot(df1,aes(x=var, y=val,fill=type)) + geom_bar(stat="identity") +
  theme(axis.text.x = element_text(colour=df1[,axisColour[1],by=var][,V1]))

A: There may be a more elegant solution but a quick hack (requires you to know the final order) would be:
ggplot(df1,aes(x=reorder(var,-val), y=val,fill=type)) +
geom_bar(stat="identity") +
theme(axis.text.x = element_text(colour=c("black","black","red")))

A solution using the variable myvar (yet, there may be better ways):
# reorder the factors in the data.frame (instead of in situ).
df1$var=reorder(df1$var, -df1$val)

# create a vector of colors for each level.
mycol=rep("black", nlevels(df1$var))
names(mycol)=levels(df1$var)

# assign the desired ones a different color.
mycol[myvar]="red"

ggplot(df1,aes(x=var, y=val,fill=type)) +
  geom_bar(stat="identity") +
  theme(axis.text.x = element_text(colour=mycol))


text:
Q: Read mail from Postfix using shell script I would like to be able to read incoming mail from a Postfix MTA using a shell script. The shell script should be able to retrieve the mail headers, subject, body, attachments, etc., then mark the mail as read. The messages are stored in the Maildir/ format. When a mail is read in Postfix, it's moved from the Maildir/new folder to the Maildir/cur folder which is helpful to retain as a backup in case a message needs to be reprocessed.
I have googled this extensively but haven't found anything helpful, plenty of examples of how to send mail, but nothing useful to read mail through a script. The mail/mailx command only seems to allow interactive access, there doesn't appear to be an option to use it through a shell script. This only needs to work for one user, since I am using a catchall configuration to catch all incoming mail into a single mailbox, for subsequent processing by the script.
There's always the option of polling the Maildir/new folder for incoming messages using a cronjob or incron but I it would be nice to use Postfix's mail management capabilities as opposed to manually managing the msg files. My script will be local to the Postfix server.
Any suggestions/ideas? thanks.
Edit: Maybe I should mention that I'm not looking for help with the script. I'm looking for some command line tool that can access Postfix Maildir/ msg store and read/do stuff with the msgs and can be invoked in a non-interative manner. In other words basic functionality of the mail tool, but non-interactive.

A: I found the following:
http://notes-cs.blogspot.in/2013/04/use-command-line-to-read-linux-local.html
This person describes exactly what I was looking for. Pure genius! To capture the essence (everything below is from the link above):
Print all email to STDOUT:
$ echo "type *" | mail

$ echo "type 1" | mail   # print the first email to stdout

$ echo "type 3-5" | mail # print the emails from 3 to 5

Check if mail box is empty (i.e. "No mail for [username]" is found):
$ echo q | mail 2>&1 | grep "No mail for [username]"

Purge the mail box:
$ echo "d *" | mail

$ echo "d 3" | mail     # Delete the 3rd email

Save all emails in a text file:
$ echo "s * test.txt" | mail

Save emails between a range in a file:
$ echo "s 3-6 test.txt" | mail # this will save email from #3 to #6 to the file test.txt

Read one email from mailbox:
$ echo 1 | mail # Read the first mail from mail box:

$ echo 5 | mail # Read the 5th email from mail box:

$ echo 6 | mail

If there is no 6th mail from mail box. It will prompt you below error:
6: Invalid message number

The error message "Invalid message number" tells you that there is no 6th email in the mailbox. If the 5th email is successfully returned. You can treat the error message "Invalid message number" as end of mailbox just like the EOF of a file. Combined this with a loop, you can browse thru all the emails inside the mailbox.

A: Your Google Fu is lacking.
One easy solution is a sendmail style ~/.forward file where you pipe | the message directly to your script, before it even gets written to your Mailbox. Your script then does its thing and writes the mail mesage to disk afterwards.
Similarly but you get a bit more flexibility when you configure procmail as the mail delivery agent and set up a ~/.procmailrc to forward the messages to your script.
The alternative is to install an IMAP or POP3 daemon and use fetchmail to poll your mailbox and read any new messages and hand them off to your script.


text:
Q: A geometric problem on number of points and lines
There are P points and L lines such that

*

*Each line contains 8 points

*Each point lies on 8 lines

*Any two distinct lines intersect in a unique point

*Any two distinct points lie on a unique line.

  Lines may be straight or curved. What is $P\times L$ ?

My answer, is that, using last two conditions, if $P$ is no of points then L = $\binom{P}{2}$. Also if no of lines is $L$ then $P = \binom{L}{2}$, from here we need $\binom{\binom{L}{2}}{2} = L$ which gives 3 as L. This is certainly incorrect.
How to approach this geometric problem?

A: Because of first two condititons we have $$L\times 8 = P\times 8\implies L=P$$
Then from the last condition we have $${8\choose 2}L = {P\choose 2}\implies P= 57$$
Such a configuration really exists, it is a projective plane of order $7$ it has $7^2+7+1$ points and the same number of lines.

A: There are $\binom P2$ pairs of points, and each pair gives a line. However, each line has $8$ points on it, meaning that the pairs of points are divided into groups of $\binom 82=28$, where any pair in a group gives the same line. So the number of distinct lines is $L= \frac{\binom P2}{28}$.
Similarly, the number of distinct points is $P= \frac{\binom L2}{28}$.
This gives the following set of equations:
$$
\cases{P=\frac{L(L-1)}{56}\\L=\frac{P(P-1)}{56}}
$$

A:

*

*Any two distinct lines intersect in a unique point

*Any two distinct points lie on a unique line.

These two rules are, essentially, the incidence axioms for two-dimensional projective geometry. As such, we have a standard model for the system described here: the projective plane over the field $\mathbb{F}_7=\mathbb{Z}/7$ with seven elements.
We can use that model to count the points and lines - or we can just do things directly. Suppose we have a projective plane such that each line has $n+1$ points and each point is on $n+1$ lines.
Then, consider the system of all $n+1$ lines through a given point $P$. These lines each contain $n$ points other than $P$. Also, each point other than $P$ is on exactly one of these lines. That's $n(n+1)$ points other than $P$; add $P$ back in, and we have a total of exactly $n^2+n+1$ points.
By symmetry between points and lines, we also have exactly $n^2+n+1$ lines; we could run a similar count using some particular line $\ell$, the $n+1$ points on it, and the $n$ other lines through each of those points.
For our example with $n+1=8$, that's $7^2+7+1=57$ each points and lines, for a product of $3249$.


text:
Q: Using CompletableFuture.allOf(CompletableFuture1, CompletableFuture2), still response time is high I have a list of elements(List<SummaryList>) which needs to be passed to two other services and those two services should run asynchronously using CompletableFuture.
I have used below logic but still it takes lot of time to respond.
If list below is of 5-6 elements, response time is 2-3 sec, but when the list has 10-25 elements, the response time is >10 sec in order to complete the two service calls.
Am I missing something as part of optimization/running asynchronously? Is there any other way to optimize these calls?
I have below class SummaryList which contains properties like id, account, name and type
    @Getter
    @Setter
    Class SummaryList {
        private String id;
        private String account;
        private String name;
        private String type;
        public SummaryList() {}
        public SummaryList(String id, String account, String name,
        String type) {
          this.id=id;
          this.account=account;
          this.name=name;
          this.type=type;
        }
    }

I have the values of id and account.
Using account, I need to call two other services(invokeFirstService & invokeSecondService) asynchronously to populate name and type of SummaryList.
And these two services use this account as input.
invokeFirstService & invokeSecondService functions below return CompletableFuture<Void>.
invokeFirstService populates name and invokeSecondService populates type
  SummaryList s1=new SummaryList("101","account1","","");
  SummaryList s2=new SummaryList("102","account2","","");
  SummaryList s3=new SummaryList("103","account3","","");
  SummaryList s4=new SummaryList("104","account4","","");
  SummaryList s5=new SummaryList("105","account5","","");
  List<SummaryList> list=Arrays.asList(s1,s2,s3,s4,s5);

    for (SummaryList summary : list) {
                FirstRequestBean firstRequestBean = new FirstRequestBean();
                SecondRequestBean secondRequestBean = new SecondRequestBean();
                FirstResponseBean firstResponseBean = new FirstResponseBean();
                SecondResponseBean secondResponseBean = new SecondResponseBean();
                firstRequestBean.setAccount(summary.getAccount());
                secondRequestBean.setAccount(summary.getAccount());
                CompletableFuture.allOf(CompletableFuture.runAsync(() -> {
                try {
                invokeFirstService(firstRequestBean,firstResponseBean).get();
                if (!CollectionUtils.isEmpty(firstResponseBean.getResponse())) {
                summary.setName(firstResponseBean.getResponse().get(0).getName());
               }
                } catch (Exception e) {
                     //throw e;
                   }
                }), CompletableFuture.runAsync(() -> {
               try {
               invokeSecondService(secondRequestBean, secondResponseBean).get();
               if (!CollectionUtils.isEmpty(secondResponseBean.getResponse())) {
               summary.setType(secondResponseBean.getResponse().get(0).getType());
               }
                   } catch (Exception e) {
                        //throw e;
                      }
                })).join();
            }

A: Two things.
1: Looking at your snippet, the underlying operation is IO intensive.
Whenever we work with IO intensive tasks with multiple thread the thread pool size should be bigger than the number of available processors.
So, first optimization would be using a custom dedicated thread pool.
2: Avoid using join() try to refactor your code so that you don't wait upon the response and implement your "after-logic" using thenApply/thenCompose/thenCombine call-back processing methods provided by CompletableFuture.
Something like:
CompletableFuture.allOf(...).thenApply(response -> {
      //handling
});


text:
Q: JavaFx, обновление сцены Делаю программу которая генерирует бинарное дерево добавляя кнопки на панель и соединяя их линией. При добавлении нового элемента он просто появляется в координатах (0,0) и встает в нужное место только если поменять размер окна(конечно я пробовал увеличить размер на один пиксель, но это ужасный костыль).
Я не смог найти метода перерисовки repaint(), revalidate() как в Swing.
Как можно обновить расположение компонента?

A: Попробуйте у компонента задать новые параметры, а потом вызвать у Pane к которой он принадлежит метод requestLayout()
Это должно выглядеть, примерно, так
public class Solution extends Application {
  private static final Pane root = new Pane();
  private static final Circle circle = new Circle(20, 20, 20);

  public static void main(String[] args) throws Exception {

    Timer timer = new Timer(true);
    timer.scheduleAtFixedRate(new TimerTask() {
        @Override
        public void run() {
            System.out.println("repaint");
            Platform.runLater(() -> {
                circle.setCenterX(circle.getCenterX() + 50);
                circle.setCenterY(circle.getCenterY() + 50);
                circle.setRadius(circle.getRadius() * 1.1);
                root.requestLayout();
            });
        }
    }, TimeUnit.SECONDS.toMillis(10), TimeUnit.SECONDS.toMillis(5));

    launch(args);
 }

 @Override
 public void start(Stage primaryStage) {
    primaryStage.setTitle("simple example");

    root.getChildren().add(circle);

    primaryStage.setScene(new Scene(root, 400, 400));
    primaryStage.show();
}}


text:
Q: What is the red-minus icon in Egit conflict? I have this strange icon in EGit, I don't know the meaning of this icon.
I have looked in https://wiki.eclipse.org/EGit/User_Guide/State, but I haven't found it.

The particular thing of this icon is that the option "merge tool" can't be choosed.
What's the meaning of this icon?


text:
Q: Labeling a point using TikZ In the following code, I want to label the point (1,1) as "P."  (It is not exciting, I know. It is part of a graph that I want to draw.)  I have the code \node[above right, outer sep=2pt] (1,1) {P}; to do this.  TikZ is putting the label above and to the right of the origin.
Why isn't TikZ putting the label above and to the right of (1,1)?
I have a grid placed on the Cartesian plane.  With outer sep=2pt, I expected that some of the grid would be obscured by the label P.  I want the letter "P" to stand out on the graph, and I think it would if some of the grid lines were obscured.
\documentclass{amsart}
\usepackage{tikz}
\usetikzlibrary{shapes,positioning,intersections,quotes}

\begin{document}

\begin{tikzpicture}
\draw[yellow] (-1.25,-1.25) grid[xstep=0.5, ystep=0.5]  (2.25,2.25);
\draw[draw=gray!30,latex-latex] (0,2) +(0,0.5cm) node[above right] {$y$} -- (0,-1) -- +(0,-0.5cm);
\draw[draw=gray!30,latex-latex] (-1,0) +(-0.5cm,0) -- (2,0) -- +(0.5cm,0) node[below right] {$x$};
\filldraw (1,1) circle[radius=1.5pt];
\node[above right, outer sep=2pt] (1,1) {P};
\end{tikzpicture}

\end{document}

A: You can obscure the grid lines behind the node using fill=white. You can also do this if you use a pin which will draw a line from the point to the label. Or you could use the label option which is similar but without the line.
\documentclass[tikz,border=5pt]{standalone}

\usetikzlibrary{shapes,positioning,intersections,quotes}

\begin{document}

  \begin{tikzpicture}
    \draw[yellow] (-1.25,-1.25) grid[xstep=0.5, ystep=0.5]  (2.25,2.25);
    \draw[draw=gray!30,latex-latex] (0,2) +(0,0.5cm) node[above right] {$y$} -- (0,-1) -- +(0,-0.5cm);
    \draw[draw=gray!30,latex-latex] (-1,0) +(-0.5cm,0) -- (2,0) -- +(0.5cm,0) node[below right] {$x$};
    \filldraw (1,1) circle[radius=1.5pt];
    \node [fill, draw, circle, minimum width=3pt, inner sep=0pt, pin={[fill=white, outer sep=2pt]135:P}] at (.5,1) {};
    \node[above right=10pt of {(1,1)}, outer sep=2pt,fill=white] {P};
  \end{tikzpicture}

\end{document}


text:
Q: Create Document with unique property in Mongoose I'm trying to save a document with a unique property across the collection.
So if someone tries to save a kitten with {name: 'kitty'} and that name already exisits it fails and retries with {name: 'kitty1'} (then 'kitty2' etc).
I really can't figure out a good way to do this, any ideas?
Here's what I have so far (doesn't work).
var kittenSchema = new Schema ({
    name: {type: String, index: {unique: true}}
})

var Kitten = mongoose.model('Kitten', kittenSchema);

var kitten = new Kitten({
    name: 'kitty'
});

kitten.save(function(err, kitten){
    if (err){
        saveKitten(kitten, 1, function(err, kitten){
            if (err){
                console.log("Damn, no kitten");
            } else {
                console.log("New kitten " + kitten.name + "saved.");
            });
    } else {
        console.log("New kitten " + kitten.name + "saved.");
    }
}));

function saveKitten(kitten, count, callback){
    kitten.name = kitten.name + count;

    kitten.save(function(err, newKitten){
        if (err){
            if (count > 100){
                // Give up!
                callback(err, null);
            }

            saveKitten(kitten, count + 1, callback);
        } else {
            callback(null, newKitten);
        }
    }));
}

A: Your example almost works as is, but with a few typos and a scoping issue.
The first time you call kitten.save, your callback's argument is kitten.  The problem is that the local kitten argument shadows the external kitten, and in the case of an error, the local kitten is undefined.
var kittenSchema = new mongoose.Schema ({
    name: {type: String, index: {unique: true}}
})

var Kitten = mongoose.model('Kitten', kittenSchema);

var kitten = new Kitten({
    name: 'kitty'
});

kitten.save(function(err, newKitten){
    if (err){
        saveKitten(kitten, 1, function(err, newKitten){
            if (err){
                console.log("Damn, no kitten");
            } else {
                console.log("New kitten " + newKitten.name + " saved.");
            }
        });
    } else {
        console.log("New kitten " + newKitten.name + " saved.");
    }
});

function saveKitten(kitten, count, callback){
    kitten.name = kitten.name + count;

    kitten.save(function(err, newKitten){
        if (err){
            if (count > 100){
                // Give up!
                callback(err, null);
            }

            saveKitten(kitten, count + 1, callback);
        } else {
            callback(null, newKitten);
        }
    });
}

Also note that the way you are using '+' here means this code will insert "kitten", "kitten1", "kitten12", "kitten123", etc.

A: After a pointer from NilsH I think I might try to pull back all possible name clashes and look for a new name locally.
Something like this:
var Kitten = mongoose.model('Kitten', kittenSchema);

var kitten = new Kitten({
    name: 'kitty'
});

Kitten.find({name: new RegExp('^'+ kitten.name +'*', "i")}, 'name').exec(function(err, docs){
    var tryName = name;
    var count = 0;

    while (True){
        if (_.indexOf(docs, tryName) != -1){
            break;
        } else {
            tryName = name + count;
        }
    }

    kitten.name = tryName;

    kitten.save(function(err, kitten){
        if (err){
            console.log("Damn, no kitten");
        } else {
            console.log("New kitten " + kitten.name + "saved.");
        }
    }));
});

There's a possible race condition between finding the name and using it but I think I can live with that.


text:
Q: Does the at symbol (@) before a definition name mean something? I'm using a resume template and see this pattern a lot in the template. What is the purpose of this redirection to @name, does the @ symbol mean anything special, and how do I use it to modify the formatting of my name?
% use this to define your name
%
\def\name#1{\def\@name{#1}}

\def\@name{}

Thanks in advance.


text:
Q: How to end the HTTP response body for a Java based web server I am trying to write a Java web server from scratch (for learning) and I am bit stuck on how should I end my HTTP response body so that I can get the proper response object at client side.
I am see the 200 OK response, as well 2 other headers I am setting.
HTTP/1.1 200 OK
Connection: close
Content-Type: text/plain

Even I am able to see the response I am writing on the client socket's o/p stream, but problem is that since I think I am missing proper ending of the HTTP response body so I am not able to get correct xmlhttp.status code and also not able to view the response in Chrome's inspect element, even though HTTP response code is 200 but response preview says "no response data available".
Below is my web server code and client code (XHR based) which I am using to call my web server.
Web server code:
package com.learn;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

public class TestWebServer {

    public static void main(String[] args) throws IOException {
        startWebServer();
    }

    /**
     * test "backlog" in ServerSocket constructor
test -- If bindAddr is null, it will default accepting
     * connections on any/all local addresses.
     * @throws IOException
     */

    private static void startWebServer() throws IOException {
        ServerSocket serverSocket = new ServerSocket(8001);

        while(true){
             // a "blocking" call which waits until a connection is requested
            /*Socket clientSocket = serverSocket.accept();*/
            TestWebServer.SocketThread socketThread = new TestWebServer().new SocketThread();
            socketThread.setClientSocket(serverSocket.accept());
            Thread thread = new Thread(socketThread);
            thread.start();
        }

    }

    public class SocketThread implements Runnable{

        Socket clientSocket;

        public void setClientSocket(Socket clientSocket) {
            this.clientSocket = clientSocket;
        }

        public void run(){
            System.out.println("####### New client session started.");
            try {
                listenToSocket();
            } catch (IOException e) {
                System.err.println("#### EXCEPTION.");
                e.printStackTrace();
            }
        }

        private void listenToSocket() throws IOException {
            /*BufferedReader clientSocketReader = new BufferedReader(new InputStreamReader(clientSocket.getInputStream()));
            BufferedWriter clientSocketWriter = new BufferedWriter(new OutputStreamWriter(clientSocket.getOutputStream()));*/

            InputStreamReader clientSocketReader = (new InputStreamReader(clientSocket.getInputStream()));
            OutputStreamWriter clientSocketWriter = (new OutputStreamWriter(clientSocket.getOutputStream()));

            int clientSocketInput;
            boolean isFirstLineFeedEncountered = false;
            boolean isFirstCarriageReturnEncountered = false;
            boolean isSecondCarriageReturnEncountered = false;
            while(clientSocket.isConnected() && (clientSocketInput = clientSocketReader.read()) != 0){
                if(isFirstCarriageReturnEncountered){
                    //System.out.println("### After first CR");
                    if(isFirstLineFeedEncountered && isFirstCarriageReturnEncountered){
                        if(isFirstLineFeedEncountered && isFirstCarriageReturnEncountered && isSecondCarriageReturnEncountered){
                            System.out.println("### 2 sets of CRLF encountered.");
                            String responseHeaders = construct_http_header(200);
                            clientSocketWriter.append(responseHeaders);
                            clientSocketWriter.append("Bye from server, thank you for contacting me!!!");
                            clientSocketWriter.append("\r\n\r\n");
                            clientSocketWriter.flush();
                            clientSocketWriter.close();
                            clientSocketReader.close();
                            clientSocket.close();
                            break;
                        } else if(clientSocketInput == 13){
                            //System.out.println("### After first set of CRLF, found another CR");
                            isSecondCarriageReturnEncountered = true;
                        } else{
                            //System.out.println("### Oops, after first set of CRLF");
                            isFirstLineFeedEncountered = false;
                            isFirstCarriageReturnEncountered = false;
                            isSecondCarriageReturnEncountered = false;
                        }
                    } else if(clientSocketInput == 10){
                        //System.out.println("### First LF");
                        isFirstLineFeedEncountered = true;
                    } else{
                        isFirstCarriageReturnEncountered = false;
                    }
                }

                // identify "CR" or ASCII 13
                if(clientSocketInput == 13){
                    //System.out.println("### First CR");
                    isFirstCarriageReturnEncountered = true;
                }

                // identify "CTRL+C" or ASCII 3
                if(clientSocketInput == 3){
                    System.out.println("### Encountered CTRL+C");
                    clientSocketWriter.append("Bye from server, thank you for contacting me!!!");
                    clientSocketWriter.flush();
                    clientSocketWriter.close();
                    clientSocketReader.close();
                    clientSocket.close();
                    break;
                }

                // identify "CTRL+D" or ASCII 4
                if(clientSocketInput == 4){
                    System.out.println("### Encountered CTRL+D");
                    clientSocketWriter.append("Bye from server, thank you for contacting me!!!");
                    clientSocketWriter.flush();
                    clientSocketWriter.close();
                    clientSocketReader.close();
                    clientSocket.close();
                    break;
                }
                System.out.print((char) clientSocketInput);
            }
        }

        /**
         * SOURCE: https://fragments.turtlemeat.com/javawebserver.php
         *
         * @param return_code
         * @param file_type
         * @return
         */
        private String construct_http_header(int return_code) {
            String s = "HTTP/1.1 ";
            // you probably have seen these if you have been surfing the web a
            // while
            switch (return_code) {
            case 200:
                s = s + "200 OK";
                break;
            case 400:
                s = s + "400 Bad Request";
                break;
            case 403:
                s = s + "403 Forbidden";
                break;
            case 404:
                s = s + "404 Not Found";
                break;
            case 500:
                s = s + "500 Internal Server Error";
                break;
            case 501:
                s = s + "501 Not Implemented";
                break;
            }

            s = s + "\r\n"; // other header fields,
            s = s + "Connection: close\r\n"; // we can't handle persistent connections
            /*s = s + "Server: SimpleHTTPtutorial v0\r\n"; // server name*/
            s = s + "Content-Type: text/plain\r\n";

            // //so on and so on......
            s = s + "\r\n"; // this marks the end of the httpheader
            // and the start of the body
            // ok return our newly created header!
            return s;
        }

    }

}

Client code:
<!DOCTYPE html>

        First Name
        <input type="text" id="name" name="name" >

        Name
        <input type="text" id="name2" name="name2" >

        <input type="submit" id="submitButton"  name="submitButton" value="Submit">

P.S. Please do not recommend me to use some Java web server API, this is for my learning on how to implement a web server so I am looking for insight on my issue.

Update: I think I got something, may be I need to also include the content length header so I included the same s = s + "Content-Length: 51\r\n"; and now I am able to see content length header as well but still problem remains same that neither in XHR nor in Chrome inspect element I am able to see the server response.


text:
Q: How do I load a CBG GeoJSON into Python for Census Block Group level maps in Plotly? I made county level maps a while ago and I'm trying to modify it to CBG level.
Am I limited to state and county?
with open('cbg.geojson') as response:
    cbgfile = json.load(response)

data = pd.read_csv("roundone.csv")

fig = px.choropleth(data, geojson = cbgfile, locations='FIPS',
                        scope = 'usa',
                        color = "bids_for_item",
                        #color_continuous_scale = ["white", "lime", "green"]
                        )

fig.show()

I'm having issues loading the JSON (invalid argument). According to some other posts it might be because the GeoJSON is 3 GB. How could I get around that?

File
"/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/site-packages/geojson/codec.py",
line 43, in load
**kwargs)   File "/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/json/init.py",
line 296, in load
return loads(fp.read(), OSError: [Errno 22] Invalid argument


text:
Q: Условия скидок Bitrix На сайте стоит условие скидки(Если в корзине свыше 2-ух позиций то применяется скидка 5% ) как сделать так , чтобы из этого условия исключить некоторые разделы?

A: Вам нужно настроить условия скидки. Это делается в административной части сайта в меню "Маркетинг"-"Товарный маркетинг" вы можете отредактировать подходящий пункт из списка Предустановленный список маркетинговых акций или можете настроить Правила работы с корзиной
Где конкретно сейчас вам настроили телепатически сложно сказать. Это места, где это настраивается штатно.


text:
Q: Matrix, Vector, Multiplication I understand what Vector and matrix are.

*

*But I don't know what is vector-matrix multiplication for? How the mathematician come up this theory?

*What is matrix-matrix multiplication for? How come up this theory?
I know how to calculate them, but no idea what it looks like in a 3D space.

*Can I understand that: Matrix Multiplication is: First we break one of two Matrixes to several vectors; Second, we do Vector-Matrix Multiplication and then adding all of them together?

Thank you for your explanation

A: Basics
Matrices can map numbers in 2 dimensions. This video shows a good example of how to calculate with matrices.
Matrix A = items sold per day (5 x 3 dimension)
             c
             o
             o  c
             k  a  p
             i  k  i
             e  e  e
             s  s  s

monday     [ 3  5  3 ]
tuesday    [ 7  1  2 ]
wednesday  [ 2  5  3 ]
thursday   [ 5  4  0 ]
friday     [ 3  4  4 ]

Matrix B = Price per item (3 x 1 dimension)
              €
cookies    [  4 ]
cakes      [ 10 ]
pies       [  8 ]

In order to be able to multiply 2 matrices, the 2nd dimension of the 1st matrix MUST match the 1st dimension of the 2nd matrix (5 x 3) * (3 x 1) (3's must match), and this multiplication will result in a 5 x 1 matrix.
In this example we're multiplying a (days/item) matrix with a (items/price) matrix, and we're expecting a (days/price) matrix that indicates how much we earn per day.
You can immediately see why the numbers of columns of the first matrix must match the number of rows of the second matrix here.
Multiplication
In order to multiply the matrices, we first position them in a better way:
                           €
                        [  4 ]
                        [ 10 ]
                        [  8 ]

monday     [ 3  5  3 ]  [    ]
tuesday    [ 7  1  2 ]  [    ]
wednesday  [ 2  5  3 ]  [    ]
thursday   [ 5  4  0 ]  [    ]
friday     [ 3  4  4 ]  [    ]

As demonstrated below, each element in the resulting matrix is the sum of following multiplications:
                            €
                      ---[  4 ]
                    ╱  --[ 10 ]
                  ╱  ╱  -[  8 ]
                ╱  ╱  ╱     |
              ╱  ╱  ╱       |
monday     [ 3  5  3 ]   [    ]
tuesday    [ 7  1  2 ]   [    ]
wednesday  [ 2  5  3 ] - [ 82 ]
thursday   [ 5  4  0 ]   [    ]
friday     [ 3  4  4 ]   [    ]

So for the third element, the result is as follows:
2 cookies * 4 €/cookie + 5 cakes * 10 €/cake + 3 pies * 8 €/pie = 82 €

Extending the example
If you also want to know how much time you're spending to bake the stuff you're selling, you can add those numbers to the second matrix as well:
              €   min.
cookies    [  4     2  ]
cakes      [ 10    30  ]
pies       [  8    20  ]

Multiplying them:
                            €   min
                      ---[  4     2  ]
                    ╱  --[ 10    30  ]
                  ╱  ╱  -[  8    20  ]
                ╱  ╱  ╱     |     |
              ╱  ╱  ╱       |     |
monday     [ 3  5  3 ]   [           ]
tuesday    [ 7  1  2 ]   [           ]
wednesday  [ 2  5  3 ] - [ 82    214 ]
thursday   [ 5  4  0 ]   [           ]
friday     [ 3  4  4 ]   [           ]

Will give you
R(3,2) = 2 * 2 + 5 * 30 + 3 * 20 = 214

So as a result, you know your earnings per day, and your spent minutes per day for the items you sell


text:
Q: How do you show the back of a device in Visio networking objects? I am diagramming a network layout, the wiring in a cabinet, from switch to san.  But I can't find a way to look at the back side of the stock shapes.  Is there a way?

A: Go to visiocafe.com, they do front and back templates for the majority of professional hardware.

A: I would show both front and back of the cabinets (maybe one cabinet per page, so in essence two images) and use the corresponding icon for the front and back. It is more work, of course, but it will give you a very detailed view of the cabling. You can control whether a cable connects to a specific port on the back or front. This is what a lot of network documentation people do for proper visualization of rack diagrams and cabling.
For the icons, as the poster below, try Visio Cafe, and then you also have the specific vendors that provide icons for you to use.


text:
Q: The converse of Euclid's Lemma Im having trouble proving the converse of Euclid's lemma, and was wondering if anyone could point me in the right direction.
Euclid's Lemma: Let $p$ be a prime number and $a$ and $b$ be natural numbers greater than 1, then if $p|ab$ we know  $p|a$ or $p|b$
Converse: For some number $p$, if for all natural numbers $a$ and $b$ greater than 1, $p|ab$ implies $p|a$ or $p|b$, then $p$ is prime.
I tried showing that $p$ had only factors 1 and $p$, but I didn't really manage to make any progress, I'm just really not sure where to start, I'd really appreciate any help, thanks.

A: If $p$ is not prime, then there are $a,b \neq p$ with $p = ab$. Now $p \mid ab$ but $p \not \mid a, p \not \mid b$.
longer version:
We already have the implication
($p$ prime) $\implies$ (if $p \mid a \cdot b$, then $p \mid a$ or $p \mid b$)
We want to show the implication
(if $p \mid a \cdot b$, then $p \mid a$ or $p \mid b$) $\implies$ ($p$ prime)
We do this my contraposition:
($p$ not prime) $\implies$ (there exist $a,b$ with $p \mid a \cdot b$ and $p \not \mid a, p \not \mid b$)
Now, if $p$ is not prime, then there is a factorization $p = a \cdot b$ with $a \neq p \neq b$. Hence we have $p \mid a \cdot b$, but $p \not \mid a, p \not \mid b$, which shows the above implication.

A: Suppose $p=ab$. By assumption, either $p\mid a$ or $p\mid b$.
If $p\mid a$, then $a=pc$, for some $c$ and so
$$
a=pc=abc
$$
Since $a\ne0$, we get $bc=1$. Can you go on?

A: By assumption, $p|ab$  and either $p|a$ or $p|b$.  Let
$$
ab = p_{1}p_{2}\cdots p_{n}
$$
be the prime decomposition of $ab$. We know that $p|ab$ and so, $p|p_{1}p_{2}\cdots p_{n}$. Then $p$ must divide one of $p_{i}$ for $1 \leq i \leq n$. Since $p_{i}$ are primes, it follows that $p$ must be prime.


text:
Q: Most efficient way to insert multiple rows in JPA I have a parent/child unidirectional relationship. When I examine the logs I see that there is a separate insert query for each child row, the equivalent of let's say:
insert into childTable(col1, col2) values(val1, val2);
insert into childTable(col1, col2) values(val3, val4);

Wouldn't it be more efficient to insert all the rows in a single query? Something along the lines of:
insert into childTable(col1, col2) values(val1, val2), (val3, val4)

Is there a way to force JPA to generate multi line inserts instead of single line inserts?
Edit: I'm currently using cascading inserts so I insert the parent and the inserts for the children are generated automatically. I would prefer to keep using that method instead of let's say manually creating an enormous SQL query as I think the cascading inserts produce cleaner code.
I already flush the session regularly in order to control the size of the L1 cache so running out of memory is not a problem.

A: It is actually less efficient to insert all rows in a single query.
First, a couple of observations:

*

*The amount of data to pass from client to server is the same either as one or many insert statements, where "amount of data" means the actual values you are storing.

*Hibernate supports batching of requests, so the number of round-trips between client and server can be approximately the same either as one or multiple insert statements.

Under the covers, Hibernate is using a PreparedStatement for each query it executes on your behalf, and these are cached and reused. And MySQL caches "compile" SQL statements. Without getting mired in details, the underlying technologies are highly optimized to run a relatively small number of queries many times.
If you do the insert as a single statement, then each time that the number of values to insert is different, the new SQL has to be compiled and cached (possibly pushing another query from the cache) which adds overhead. This overhead is avoided when you just use the same SQL every time.
For many reasons, you must use bind variables in your SQL, and Hibernate will do that for you automatically. If you do some custom queries to test the all-at-once insert method, you definitely should use bind variables as well.
Another consideration is how you generate identifiers. If it is via an identity column in the database, then Hibernate needs to receive back the ID for each column, which generally is only possible when one row was created. For this reason, a sequence-based identifier generator is preferred for efficiency, with client-side caching of sequence values.
I just noticed your edit: My experience has been that Hibernate does "extra" updates when dealing with inserting parent-child data. I managed to get "pure" inserts by changing the mapping to have a "join" table (like you would see for many-to-many relationship) even though I only had a many-to-one relationship. In my case, it was significantly faster to do significantly more inserts into three tables vs. fewer inserts plus updates into two tables. If you are concerned about performance, you definitely should plan on some time to tune the Hibernate configuration.


text:
Q: Cant execute coffeescript in modal first of all, im still learning Ruby on rails, currently im working on rails 4.2.6.
I have a problem with my code, i have a modal where i want to show the information dynamically with ajax (Calling a method in a controller and showing the information on the modal without closing it) but i have a problem, i cant call any function on the modal.
.col-xs-7
  %h5="#{period.name}"
.col-xs-5
  %form
    .input-group
      %input.form-control{type: "text", placeholder: "#{t('reports.periods')}"}/
      .input-group-btn
        %button.btn.transparent-button.dropdown-toggle{"data-toggle" => |
                                                         "dropdown", |
                                                       type: "button"} |
          = svg_icon('icon-arrow-down')
        %ul.dropdown-menu.pull-right
          - @batch_id.periods.each do |period|
            %li
              = link_to period.name, '#', :onclick => "myFunction", id: "#{period.id}_id", value: period.id

.row.actions-container
.col-xs-12
  %h4="#{@student_id.name}"
  %hr
.row.actions-container
.col-xs-12
  %form
    = label_tag t('batches.observations')
    %br
    = text_area_tag 'rejection_comments', @comment.try(:comment) , class: 'form-control', :rows => 10, :cols => 30

- content_for(:page_javascript) do

  :coffeescript
  myFunction = ->
    alert 'hello world'
    return

Right now im trying only to call the function 'MyFunction' after i select a period but it throws an error:

myFunction is not defined

But if i do this:
  - @batch_id.periods.each do |period|
    %li
      = link_to period.name, '#', :onclick => "alert('hello')", id: "#{period.id}_id", value: period.id

It works...
Can someone tell me what im doing wrong? I want to do the ajax thing as soon as possible.
Ps: The comment part on the text area is the info i want to get from the controller dynamically.
Thanks!


text:
Q: How to reset PayPal next billing date? I am using monthly and yearly PayPal subscriptions in my application.
I want to reset my PayPal subscription billing date.
Reason: My problem is a subs/paypal issue.
I want If I increase the subscription end date by 1 or 2 months in my DB, the user's PayPal account should not be charged with PayPal 1 or 2 months before the subscription of DB is completed.
I am not sure it is possible, but I should solve this problem.
How can I reset the paypal billing date?

A: You can update or suspend and later re-activate the subscription. There are API calls for this.
Update: https://developer.paypal.com/docs/api/subscriptions/v1/#subscriptions_patch
Suspend: https://developer.paypal.com/docs/api/subscriptions/v1/#subscriptions_suspend


text:
Q: Integrate Robot Framework with Zephyr for jira I would like to know if there is the option of integrating automated test cases with zephyr de jira.
Currently, I have a battery of automated tests in robot framework. In parallel, I have the test cases defined in Zephyr for jira. I would like to be able to launch the execution of the automated test cases from Zephyr or else, that the result of the executions will be reflected in the Zephyr test cases.
Thank you.

A: You need to parse output.xml file generated by Robot Framework to get results of your test suite. Alternatively JUnit xml reporting file may be generated by using -x parameter:
robot -x junit.xml test1.robot

To update results in Zephyr test cases use ZAPI for Jira. Please check https://getzephyr.docs.apiary.io.
Execution status update
Find test case id (issue id) by test case name (issue key):
https://<jira_server>/rest/api/2/issue/<test_case_name>

Find execution id by test case id:
https://<jira_server>/rest/zapi/latest/execution?issueId=<test_case_id>

Request:
PUT https://<jira_server>/rest/zapi/latest/execution/<execution_id>/execute

Headers:
Content-Type: application/json

Body:
{
  "status": "1"
}

Status "1" is for PASS.
Step status update
Find step id by execution id:
https://<jira_server>/rest/zapi/latest/stepResult?executionId=<execution_id>&expand=

Request:
PUT https://<jira_server>/rest/zapi/latest/stepResult/<step_id>

Headers and body the same as above.


text:
Q: GetOption PERL to Python How would I write this PERL line in python?
GetOptions('help|?' => \$help, 'man' => \$man, 'debug!' => \$debug, 'devpath:s' => \$devpath, 'dev2:s' => \$dev2,'rev1:s' => \$prj_rev1, 'rev2:s' => \$prj_rev2, 'prj:s' => \$prj)

Thanks!

A: There is a module in python called argparse. You can use the module to solve your problem.
Code example : test.py
import argparse
import os

commandLineArgumentParser = argparse.ArgumentParser()
commandLineArgumentParser.add_argument("-fname", "--fname",  help="first name")
commandLineArgumentParser.add_argument("-lname","--lname", help="last name")
commandLineArguments = commandLineArgumentParser.parse_args()

fname = commandLineArguments.fname
lname = commandLineArguments.lname

print "%s\n%s" %(fname,lname)

Run example
python test.py -fname ms -lname = dhoni

Output
ms
dhoni


text:
Q: Error when starting workflow via REST webservice from another workflow I have two sharepoint 2013 list workflows created in SharePoint Designer. One exists in the root of the site collection while another exists on a subsite. Through the use of several Call HTTP Web Service actions, the workflow on the root site list creates an item on a seperate list in the subsite
POST to: .../subsite/_api/web/lists/getbytitle('[ListName]')/items

and then attempts to start the subsite workflow on the newly created list item
POST to: .../subsite/_api/SP.WorkflowServices.WorkflowInstanceService.Current/StartWorkflowOnListItemBySubscriptionId(subscriptionId='[SubscriptionID]', itemId='[NewItemId]')

I am able to create the list item in the subsite, however, the web service call to start the workflow returns an InternalServerError status along with a correlation Id. If I check the SharePoint logs for the correlation Id, I see the following error:

Microsoft.Workflow.Client.WorkflowCommunicationException: The request was aborted: The request was canceled. Client ActivityId : cefbf0c2-e3d0-4d82-9b47-3e2a47be5d6b. ---> System.Net.WebException: The request was aborted: The request was canceled. ---> System.NotSupportedException: Do not know how to create outbound claims for app only identity

Most of what I can find on this error doesn't seem to apply to my situation. For example, in this technet discussion the problem seems to be that the message gets posted to the log many times over, filling the log files up very quickly, and the solution is to reset the log level to the default and restart the workflow management pool. In my case, the message is not filling up the logs and is only associated with the root list workflow attempting to start the subsite workflow, and resetting log levels and restarting application pools hasn't helped any.
Also, if I attempt to invoke the StartWorkflowOnListItemBySubscriptionId web service manually using a tool like Postman there are no errors and the workflow starts as expected.
Things I have ensured:

*

*The Workflow Can Use App Permissions site feature is enabled

*The Workflow app has been granted full control to the scope: http://sharepoint/content/sitecollection/web

*The Call HTTP Web Service action is wrapped in an app step in the workflow

A: Try removing the call from AppStep.
I was running into the same had the same problem and the workflow started when I moved the "call HTTP" outside of the App Step


text:
Q: Disable pdf-text searching with pdfBox I have a pdf document (no form) where I want to disable the text searching using pdfBox (java).
Following possibilities I can imagine:

*

*Flatten text

*Remove Text information (without removing text itself)

*Add overlay to document.

Currently I've no idea how I can implement that. Does anyone has an idea how to solve that?

A: many thanks for your help here. I guess I found a way that fit to the requirements. (Honestly, not really clean):

*

*Add the rectangle to the address sections

*convert PDF to image

*convert image back to pdf.

While losing all text information, the user isn't able to see the critical information anymore. Due to the reason, that this is only for display (the initial PDF document doesn't get changed) this is ok for now.

A: It depends on your goals:

*

*avoid everything on some texts: print, mark with black ink, and scan again;

*delete sensible text: you have to scan inside text, and remove/replace it (with pdfbox), but it is risky (some text are splitted);

*mask some text for viewer : find text and add a black rectangle (with pdfbox), but it is not very safe. You can remove the rectangle, or use another tool to read the text. Usually, if text is inside, some tool can find it;

*avoiding copy/paste the text (but not search / view): use security options, with password:
see: https://pdfbox.apache.org/2.0/cookbook/encryption.html
PDDocument doc = PDDocument.load(new File("filename.pdf"));

// Define the length of the encryption key.
// Possible values are 40, 128 or 256.
int keyLength = 128;
// 256 => plante

AccessPermission ap = new AccessPermission();

// disable printing, everything else is allowed
ap.setCanPrint(false);

ap.setCanExtractContent(false);
ap.setCanExtractForAccessibility(false);

// Owner password (to open the file with all permissions) is "12345"
// User password (to open the file but with restricted permissions, is empty here)
StandardProtectionPolicy spp = new StandardProtectionPolicy("12345", "", ap);
spp.setEncryptionKeyLength(keyLength);
spp.setPermissions(ap);
doc.protect(spp);

doc.save("filename-encrypted2.pdf");
doc.close();


text:
Q: Is there any code torch.backends.cudnn.benchmark/torch.cuda.synchronize() similar in tensorflow? I am working on optimizing CUDA program's performance.
I used torch.backends.cudnn.benchmark to optimize performance and torch.cuda.synchronize() to synchronize CUDA applications in pytorch.
To do the same job in tensorflow I searched a lot time whether similar code is in tensorflow, however I could'nt find anything.
I wonder is there any equivalent code to
torch.cuda.synchronize() and torch.backends.cudnn.benchmark exists in tensorflow.


text:
Q: Native method in Java, C in Java, Java Native Interface (JNI) I create native method but I have bad signature

*

*algorithm.java

package knapsacproject;

public class algorithm {

    /**
     *
     * @param cost
     * @param profit
     * @param cmax
     * @param gens
     * @param turns
     * @return
     */
    public native int [] geneticAlgorithm(int[] cost, int[] profit, int gens, int turns,int cmax);
static  {
try {
 System.load("C:/Users/Desktop/dp/KnapSacProject/src/knapsacproject/helllo.dll");
    System.out.println("loaded successfully");
} catch (Exception e){
    e.printStackTrace();
}
}
protected int[] cost, profit, result;
protected int gens, turns, cmax;

 public algorithm(int[] cost,int[] profit, int gens ,int turns , int cmax ) {
 this.cost=cost;
 this.profit=profit;
 this.gens=gens;
 this.turns=turns;
 this.cmax=cmax;
 }

 public int[] getResult(){
 return geneticAlgorithm(cost, profit, gens, turns, cmax);
 }
 public static void main (String[] args ) {
         }
}

my generate header
knapsacproject_algorithm.h

/* DO NOT EDIT THIS FILE - it is machine generated */
#include <jni.h>
/* Header for class knapsacproject_algorithm */

#ifndef _Included_knapsacproject_algorithm
#define _Included_knapsacproject_algorithm
#ifdef __cplusplus
extern "C" {
#endif
/*
 * Class:     knapsacproject_algorithm
 * Method:    geneticAlgorithm
 * Signature: ([I[IIII)[I
 */
JNIEXPORT jintArray JNICALL Java_knapsacproject_algorithm_geneticAlgorithm
  ( JNIEnv *, jobject , jintArray  , jintArray , jint , jint , jint);

#ifdef __cplusplus
}
#endif
#endif

 and my C. in Java

galib.c

#include <jni.h>
#include "knapsacproject_algorithm.h"
#include "gaParameters.h"
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>

JNIEXPORT jintArray JNICALL Java_knapsacproject_algorithm_geneticAlgorithm
 ( JNIEnv * ?, jobject ?, jintArray  ?, jintArray ?, jint ? , jint  ?, jint ?);

So, I can not add parameters in my galib.c and what will be instead of "?", or how to create .c file?

A: You can use whatever parameter names you like in the C function implementation.  It makes no difference whatsoever to any caller, including the JVM.
With that said, for the parameters that correspond between the Java method parameters and the C method parameters, it is common to use the same names.  The other two parameters represent the JNI environment in which the call occurs, and the object on which the method is invoked.  The former is often named env.  I tend to name the latter according to the class to which the method belongs (e.g. algorithm), but other names abound -- obj, o, self, etc..
One of the many possible combinations would be
JNIEXPORT jintArray JNICALL Java_knapsacproject_algorithm_geneticAlgorithm(
        JNIEnv *env, jobject algorithm, jintArray cost, jintArray profit,
        jint gens, jint turns, jint cmax) {
    // ...
}

Note, too, that in your example C file you present a function prototype, but the header file already contains a prototype.  It is not wrong to provide another, but neither is it useful.