text:
Q: Past Simple for repeated actions/habits This question evolved from a thread I created here yesterday (Past simple vs used to vs would). But as some of my previous doubts were resolved, another arose, and for the sake of brevity, and because I hoped this might draw in some new people, I decided it'd be best to write a separate post.
I'm having a bit of trouble telling the difference between using the past simple tense and "would" form in sentences that describe past repeated/habitual actions. The main troubling issue for me is the fact that it's sometimes pretty vague whether the speaker implies single or repeated action if they use solely the past tense. Does it always depend on the context of the whole statement?
Is there a situation when one of these forms is preferred to another? Are there even any rules regarding their use, or are they mostly interchangable?
For example, this quotation from The Clockwork Orange incorporates both forms in separate, consecutive utterances:

The Korova milkbar sold milk-plus, milk plus vellocet or synthemesc or drencrom, which is what we were drinking. This would sharpen you up and make you ready for a bit of the old ultraviolence.

Still, a short note about Ted Bundy's Modus Operandi seems to limit its structure solely to "would" forms.

Sometimes, Bundy would use a fake cast to play on a potential victim's sympathy. He would ask them for assistance of some kind, such as helping him put something in his car or asking for directions.

On the other hand though, the Wikipedia article about this murderer again utilizes both forms:

He would employ various ruses designed to lure his victim to the vicinity of his vehicle where he had pre-positioned a weapon, usually a crowbar. In many cases he wore a plaster cast on one leg or a sling on one arm, and sometimes hobbled on crutches, then requested assistance in carrying something to his vehicle.

To top it all, the two following sentences sound to my ear equally good no matter which form I choose and I really can't tell if one's better than another.

*

*The Aztecs used/would use shells and jewels to create dyes.

*He only spoke of it/would only speak of it when he was under a lot of pressure.

I find the entire issue really twisted and tangled, and I really hope someone can provide an in-depth explanation.

A: In this statement
He spoke of it when he was drunk.
we don't know if he was often drunk. He might have been. Maybe it was just that one time. Or now and then.
In this statement
He would speak of it when he was drunk.
we know that he was drunk at least from time to time. More than once. Enough to qualify as a "recurrence".
P.S. But all we have to do, to change the first sentence into a recurrent scenario, is to change one little word:
He spoke of it whenever he was drunk.
The tense did not change.  You must attend to the other time-aspect-words in the sentence (e.g. "only ... when").
P.P.S. The simple past can be used to express a recurrent or habitual situation, or a modus operandi/modus vivendi scenario; however, it cannot do so unambiguously, not unless corroborating time-phrases appear in the statement itself, or a corroborating context has been established in the conversation.
In antiquity, they made pain-killers from willow bark.
They spent winters in Florida and summers in Maine.

A:
The Korova milkbar sold milk-plus, milk plus vellocet or synthemesc or drencrom, which is what we were drinking. This would sharpen you up and make you ready for a bit of the old ultraviolence.

There are actually two different uses going on here. I think the "would" in "This would sharpen you up" is used to transform the statement into a conditional or hypothetical. For example, "That painting would look nice over the fireplace." In this case the implied condition under which "sharpening up" will occur is the drinking the milk-plus.
In the Bundy examples, "would" is preferred because they are generalized statements about his tactics rather than a recital of his crimes. The same generalization is accomplished without the use of "would" by starting a sentence with "in many cases," although the meaning of the sentence would not significantly change had the author chosen to include the word "would".
The last two examples are perfectly valid constructions either way, but you might prefer one over the other depending on context. The meanings are only very subtly different.

The Aztecs used shells and jewels to create dyes.

The above sentence simply states a historical fact about what the Aztecs did. It works well in multiple contexts.

Example A: "I walked through the exhibit. In one diorama, the Aztecs sacrificed a human being. In another, the Aztecs used shells and jewels to create dyes."
Example B1: "Archaeological evidence suggests that the Aztecs used shells and jewels to create dyes for application to clothing, ceramics, and architecture."
Example B2: "Archaeological evidence suggests that the Aztecs would use shells and jewels to create dyes for application to clothing, ceramics, and architecture."

Note that in Example A, "would use" would not be appropriate. However, in Example B, "used" and "would use" are interchangeable without losing the essential meaning.

The Aztecs would use shells and jewels to create dyes.

The above sentence states the same historical fact, but generalizes it as a habitual aspect in past time. As an example, it might be used when describing a scene or trying build a sense of atmosphere. The "would" might also be used for emphasis or contrast.

Example C: "The Aztecs would gladly use shells and jewels to create dyes, but they would never use turmeric."
Example D: "In the fourteenth century, Aztecs would use shells and jewels to create dyes, toiling for untold hours to achieve what is now accomplished by simply boiling powdered cochineal insects. How fortunate we are to live in such an enlightened age."

Again, in the Example D above, you could substitute "used" for "would use" without greatly affecting the meaning. However, "would use" is favored by the author to call attention to the abnormality.

Edit for more examples:
Remember that "would" in this usage describes habitual, or typical behavior.
I'm going to drop the "only" from your final example, because the modifier makes the two statements roughly equivalent. There is more contrast without it.

He spoke of it when he was under a lot of pressure

This statement means he spoke of it at least one time, and he was under pressure at the time that he spoke of it.
It can be considered a discrete event, solidly in the past.

He would speak of it when he was under a lot of pressure

This statement means that whenever he was under pressure, he spoke of it. It suggests that this occurred more than once. The central meaning conveyed is not the past event(s), but the past behavior: activity that was typical, or which could be generalized. This is why we call it "habitual."
The behavior is typical, such that if you traveled back to the timeframe being discussed, the occurrence "would" happen again (conditional/future tense) if the correct conditions were supplied.
Here are a few more examples that may shed some light on the different scenarios:
Simple Past for Discrete event(s):

Last month, I stopped at a gas station for a bite to eat after work.
Seven times last month, I stopped at a gas station for a bite to eat after work.

Simple Past with a frequency for Habitual Behavior:

Last month I frequently stopped at a gas station for a bite to eat after work.

Would for Habitual Behavior:

Before getting married I would stop at a gas station for a bite to eat after work.

Would for Contrasting Habitual Behavior:

In previous years I would stop at a gas station for a bite to eat. Now I wait until I get home.

Would for Habitual Past Tense Conditional:

I would stop at a gas station for a bite to eat if it wasn't too cold outside.

And for the sake of completeness...
Would for Present Tense Conditional:

I would stop at a gas station for a bite to eat if it weren't so cold outside.

Would for Discrete Past Tense Conditional:

I would have stopped at a gas station for a bite to eat if it hadn't been so cold outside.

A: This is just to add some commentary regarding the ambiguity of the simple past. And also some strategies that a person  might use to try to resolve this ambiguity.
Yesterday I started reading a new book. (This is not an example sentence; I'm telling you something true about my life, something that brought this question to my mind.) Anyway, I opened the book and read the first paragraph (which is one sentence), and I have no Idea whether the simple past is being used to talk about a single activity in the past or about a habitual activity. Let me quote this opening sentence from Men at Arms, the first novel in the trilogy Sword of Honour by Evelyn Waugh.

When Guy Crouchback's grandparents, Gervase and Hermione, came to Italy on their honeymoon, French troops manned the defenses of Rome, the Sovereign Pontiff drove out in an open carriage and Cardinals took their exercise side-saddle on the Pincian Hill.

Now, I am not sure how great an opening sentence to a novel that is. An opening sentence is supposed to grab you and make you want to keep reading, or so say many. However, the point is that when I read that opening sentence, my mind was trying to interpret what the author, or rather the text, was saying.
For one who is fairly new to Evelyn Waugh's style and also who is ignorant of all but the most cursory description of what the book is about, I am all but "flying blind" here, with no instruments to guide me.
Anyway, as I read the sentence, I frowned. Because I immediately recognized that the simple past here could be referring to a one time action (all the verbs) or those verbs in the independent clause could be talking about three customary or habitual activities that just happened to be going on when 'the grandparents came to Italy'.
It is very easy to read the sentence either way.
Now the strategies we use to solve this conundrum include our knowledge of how novels usually begin. Many novels, as I hinted, begin with action. So, taking this into account points toward the single event interpretation. Supporting evidence for this is that the arrival of a honeymooning couple often calls for certain individuals to perform certain activities.
On the other hand, novels can open with description, in order to set up a background against which events unfold. In addition, the singularity of events being described point a customary activity, because the singularity suggests that they occur repeatedly at a certain place only.
One last clue that is ultimately inconclusive  in helping solve our mystery is to notice that the use of the zero-article before French troops and Cardinals serves as an indefinite rather than as a definite reference to these two groups. One could argue that such an indefinite reference is used for descriptions of habitual activities, but, alas, this is not always the case. Again, we cannot lay down ironclad rules for these things. Which is a good thing, because this openness does not restrain the speaker or writer in his creativity. It also allows for a reader or listener to potentially take wonder in how different texts, speakers or authors can utilize the language as a means of unique and even genius creative expression.
Thus the point of posting this real life example from a native speaker who is a skilled and educated reader is to show you that struggling with this issue is not unique to the language learner. It was also meant to show that we use our intuition to try to intuit the text's meaning. We make a possible case for each meaning, and perhaps most importantly we rely on context to provide clues to the intended meaning. And we do this no matter which text is before us,   whether a novel or the screaming rampage of a neighbor.
So now what does one do?
The only answer is to keep reading. The hope is that reading further will lend more clues as to which sense the simple past is being used in. Further reading could provide clues lifted from the writer's style itself (this is how the writer normally describes a single  activity or a customary activity) or from further description of the plot. It remains to be seen if the French troops, the Supreme Pontiff and the Cardinals were actually performing a (single) activity or just having their normal or customary behavior described. Certainly a simple would before the last three verbs would solve the issue. But why would an author choose not to do this? I doubt it is to disconcert his reader.  I think it has to do with style and how the sentences read with the 'bare' simple past. That is a question you can ponder.


text:
Q: How to bind dynamic values to the dropdown using ionic 2 & Angular Hi im just trying to bind the  dynamic values to the dropdown but i confused how to bind it .
here is my json data
    [
  {
    "Name": "data1",
    "sno": 3

  },
  {
    "Name": "data2",
    "sno": 4
  },
  {
    "Name": "data3",
    "sno": 5
  }

here im calling my dynamic data using providers
dropDown(){
var url1 ='http://xxxxx.xxxx.xxxx.xxx/info/Service1.svc/getData';
return this.http.get(url1).map(result=>{
  return result.json();
})

after that im calling this in a page by calling it in the constructor and  then using ngOnIt im initializing it
selectedValue: number;
  optionsList: Array<{ value: number, text: string}> = [];

the after declaring in the constructor
`ngOnInit(){

    this.optionsList = this.serv.dropDown().subscribe( response =>{

      console.log(response.json());

    });

  }`

 <ion-select>
    <ion-option *ngFor="let item of optionsList" value="{{item.value}}">{{item.text}}</ion-option>
  </ion-select>

but im getting error as subscription is not assignable to the type and how to get the selected value and text?

A: You are assigning the returned value of subscribe which is an Observable to this.optionsList hence the error.
There are 2 ways to fix this:
1- you can use the async pipe to your *ngFor :
<ion-select>
    <ion-option *ngFor="let item of optionsList | async" value="{{item.value}}">
    {{item.text}}</ion-option>
</ion-select>

Also remove the callback in subscribe :
ngOnInit(){
    this.optionsList = this.serv.dropDown().subscribe();
}

2- Assigning the your property optionsList :
ngOnInit(){
    this.serv.dropDown().subscribe( response =>{
      this.optionsList = response;
    });

}

Note that I removed .json() function since the map function is already doing it for you.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Why is $PSScriptRoot referencing itself? I'm in PowerShell ISE and $roster = Import-Csv '$PSScriptRoot\Company Roster.csv' returns the error

Import-Csv : Could not find a part of the path 'C:\Users\\Desktop\Change\
$PSScriptRoot\Company Roster.csv'.
At C:\Users\\Desktop\Change\Form.ps1:30 char:15
+     $roster = Import-Csv '$PSScriptRoot\Company Roster.csv'

Why is $PSScriptRoot seemingly including its own variable name in its reference?

A: No, the variable does not include itself. You just put it in single quotes, which prevent variable expansion, so your script is looking for a file with the literal name $PSScriptRoot\Company Roster.csv in the current working directory.
Change the single quotes to double quotes, and the problem will disappear.
$roster = Import-Csv "$PSScriptRoot\Company Roster.csv"


text:
Q: Background image covers the game I just started learning Java and I am trying to develop a simple game (pretty much like Space Invaders). I am trying to set up a background image to my game instead of just setting a color for the background.
Problem: The background image overrides/overlaps my game. I can't see my game anymore. How do I fix this?
Relevant Codes:
public class Board extends JPanel implements Runnable
{

    private Player player;
    private Player2 player2;
    private EnemyWave enemyWave;
    private List<Guard> guards;

    private boolean inGame;
    private Integer lives;
    private Integer lives2;
    private String message;

    Board()
    {

        JLabel backgroundImage;

        inGame=true;
        lives=3;
        lives2=3;

        player=new Player(START_X, START_Y);
        player2  =new Player2(START_X-180, START_Y);
        enemyWave = new EnemyWave();

        guards = new ArrayList<>();
        for(int i=0; i<6 ; i++) {
            guards.add(new Guard(GUARD_POSX + i * 125, GUARD_POSY));
        }

        addKeyListener(new KAdapter());
        setFocusable(true);
        //setBackground(new Color(168, 219, 127, 116)); // Background color

        // BACKGROUND IMAGE
        ImageIcon img = new ImageIcon("background.jpg");
        backgroundImage = new JLabel("",img,JLabel.CENTER);
        backgroundImage.setBounds(0,0,1200,700);
        add(backgroundImage);

    setVisible(true);
    }

    @Override
    public void addNotify() {
        super.addNotify();

        Thread animator = new Thread(this);
        animator.start();
    }

    @Override
    public void run() {

        long beforeTime, timeDiff, sleep;

        beforeTime = System.currentTimeMillis();

        while(inGame) {
            repaint();
            animationCycle();       //mechanics of a game

            timeDiff = System.currentTimeMillis() - beforeTime;
            sleep = DELAY - timeDiff;

            if(sleep<0) {
                sleep = 2;
            }
            try {
                Thread.sleep(sleep);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            beforeTime=System.currentTimeMillis();
        }
        gameOver();
    }

    @Override
    public void paintComponent(Graphics g) {

        super.paintComponent(g);

        Font font = new Font("Verdana", Font.PLAIN, 18);
        g.setColor(Color.RED);
        g.setFont(font);

        g.drawString("Player 1 Lives: " + lives.toString(), BOARD_WIDTH - 185, 25);
        g.drawString("Enemies Left: " + enemyWave.getNumberOfEnemies().toString(), 28, 25);

        g.drawString("Player 2 Lives: " + lives2.toString(), BOARD_WIDTH - 185, 55);

        g.setColor(Color.GREEN); // border color where the plane lies
        g.drawLine(0, GROUND, BOARD_WIDTH, GROUND);

        player.draw(g, this);
        if (player.getM().isVisible())
            player.getM().draw(g, this);

        //create
        player2.draw(g, this);
        if (player2.getM().isVisible())
            player2.getM().draw(g, this);

        enemyWave.draw(g, this);

        for (Guard guard : guards) {
            guard.draw(g);
        }
    }
}

Before setting background image:
After setting background image (completely covered my game):

A: Swing has a parent/child relationship.
So a component will:

*

*first paint itself based on the painting logic found in the paintComponent(...) method.

*then paint any child components added to the panel.

In the constructor of your class you have:
add(backgroundImage);

which add the component to the panel, meaning it will paint on top of your custom painting.
Don't use a JLabel for your background.
Just paint the Image as the first step in your paintComponent(...) method.

A: Added this in my Board class:
Image bg = Toolkit.getDefaultToolkit().getImage("bg.jpg");

Added this in my paintComponent method:
g.drawImage(bg, 0, 0, null);

And it worked!


text:
Q: Using both Entity Framework and SqlConnection? Background
I'm working on a project which contains both legacy code and Entity Framework code. I was advised to use a specific dataservice method to operate on a record from the database. The record was retrieved via Entity Framework, and I passed the PK into the dataservice function to perform the operation.
Preconditions for success and failure
If the network was up, both DB calls (entity and SQL) would succeed. If the network went down, then came back up and this code was executed, then it would retrieve the locked records with entity framework but then fail with the SqlException below.
This got me thinking, what is going on here that might cause the SqlConnection to fail despite EF being able to make the connection.
Code Samples
A code sample follows:
public void HandleNetworkBecomesAvailable() {
    _entityFrameworkDataService.ReleaseRecords();
}

EntityFrameworkDataService.cs
    public void ReleaseRecords()
    {
        using (var context = new Entities()) // using EntityConnection
        {
            var records = context.Records.Where(
                record => record.IsLocked).ToList();

            foreach (var record in records)
            {
                 _sqlConnectionDataService.UnlockRecord(record.ID);
            }
        }
    }

SqlConnectionDataService.cs
    public void UnlockRecord(int recordId)
    {
        using (var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["Sqlconnection"].ConnectionString))
        {
            connection.Open();

            using (var command = connection.CreateCommand())
            {
                command.CommandText = @"UPDATE [Records] SET [IsLocked] = 0";
                //etc

                command.ExecuteNonQuery();
            }
        }
    }

App.config
<add name="EntityConnection" connectionString="metadata=res://*/FooDatabase.csdl|res://*/FooDatabase.ssdl|res://*/FooDatabase.msl;provider=System.Data.SqlClient;provider connection string="data source=RemoteServer;initial catalog=FooDatabase;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
<add name="SqlConnection" connectionString="Server=RemoteServer;Database=FooDatabase;Trusted_Connection=True" />

Now, after discussing with my coworkers, I ended up moving the logic into the entity framework dataservice and doing the work there. But I'm still not quite sure why the connection kept failing.
Edit: The actual error is:

An exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll but was not handled in user code
Additional information: A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)
Inner Exception:
The network path was not found

But Entity Framework is using the same network path, as can be seen in the two connection strings in the App.config.

A: Could you be benefiting from entity framework's new resiliency, where it retries transparently? If the error is intermittent, you won't even know it retried, whereas ADO.net is letting you know it fails as soon as it fails. Just checking...


text:
Q: Fabric Crashlytics Android events sending I'm using Fabric Crashlytics for Android and it's really a great engine, and notifies me whenever there's a crash (on both the dashboard and my emai), but what i want to know is that:
Can I send an event to the dashboard (or my email) when the app catches an exception (i.e can i send the exception.printStackTrace() whenever the app catches an exception)?

A: Yes, you can.
https://docs.fabric.io/android/crashlytics/caught-exceptions.html
try {
    ...
} catch (Exception e) {
    Crashlytics.logException(e);
    // handle your exception here!
}

A: If you want to log details of the error, see fabric doc
try
{
   // your code
}
catch(Exception e)
{
   Crashlytics.logException(e);
}

A: I found it, we can log the catched exceptions
HERE IT IS
https://docs.fabric.io/android/crashlytics/caught-exceptions.html


text:
Q: How do Firestore writes done offline handle authentication state? Firestore.firestore().document("someCol/someDoc").updateData([
    "someField": FieldValue.delete()
]) { (error) in
    // returns nothing in the scenario described below
}

*

*The client is signed into Firebase Auth.

*The Firestore security rules require authentication to perform writes.

*The client is offline and performs a write operation.

If the client signs out of Auth before it comes back online, the write will not execute, as I would expect. I assume this is because the authentication credentials were not queued with the write operation when the client was offline. Can this be confirmed? However, I would expect the completion handler of this write operation to return an error, but it returns nothing. Why does it return nothing and is this the way it should behave?

A: In a normal situation the Authentication SDK will try to refresh the auth credentials once the connection is restored, before it tries to commit the writes to Firestore.
If you explicitly sign the user out while offline, that refresh won't happen as you signed the user out, so your writes will indeed fail.

I'm not sure why you don't get an error in your completion handler, but it's hard to be certain of anything without seeing the exact flow of all three components: Firestore writes, user authentication state, and being online/offline. A repro in a site like jsbin/stackblitz might be the easiest way to share that in a minimal form.


text:
Q: mysql get conditional value from mysql select? So say I have a table called users with the following values: ip, id, and user. If I want to get all the users based on ip, but don't have the ip, then I would do first select ip from users where user = "user"; and afterwards, select user from users where ip = "xxx.xxx.xxx.xx[x]"; (the x's being the ip numbers gotten from the first query). Is there not a way to do something like select user from users where ip = "[insert ip query here to get ip]" where the whole thing is compacted in 1 query? I know this may sound silly over 2 statements, but every cpu cycle counts for my program especially on a rather slow platform.

A: If I understand correctly a question for the query you're looking for is Find me all users who share the same ip as userX. If it is the case then you can do it either with JOIN
SELECT DISTINCT u1.user
  FROM users u1 JOIN users u2
    ON u1.ip = u2.ip
 WHERE u2.user = 'some_user';

or with a subquery
SELECT user
  FROM users
 WHERE ip IN
 (
     SELECT DISTINCT ip
       FROM users
      WHERE user = 'some_user'
 );

or with EXISTS
SELECT DISTINCT u.user
  FROM users u
 WHERE EXISTS
 (
     SELECT *
       FROM users
      WHERE ip = u.ip
      AND user = 'some_user'
 );

Note: make sure that you have indices on ip and user.
Here is SQLFiddle demo

A: It looks like you're doing the same query twice, the following example shows a nested select, it it an incredibly redundant example but It shows what you want (I think)
SELECT user FROM users
WHERE user = (SELECT user FROM users
              WHERE ip = "xxx.xxx.xxx.xx[x]");

In this query the subquery will actually return the same as the outer query so it's pointless.

A: i guess that u can use subquery like this:
select user from USERS where ip in(select ip from USERS where user like "%user%")


text:
Q: Базовая логика экранов в рамках Clean Architecture Есть n фрагментов, на каждом из них необходимо отображать информацию о Relationship (online status, relationship name, users count). До этого загрузка была вынесена в BaseFragment (запрос к базе реализован с помощью Single).  Но как эту же логику реализовать в рамках Clean Architecture?

A: Согласно подходу Чистой архитектуры, ваша бизнес логика должна быть выделена в UseCase или интерактор. Однако, вы можете переиспользовать один и тот же интерактор для работы с некоторой сущностью, в вашем случае, Relationship, который внутри себя будет иметь репозиторий, в котором и будет описана сетевая логика и логика кеширования.
Если у фрагментов есть своя логика, у них будут свои интеракторы-фасады. Эти интеракторы могут содержить один "общий" интерактор, описанный выше. Инстанс этого интерактора с нужным скоупом вы можете внедрить в туда, где он нужен.
Таким образом, логика вызова и первичной обработки модели будет в одном месте.
Данный подход избавляет вас от стандартной проблемы наследования. Если у одного из фрагментов будет несколько "базовых" сущностей, то вместо сложной иерархии наследовании, вы сможете использовать обычную композицию.


text:
Q: 'Invalid multibyte sequence in JVM console output: Invalid or incomplete multibyte or wide character' after Java special symbol logging I try to log special symbol '®' with Java slf4j Logger
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

private static final Logger LOG = LoggerFactory.getLogger(MyClass.class);

LOG.info("®");

And get this error message in console
WARN   | wrapper  | main    | 2019/10/10 12:29:09.677 | Invalid multibyte sequence in JVM console output: Invalid or incomplete multibyte or wide character

My locale:
LANG=en_US.UTF-8
LC_CTYPE="en_US.UTF-8"
LC_NUMERIC="en_US.UTF-8"
LC_TIME="en_US.UTF-8"
LC_COLLATE="en_US.UTF-8"
LC_MONETARY="en_US.UTF-8"
LC_MESSAGES="en_US.UTF-8"
LC_PAPER="en_US.UTF-8"
LC_NAME="en_US.UTF-8"
LC_ADDRESS="en_US.UTF-8"
LC_TELEPHONE="en_US.UTF-8"
LC_MEASUREMENT="en_US.UTF-8"
LC_IDENTIFICATION="en_US.UTF-8"
LC_ALL=

What the reason of the problem?
echo ®

This command works


text:
Q: Android custom view onDraw I'm trying to make a control that is a composition of another controls. I've tried many ways but none seems to work... You ask why do I need that? Becaused

*

*I've faced the impossibility of creating a TextView with
different colors of shadow and gradient foreground

*I want to make
    a volume text and it's going to be presented by this custom controls
public class MainMenuItem extends View {
    private MainMenuItemHelper firstLayerItem;
    private MainMenuItemHelper secondLayerItem;

    ...
    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        secondLayerItem.draw(canvas);
        firstLayerItem.draw(canvas);
    }
}

public class MainMenuItemHelper extends TextView {
    private List<DrawCommand> commands;

    ...
    @Override
    protected void onDraw(Canvas canvas) {
        for (DrawCommand command : commands) {
            command.draw(canvas, getPaint());
            super.onDraw(canvas);
        }
    }
}

A:
a control that is a composition of another controls

You need at least a Layout like RelativeLayout or LinearLayout as a View can't contain another View. You need a ViewGroup instead.
I don't know where and how you want to place it but the easiest way is to simply make a xml file containing your controls and style them like you would normally do.
A shadow color can be defined by android:shadowColor to have a shadow for your text.
Making the text itself being a gradient might be very tricky.


text:
Q: Probability using tree diagram. There are three army privates and they are shooting at the same target, each with one
bullet only. The first private has a 0.8 chance of hitting the target, the second private has a 40% chance of missing the target, and the last private has a probability of 90% of being on target. What is the probability that all three privates will hit the target?
Hint : Use tree diagram.

A: Since it is assumed the privates' chances of hitting the target are independent of each other, the probability of all three hitting is simply the product of the probabilities of each hitting $=.8\times .6\times .9=0.432$.


text:
Q: graph-theory combinatorics Here is a combinatorics problem having to do with graph-theory
Ten players participate at a chess tournament. Eleven games have
already been played. Prove that there is a player who has played at least 3 games.

A: Say player $i$ has played $r_i$ games. Since $11$ games have been played
$$r_1+r_2+\ldots +r_{10}=22.$$
If we suppose that each player has played at most 2 games then
$$r_1+r_2+\ldots +r_{10}\leq 20$$
giving us a contradiction.

A: Not exacly Graph Theory, more Pigeonhole Principle. Every time a player plays a game, she makes an X on the blackboard. Since $11$ games have been played, and each game involves $2$ people, there are $22$ X on the blackboard. So one player must have made $3$ or more X. This is because if all players had made $2$ or fewer X, there would be at most $20$ X on the board.
Or else think in terms of money. Every time a player plays, she puts $1$ dollar into the beer fund. Since $11$ games have been played, there are $22$ dollars in the beer fund. So one player at least must have put in $3$ dollars or more, that is, played $3$ or more games.


text:
Q: Ошибка "no matching function" программисты! Учу C++ по книне Васильева А.Н. "Программирование на С++ ". Столкнулся с такой проблемой, что не могу скомпилировать код из главы "Наследование обобщенных классов". Ниже приведу сам код. Пишу все в CodeBlocks.
Ошибка:

error: no matching function for call to 'Charlie<std::__cxx11::basic_string<char>, и тд>'

Что тут не так?
#include <iostream>
#include <cstdlib>
#include <string>

using namespace std;

template<class A> class Alpha
{
public:
    A alpha;

    Alpha(A a)
    {
        alpha = a;
    }

    void show()
    {
        cout << "Поле Alpha: " << alpha << endl;
    }
};

template<class B> class Bravo
{
public:
    B bravo;

    Bravo(B b)
    {
        bravo = b;
    }

    void show()
    {
        cout << "Поле Bravo: " << bravo << endl;
    }
};

template<class A, class B, class C> class Charlie : public Alpha<A>, public Bravo<B>
{
public:
    C charlie;

    Charlie(C c) :Alpha<A>(a), Bravo<B>(b)
    {
        charlie = c;
    }

    void show()
    {
        Alpha<A>::show();
        Bravo<B>::show();
        cout << "Поле Charlie: " << charlie << endl;
    }
};

int main()
{
    system("chcp 1251>nul");

    Charlie<string, char, int> objA("текст", 'A', 100);
    Charlie<int, double, char> objB(200, 5.5, 'B');

    objA.show();
    objB.show();

    return 0;
}

A: Достаточно написать корректный конструктор....
template<class A, class B, class C>
Charlie(A a, B b, C c) :Alpha<A>(a), Bravo<B>(b)
{
    charlie = c;
}


text:
Q: How to format  elements in HTML5 to provide meaningful insight to assistive device users? What is the best way is to have a screen reader type assistive device announce sections in an insightful way?
Ideally, rather than passing this job onto a child
 tag is there a way to mark up the actual
 tag that can serve this purpose?
Where an
 is broken into
s the idea is that
s are not suitable for syndication but they should still have their own inherent identity within the document structure. How do we as HTML authors document this?
Example: given this tree:
Article: A review of the iPad
section: brief preamble, statement of goals
section: aesthetics
section: performance
section: target market
section: wrap up

How do we mark up the
s to empower assistive devices to pluck the section focus from the
 tag?
Here's an example in HTML:
<!DOCTYPE html>

An article about markup!

Example 1

Example 2

Example 3

So: are any of examples 1 through 3 a good choice, or is there a better option?

A: If I understand what you are after, you should add role="region" to the section elements, like  so:

This will tell the screen reader that the section is indeed a section, and will provide the correct accessibility information to the user. This role is an WAI-ARIA role. Ideally it would not be needed, as the section element has implied semantics, but there is better support for ARIA in screen readers than there is for HTML5 elements, so this plugs the gaps until support is widespread.
You can add the aria-labelledby attribute to the section element and associate it with the ID of the h* if you want the heading to be announced by the screen reader when it is announcing the section, such as "Example 1 region" in Jaws.
For each of your headings in the sections, it could be a good idea to include them in a header element too, like so, although not strictly needed (I often do it just for the main article heading)

An article about markup!

Example 1

Example 2

Example 3

For more information see http://blog.paciellogroup.com/2011/03/html5-accessibility-chops-section-elements/, http://blog.paciellogroup.com/2010/10/using-wai-aria-landmark-roles/ and http://blog.paciellogroup.com/2013/10/using-html5-section-element/

A: I addition to dstorey's excellent advice, I would say that you should not use
 at each section level.
Although it was previously recommended, that recommendation has changed in HTML5 and now the advice is to use the <h?> level that works for the whole document. i.e. if the top level article uses an
 then the sections should use
, the same as you would have done in HTML 4.
The reason is that using
 throughout depends on the implementation of the HTML5 outline algorithm. Unfortunately, it seems that browsers are unwilling to implement the algorithm, and the screen readers are either unwilling or unable to do so correctly. So nowhere in the accessibility tool chain is the outline being correctly processed and assistive device users will not be able to understand the heading levels correctly.

A: Possible styling solution via CSS3 is shown below; you can modify it up to your needs.
Here is a link to jsfiddle for your convenience: http://jsfiddle.net/M6mpt/
HTML
<!DOCTYPE html>

An article about markup!

Example 1

Example 2

Example 3

CSS3
.article1 {
    font-family: Arial;
}

.article1 h1 {
    text-transform:uppercase;
    font-size:1.2em;
}

.section1 h1 {
    font-size:1.1em;
    color:#606060;
}

.section2 h1 {
    color:#909090;
}

.section3 h1 {
    color:#a0a0a0;
    font-size:0.9em;
}


text:
Q: iPhone animations - Moving a view in a circle Is there a way to move a view around a center point without rotating it using the view animations?

   A

A  C  A

   A

A:     #import <QuartzCore/QuartzCore.h>
    #define degreesToRadians(deg) (deg / 180.0 * M_PI)

manualy :
-(CGPoint)setPointToAngle:(int)angle center:(CGPoint)centerPoint radius:(double)radius
 {
    return CGPointMake(radius*cos(degreesToRadians(angle)) + centerPoint.x, radius*sin(degreesToRadians(angle)) + centerPoint.y);
 }

with animation something like this:
    int angle = 0; // start angle position 0-360 deg
    CGPoint center = self.view.center;
    CGPoint start = [self setPointToAngle:angle center:center radius:radius]; //point for start moving
    CGMutablePathRef path = CGPathCreateMutable();
    CGPathMoveToPoint(path, NULL, start.x, start.y);

    for(int a =0;a<4;a++) //set path points for 90, 180, 270,360 deg form begining angle
    {
        angle+=45;
        expPoint = [self setPointToAngle:angle center:center radius:expRadius];
        angle+=45;
        start = [self setPointToAngle:angle center:center radius:radius];
        CGPathAddQuadCurveToPoint(path, NULL,expPoint.x, expPoint.y, start.x, start.y);
    }

    CAKeyframeAnimation *pathAnimation = [CAKeyframeAnimation animationWithKeyPath:@"position"];
    pathAnimation.removedOnCompletion = NO;
    pathAnimation.path = path;
    [pathAnimation setCalculationMode:kCAAnimationCubic];
    [pathAnimation setFillMode:kCAFillModeForwards];
    pathAnimation.duration = 14.0;

    [MY_VIEW.layer addAnimation:pathAnimation forKey:nil];

also look at
CGPathAddQuadCurveToPoint,
CGPathAddCurveToPoint,
CGPathAddArcToPoint,
CGPathAddArc

and others

A: Its not that big a deal to put an animation thread in and move it manually every frame so thats what I went with.


text:
Q: Sum (i...j) - is there a more efficient / elegant solution for this? We were given a simple task to come up with the most efficient way we can to sum all the numbers between a start and end point ('from' and 'to') using recursion and iteration respectively, without using the obvious formula which would be O(1).
There is no application for this, I am simply curious and challenged to see if my solution can be improved / polished more than it already is:
/* recursion */
unsigned int sum1(unsigned int from, unsigned int to) {
    if (to - from < 2)
        return from + (from == to ? 0 : to);
    else
        return from + to + sum1(from + 1, to - 1);
}

/* iteration */
unsigned int sum2(unsigned int from, unsigned int to) {
    int p = to - from;
    if (p == 0) return from;
    int i, s, n = p / 2;
    if (p % 2 == 0) s = n + from;
    else {
        s = 0;
        n++;
    }
    for (i = 0; i < n; i++) {
        s += from++ + to--;
    }
    return s;
}

A: I tried improving the iterative version:
unsigned int sum2_improved(unsigned int from, unsigned int to) {
    int p = to - from;
    if (p == 0) return from;
    int x = to + from;
    int s = 0;
    int i;
    for (i = p >> 1; i > 0; i--)
    {
        s += x;
    }
    s += (p % 2 == 0) ? x >> 1 : x;
    return s;
}

I tested your version with:
for (i = 0; i < 9999999; i++) sum2(1,999);

This is what I see:
$ time ./addm
real    0m18.315s
user    0m18.220s
sys     0m0.015s

I tried my implementation with the same number of loops. Here's how the improved function performed:
$ time ./addm
real    0m14.196s
user    0m14.070s
sys     0m0.015s

UPDATE
In my implementation x = to + from is the sum of the first and the last number in the sequence. If you consider any consecutive sequence of integers, and sum the first and last, the second and the penultimate, and so on ... all these sum up to the same value. For example, in (1 ... 6), 1 + 6 = 2 + 5 = 3 + 4 = 7. However, with a sequence containing odd number of elements, you are left with the middle number which you will then have to add to the cumulative sum (that's what the assignment following the for loop was doing.
Also, note that this is still O(n). I realized after I initially posted my answer that my approach can actually be done in constant time. Here's the updated code:
unsigned int sum0(unsigned int from, unsigned int to) {
    int p = to - from;
    if (p == 0) return from;
    int x = to + from;
    int s = 0;

    s += (x * (p >> 1));

    s += (p % 2 == 0) ? x >> 1 : x;

    return s;
}

I ran this with the same number of loops as the earlier tests. Here's what I saw:
$ time ./addm

real    0m0.158s
user    0m0.093s
sys     0m0.047s

I'm not sure if this can be considered a variation of the formula for your purposes. In any case, it was an interesting exercise for me.

A: Split the range (from zero to the upper limit n) in a lower and an upper half. For each value in the lower half there's a value in the upper half that's n/2 larger; there are n/2 of them, so the sum of the upper half is the sum of the lower half + (n/2)^2.
In Python that would be:
def sum1(lower, upper):
    if upper <= 0:
        return 0
    m, r = divmod(upper, 2)
    return sum1(0, m) * 2 + m * m + r * upper - sum1(0, lower - 1)

A: I am not going to write the code for it, but this is the kind of thing that would directly scale with the number of cores you have working on the task.
Dividing the range into tasks and starting a thread to sum each subsection of the range would divide the time required for whatever implementation you choose by the number of cores (give or take).
You could also use SIMD extensions to facilitate the addition (vector addition) by writing out the data in the memory before hand. Taking it to another extreme, you could actually use the GPU to calculate the addition of subranges (but you'd have to have a big enough range to make it worth the overhead), making it stupid fast; as this question is as simple as you can get with no dependencies whatsoever between the instructions.

A: You can use a segment tree to get the sum on the segement from i to j. This structure has O(log n) lookup time.

A: The function:
long sum(long lower, long upper) {
    long s = 0;
    s = ((upper * (upper + 1)) - (lower - 1) * (lower))/2;
    return s;
}

called with parameters: (1,9999999) returns 49999995000000 which agrees with summation formula n(n+1)/2 and runs with the following profile on a core duo:
real    0m0.005s
user    0m0.002s
sys     0m0.003s

It might be worth checking your functions, I can't see them returning this result - the mathematical option is a far superior solution ;)


text:
Q: Returning header as array using Curl I'm trying to get the response & the response headers from CURL using PHP, specifically for Content-Disposition: attachment; so I can return the filename passed within the header. This doesn't seem to get returned within curl_getinfo.
I've tried using the HeaderFunction to call a function to read the additional headers, however, I am unable to add the contents to an array.
Does anyone have any ideas please?

Below is part of my code which is a Curl wrapper class:
 ...
 curl_setopt($this->_ch, CURLOPT_URL, $this->_url);
 curl_setopt($this->_ch, CURLOPT_HEADER, false);
 curl_setopt($this->_ch, CURLOPT_POST, 1);
 curl_setopt($this->_ch, CURLOPT_POSTFIELDS, $this->_postData);
 curl_setopt($this->_ch, CURLOPT_RETURNTRANSFER, 1);
 curl_setopt($this->_ch, CURLOPT_USERAGENT, $this->_userAgent);
 curl_setopt($this->_ch, CURLOPT_HEADERFUNCTION, 'readHeader');

 $this->_response = curl_exec($this->_ch);
 $info = curl_getinfo($this->_ch);
 ...

 function readHeader($ch, $header)
 {
      array_push($this->_headers, $header);
 }

A: Here, this should do it:
curl_setopt($this->_ch, CURLOPT_URL, $this->_url);
curl_setopt($this->_ch, CURLOPT_HEADER, 1);
curl_setopt($this->_ch, CURLOPT_RETURNTRANSFER, 1);

$response = curl_exec($this->_ch);
$info = curl_getinfo($this->_ch);

$headers = get_headers_from_curl_response($response);

function get_headers_from_curl_response($response)
{
    $headers = array();

    $header_text = substr($response, 0, strpos($response, "\r\n\r\n"));

    foreach (explode("\r\n", $header_text) as $i => $line)
        if ($i === 0)
            $headers['http_code'] = $line;
        else
        {
            list ($key, $value) = explode(': ', $line);

            $headers[$key] = $value;
        }

    return $headers;
}

A: The anwser from c.hill is great but the code will not handle if the first response is a 301 or 302 - in that case only the first header will be added to the array returned by get_header_from_curl_response().
I've updated the function to return an array with each of the headers.
First I use this lines to create a variable with only the header content
$header_size = curl_getinfo($ch, CURLINFO_HEADER_SIZE);
$header = substr($a, 0, $header_size);

Than I pass $header in to the new get_headers_from_curl_response()-function:
static function get_headers_from_curl_response($headerContent)
{

    $headers = array();

    // Split the string on every "double" new line.
    $arrRequests = explode("\r\n\r\n", $headerContent);

    // Loop of response headers. The "count() -1" is to
    //avoid an empty row for the extra line break before the body of the response.
    for ($index = 0; $index < count($arrRequests) -1; $index++) {

        foreach (explode("\r\n", $arrRequests[$index]) as $i => $line)
        {
            if ($i === 0)
                $headers[$index]['http_code'] = $line;
            else
            {
                list ($key, $value) = explode(': ', $line);
                $headers[$index][$key] = $value;
            }
        }
    }

    return $headers;
}

This function will take header like this:
HTTP/1.1 302 Found
Cache-Control: no-cache
Pragma: no-cache
Content-Type: text/html; charset=utf-8
Expires: -1
Location: http://www.website.com/
Server: Microsoft-IIS/7.5
X-AspNet-Version: 4.0.30319
Date: Sun, 08 Sep 2013 10:51:39 GMT
Connection: close
Content-Length: 16313

HTTP/1.1 200 OK
Cache-Control: private
Content-Type: text/html; charset=utf-8
Server: Microsoft-IIS/7.5
X-AspNet-Version: 4.0.30319
Date: Sun, 08 Sep 2013 10:51:39 GMT
Connection: close
Content-Length: 15519

And return an array like this:
(
    [0] => Array
        (
            [http_code] => HTTP/1.1 302 Found
            [Cache-Control] => no-cache
            [Pragma] => no-cache
            [Content-Type] => text/html; charset=utf-8
            [Expires] => -1
            [Location] => http://www.website.com/
            [Server] => Microsoft-IIS/7.5
            [X-AspNet-Version] => 4.0.30319
            [Date] => Sun, 08 Sep 2013 10:51:39 GMT
            [Connection] => close
            [Content-Length] => 16313
        )

    [1] => Array
        (
            [http_code] => HTTP/1.1 200 OK
            [Cache-Control] => private
            [Content-Type] => text/html; charset=utf-8
            [Server] => Microsoft-IIS/7.5
            [X-AspNet-Version] => 4.0.30319
            [Date] => Sun, 08 Sep 2013 10:51:39 GMT
            [Connection] => close
            [Content-Length] => 15519
        )

)

A: Using the array() form for method callbacks should make the original example work:
curl_setopt($this->_ch, CURLOPT_HEADERFUNCTION, array($this, 'readHeader'));

A: Another my implementation:
function getHeaders($response){

    if (!preg_match_all('/([A-Za-z\-]{1,})\:(.*)\\r/', $response, $matches)
            || !isset($matches[1], $matches[2])){
        return false;
    }

    $headers = [];

    foreach ($matches[1] as $index => $key){
        $headers[$key] = $matches[2][$index];
    }

    return $headers;
}

Used in case, which request format is:

Host: *
  Accept: *
  Content-Length: *
  and etc ...

A: Simple and straightforward
$headers = [];
// Get the response body as string
$response = curl_exec($curl);
// Get the response headers as string
$headerSize = curl_getinfo($curl, CURLINFO_HEADER_SIZE);
// Get the substring of the headers and explode as an array by \r\n
// Each element of the array will be a string `Header-Key: Header-Value`
// Retrieve this two parts with a simple regex `/(.*?): (.*)/`
foreach(explode("\r\n", trim(substr($response, 0, $headerSize))) as $row) {
    if(preg_match('/(.*?): (.*)/', $row, $matches)) {
        $headers[$matches[1]] = $matches[2];
    }
}

A: Fixing issues:

*

*Error when content of the header contained ': '(split string)

*Multiline-headers were not supported

*Duplicate headers (Set-Cookie) were not supported

This is my take on the topic ;-)
list($head, $body)=explode("\r\n\r\n", $content, 2);
$headers=parseHeaders($head);

function parseHeaders($text) {
    $headers=array();

    foreach (explode("\r\n", $text) as $i => $line) {
        // Special HTTP first line
        if (!$i && preg_match('@^HTTP/(?<protocol>[0-9.]+)\s+(?<code>\d+)(?:\s+(?<message>.*))?$@', $line, $match)) {
            $headers['@status']=$line;
            $headers['@code']=$match['code'];
            $headers['@protocol']=$match['protocol'];
            $headers['@message']=$match['message'];
            continue;
        }

        // Multiline header - join with previous
        if ($key && preg_match('/^\s/', $line)) {
            $headers[$key].=' '.trim($line);
            continue;
        }

        list ($key, $value) = explode(': ', $line, 2);
        $key=strtolower($key);
        // Append duplicate headers - namely Set-Cookie header
        $headers[$key]=isset($headers[$key]) ? $headers[$key].' ' : $value;
    }

    return $headers;
}

A: C.hill's answer is great but breaks when retrieving multiple cookies. Made the change here
public function get_headers_from_curl_response($response) {
    $headers = array();
    $header_text = substr($response, 0, strpos($response, "\r\n\r\n"));
    foreach (explode("\r\n", $header_text) as $i => $line)
         if ($i === 0) $headers['http_code'] = $line;
         else {
              list ($key, $value) = explode(': ', $line); $headers[$key][] = $value;
         }
    return $headers;
}

A: you can do 2 ways

*

*by set curl_setopt($this->_ch, CURLOPT_HEADER, true);
header will come out with response message from curl_exec();
you must search keyword  'Content-Disposition:' from response message.

*by use this function get_headers($url) right after you call curl_exec(). $url is url called in curl.  the return is array of headers. search for 'Content-Disposition' in array to get what you want.

A: You can use http_parse_headers function.
It comes from PECL but you will find fallbacks in this SO thread.


text:
Q: Implementando callbacks en node entre llamadas a ficheros en java y servicios en la nube Estoy haciendo una aplicación que extrae el texto contenido en una imagen que está en el portapapeles. Esto es útil para cuando estoy siguiendo algún tutorial y así no tengo que copiar el código manualmente. Sino que con la herramienta de recortes de windows selecciono la porción de la imagen que quiero copiar en el portapapeles y pulsando un botón secundario del mouse (para mouse que tienen varios botones extra) pues ejecuto un script en node que hace todo el trabajo de ir al portapapeles ver que imagen hay y extraer el texto y cambiar la imagen por el texto extraido en el propio portapapeles. Así copio una imagen y pego un texto.
El proyecto está en https://github.com/GuillermoBaldan/smartClipboard
De momento lo que he conseguido:

*

*Extraer una imagen del portapapeles: usando un programita en java: Si, he usado un programa en java porque no he encontrado un paquete de npm que fuera capaz de acceder al portapapeles y extraer una imagen.

*Enviar la imagen a un servicio cloud de google que me devuelve el texto

Lo siguiente que quiero hacer es sincronizar estas dos operaciones mediante callbacks:
Primero envío una orden desde mi script en node que ejecutará el programa de java que extrae la imagen del portapapeles y después ejecuto la parte del script que envía la imagen al servicio de google.
Este es el código que tengo:
import vision from "@google-cloud/vision";

// Creates a client
const client = new vision.ImageAnnotatorClient();

//Firts we create the image from clipboard using the java file.
const fileName = "./buffer/image.png";

// Performs text detection on the local file
const [result] = await client.textDetection(fileName);
const detections = result.textAnnotations;
//detections.forEach((text) => console.log(text.description));
console.log(detections[0].description);

He intentado encadenarlo con callbacks, fichero: textFromCopiedImage.js
import vision from "@google-cloud/vision";
import child_process from "child_process";
//Creamos un cliente
const client = new vision.ImageAnnotatorClient();

const fileName = "./buffer/image.png";

//1º Ejecutar el fichero .jar para generar la imagen que después vamos a enviar para sacar el texto
//exec a .cmd file using node

function task1(cb) {
  child_process.exec(
    "java -jar ./ClipboardToImageData.jar",
    (err, stdout, stderr) => {
      if (err) {
        // node couldn't execute the command
        return;
      }
      if (stderr) {
        // the command had an error
        console.log(stderr);
        return;
      }
      console.log(stdout);
    }
  );
  cb();
}

//2º  Ejecutamos la detección del texto
function task2(cb) {
  const [result] = client.textDetection(fileName);
  cb(result);
}

function task3(result) {
  const detections = result.textAnnotations;

  console.log(detections[0].description);
  cb();
}

task1(() => {
  task2((r2) => {
    task3(r2);
  });
});

Pero me da un error:

Sospecho que client.textDetection(fileName) es una sentencia asíncrona pero no sé como manejarla, en el código anterior iba precedida de await.
Por cierto, para usar esta aplicación hay que abrir un proyecto en el google cloud platform ya que vamos a usar uno de sus servicios para extraer el texto de las imágenes.

A: Al final he optado por una solución basada en un setTimeOut y en promesas:
import vision from "@google-cloud/vision";
import child_process from "child_process";
//Creamos un cliente
const client = new vision.ImageAnnotatorClient();

const fileName = "./buffer/image.png";

//1º Ejecutar el fichero .jar para generar la imagen que después vamos a enviar para sacar el texto
//exec a .cmd file using node

function task1() {
  child_process.exec(
    "java -jar ./ClipboardToImageData.jar",
    (err, stdout, stderr) => {
      if (err) {
        // node couldn't execute the command
        return;
      }
      if (stderr) {
        // the command had an error
        console.log(stderr);
        return;
      }
      console.log(stdout);
    }
  );
}

//2º  Performs text detection on the local file

async function task2() {
  const [result] = await client.textDetection(fileName);

  const detections = result.textAnnotations;

  console.log(detections[0].description);
}

task1();
setTimeout(() => {
  task2();
}, 1000);

Realmente aunque se pueda escribir en node "Cuando acabe task1, comienzas task2" el problema no es ese, el problema es que no tenemos control sobre cuando acaba de ejecutarse el  programa de Java que se pone en marcha en task1. Así que lo que hacemos es darle un tiempo, que de forma genérica es 1 segundo (1000 milisegundos) y eso lo hacemos usando un setTimeout y declarando como asíncrona la función task2(), ya que contiene una promesa.


text:
Q: Mocking any value as input parameter with ZIO Test I mock the following function:
def deploy(deployRequest: DeployRequest, mergeResults: Seq[MergeResult]): Task[Deployment]

For the result I don't care for the inputs. So my question, is there a Way to achieve this with zio.test.mock.
Something like:
ProcessEngineMock.Deploy(any, any) returns value(deployment)

(deployment is the output)

A: Assertion.anything should do the work


text:
Q: Delete Multiple Records from ListView in ASP.NET using CheckBox in ListView Using confirmation before delete from ListView using C#. I have a ListView with CheckBox in it and I want to Delete the Items/Records from ListView which are selected with CheckBox in to it.
i.e Multiple select items and then Delete these Multiple Records from ListView
Any Idea?

A: would have left this as a comment but for some reason, I can't find where to add a comment...
The ListView control has a CheckedItems collection which you can iterate through, something like:
For Each lvi As ListViewItem In ListView1.CheckedItems
        lvi.Remove()
Next

A: foreach(ListViewItem In ListView1.CheckedItems lvi)
{
lvi.Remove()
}


text:
Q: Macro de excel que tiene problema al colocar un valor en una pagina web Estoy haciendo una macro en excel que toma los valores de una hoja de excel y la escribe en una pagina web, escribe algunos valores en algunos campo, pero en otros no me deja escribilo.
A continuacion voy a colocar el codigo de la macro y el codigo HTML de la pagina en donde no me deja escribir:
Dim ie As InternetExplorer
Set ie = New InternetExplorerMedium
ie.Navigate "https://thisisapage.com"

Do
    DoEvents
Loop Until ie.ReadyState = READYSTATE_COMPLETE

ie.Document.getElementById("ctl00_ctl33_g_208a2c49_d0a0_4f86_8940_a36b9b4b55bd_FormControl0_ctl00_ctl33_g_208a2c49_d0a0_4f86_8940_a36b9b4b55bd_FormControl0__customcontrol1_upLevelDiv").Value = Range("B1").Value
ie.Document.getElementById("ctl00_ctl33_g_208a2c49_d0a0_4f86_8940_a36b9b4b55bd_FormControl0_V1_I1_T5").Value = Range("B2").Value

ie.Visible = True
Set ie = Nothing

Este es el campo que no me deja escribir el valor alli
ie.Document.getElementById("ctl00_ctl33_g_208a2c49_d0a0_4f86_8940_a36b9b4b55bd_FormControl0_ctl00_ctl33_g_208a2c49_d0a0_4f86_8940_a36b9b4b55bd_FormControl0__customcontrol1_upLevelDiv").Value= Range("B1").Value

Y este es el error que muestra:

Run-time error '438':
Object doesn´t support this property or method
Este es el codigo HTML del campo en donde no me deja escribir el valor
<div tabindex="0" title="People Picker" class="ms-inputuserfield ms-inputBox" id="ctl00_ctl33_g_208a2c49_d0a0_4f86_8940_a36b9b4b55bd_FormControl0_ctl00_ctl33_g_208a2c49_d0a0_4f86_8940_a36b9b4b55bd_FormControl0__customcontrol1_upLevelDiv" role="textbox" aria-haspopup="true" style="height: 20px; -ms-overflow-x: hidden; -ms-word-wrap: break-word;" contenteditable="true" spellcheck="false" aria-multiline="true" onkeydown="return onKeyDownRw('ctl00_ctl33_g_208a2c49_d0a0_4f86_8940_a36b9b4b55bd_FormControl0_ctl00_ctl33_g_208a2c49_d0a0_4f86_8940_a36b9b4b55bd_FormControl0__customcontrol1', 3, true, event);" onkeyup="return onKeyUpRw('ctl00_ctl33_g_208a2c49_d0a0_4f86_8940_a36b9b4b55bd_FormControl0_ctl00_ctl33_g_208a2c49_d0a0_4f86_8940_a36b9b4b55bd_FormControl0__customcontrol1');" onclick="onClickRw(true, true,event,'ctl00_ctl33_g_208a2c49_d0a0_4f86_8940_a36b9b4b55bd_FormControl0_ctl00_ctl33_g_208a2c49_d0a0_4f86_8940_a36b9b4b55bd_FormControl0__customcontrol1');" onchange='CustomControl.OnValueChanged("ctl00_ctl33_g_208a2c49_d0a0_4f86_8940_a36b9b4b55bd_FormControl0_ctl00_ctl33_g_208a2c49_d0a0_4f86_8940_a36b9b4b55bd_FormControl0__customcontrol1");' ondragstart="canEvt(event);" oncopy="docopy('ctl00_ctl33_g_208a2c49_d0a0_4f86_8940_a36b9b4b55bd_FormControl0_ctl00_ctl33_g_208a2c49_d0a0_4f86_8940_a36b9b4b55bd_FormControl0__customcontrol1',event);" onpaste="dopaste('ctl00_ctl33_g_208a2c49_d0a0_4f86_8940_a36b9b4b55bd_FormControl0_ctl00_ctl33_g_208a2c49_d0a0_4f86_8940_a36b9b4b55bd_FormControl0__customcontrol1',event);" onfocusin="StoreOldValue('ctl00_ctl33_g_208a2c49_d0a0_4f86_8940_a36b9b4b55bd_FormControl0_ctl00_ctl33_g_208a2c49_d0a0_4f86_8940_a36b9b4b55bd_FormControl0__customcontrol1'); saveOldEntities('ctl00_ctl33_g_208a2c49_d0a0_4f86_8940_a36b9b4b55bd_FormControl0_ctl00_ctl33_g_208a2c49_d0a0_4f86_8940_a36b9b4b55bd_FormControl0__customcontrol1'); Sys.UI.DomElement.addCssClass(this, 'ms-inputBoxActive');" onfocusout="if(typeof(ExternalCustomControlCallback)=='function'){ if(ShouldCallCustomCallBack('ctl00_ctl33_g_208a2c49_d0a0_4f86_8940_a36b9b4b55bd_FormControl0_ctl00_ctl33_g_208a2c49_d0a0_4f86_8940_a36b9b4b55bd_FormControl0__customcontrol1',event)){if(!ValidatePickerControl('ctl00_ctl33_g_208a2c49_d0a0_4f86_8940_a36b9b4b55bd_FormControl0_ctl00_ctl33_g_208a2c49_d0a0_4f86_8940_a36b9b4b55bd_FormControl0__customcontrol1')){ShowValidationError();return false;}else {ExternalCustomControlCallback('ctl00_ctl33_g_208a2c49_d0a0_4f86_8940_a36b9b4b55bd_FormControl0_ctl00_ctl33_g_208a2c49_d0a0_4f86_8940_a36b9b4b55bd_FormControl0__customcontrol1');}}} Sys.UI.DomElement.removeCssClass(this, 'ms-inputBoxActive');" name="upLevelDiv" prefercontenteditablediv="true" autopostback="0" isblankruleset="true" onvaluesetfrompicker='CustomControl.OnValueChanged("ctl00_ctl33_g_208a2c49_d0a0_4f86_8940_a36b9b4b55bd_FormControl0_ctl00_ctl33_g_208a2c49_d0a0_4f86_8940_a36b9b4b55bd_FormControl0__customcontrol1");' rows="1">


text:
Q: How to Fetch API (POST) using one single url but with each 4 different parameters Okay, I am still new in Javascript. As per title, how to fetch a single API url but with 4 different parameters. My goal is to display 4 different categories as the result
Example (I have 4 different categories):
const category = [1,2,3,4];

I want to make each category calls for an api
Method 1
To call category 1:
const url = 'http://www.myapiurl.com/thisapi';
const parameter = {
        method: 'POST',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        body: `USERID=userid&TOKEN=usertoken&CATEGORY=1`
    };
fetch(url, options)
        .then(response => response.json())
        .then(object => {})

To call category 2:
const url = 'http://www.myapiurl.com/thisapi';
const parameter = {
        method: 'POST',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        body: `USERID=userid&TOKEN=usertoken&CATEGORY=2`
    };
fetch(url, options)
        .then(response => response.json())
        .then(object => {})

To call category 3:
const url = 'http://www.myapiurl.com/thisapi';
const parameter = {
        method: 'POST',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        body: `USERID=userid&TOKEN=usertoken&CATEGORY=3`
    };
fetch(url, options)
        .then(response => response.json())
        .then(object => {})

To call category 4:
const url = 'http://www.myapiurl.com/thisapi';
const parameter = {
        method: 'POST',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        body: `USERID=userid&TOKEN=usertoken&CATEGORY=4`
    };
fetch(url, options)
        .then(response => response.json())
        .then(object => {})

Or maybe I can simplify them a bit like this:
Method 2
const parameter1 = {
        method: 'POST',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        body: `USERID=userid&TOKEN=usertoken&CATEGORY=1`
    };

const parameter2 = {
        method: 'POST',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        body: `USERID=userid&TOKEN=usertoken&CATEGORY=2`
    };

const parameter3 = {
        method: 'POST',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        body: `USERID=userid&TOKEN=usertoken&CATEGORY=3`
    };

const parameter4 = {
        method: 'POST',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        body: `USERID=userid&TOKEN=usertoken&CATEGORY=4`
    };

    Promise.all([
        fetch(url,parameter1).then(value => value.json()),
        fetch(url,parameter2).then(value => value.json()),
        fetch(url,parameter3).then(value => value.json()),
        fetch(url,parameter4).then(value => value.json()),
        ])
        .then((value) => {
           console.log(value)
          //json response
        })
        .catch((err) => {
            console.log(err);
        });

But all of these are very redundant and uneccesarry repetition. What if I have 50 categories? How do I simplify all of these Fetch API calls? Please give me an enlightment. Thanks in advance

A: You can take it a step further. Since your method, headers and part of the body are all identical, just extract that to one function. Custom-build the parameters to the category, then call fetch.
const thatPostFunction = category => {
  const method = 'POST'
  const headers = { 'Content-Type': 'application/x-www-form-urlencoded' }
  const body = `USERID=userid&TOKEN=usertoken&CATEGORY=${category}`

  return fetch(url, { method, headers, body })
}

const categories = [...category ids...]

const promises = categories.map(c => thatPostFunction(c))

Promise.all(promises)
  .then((value) => {
    console.log(value)
    //json response
  })
  .catch((err) => {
    console.log(err);
  });

A: You can just create a function that runs all of them:

const categories = [1,2,3,4];

const postUrls = (items) => {
  const promises = []

  items.forEach(item => {
    const url = 'http://www.myapiurl.com/thisapi';
    const options = {
        method: 'POST',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        body: `USERID=userid&TOKEN=usertoken&CATEGORY=${item}`
    };
    const prms = fetch(url, options)
    .then(response => response.json())

    promises.push(prms)
  })

  return Promise.all(promises)
}

postUrls(categories)
.then(data => console.log('Done!'))

A: I would write a function to convert a category id to a Promise, and then write a wrapper function to convert an array of category ids to a Promise resolving to an array of fetch results:

const fetchCategory = (catId) => {
  const url = 'http://www.myapiurl.com/thisapi';
  const options = {
    method: 'POST',
    headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
    body: `USERID=userid&TOKEN=usertoken&CATEGORY=${catId}`
  };
  return fetch(url, options)
    .then(response => response.json())
}

const fetchCategories = (categories) => Promise.all(categories.map(fetchCategory))

const categories = [1, 2, 3, 4]

fetchCategories(categories).then(categoryResults => {
  // here categoryResults is an array of the fetch results for each category.
  console.log(categoryResults)
})
<script>
    // Faking out fetch for testing
    const fetch = (url, opts) => Promise.resolve({
      json: () => ({
        categoryId: `${opts.body.slice(opts.body.lastIndexOf('=') + 1)}`,
        more: 'here'
      })
    })
</script>

A: If your API is flexible then you may be able to ask for all 4 categories at the same time. I have seen APIs do it like this:
        body: `USERID=userid&TOKEN=usertoken&CATEGORY=1,2,3,4`

And I have seen them do it like this:
        body: `USERID=userid&TOKEN=usertoken&CATEGORY=1&CATEGORY=2&CATEGORY=3&CATEGORY=4`

Again, your API would need to be able to enumerate through the categories and return the results in some kind of object or array.


text:
Q: Should I store Type in database or should I store it in enum? For example, I have a table name Fruit and each fruit belong to a FruitType. So should I store FruitType in data base then make a foreign key in Fruit or just store a reference id to Enum name FruitType
Update:
The database is only used for one application. I need to display a table of fruit include their fruit type to user.I also use type as a filter in fruit table view.
My current solution:
I will always have an Enum for Type. But
If the Type have more information than just id and name i.e description ... I will also store it in database so I can have a reference view to display all Type information. Other wise just Enum.

A: You have to use the database to save FruitType. I'll explain to two-ways to implement enum for the 'FruitType'. I assumed you're using javax.persistance.
enum FruitType {
 YELLOW,GREEN,RED;
}

class Fruit{
 private String name;
 @Enumerated(EnumType.ORDINAL) or @Enumerated(EnumType.STRING)
 private FruitType fruitType;
}

If you use EnumType.STRING then save string name of enum like (YELLOW, RED). For EnumType.ORDINAL save the order like 1,2 etc.
If you're planing to handle (adding,updating and deleting) lot of FruitTypes then use another table to keep data.

A: If your types are static and you don't want to add them during app work time it's better to use enum. If there are really a lot of types or the types could be added/changed on fly it's better to store them in a separate DB table and set the relation.


text:
Q: Will Junit execute the @Test case when the code in the @before Section fails? I'm new to Junit.
If I execute something in the @before part, and my code fails. e.g. I want to make a server connection, but it fails for some reason.
Will Junit execute my Test in the @Test section even if the @before fails? Because then my test would fail because I haven't a server connection. How can I handle it if its the case?

A: You can try this out with a basic junit.
public class SamplePlayTest {

    @Before
    public void setup() {
        System.out.println("Before called");
        throw new RuntimeException();
    }

    @Test
    public void test() {
        System.out.println("Test case called");
    }

}

This gives output as

Before called

And fails with error java.lang.RuntimeException. Test case called is not printed.


text:
Q: mongorestore incremental backups with preserveUUID I have large Mongo databases that should be incremental backup and then incremental restored. The _id field in my collections is referenced by other collections, so I must preserve these _id values when restoring.
mongorestore has --preserveUUID for this purpose, but it must be used with the --drop option, which means that it is not suitable for incremental restore.
Is there any way to archive what I want to do?


text:
Q: Android-11 "Only-This Time" Permission Behavior In Android-11, If I choose Only This Time permission and access Camera then:
Observed Behaviour: One-Time permission stays granted for a few seconds (approx 3-5 sec) after we kill the application. If I re-open the application instantly or before this short period of time then the permission stays granted and If I re-open it after this short period of time then it will ask permission again and works fine.
Expected Behaviour: The permission will be revoked instantly after we kill the application instead of waiting for any specific period of time.
Is there any solution to it or is it a bug in Android-11? Also, nothing is mentioned in the documentation related to it. https://developer.android.com/guide/topics/permissions/overview#one-time
(P.S: All permission related checks are already implemented in the code.)


text:
Q: Android leanback create HeaderItem with icon how? i have in my TV android application a SparseArray and a loop to iterate this array and create HeaderItem for every group of objects, i have the code below to create the HeaderItems
for(int i=0;i<sparseArraysize();i++){
      ObjectRow row = sparseArraysize.get(i);

        HeaderItem headerItem = new HeaderItem(row.getId(), row.getTitle());
        ListRow listRow = new ListRow(headerItem, row.getAdapter());
        rowsAdapter.add(listRow);
   }

The list of headers is created well, but i need to add icon to every HeaderItem, what is the best way to do that?


text:
Q: jQuery addClass on $.post I am basically trying to create a small registration form. If the username is already taken, I want to add the 'red' class, if not then 'green'.
The PHP here works fine, and returns either a "YES" or "NO" to determine whether it's ok.
The CSS:
input {

 border:1px solid #ccc;
}
.red {

 border:1px solid #c00;
}
.green {

 border:1px solid green;
 background:#afdfaf;
}

The Javascript I'm using is:
 $("#username").change(function() {

             var value = $("#username").val();

  if(value!= '') {
   $.post("check.php", {
    value: value
   }, function(data){

   $("#test").html(data);

    if(data=='YES') {
     $("#username").removeClass('red').addClass('green');
    } if(data=='NO') {
     $("#username").removeClass('green').addClass('red');
    }
   });
  }
 });

I've got the document.ready stuff too... It all works fine because the #test div html changes to either "YES" or "NO", apart from the last part where I check what the value of the data is. Here is the php:
 $value=$_POST['value'];

 if ($value!="") {
  $sql="select * FROM users WHERE username='".$value."'";
  $query = mysql_query($sql) or die ("Could not match data because ".mysql_error());
  $num_rows = mysql_num_rows($query);

  if ($num_rows > 0) {
   echo "NO";
  } else {
   echo "YES";
  }
 }

A: try this one

if(data=='YES')
  {
     $("#username").attr('style','').attr('style', 'border:1px solid green;background:#afdfaf;');
  }
else
  {
     $("#username").attr('style','').attr('style', 'border:1px solid #c00;');
  }

let me know if it works.

A: @Jimmy - The class change just doesn't happen.
@Gaurav - Using your code, the border changes but it's always set to red, whether the data is "YES" or "NO".
It must be something with checking the data? But I don't see how...

A: Here's a basic example of how I think you should implement your feature. The code is pretty much self-explanatory, but feel free to ask if anything's unclear.
<?php
function readArray( $arr, $key, $default ='' ) { return isset($arr[$key]) ? $arr[$key] : $default ; }
function error( $message ){ echo "{ result: false, message: \"$message\" }"; exit; }
function success( $isFound ){ echo "{ result: true, exists: " . ($isFound?'true':'false') . "}" ; exit; }

if( sizeof( $_POST ) ) {
    $value = readArray( $_POST, "value", false ) ;
    if( false === $value ) error( "Empty username" ) ;

    @$db = mysql_connect("localhost","root","") ;
    if( !$db ) error( "Can't connect to database" ) ;

    @$result = mysql_select_db( "mysql" ) ;
    if( !$result ) error( "Can't select database" ) ;

    $query = "SELECT COUNT(User) as count FROM user WHERE User='" . mysql_real_escape_string( $value ) . "'";
    @$result = mysql_query( $query ) ;
    if( !$result ) error( "Can't execute query: " . mysql_error() ) ;

    success( readArray( mysql_fetch_assoc( $result ), "count" ) > 0 ) ;
}
?>

<input id="username" name="username" value="" />


text:
Q: Method to merge objects which are similar (differing by quantity) I need help with a cart object which has_many line_items. If a line_item in the cart is created and it has the same exact attributes as a line_item which is already in the cart I just want to update the pre existing line_items quantity rather than create duplicate objects with separate quantities.
I wrote a few methods in my models to try and make this work but it isn't working. Below is my code:
models
class LineItem < ActiveRecord::Base
  attr_accessible :cart_id, :product_id, :quantity, :unit_price, :product, :cart, :color_id, :size_id, :extra_id
  belongs_to :cart
  belongs_to :product
  belongs_to :color
  belongs_to :size
  belongs_to :extra
  validates :quantity, :presence => true

  def update_quantity(qty)
    quantity += qty
    quantity.save
  end
  def exists_in_collect?(items)
    if items.include?(product)
        if color == items.color && size == items.sizes && extra == items.extra
            return true
        end
    else
        return false
    end
  end
end

class Cart < ActiveRecord::Base
  attr_accessible :purchased_at
  has_many :line_items
  has_one :order

  def where_line_item_with(prod_id)
    line_items.where(:product_id => prod_id)
  end
end

controller
class LineItemsController < ApplicationController
  def new
    @line_item = LineItem.new
  end
  def create
    @line_item = LineItem.new(params[:line_item].merge(:cart => current_cart))
    if @line_item.exists_in_collect?(current_cart.line_items)
      current_cart.where_line_item_with(product.id).update_quantity(@line_item.quantity)
      @line_item.destroy!
    else
    @line_item.save!
    @line_item.update_attributes!(:unit_price => @line_item.item_price)
    end

    redirect_to current_cart_url
  end
  def update
    @line_item = LineItem.find(params[:id])
    @line_item.update_attributes(params[:line_item])
    redirect_to current_cart_url
  end

Any insight is fully appreciated.

A: 1.You should change your where_line_item_with(prod_id) to the following:
def where_line_item_with(prod_id)
  line_items.where(:product_id => prod_id).first
end

As the where returns an array and you cannot do update_quantity(@line_item.quantity) on an array.
2.In exists_in_collect?(items) - Here your aim is to find if the items of the cart include the item similar to new item. it should be updated as following:
def exists_in_collect?(items)
  items.each do |item|
    if color == item.color && size == item.sizes && extra == item.extra && product == item.product
        return true
    end
  end
  return false
end


text:
Q: Image.asset in Expanded FittedBox widgets show blank I am trying to use Image.asset inside FittedBox in Expanded widget. But it always shows black screen.
Scaffold(
 body: Column(
    children: [
     Expanded(
      child: FittedBox(
       fit: BoxFit.contain,
       child: Image.asset('assets/images/logo.png'),
      ),
    )
  ]
 )
)

If I use it without Expanded and FittedBox then it works
Scaffold(
 body: Column(
   children: [
    Image.asset('assets/images/logo.png')
  ]
 )
)

Any idea what I am doing wrong?

A: Just figured it out. It seems I was overusing the widgets. I have to simply use the fit property of Image.asset instead of using another parent widget FittedBox. My code reduces to:
Scaffold(
 body: Column(
  children: [
   Expanded(
    child: Image.asset('assets/images/logo.png', fit: BoxFit.contain)
   )
  ]
 )
)


text:
Q: Aggregate all documents with the newest date in one query I have the following documents in a mongo collection and want to select all documents which has the latest LastUpdate value.
{ "_id" : ObjectId("1234a1acb3fbf26334ef6117"), "LastUpdate" : ISODate("2021-01-10T00:00:00Z"), "ProductName" : "Foo" }
{ "_id" : ObjectId("1234a1b9b3fbf26334ef6118"), "LastUpdate" : ISODate("2021-02-05T00:00:00Z"), "ProductName" : "Bar" }
{ "_id" : ObjectId("1234a1c8b3fbf26334ef6119"), "LastUpdate" : ISODate("2021-02-05T00:00:00Z"), "ProductName" : "Foo-Bar" }

My first guess was, to sort LastUpdate with -1 and then group like:
{
  _id: "$ProductName",
  LastUpdate: { $first: "$LastUpdate" },
  documents: { $push : "$$ROOT" }
}

But in documents there are always all documents (in this sample 3) instead of the only two with the date 2021-02-05...?

A: You can do it with group
db.collection.aggregate([
    {$group: {_id: "$LastUpdate", items: {$push: "$$ROOT"} }},
    {$sort: {LastUpdate: -1}},
    {$limit: 1},
    {$project: {"items": 1}}
])

Here I group by the LastUpdate field (and for each group push the relevant documents into items), then sort and select the group with the latest LastUpdate value.


text:
Q: Removing strings from column I need to remove specific strings from a table which looks something like this:
1->KOM0001 column2 column3...
2->KOM0002 column2 column3...
.
10->KOM00011 column2 column3...
.
.
156->KOM0159 column2 column3...

and so on. I would like to remove either of these: KOM000, KOM00, KOM0, KOM if they appear in the first column and replace them with whitespace. I should use Perl to achieve this (not a must) but I'm the newbiest newbie you can imagine and I'm completely stuck.
I should add that the table is large, it has around 1000 lines and more than 100 000 columns.
Unfortunately, my problem is not over with this, but this is a necessary first step so I won't make my question any longer.

A: You could clarify this a lot, but assuming it's a file:
perl -i -pe 's/^\d+->\K(KOM0{0,3})/q{ }x length($1)/e' file

Finds your string near the start of a line and replaces each character with a space.

A: You could try:
awk '{sub(/KOM0*/,"",$1)}1' file


text:
Q: Visual Studio 2008: Can't connect to known good TFS 2010 A freshly installed TFS 2010 is at http://serverX:8080/tfs.
A Windows 7 developer machine with VS 2008 Pro SP1 and the VS2008 Team Explorer (no SP). The TFS 2008 Service Pack 1 didn't work for me - "None of the products that are addressed by this software update are installed on this computer."
The developer machine is able to browse the TFS site at the above URL.
The Issue is around trying to add the TFS server into the Team Explorer window in Visual Studio 2008. Here's a screenshot showing the error:

unable to connect to this Team Foundation Server. Possible reasons for failure include: The Team Foundation Server name, port number or protocol is incorrect. The Team Foundation Server is offline. Password is expired or incorrect.

The TFS server is up and running properly. Firewall ports are open, and is accessible via the browser on the dev machine!!

larger image
Question: how can you connect from VS 2008 Pro to a TFS 2010 server?
Resolution
Here's how I solved this problem:
Installations

*

*install Visual Studio 2008

*install VS 2008 Team Explorer as above.

*re-install VS 2008 Service Pack 1

*install the Visual Studio Team System 2008 Service Pack 1 Forward Compatibility Update for Team Foundation Server 2010  (VS90SP1-KB974558-x86.exe)

Config

*

*when adding a TFS server to Team Explorer, you MUST specify the URL as such:
http://[tfsserver]:[port]/[vdir]/[projectCollection]

*in my case above, it was http://serverX:8080/tfs/AppDev-TestProject

*you cannot simply add the TFS server name and have VS look for all Project Collections on the server. TFS 2010 has a new URL (by default) and VS 2008 doesn't recognize how to gather that list.

A: Check out this article 'Connecting VS2008 to any TFS2010 Project Collection'.
The only catch here is that the author didn't mention that you need to install/reinstall Service Pack 1 'Microsoft Visual Studio 2008 Service Pack 1 (Installer)' for Visual Studio 2008 after installing Team Explorer 2008. This will take care of the invalid characters error message when trying to connect.

A: To Connect Visual Studio 2008 to a TFS2010 server this is what it took for me to connect: Install TFS plugin; install VS2008SP1; install TFS compatibility update. Before I did this I was getting an error tf3002 Here are some details:

*

*Install Team Explorer 2008 from http://www.microsoft.com/downloads/en/details.aspx?FamilyID=0ed12659-3d41-4420-bbb0-a46e51bfca86. It's an iso file so I used MagicISO to mount it. After this when the source control options (Tools --> Options --> Source Control) will have TFS in drop down in addition to VSS.

2 Install VS2008SP1 - Visual Studio 2008 Service Pack 1 from http://www.microsoft.com/downloads/en/details.aspx?FamilyId=FBEE1648-7106-44A7-9649-6D9F6D58056E
3 Install Compatibility Update - Visual Studio Team System 2008 Service Pack 1 Forward Compatibility Update for Team Foundation Server 2010 from http://www.microsoft.com/downloads/en/details.aspx?FamilyID=cf13ea45-d17b-4edc-8e6c-6c5b208ec54
Also when I opened the Connect to TFS window (Tools --> Connect to TFS). After I entered in the complete path such as http://YourServerName:8080/so/TFSProjects including the http://. Also I noticed that when it's installed correctly on the Add TFS window when the http:// is typed in the Port # txtbox will be disabled.
This question helped me & I Hope this answer helps.

A: I'm surprised no one here has mentioned the Visual Studio 2008 Service Pack 1 Forward Compatibility Update for Team Foundation Server 2010.  I followed the directions above, but still was unable to connect; Installing the Forward Compatibility Patch finally let me connect.


text:
Q: Insert html table row to a specific location with jquery I have a HTML table that contains price information. The table is sorted be price Ascending.  I'm looking to update the table with a new price item. I'm pretty sure jquery should be able to solve this issue. Here is my starting table:

        Item 1

        $256.07

    USD

        Item 2

        $301.00

    USD

        Item 3

        $305.57

    USD

I need to insert a new row.

            Item 5

            $290.00

        USD

This row needs to be inserted between the  with id 25607 and id 30100.
I'm thinking that there should be a way to use the id of the tr's (Which are the prices with only numbers). Possibly sort the ids and figure out where the new item should be inserted.

A: Yes, jQuery is  able to solve this issue.
var row = '
Item 5	$290.00	USD
';
var $tr = $(row);

$('#priceTable tr')
         .add($tr) // add the new tr to the collection
         .sort(function(a, b){  // sort them
             return a.id > b.id
         })
         .appendTo('#priceTable'); // end of the game

http://jsfiddle.net/PTxjk/

A: you can use the after() method:
$('#25607').after("
....");

A: You can use jQuery after() and before() Methods
The jQuery after() method inserts content AFTER the selected HTML elements.
The jQuery before() method inserts content BEFORE the selected HTML elements.
$('#25607').after("
....");

or
$('#30100').before("
....");


text:
Q: SWIFT MT message validation I am looking for java library or a vb addin that can be used for
 - SWIFT message syntax validation
 - Building SWIFT message from available data.
 - Retrieving the required tag/field data.
Can anybody help me in this regard??
I have seen few of the available libraries like WIFE but all fails in catching errors if the message is not in standard format.
Pavan

A: with "SWIFT message syntax validation" I guess you are speaking about getting the FIN syntax right?
If so, I have just posted an answer to another SWIFT related question on StackOverflow.
I have copy and pasted my response below again for your convenience (from here: java-swift-library):

SWIFT is releasing a "Standards Developer Kit" which includes an "MT/XML Schema Library".

From the doc: "The MT/XML Schema Library is a complete set of XML schema definitions for MT messages, and software which shows how to convert messages from an MT format to an MT XML representation and back. This approach allows XML integration between applications while the MT (FIN) format will continue to be transported over the SWIFT network."
Java source code will also be made available, again from the doc: "Working sample Java source code that converts a message in MT format to an XML instance and from an XML instance to a message in MT format."
See: https://www.swiftcommunity.net/communities/download.cfm?id=4798
This can be a great aid in dealing with FIN messages in XML syntax.

So, using the "Standards Developer Kit" you do not have to worry anymore about getting the FIN syntax right.
Hope it is useful for you,
Stijn.

A: We use WIFE and have to do validation on the Swift tag data prior to constructing the message using WIFE.  I don't believe WIFE provides any validation.
Update: A Google search turns up the AnaSys service along with a few others that look promising.


text:
Q: Increment number found with JavaScript regex after a specific string I really tried my best but somehow I cannot make it work.
I have the following SVG path data:
var str = "m 0.05291667,1.7345817 h 0.16018 V 0.05291667 H 1.4943367 v 0.56054601 l -0.16015,0.16017899 0.16015,0.16012501 V 1.4943397 H 0.69354668 V 1.2541247 H 1.2540967 V 1.0138577 L 1.0939467,0.90175268 H 0.69354668 v -0.240215 H 1.0939467 l 0.16015,-0.128138 V 0.29313166 H 0.45330668 V 1.7345817 H 1.6544867"

What I want to achieve is to get all values that come after each H and increase this value by a number (let's say 2).
The regex I currently have selects all these numbers:
/(?<=H )(.*?)(?= )/g

However, I don't know how I can increase these numbers now using the replace() function.
This is what I currently have:
var H = str.match(/(?<=H )(.*?)(?= )/g)

for (var j=0; j<H.length; j++) {
    str = str.replace(/(?<=H )(.*?)(?= )/g, function (match, i, original) {
            nth++;
            return (nth == j) ? (parseFloat(H[j]) + 2).toString() : match;
    });
}

But it does not give me the desired result.
What can I do?

A: Use match parameter

var str = "m 0.05291667,1.7345817 h 0.16018 V 0.05291667 H 1.4943367 v 0.56054601 l -0.16015,0.16017899 0.16015,0.16012501 V 1.4943397 H 0.69354668 V 1.2541247 H 1.2540967 V 1.0138577 L 1.0939467,0.90175268 H 0.69354668 v -0.240215 H 1.0939467 l 0.16015,-0.128138 V 0.29313166 H 0.45330668 V 1.7345817 H 1.6544867"

str = str.replace(/(?<=H )(.*?)(?= )/g, function(match, i, original) {
  return parseFloat(match) + 2
});

console.log(str)

A: You could make use of the callback function from replace and use 2 capturing groups.
Note that you don't need a lookbehind (?<= and that lookbehinds are not yet widely supported in Javascript.
You could match the numbers and the capital H using:
\b(H )(\d+(?:\.\d+)?)

*

*\b(H ) Capture group 1, match H and a space preceded by a word boundary

*( Capture group 2

*

*\d+(?:\.\d+)? Match 1+ digits, optionally match a dot and 1+ digits

*) Close group

Regex demo
In the replacement use the 2 capturing groups and add a number to what is captured in group 2.

let pattern = /\b(H )(\d+(?:\.\d+)?)/g;
var str = "m 0.05291667,1.7345817 h 0.16018 V 0.05291667 H 1.4943367 v 0.56054601 l -0.16015,0.16017899 0.16015,0.16012501 V 1.4943397 H 0.69354668 V 1.2541247 H 1.2540967 V 1.0138577 L 1.0939467,0.90175268 H 0.69354668 v -0.240215 H 1.0939467 l 0.16015,-0.128138 V 0.29313166 H 0.45330668 V 1.7345817 H 1.6544867"
str = str.replace(pattern, function(_, g1, g2) {
  return g1 + (Number(g2) + 2);
});
console.log(str);

A: const str = "m 0.05291667,1.7345817 h 0.16018 V 0.05291667 H 1.4943367 v 0.56054601 l -0.16015,0.16017899 0.16015,0.16012501 V 1.4943397 H 0.69354668 V 1.2541247 H 1.2540967 V 1.0138577 L 1.0939467,0.90175268 H 0.69354668 v -0.240215 H 1.0939467 l 0.16015,-0.128138 V 0.29313166 H 0.45330668 V 1.7345817 H 1.6544867"

const regex = new RegExp('H\\s*([\\d\\.]+)', 'g');
let matches;
while ((matches = regex.exec(str))) {
    const found = matches[1];
    const newValue = parseFloat(found) + 2.0;
    console.log(newValue);
}

A: You should try with a regex replace
str.replace( new RegExp("(?<=H )(.*?)(?= )","g"), function(match) {
    return parseFloat(match) + 2;
}):


text:
Q: GLSL to SPIR-V using VS2019 Cusotm build step I'm looking to take my GLSL shader files which have the extension .vert and .frag and have them compile to SPIR-V format after the project build. Currently I have been using a .bat file which compiles all my GLSL files to SPIR-V however, hitting the .bat file every time I make a change to a shader is far from ideal so I have been exploring other methods such as VS2019 Build step. I have read through the docs on MSDN but I am still finding myself confused on how to correctly utilise this feature so I can compile all my GLSL files to SPIR-V.
What I have tried:
Properties -> Custom Build Step -> General
Command Line:
glslangValidator.exe -V %(SolutionDir)%(Shaders)%(Filename).vert-o "%(SolutionDir)%(Shaders)%(Filename).spv
Ouputs:
%(SolutionDir)%(Shaders)%(Filename).spv
The error I receive is
MSB3073: The command "glslangValidator.exe -V App.vert-o App.spv :VCEnd" exited with code 1. App.
Where App is the name of the project and not a GLSL file. I have also tried specifying the name of a single GLSL file (replacing Filename) but this resulted in the same error except App was no longer present glslangValidator.exe -V .vert-o .spv :VCEnd
Would appreciate any insight into how I might go about compiling my GLSL files to SPIR-V using glslangValidator through the Custom Build Step.


text:
Q: Upgrade classic loadbalancer to network loadbalancer I am having trouble upgrading our CLB to a NLB. I did a manual upgrade via the wizard through the console, but the connectivity wouldn't work. This upgrade is needed so we can use static IPs in the loadbalancer. I think it needs to be upgraded through kubernetes, but my attempts failed.
What I (think I) understand about this setup is that this loadbalancer was set up using Helm. What I also understand is that the ingress (controller) is responsible for redirecting http requests to https. and that this lb is working on layer 4.
apiVersion: v1
kind: Service
metadata:
  labels:
    app: nginx-ingress
    chart: nginx-ingress-1.30.0
    component: controller
    heritage: Tiller
    release: nginx-ingress-external
  name: nginx-ingress-external-controller
  namespace: kube-system
  selfLink: /api/v1/namespaces/kube-system/services/nginx-ingress-external-controller
spec:
  clusterIP: 172.20.41.16
  externalTrafficPolicy: Cluster
  ports:
  - name: http
    nodePort: 30854
    port: 80
    protocol: TCP
    targetPort: http
  - name: https
    nodePort: 30621
    port: 443
    protocol: TCP
    targetPort: https
  selector:
    app: nginx-ingress
    component: controller
    release: nginx-ingress-external
  sessionAffinity: None
  type: LoadBalancer
status:
  loadBalancer:
    ingress:
    - hostname: xxx.region.elb.amazonaws.com

How would I be able to perform the upgrade by modifying this configuration file?

A: As @Jonas pointed out in the comments section, creating a new LoadBalancer Service with the same selector as the existing one is probably the fastest and easiest method. As a result we will have two LoadBalancer Services using the same ingress-controller.
You can see in the following snippet that I have two Services (ingress-nginx-1-controller and ingress-nginx-2-controller) with exactly the same endpoint:
$ kubectl get pod -o wide ingress-nginx-1-controller-5856bddb98-hb865
NAME                                          READY   STATUS    RESTARTS   AGE   IP
ingress-nginx-1-controller-5856bddb98-hb865   1/1     Running   0          55m   10.36.2.8

$ kubectl get svc ingress-nginx-1-controller ingress-nginx-2-controller
NAME                         TYPE           CLUSTER-IP     EXTERNAL-IP
ingress-nginx-1-controller   LoadBalancer   10.40.15.230   <PUBLIC_IP>
ingress-nginx-2-controller   LoadBalancer   10.40.11.221   <PUBLIC_IP>

$ kubectl get endpoints ingress-nginx-1-controller ingress-nginx-2-controller
NAME                         ENDPOINTS                    AGE
ingress-nginx-1-controller   10.36.2.8:443,10.36.2.8:80   39m
ingress-nginx-2-controller   10.36.2.8:443,10.36.2.8:80   11m

Additionally to avoid downtime, we can first change the DNS records to point at the new LoadBalancer and after the propagation time we can safely delete the old LoadBalancer Service.