text:
Q: How to Access ViewData in javascript I am having a problem accessing the ViewData object through javascript.
I have set the ViewData object on the controller and on document.ready event of the view i am trying to see the contents of that same ViewData object like so:
     var test = <%= ViewData["NAME"].ToString() %>;
     alert(test);

I don't get an alert message after this and none of my script after this statement will run.  I am assuming this script is invalid thus killing everything afterwards.  I have tried a few different variations of this same script without any luck.
What am i missing here?
Thanks in advance,
Billy

A: try
var test = '<%= ViewData["NAME"].ToString() %>';
alert(test);

(notice the quotes around <%= %>)

A: Try adding some quotes around the output:
var test = '<%= ViewData["NAME"].ToString() %>';
alert(test);

Edit:
I notice you're using NAME for the key; could this name ever have a single quote in it? If it's possible that any value will ever contain one, you will want something like this instead so your page doesn't break again (although technically this seems to be more of a job for the controller or model):
var test = '<%= ViewData["NAME"].ToString().Replace("'", "\\'") %>';
alert(test);


text:
Q: Need help in working with cs50 library, in window device I'm using visual studio code, in window 10 device, and live in a area where internet accessibility is not good.
I have completed of lecturers of first week of cs50x.
Had extracted cs50.h and cs50.c and copy them to C:\msys64\mingw64\include\
Now after running the code, I'm getting undefined reference to 'get_int' and  Id returned 1 exit status.

*

*After going through some online solutions, I get this

In your source code, change #include <cs50.h> to #include <cs50.c>
But I'm not finding any <cs50.h> in cs50.c source file instead it has "cs50.h"

*I'm not able to understand

How to link cs50 when compiling your code with clang, by using -lcs50

redpajama_set_name: RedPajamaStackExchange


text:
Q: Filter Out NULL Columns from GROUP BY CUBE Results I am using GROUP BY CUBE to output
the Total Min. for each Incident # for each year.
SELECT
            IncidentNumber AS [Incident #]
          , SUM(Duration) AS [Total Min.]
          , YEAR(EntryDateTime) AS [Year]

     FROM TableX
     WHERE
    GROUP BY CUBE
    (
        IncidentNumber
          , YEAR(EntryDateTime)
    )

But I don't want rows where the Year is NULL becuase
they are redundant of the information from the rows
showing the years.
OUTPUT

So I set this as a subquery.
    SELECT * FROM
    (
            SELECT
                        IncidentNumber AS [Incident #]
                      , SUM(Duration) AS [Total Min.]
                      , YEAR(EntryDateTime) AS [Year]

                 FROM TableX
                 WHERE
                GROUP BY CUBE
                (
                    IncidentNumber
                      , YEAR(EntryDateTime)
                )
    ) T
    WHERE T.Year IS NOT NULL;

Is there an alternative where I can filter out the
NULL without making this a subquery?
If I use GROUP BY ROLLUP I still get NULL.

A: You could add
HAVING GROUPING(YEAR(EntryDateTime))=0

But the most efficient way would be to just not calculate it at all if you don't need it.
you can use ROLLUP instead
GROUP BY ROLLUP (YEAR(EntryDateTime), IncidentNumber)

And if you don't even want the grand total row you can use GROUPING SETS
GROUP  BY GROUPING SETS ( (IncidentNumber, YEAR(EntryDateTime)),
                           (YEAR(EntryDateTime))
                         )


text:
Q: A Question About the Elliott-Natsume-Nest Proof of Bott Periodicity In Wegge-Olsen's book K-Theory and C$ ^{*} $-Algebras, there is an outline of a proof of Bott Periodicity (the proof is due to George Elliott, Toshikazu Natsume and Ryszard Nest). The first step of the proof outline goes as follows:

Suppose that there are natural transformations

*

*$ \Phi^{0} $ from the $ K_{0} S $-functor to the $ K_{1} $-functor and

*$ \Phi^{1} $ from the $ K_{1} S $-functor to the $ K_{0} $-functor,

  where $ S $ denotes the suspension functor. In other words, for every C$ ^{*} $-algebra $ \mathscr{A} $ (not necessarily unital), there are abelian-group homomorphisms
  $$
\Phi^{0}_{\mathscr{A}}: {K_{0}}(S(\mathscr{A})) \to {K_{1}}(\mathscr{A})
\quad \text{and} \quad
\Phi^{1}_{\mathscr{A}}: {K_{1}}(S(\mathscr{A})) \to {K_{0}}(\mathscr{A})
$$
  such that for every C$ ^{*} $-algebraic homomorphism $ \alpha: \mathscr{A} \to \mathscr{B} $, the following diagrams commute:
  $$
\require{AMScd}
\begin{CD}
{K_{0}}(S(\mathscr{A}))      @>{{K_{0} S}(\alpha)}>> {K_{0}}(S(\mathscr{B})) \\
@V{\Phi^{0}_{\mathscr{A}}}VV                         @VV{\Phi^{0}_{\mathscr{B}}}V \\
{K_{1}}(\mathscr{A})         @>>{{K_{1}}(\alpha)}>   {K_{1}}(\mathscr{B})
\end{CD}
\quad \quad \quad
\begin{CD}
{K_{1}}(S(\mathscr{A}))      @>{{K_{1} S}(\alpha)}>> {K_{1}}(S(\mathscr{B})) \\
@V{\Phi^{1}_{\mathscr{A}}}VV                         @VV{\Phi^{1}_{\mathscr{B}}}V \\
{K_{0}}(\mathscr{A})         @>>{{K_{0}}(\alpha)}>   {K_{0}}(\mathscr{B})
\end{CD}
$$
  Suppose further that $ \Phi^{0}_{\mathbb{C}} $ and $ \Phi^{1}_{\mathbb{C}} $ are isomorphisms. Then prove that $ \Phi^{0}_{\mathscr{A}} $ and $ \Phi^{1}_{\mathscr{A}} $ are isomorphisms for every C$ ^{*} $-algebra $ \mathscr{A} $.

Wegge-Olsen's hint is to consider the commutative diagrams above for the homomorphism
\begin{align*}
\alpha: \mathbb{C} & \to     \mathscr{A} \otimes \mathbb{K}; \\
        1          & \mapsto p \otimes e_{11},
\end{align*}
where $ p $ is a fixed choice of a projection in $ \mathscr{A} $ and $ e_{11} $ is a rank-$ 1 $ projection in $ \mathbb{K} \stackrel{\text{def}}{=} {M_{\infty}}(\mathbb{C}) $.

My difficulty:
I do not see how
\begin{align*}
{K_{0}}(\alpha):   & {K_{0}}(\mathbb{C})    \to {K_{0}}(\mathscr{A} \otimes \mathbb{K}), \\
{K_{1}}(\alpha):   & {K_{1}}(\mathbb{C})    \to {K_{1}}(\mathscr{A} \otimes \mathbb{K}), \\
{K_{0} S}(\alpha): & {K_{0}}(S(\mathbb{C})) \to {K_{0}}(S(\mathscr{A} \otimes \mathbb{K}))
\quad \text{and} \\
{K_{1} S}(\alpha): & {K_{1}}(S(\mathbb{C})) \to {K_{1}}(S(\mathscr{A} \otimes \mathbb{K}))
\end{align*}
are isomorphisms. If this hurdle can be overcome, then $ \Phi^{0}_{\mathscr{A}} $ and $ \Phi^{1}_{\mathscr{A}} $ are clearly isomorphisms.
Thank you for any assistance!

A: A vague guess:
Consider something by putting your two Diagramms together (for the map $\alpha:\mathbf{C} \rightarrow A$) so that they fuse to one diagram with three lines. In the first diagram you replace $A$ by $S(A)$ so that double Suspension $SS(A)$ is involved.
The first column is then an isomorphism $K_0(SS(\mathbf{C}) \cong K_0(\mathbf{C})$.
Chase in the Diagramm, to see that the second column is also something (a isomorphism (??!)) for the subgroup generated by $[p]$. Then vary over all $p$.
Maybe something like this.. or a starting Point to think further.


text:
Q: Remove special characters (in list) in string I have a bunch of special characters which are in a list like:
special=[r'''\\''', r'''+''', r'''-''', r'''&''', r'''|''', r'''!''', r'''(''', r''')''', r'''{''', r'''}''',\
     r'''[''', r''']''', r'''^''', r'''~''', r'''*''', r'''?''', r''':''', r'''"''', r''';''', r''' ''']

And I have a string:
stringer="Müller my [ string ! is cool^&"

How do I make this replacement? I am expecting:
stringer = "Müller my string is cool"

Also, is there some builtin to replace these 'special' chars in Python?

A: This can be solved with a simple generator expression:
>>> ''.join(ch for ch in stringer if ch not in special)
'M\xc3\xbcllermystringiscool'

Note that this also removes the spaces, since they're in your special list (the last element). If you don't want them removed, either don't include the space in special or do modify the if check accordingly.

A: If you remove the space from your specials you can do it using re.sub() but note that first you need to escape the special regex characters.
In [58]: special=[r'''\\''', r'''+''', r'''-''', r'''&''', r'''|''', r'''!''', r'''(''', r''')''', r'''{''', r'''}''',\
     r'''[''', r''']''', r'''^''', r'''~''', r'''*''', r'''?''', r''':''', r'''"''', r''';''']

In [59]: print re.sub(r"[{}]".format(re.escape(''.join(special))), '', stringer, re.U)
Müller my  string  is cool


text:
Q: Cannot submit a form in jquery I am using jquery smarty, php. I am validating a form using jquery but the submit button is not working.
In checkemail.php I am echoing no of rows;

$(document).ready(function() { //newly added
  $("#formpge").submit(function(event) {
    event.preventDefault();
    var emailVal = $('#useremail').val();
    alert(emailVal);
    // assuming this is a input text field
    $.post("checkemail.php", {
      "useremail": emailVal
    }, function(data) {
      alert(data);
      if (data == 0) {
        alert("has to be added");
        $("#formpge")[0].submit();
      } else
        $("#useremail").focus();
    });

  });
});

<form id="formpge" name="frmadduser" method="post">

    <input type="text" placeholder="Your Full Name" id="username" name="username">

    <input type="text" placeholder="Your Email Address" id="useremail" name="useremail">

    <input type="hidden" value="Y" name="active">

    <input type="submit" id="formsubmit" name="formsubmit" value="I Want One!">

</form>

A: try this code its working: -
<form id="formpge" name="frmadduser" method="post">

    <input type="text" placeholder="Your Full Name" id="username" name="username">

    <input type="text" placeholder="Your Email Address" id="useremail" name="useremail">

    <input type="hidden" value="Y" name="active">

    <input type="submit" id="formsubmit" name="formsubmit" value="I Want One!" >

  </form>

try fiddle here

A: First of all thanks to mplungjan, Gaurav Srivastava andStarscream1984. The problem is, in checkemail.php I checked isset($_REQUEST['formsubmit'], but this is not set only the text fields are set. I dont know why type submit is not set.
Again, Thanks.


text:
Q: c# - Select specific text boxes on WebBrowser and write in them how would I select a specific text box on a web browser (the default c# webbrowser) and write a string in it? I have been thinking of webrequests but that may be illegal due to the amount of packets you will send to the host server.

A: If you are just wanting to fill in a field, you need to use the DOM. Here are some examples that assume your browser is named browser and has navigated to google.com.
WPF
     mshtml.IHTMLDocument2 htmlDoc = browser.Document as mshtml.IHTMLDocument2;
     ((mshtml.HTMLInputElement)htmlDoc.all.item("lst-ib")).value = "wpf web browser access dom";

WinForms
     HtmlDocument htmlDoc = browser.Document;
     htmlDoc.All["lst-ib"].InnerText = "c# web browser access dom";


text:
Q: Display all the items I have ordered How to display all the items I have ordered in "Sales Report File"? Like whenever I ordered 2 cookies, It will display on the Sale Report file. I have this code currently..
     private final Dispenser candy = new Dispenser(100, 50);
     private final Dispenser chips = new Dispenser(100, 65);
     private final Dispenser gum = new Dispenser(75, 45);
     private final Dispenser cookies = new Dispenser(100, 85);
     public int products;

     private final JButton candyB;
     private final JButton chipsB;
     private final JButton gumB;
     private final JButton cookiesB;

   private class ButtonHandler implements ActionListener
   {
     public void actionPerformed (ActionEvent e)
     {
        switch (e.getActionCommand())
        {
            case "Exit":
              System.exit(0);
            case "Candy":
                sellProduct(candy, "Candy");
                products++;
                break;
            case "Chips":
                sellProduct(chips, "Chips");
                products++;
                break;
            case "Gum":
                sellProduct(gum, "Gum");
                products++;
                break;
            case "Cookies":
                sellProduct(cookies, "Cookies");
                products++;
            case "Sales Report File":
               JOptionPane.showMessageDialog(null,"Items list sold + "+ DISPLAY ALL THE ITEMS ORDERED
               ,"Sales Report ~ ",JOptionPane.PLAIN_MESSAGE)
                break;
     }
   }

A: If you want like a text list of what you have ordered, you can simply create an ArrayList<String> and every time you click on a product you do list.add('Cookies') or whatever the product is, depending on the switch. In this way you have a list ordered by time-ordered products.
The output would be something like:
Cookies,
Candies,
Candies,
Gum,
Chips,
Gum
...


text:
Q: Where is my Touchpad toggle button missing (Windows 11)? I'm using a Windows 11 machine and I'm trying to disable the touchpad when an external mouse is plugged in. But, when I go into the settings for the Touchpad:
Settings > Bluetooth & devices > Touchpad

...this is what I see:

I've run updates and I'm not missing anything. The Touchpad is an Elan Touchpad and it's driver is updated. I've restarted the computer after updates made, but nothing.
Any idea how to bring back the toggle button or any of the additional settings?


text:
Q: Using java code how to extract text from single quotes. Also a specific instance I need to extract the third instance of text between single quotes using Java code.
Input text is:   'a','b','c'
Output text should be:    c
Any help is appreciated.

A: you could do something simple and first split on the comma character from your string. myString.split(",")
This will supply you with an array containing ['a','b','c']   array[0] = 'a', array[1] = 'b'....
with then you can grab the third item or array[2] which will give you 'c'
You could then do a charAt(1) to retrieve this item. or if the item between the quotes is text, you could use substring to retrieve the item from the string.
So for array[2] = "'bleh'"  you could use array[2].substring(1,array[2].length - 2); Just make sure to do validation as this could easily cause index out of range exceptions.
an example of this would be:
public String getThirdVal(String input)
{
    String[] myArray = input.split(',');
    String wantedValue = myArray[2].substring(1, myArray[2].length - 2);
    return wantedValue;
}


text:
Q: Login to both CakePHP and vbulletin I'm looking to get a single sign on set-up between a cakePHP (1.3) app and a vBulletin (4.0.2) forum.
I've managed to get so far with it, i.e I've been able to get Auth to use the vB user table to let people login, and that works pretty well - the issue now is getting the two different systems to share a session so that users can pass between the main cake site, and the vB forum, without losing their session and being logged out.
Can anyone help point me in the right direction? Thank you.

A: *

*Make sure your CakePHP app uses the same session cookie name as vBulletin. You can change this in app/Config/core.php under the Session.cookie key.

*It has to be as the session_name() in vBulletin uses

If this is done, you have the same data in the global $_SESSION variable in both systems. You also have to make sure they run under the same top-level domain, so cookies can be read. Also, the cookie has to be a wildcard one, meaning that the session.cookie_domain has to start with a ".".
For example: .your-domain.com will allow cakephp.your-domain.com and forum.your-domain.com to access the same session cookie.


text:
Q: How to get merged project results in SonarQube from 2 scanners? We are using the SonarQube Scanner for MSBuild and the default SonarQube Scanner through Jenkins in our project. The two scanners are executed from different jenkins jobs. One job for .net code and the default scanner for java & typescript.
As project version, the git commit hash is used. The results from both scanners seem to overwrite each other even with the same commit hash.
Either we have only C# results or only java / ts results.
How can we get merged results in one SQ project?
SonarQube Version 5.6

A: This is just impossible to merge analysis reports for one project.
Technically, this would probably be achievable to execute only 1 single SonarQube analysis that does both the .NET part and the Java/JavaScript part. This would answer your use case. But this would be a kind of hack.
IMO, the good way to do it is to split your source code in 2: the .NET part and the Java part. There are chances that these are 2 different technical components anyway, that might have different life cycles even though they relate to the same "business" application.


text:
Q: Why do I need to check if a file can be read twice (once with built in File method once with Scanner) So I'm reviewing my professor's code for a project (my goal is to just understand everything) and she verifies that a file can be opened/read three times, and I'm not sure why all three are necessary.
1: if (!File.exists()) { }  Checks if the file exists using the built in exists method on a File object
2: if (!File.canRead()){ checks if the file can be read using the built in canRead method on the File object
3 (the part I don't understand):
Scanner blank = null;
try {
            blank = new Scanner(File) ;
        } catch (FileNotFoundException e) {
           do whatever
    }

I don't understand why if we already checked if the file can be opened using the canRead method why we need to check AGAIN if it can be opened using a Scanner.
I would appreciate any insight. Thanks.

A: In this example, you are not checking a second time if the file can be opened.
In the code snippet you have provided, there is a new Scanner object made, with the object colorFile passed to it through the parentheses.
The catch section simply is error handling if the file is to not exist on the drive, it will throw an error letting you know.

A: Because Scanner(File) can throw FileNotFoundException. It's part of the API, and a checked Exception. Thus, you have to catch it (or add throws to your own method). Finally, you should always close() your Scanner(s) when they wrap a File. Else you leak a file handle. The best way, in my opinion, would be try-with-resources statement.

A: You understand correctly the idea behind the try/catch first you have to have an understanding of what the Exceptions are.
Basically, Exception is a special kind of object that contains information related to the abnormal behavior of the application.
Exceptions are divided into two categories:

*

*checked;

*unchecked (runtime exceptions).

Checked exceptions represent situations that are more or less expected (something could go wrong not because of some king of in your code, but because file system works this way or because database works in such way, because network connection could fail, etc). It's mandatory for your code to have a scenario for these cases. Checked exceptions are called this way because the compiler checks if they are treated or not. You have to provide a try with catch that matches the expected exception or its parent. Or as an option declare using the throws clause that method may throw an exception and then handle it downstream (as a rule of thumb remember that checked exceptions must be necessarily treated somewhere).
With regards to unchecked exceptions - these are exceptions caused by the drawbacks of code. And are represented by RuntimeException and its subclasses.
When your code tries to access a file a checked exception which is called FileNotFoundException has to be treated.
There are many things that could cause FileNotFoundException:

*

*file-path is wrong;

*file exist, but can not be accessed (due to security reasons, another process uses this file, etc);

*target path exists, but it's a directory and not a file.

And even if this file was successfully accessed previously there could be some wrinkles next time. Every piece of code that deals files must threat FileNotFoundException or one of its parents like `IOException' just because a filesystem behaves this way.
Hope it answers your question.


text:
Q: Run cronjobs in a sequential manner using kubernetes scheduler I am new to kubernetes. I want to run a cronjob using kubernetes scheduler that does the following tasks in a sequence:

*

*Ingest data from datawarehouse into a mysql RDMS

*Process the data

*Indexing of the data using elastic search

Step 2 should occur after the completion of step 1 and step 3 should occur after the completion of step 2. May I know how can I achieve this without using argo or Brigade and simply with kubernetes cronjobs (The idea is to make the ingestion-processing-indexing workflow simple)? And if there's a sample code available for it?


text:
Q: Java How to find a specific line after a specific string? I got a text from a BufferedReader and I need to get a specific line after a specific string
This is the text for example:

<all>

example with linebreak

<all>

example with other character

<all>
UTUYGBLK

I only want the img src line after 'all' which cont and end loop after that. the image number are random so I cant possible hit any of those.
currently my code is as follows.
while ((line = rd.readLine()) != null) {

  if (line.contains("all"))  {
    line = rd.readLine();
    System.out.println(line);
  }
 }

but if there is a linebreak after the 'all' i will get a null return... or funny character UTUYGBLK

A: You will need to loop after the  element then until the result is not null. The code below should protect you against reading lines after end of file and also stop after the first line is shown after  is read.
boolean loop = true;
// global loop
while ((line = rd.readLine()) != null && loop) {
  // line with "all" in it is found?
  if(line.contains("all"))  {
    // Continue going through the input until end of input
    while((line = rd.readLine()) != null && loop) {
      // When the line is not empty you have found the line after all!
      if(!line.isEmpty()) {
        System.out.println(line);
        // to stop the loops
        loop = false;
      }
    }
  }
}

A: Then just skip the blank lines.
while ((line = rd.readLine()) != null) {

    if (line.contains("all"))  {
        while ((line = rd.readLine()) != null && line.trim().isEmpty());
        System.out.println(line);
        break;
    }
}

A: String line = "";
while (!line.contains("all"))
    line = rd.readLine();
line = rd.readLine();
while ("".equals(line.trim()))
    line = rd.readLine();
return line;
//or System.out.println(line);

This will:

*

*Set line to the empty string.

*Read lines until it gets one containing all.

*Read the next line.

*Read lines until it gets a non-empty one.

*Return the last thing it read.

This operates on the assumption that there really will be a line containing all, and that there really will be a non-blank somewhere after it.

A: You can go into a second loop to check for nulls.
while ((line = rd.readLine()) != null) {

        if (line.contains("all"))  {
            while ((line = rd.readLine()) == null || line.isEmpty()) {
                  //keep looping while line is null

                  //check if it is no longer ready to avoid infinite loop
                  if (!rd.ready()) {break;}
            }
            //line should not be null here
            System.out.println(line);
       }

Or something to that affect.

A: If you use contains() if you have an image with a name containing 'all' you will have incorrect results. Better use equals() after trimming the line. So the code will look like this:
while ((line = rd.readLine()) != null ) {
    if (line.trim().equals("<all>"))  {
        while ((line = rd.readLine()).isEmpty());
        System.out.println(line);
        break;
    }
}

A: You can use the method
line.isEmpty()

to handle that case


text:
Q: JSON for GSM Comm on STM32 I am making a remote monitoring system using STM32F1 MCU in which there are few digital and analog sensors attached and I would send their readings to a remote server periodically. Can I use JSON string to send over GSM to the remote server?
I am using M95 GSM Module for TCP Socket connections. The data is over 3G connection.

A: Yes you can. Usually the cellular modules support both TCP and HTTP, so you can send any data you want. The connections are usually initiated and controlled via special AT commands over the UART.


text:
Q: How to disable scrolling on a scroll view without blocking scrolling I am working on an app on android which simulates parallax scrolling with a top scrollview, the content and the bottom scroll view.
I would like to scroll using only the middle scrollview, but I am able to independently scroll the top view manually. This I would like to prevent.
I tried this from another related question, but this seems to disable scrolling in this case.. What I would like is for the touch to fall through to the 2nd layer and for that to handle the scrolling.
.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View view, MotionEvent motionEvent) {
                return true;
            }
        });
Is this a call for onInterceptTouchEvent? I am still trying to understand that.
Let me know if this is not enough information or if it isnt clear.
tl;dr - I want my scroll view to be completely passive touch wise, act as if it doesn't exist, and pass the touch to lower layers.

A: This is just an idea and I haven't tested it but I think the following steps should work:
1.On your top scrollView,intercept the onTouch event(monitor especially the ACTION_MOVE event);
2.Take a handle of the scrollview that you actually want to move. and use ScrollView.smoothScrollto(int x,int y) function to move that scrollView programmatically.Pass the getX() and getY() values that you receive in this motionEvent, thus allowing you to pass the touch to lower layers.
refer the android doc of smoothScrollto for clarity.
3.Obviously as a last note , you should be swallowing the touches on the lower scrollView that you'll be moving programmatically.This will avoid the lower scrollView to move on its own onTouch.
Since you said you want to implement parallax you can multiply the x and y values received in step #2 by some factor thus creating a parrallax effect.
You can easily find code snippets for above steps on SO. Best of luck!
EDIT : refer this link if you want to get the onScroll event when the uppermost scrollView scrolls.

A: My solution is inspired by @Parvaz Bhaskar's solution, but a lot simpler... indeed so simple that i'm surprised that it didn't occur to me when i thought of my question.
To pass the touch to the layer below... I just pass the touch to the layer below
grassView.setOnTouchListener(new View.OnTouchListener() {
      @Override
      public boolean onTouch(View view, MotionEvent motionEvent) {
           mViewPager.onTouchEvent(motionEvent); //Scroll the view pager so that scrolling works through the grass.
           return true; // NO SCROLLING FOR YOU!  http://stackoverflow.com/a/10481239/1520364
       }
 });

In my case I have a layer on top which is the grassView here, and a view pager below which has my actual tabs that that need to scroll. So I swallow the touch on the grass level, and pass it to my ViewPager


text:
Q: Dell OpenManage Causing Periodic Slowness Today we diagnosed the cause of a Periodic slowness issue: see here.
Dell OpenManage Server Administrator seems to have been causing hourly slowness. It would occasionally peg one of the CPUs for upwards of two minutes. Disabling it drastically improved the performance of the SQL Server.
The server hardware:

*

*Dell R710

*Dual Quad Core 2.9GHz Processors

*96GB Memory

*2 Disk RAID 1 SAS System Disk (Internal)

*4 Disk RAID 10 SAS Log Disk (Internal)

*14 Disk RAID 10 SAS Data Disk (External DAS MD1000)

*Windows 2008 Enterprise R2 x64

We installed the OS using Dell OpenManage Server Assistant, so I assume that it was correctly configured.
For now we have disabled OMSA to alleviate the performance issues it was causing, but I'd like to be able to re-enable it.
Has anyone had a similar experience that can shed a little light on the nature of this problem?

A: Yes I have had the same problems with OMSA before, and in some instances it has been in an infinite loop and I have had to kill the process to restore the server to normal operation.
I never found a resolution for the issue (google returns lots of posts like this one and KB articles for VMware and Xen discussing a similar problem).
In my environment I can afford to have it run normally (<5 mins of 100%) but scripted up a tool to look for processes that had run at 90% (or higher) for more than 5 minutes.

A: I've seen that OpenManage can actually crash Window's SNMP service. It's quite depressing, really.


text:
Q: Не отображаются изменения шаблона в Prestashop Не отображаются изменения шаблона в Prestashop, меняю классы и тп. Но, на сайте ничего из этого не отображается. В чем проблема?

A: Smarty комилирует .tpl шаблон в обычный пхп-шаблон. Шаблоны обычно хранят в директориях templates ($templates_dir),  а для компилированных шаблонов обычно выделяют папку templates_c ($compile_dir), к которой настривают права на запись.
Далее смарти работает двумя путями. На продакшене обычно всегда используются скомпилированные варианты, кэш которых очищается только вручную при необходимости (обновили шаблоны), при разработке есть параметр $compile_check, позволяет проверить шаблон на изменение (по дате изменения). Если шаблон был изменен, то смарти компилирует его заново и обновляет кэш. Если не изменялся, то используется из кэша.
Так что в вашем варианте очистка кэша шаблонов решит вопрос, но и при переносе на продакешн сервер не забудьте выключить проверку шаблонов, ибо она серьезно замедляет работу.
В целом можно также и программным путем очистить кэш одного или всех шаблонов сразу. Для этих целей используется clearCompiledTemplate().
Если для переноса кода на продашкен сервер вы, к примеру, используете какие-либо инструменты контроля версий кода (svn, git и т.д.), то (если система позволяет) можно настроить какие-нибудь post-update скрипты, которые будет очищать кэш автоматчиески


text:
Q: Label or index images Question:
How can I index (like in the example below: "c" and "d") images outside the frame?

I started to code, but I got stuck in the lack of documentation:
state0 = Import[
  "d:\\bitbucket\\monte-carlo-borderline\\pics\\torus-0-l5.png"]
state3 = Import[
  "d:\\bitbucket\\monte-carlo-borderline\\pics\\torus-3-l5.png"]
GraphicsGrid[{{state0, state3}}, Spacings -> {1, 2}, Frame -> All]

Input images:

Part-result:

A: states = {state0, state1, ImageMultiply[state0, Red], ImageMultiply[state0, Yellow]};
labels = {"(a)", "(b)", "(c)", "(d)"};

Labeled
Grid[Partition[Labeled[Show[#, ImageMargins -> {{30, 0}, {0, 0}}],
 Style[#2, 16], {{Top, Left}}] & @@@
  Transpose[{states, labels}], 2], Spacings -> 5]

Legended
Grid[Partition[Legended[Show[#, ImagePadding -> {{40, 0}, {0, 40}}],
     Placed[Style[#2, 16], {{0, 1}, {1.1, 0}}]] & @@@
   Transpose[{states, labels}], 2], Spacings -> 1]

A: Grid[{{Labeled[state0, "state0", {{Top, Left}}],
       Labeled[state3, "state3", {{Top, Left}}]}}]

Edit:
You can always use Framed to put a frame around each graph individually. E.g.,
Grid[{{Labeled[Framed[state0], "state0", {{Top, Left}}],
       Labeled[Framed[state3], "state3", {{Top, Left}}]}}]


text:
Q: "The model item passed into the dictionary is of type '" i need show all category in view . i used this code for show all :
Category = Tabel name of Database
public List<Category> GetAllCategory()
    {
        return _repository.GetAll();
    }

/****************************************/
public ActionResult ListCategory()
    {
        return View(_CategoryService.GetAllCategory());
    }

/*****************************************/
i create model CategoryModel .
 public class CategoryModel
{
    [Display(Name ="کد دسته")]
    public int CatID { get; set; }
    [Display(Name = " نام دسته")]
    public string CategoryName { get; set; }
    [Display(Name = " سر دسته")]
    public int ParentID { get; set; }
}

/**********************************/
and in view i use this :
@model IEnumerable<Amene.Models.CategoryModel>

but it show me this error :

The model item passed into the dictionary is of type 'System.Collections.Generic.List1[DA.Data.DB.Category]', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable1[Amene.Models.CategoryModel]'.

o know i must user table name in view Category but i need use CategoryModel .
how can i do this ?


text:
Q: Batch-adding properties in Python? In my code I want to create a bunch of lazy variables, however, if any one of them is being queried, the Load() function as a whole should be called, which will populate all the underlying lazy variables at once.
Currently my class looks like this:
@property
def test1(self):
    if (not self.__test1):
        self.Load()
    return self.__test1

@property
def test2(self):
    if (not self.__test2):
        self.Load()
    return self.__test2

....

Since this looks quite ugly if being done on 30+ variables, I was wondering if there is a way to do this prettier in Python, maybe with some smart decorator?
Thank you for your replies

A: You can define a metaclass to dynamically create all the properties that needs lazy loading. This metaclass gets the property names from a list lazy_props defined in your own class, and within __new__() generate the properties in your class.
The code is like this:
class LazyMeta(type):
    def __new__(cls, clsname, bases, clsdict):
        d = dict(clsdict)
        props = d.get("lazy_props")
        def lazy_load(_attr):
            def wrapped_method(self):
                variable = "_" + _attr
                if not hasattr(self, variable):
                    self.Load()
                return getattr(self, variable)
            return wrapped_method

        for prop in props:
            _method = lazy_load(prop)
            _property = property(_method)
            d[prop] = _property

        return type.__new__(cls, clsname, bases, d)

# Your class uses LazyMeta as metaclass
class LazyClass:
    __metaclass__ = LazyMeta
    lazy_props = ['test1', 'test2']
    def Load(self):
        print "Loading ..."
        self._test1=123
        self._test2=456

Now when you instantiate a object of LazyClass:
>>> l = LazyClass()
>>> l.test1
Loading ...
123
>>> l.test2
456

Note I used _test1, _test2 in place of __test1, __test2, because python treat variables starting with double underscore specially, and it prevents getattr() from working properly.


text:
Q: Question about adding nodes to jedisCluster I have been reading what seems to be conflicting information to me on the correct way to setup jedisCluster. According to what I read on the Jedis GitHub, they state that you only need one of the nodes and jedisCluster will discover the others. I have read others stating that you should add all masters, and yet others say to add all nodes. So, which is the best way to configure this?  Any information on the best way to go with this is greatly appreciated.
Also, can you still us the single Redis stack Docker container with jedisCluster? I plan to just use the Redis Cluster that will be in our Kubernetes when in the office, but we need a way to work on this when out of the office. I'm supposed to get all this figured out in 1 sprint along with a few changes, and we have lost most of our senior developers. Joy!

A: I found the answer to my main question in the article I linked below in case anyone else comes looking for more information.
With jedisCluster you only need to add some of the nodes, from there it will retrieve the information for the other nodes since they all share this information. So, in my case I plan to just add the 3 master nodes. I will update if the standalone stack works or not once, I make it that far in my setup.
https://www.programmerall.com/article/8540798580/#:~:text=Since%20each%20node%20contains%20all%20node%20information%2C%20the,configurations%20are%20for%20high%20availability%29.%20127.0.0.1%3A9380%3E%20cluster%20nodes


text:
Q: Move to next form control from another class C# Is there any way to call processTabKey(); from MyClass.cs which has helpers, and use it for each form that calls it, instead of making one method on each form?
For example Form1.cs calls myMethod() from MyClass.cs which contains processTabKey(); and then move to next control on Form1.cs ?
Thanks in advice.
MyClass.cs
public static void TextBoxKeyDown(this TextBox tb, KeyEventArgs e)
{
    switch (e.KeyCode)
    {
        case Keys.Enter:
        case Keys.Add:
            e.SuppressKeyPress = true;
            processTabKey(true);
            break;
        case Keys.Decimal:
            if (tb.Tag == "importe")
            {
                e.SuppressKeyPress = true;
                processTabKey(true);
            }
            break;
        case Keys.Subtract:
            e.SuppressKeyPress = true;
            processTabKey(false);
            break;
    }
}

Form1.cs

This method calls the helper for moving to next element using ADD, SUBSTRACT, ENTER or DECIMAL keys. The helper is needed in order to use the same method for every form.

private void tb_KeyDown(object sender, KeyPressEventArgs e)
{
    (sender as TextBox).TextBoxKeyDown(e);
}

A: It is possible by creating an instant but I can suggest a more proper way. You can create a class and put all methods you want to share in that class and then call that class from your forms. More effective way is to group methods and create different classes, so you dont have to implement all methods in all forms.

A: Found the way to do it...
MyClass.cs
public static void TextBoxKeyDown(this TextBox tb, KeyEventArgs e, Control container)
{
    switch (e.KeyCode)
    {
        case Keys.Enter:
        case Keys.Add:
            e.SuppressKeyPress = true;
            container.SelectNextControl(tb, true, true, false, true);
            //processTabKey(true);
            break;
        case Keys.Decimal:
            if (tb.Tag == "importe")
            {
                e.SuppressKeyPress = true;
                container.SelectNextControl(tb, true, true, false, true);
            }
            break;
        case Keys.Subtract:
            e.SuppressKeyPress = true;
            container.SelectNextControl(tb, false, true, false, true);
            break;
    }
}

Form1.cs
private void tb_KeyDown(object sender, KeyEventArgs e)
{
    (sender as TextBox).TextBoxKeyDown(e, this);
}


text:
Q: Order of the lines on makefile I have main.cpp (including main function) and func1.cpp, and I want to link these files with a makefile. Classic form would be:
main: main.o func1.o
    g++ main.o func1.o -o main
main.o: main.cpp
    g++ -c main.cpp
func1.o: func1.cpp
    g++ -c func1.cpp

or one can write
main: func1.o main.o
    g++ main.o func1.o -o main
func1.o: func1.cpp
    g++ -c func1.cpp
main.o: main.cpp
    g++ -c main.cpp

or
main: main.o func1.o
    g++ main.o func1.o -o main
func1.o: func1.cpp
    g++ -c func1.cpp
main.o: main.cpp
    g++ -c main.cpp

Do the last two differ from the classic one ? Does one have some advantages over the other?

A: No, the only time the order of the rules comes into play is when you just enter make, in which case it can choose the first rule as the default.
Beyond that, make is intelligent enough to execute dependent rules no matter where they are in the file.

A: There is no difference between the three sets of ruls.  However, make knows how build .cpp files into object files, so all you really need is:
main: main.o func1.o
        g++ main.o func1.o -o $@


text:
Q: How to dim a parent UIView (50% transparent) for login? I have a view with a Login button. When the button is clicked, I add a view with fields for login. When this happens, I need to dim the parent view. How I do that?

A: Add a UIView over the parent view that is initially transparent with a background color of black. When you need to dim it, change the view's alpha to 0.5. This will be 50% transparent.

A: I would go for a view with white background:
whiteView=[[UIView alloc]initWithFrame:viewToDim.frame];
[whiteView setBackgroundColor:[UIColor whiteColor]];
[whiteView setAlpha:0.5f];
[self.view insertSubview:whiteView aboveSubview:viewToDim];

A: UIViews have a property named mask.
mask will always be on top of the UIView who owns it.
So, your approach should be something like this:
(This is for Swift, but it's easily converted to Obj-c)
self.view.mask = UIView(frame: self.frame)
self.view.mask?.backgroundColor = UIColor.black.withAlphaComponent(0.5)

//Do your work here, block UI, anything you need to, and then...
self.view.mask = nil

Update

*

*Removed Swift 2 refernce as it's not relevant anymore. Just as a curiosity, then the property was called maskView

A: class UIDecorator: NSObject {

    static let sharedInstance = UIDecorator()
    private let dimView = UIView()
    private let loadingView = MOOverWatchLoadingView(frame: CGRectMake(0, 0, 100, 100),
                                                             autoStartAnimation: true)
    func showLoadingView() {
        if let currentPage = UIApplication.topViewController(){
            dimView.frame = currentPage.view.frame
            dimView.backgroundColor = UIColor.blackColor()
            dimView.alpha = 0.5
            currentPage.view.addSubview(dimView)
            currentPage.view.userInteractionEnabled = false
            loadingView.center = currentPage.view.center
            loadingView.backgroundColor = UIColor.clearColor()
            currentPage.view.addSubview(loadingView)
        }
    }

    func dismissLocadingView() {
        if let currentPage = UIApplication.topViewController(){
            currentPage.view.userInteractionEnabled = true
            dimView.removeFromSuperview()
            loadingView.removeFromSuperview()
        }
    }
}


text:
Q: How to search repeated positions? I am developing a simple game in Haskell. It's a board game, where Pieces are organized on a "board" by coordinates.
type Piece = (PType, Orientation,Coordinates)
type PType = Char
type Orientation = String
type Coordinates = (Int,Int)

Ok so i read how the board is now from a XML file, and i get a new piece. I want to know what possible plays are possible for that piece in that board.
I look to the first piece, and i see if there are pieces around it. For example imagine a Piece with the coordinates (0,0). If there where other Pieces in the coordinates (1,0),(-1,0),(0,1) and (0,-1) it wouldn't produce any possible play for that new piece that i wanna put in the board, because there are not empty spaces around it. So i have functions that make all possible plays around all pieces in the board.
But i have a problem. So for example, i can have a Piece A in coordinates (0,0) and a Piece B in coordinates (2,0), and after i run all possible plays it will give me a list of possible plays ignoring the plays of each other. Since (1,0) is empty it will diferent plays for that position.
Imagine this list on my output of the possible plays for the example above, for a new piece C. All possible plays would be
[
(C,North,(3,0)),
(C,North,(-1,0)),

(C,North,(1,0)),
(C,South,(1,0)),
(C,North,(1,0)),
(C,East,(1,0))
]

So as you can see there are multiple plays for the coordinate (1,0). I only want the ones that repeat themselvs. I want to make some kind of filter, that first, only looks to the pieces that repeat the same coordinates of this list of possible plays, and then only takes the pieces that have the same PType and Orientation. So the output for the above list would be
[
(C,North,(3,0)),
(C,North,(-1,0)),

(C,North,(1,0)),
]

Can someone help with my problem? My atempts on doing this allways get me the same plays lol


text:
Q: Are Arch Community Packages safe from virus or malwares? I am new on Linux ecosystem and have some confusions regarding the terminology that are being used. With that being said, my reason to switch to a Linux Distro from Windows because it provides a unified package manager from where I can download and install software, without needing to go on the web and find necessary ones. The distro I am currently using is Ubuntu 20.04.2.0, which is good, but the packages they provide are kind of old and I would not be complaining if they had at least provided the LTS version of the software. So, I recently came across Arch and Manjaro which are rolling release distros, but I am interested as it provides both the latest versions and LTS versions of the softwares. That is great. But, I am little worried because most of the software I use are in the Community Repo (Node JS, Dotnet Core and gh). And, here is quote from Arch documentation:

community contains packages that have been adopted by Trusted Users from the Arch User Repository. Some of these packages may eventually make the transition to the core or extra repositories as the developers consider them crucial to the distribution.

It says "Trusted Users" (respect for them) pick the packages from the AUR to "Community Repo". From some online forums and articles, I learnt that it a good practice to avoid using AUR as it may cause unwanted things or even infect ones PC with viruses and malwares. Once again, I am a noob in Linux world and have absolutely no idea about Arch Linux and its derivatives. So, I wanted to know, is it safe to use packages from the Community Repo. Does the "Trusted Users" (maintainers of Community Repo) check for validity and security of the AURs that transition to the Community Repo?

A: Yes, you can trust 'Trusted users' of Archlinux and in general also trust well-known distro maintainers. If you don't, you can compile software yourself (but in that case you should trust software developers). I am not familiar with any case when developer of any kind of any distro intentially was spreading malvare in public repositories.
Regarding 'trusted users' in archlinux. They are not just expert users who randomly move packages from AUR to community repo. They are elected and their AUR packages are reviewed. After electing they are granted special rights, including adding packages to community repo. So, essentially in archlinux there are two types of developers: core developers who 'manage' core/extra repositories and trusted users who manage community repo and AUR package scripts.
Also, not many packages are moved from AUR to community repo. It usually happens when someone is elected as trusted user - he can move some of AUR packages he uses to community repo. If you think dozens of random AUR scripts are moved to community repo each day, then this is not the case.
Tl;dr you can trust community repo packages. By default, you should not 'trust' AUR package (PKGBUILD script) because any user can upload it.

A: Are Arch Community Packages safe from virus or malwares?
No! And why not:
Most packages are compiled from original sources or e.g. package for another distro is used and extracted/repacked, so there are complex buildscripts, stuff downloaded e.g. from github, patches... you will never be sure other if you read all! scripts, patches and sourcefiles.
So even if the AUR scripts are clean, stuff which comes from other sources might be contaminated.
But, I never read about such an issue in the last decade or so.


text:
Q: Cannot ssh into EC2 instance from Windows using Putty I was using a Mac to ssh into my ec2 instance, I am now using a Windows laptop and I cannot connect to the ec2 instance, any recommendations? I have followed the instructions using Putty but it still does not connect. I have even tried using MobaXterm to ssh into my a Ubuntu machine and then ssh from there and that still does not work either. I receive timeout errors in both cases. I have also checked the VPC and Subnets and everything in the route table is connected to each other how it should be. The Mac connection still works but I am just having trouble connecting through the Windows machine (using Putty).

A: The following is a helpful walk through guide: https://www2.linuxacademy.com/howtoguides/17385-use-putty-to-access-ec2-linux-instances-via-ssh-from-windows/

*

*Ensure that you transform the .pem to a .ppk file using PuttyGen found here: https://www.ssh.com/ssh/putty/windows/puttygen#sec-PuTTYgen-download-and-install

*Note: the user you login as by default one of the following:

•For an Amazon Linux AMI, the user name is ec2-user.
•For a RHEL AMI, the user name is ec2-user or root.
•For an Ubuntu AMI, the user name is ubuntu or root.
•For a Centos AMI, the user name is centos.
•For a Fedora AMI, the user name is ec2-user.
•For SUSE, the user name is ec2-user or root.
•Otherwise, if ec2-user and root don't work, check with the AMI provider.

*

*Open Putty and add your the username@xxx.xxx.xxx.xxx (replace with your ec2's IP) to the host section

*use port 22

*Click the 'Auth' section on the right panel and select your .ppk file

*Go back to the 'Session' section and click 'open'

A: 1)you can use Mobaxterm or GitBash
2)gitbash is most recommended .
3) its easy to install and easy to work with.
4) follow this link : https://www.youtube.com/watch?v=r-3KjGtvU-E
5) and you are good to go connecting ec2 instance in your windows


text:
Q: Can a user get the status of the server with a simple http request? I want to show the status of the server to the user every second.
For example, if the server has a status of 1, it takes 5 seconds to download a 1MB file, and if it is 0.1, it takes 50 seconds.
The most intuitive way is to send a GET request each time, but I want to avoid it as much as possible because there is too much data to be sent and received.
Sending a HEAD request has a small amount of data to be sent and received, but it has a large gap with the speed of the Api that the user actually experiences.
Is there any way I can guess at what speed to read in addition to reading content every second?

A: Typically, you would use an HTTP or HTTPS request to verify that your service is up.
Given that your server has a high-bandwidth Internet connection, download speed will be determined by the client's Internet connection and route to your server. Therefore, trying to test bandwidth will 1) waste bandwidth that you pay for and 2) provide you with not-too-useful information.
Rethink what you want to monitor on your server. Typical metrics are CPU utilization, Free Memory, Free Disk Space, Disk I/O, etc. By tracking these metrics you will be able to determine how responsive your server will be to clients.


text:
Q: CUDA: How to find index of extrema in sub matrices? I have a large rectangular matrix NxM in GPU memory, stored as 1-dimensional array in row-by-row representation. Let us say that this matrix is actually composed of submatrices of size nxm. For simplicity, assume that N is a multiple of n and same with M and m. Let us say, the data type of the array is float or double.
What is an efficient method to find the index of the extrema in each sub-matrix? For example, how to find the 1-dimensional index of the maximum element of each submatrix and write down those indices in some array.

A: I can hardly imagine to be so self-confident (or arrogant?) to say that one particular solution is the "most efficient way" to do something.
However, some thoughts (without the claim to cover the "most efficient" solution) :
I think that there are basically two "orthogonal" ways of approaching this

*

*For all sub-matrices in parallel: Find the extremum sequentially

*For all sub-matrices sequentially: Find the extremum in parallel

The question which one is more appropriate probably depends on the sizes of the matrices. You mentioned that "N is a multiple of n" (similarly for M and m). Let's the matrix of size M x N is composed of a*b sub-matrices of size m x n.
For the first approach, one could simply let each thread take care of one sub-matrix, with a trivial loop like
for (all elements of my sub-matrix) max = element > max ? element : max;

The prerequisite here is that a*b is "reasonably large". That is, when you can launch this kernel for, let's say, 10000 sub-matrices, then this could already bring a good speedup.
In contrast to that, in the second approach, each kernel (with all its threads) would take care of one sub-matrix. In this case, the kernel could be a standard "reduction" kernel. (The reduction is often presented an example for "computing the sum/product of the elements of an array", but it works for any binary associative operation, so instead of computing the sum or product, one can basically use the same kernel for computing the minimum or maximum). So the kernel would be launched for each sub-matrix, and this would only make sense when the sub-matrix is "reasonably large".
However, in both cases, one has to consider the general performance guidelines. Particularly, since in this case, the operation is obviously memory-bound (and not compute-bound), one has to make sure that the accesses to global memory (that is, to the matrix itself) are coalesced, and that the occupancy that is created by the kernel is as high as possible.
EDIT: Of course, one could consider to somehow combine these approaches, but I think that they are at least showing the most important directions of the space of available options.


text:
Q: Wireshark cannot see traffic from a VirtualBox guest on Windows 7 I have been trying to use Wireshark to capture some traffic that comes from a virtual machine.
The setup is:

*

*Windows 7 host

*Ubuntu guest

*VirtualBox 4

I send some packets from the guest to the host or another IP in the host LAN. The packets get there, but Wireshark cannot see them.
I have run Wireshark on both the guest and the host. Curiously, if I send the packet to another computer, the packets are captured without problem in the second machine. I don't understand how I cannot capture the packets in the machine that is sending them.
How should I setup VirtualBox, Windows 7 or Wireshark in order to capture the packets sent by the guest machine?

A: When guest OS is set up, a network interface is assigned to it.
        Is wireshark listening on that interface?
In linux, there is an option to use "any" interface, which listens on all possible network interfaces, but I don't know if such option exists on the windows.
Here is explained that wireshark in  windows has difficulties listening on loopback interface, the interface used when machine sends messages to it self.

A: Configure the Attached to: combo box to Bridged Adapter and set the Promiscuous Mode: combo box to Allow All.
Having done this I'm now seeing all traffic going to/from the guest OS.

A: I have an idea for solve your issue , too late but hope it help somebody else:)
Create Host-Only Adapter and bridge with your LAN Adapter. run wireshark on LAN Adapter, It will do the work

A: In my experience Wireshark only sees the host's really external network interfaces. For example, if you use a web browser to look at a web page served by a web-server on the same PC (http://localhost), you can't use Wireshark to look at this traffic.
Similarly, the delivery of data by the VM to the host is local and not directed through a physical NIC. Presumably this provides no structure in the host operating system that looks like a "network interface" to Wireshark.

A: As of March 18, 2022, Wireshark can capture traffic on the Loopback interface.  There is a dashboard when the application opens with a list of network interfaces.  Double click on "Adapter for Loopback Traffic Capture".
Wireshark needs to use the npcap packet capture library for loopback traffic to be detected.


text:
Q: How to use "private" attributes with properties in a class? Considering the following "class" :
function Test()
{
    var data = new Uint8Array(232);
}

I would like to add the following accessor to the data attribute :
Object.defineProperty(Test.prototype, "data",
{
    get: function()
    {
        // calculate other things related to data
        return data;
    }
});

I encountered the following problems :

*

*Defining the property inside the "class" scope works but makes each instances to redefine the property which is bad. Edit: this is where the relevancy of this question stops.

*Defining the property outside obviously don't work since data is made private by closure.

So I tried to make the attributes public :
function Test2()
{
    this._data = new Uint8Array(232);
}

Object.defineProperty(Test2.prototype, "data",
{
    get: function()
    {
        // calculate other things related to data
        return this._data;
    },
    // Avoid "TypeError: setting a property that has only a getter"
    set: function(nv)
    {
        this._data = nv;
    }
});

Edit: I now use "_data" (instead of "data") as my private attribute to avoid a recursion problem with the "data" property. This pattern seems to work.
But is it a good and efficient pattern ? Is there a pattern that allow use of pseudo-private variables with properties ?


text:
Q: Networking in C/C++? I am a begginer C++ programmer. In C#, I used the System.Net.Sockets.Socket class, which represents a networking socket, to create/connect a server. How can I do the same thing in C/C++? Are there any classes like this?

A: In windows theres a library called winsock.dll.
In Unix, you can use unix sockets
Then, theres boost sockets
beej guide to internet sockets
windows sockets
boost networking

A: I would recommend reading beej's guide to Network Socket programming. It is a really good source full of good explanations.

A: Sockets are not a fundamental part of either C or C++. If you are on Windows, start off with Winsock.

A: I've done a little bit with libcurl, this question has tonnes of answers:
Best C/C++ Network Library
...OK to be fair, libcurl doesn't work directly with sockets, so maybe it's not what you're looking for. But it does support a great many protocols.

A: Since you used System.Net.Sockets.Socket in C#, you can use System::Net::Sockets::Socket in C++/CLI--a language which is a .NET flavor of C++.


text:
Q: Does exponential distribution assume proportionality? For example if I'm given $\lambda = 3$ births every $5$ minutes
this average rate must be proportional to the length of the period. Correct?
So $\lambda = 3/5$ births every minute via proportionality. Correct?
This is an assumption we must make to use exponential distribution just like we do with the Poisson distribution. correct? We must assume that the average rate they give us in a question is proportional to the length of the period. Is this right?

A: Something more fundamental is going on here.
$$  \frac{3 \text{ birth}}{5 \text{ minute}} = \frac{3}{5} \frac{\text{birth}}{\text{minute}}  \text{.}  $$
This is just the correct use of units (and remember that the use of singular or plural units is a convention -- the arightmetic of units does not care about the choice of this convention).


text:
Q: Cannot find package cid in $GOROOT or $GOPATH I am trying to customize tuna-app chaincode of the tuna-app example. I want to use cid package inside my chaincode to make ABAC decisions about who is allowed to run the chaincode. When I try to install chaincode, I get the following error:
Error: Error getting chaincode code chaincode:
Error getting chaincode package bytes: Error obtaining dependencies for github.com/hyperledger/fabric/core/chaincode/lib/cid:
<go, [list -f {{ join .Deps "\n"}} github.com/hyperledger/fabric/core/chaincode/lib/cid]>: failed with error: "exit status 1"
cannot load package: package github.com/hyperledger/fabric/core/chaincode/lib/cid: cannot find package "github.com/hyperledger/fabric/core/chaincode/lib/cid" in any of:
/opt/go/src/github.com/hyperledger/fabric/core/chaincode/lib/cid (from $GOROOT)
/opt/gopath/src/github.com/hyperledger/fabric/core/chaincode/lib/cid (from $GOPATH)

I am usind Docker to run peer, orderer, ca, and cli containers. The Docker image which is used to build chaincode is hyperledger/fabric-ccenv. This image is created using Dockerfile; the interesting line I found was:
ADD payload/goshim.tar.bz2 $GOPATH/src/

which adds the tar.bz2 inside the $GOPATH/src folder (I believe). The .tar.bz2 file contains all Go packages used by chaincode. I tried to insert the cid package and to create a new .tar.bz2 file with the package inside. Then I rebuilt the image. The image now contains the cid package, but I still get the same error.
Why is it still missing the package?

A: In the startFabric.sh from your tuna-app, you launch the cli container using:
docker-compose -f ./docker-compose.yml up -d cli

Have a look at the mounting declaration of the persistent volumes in your compose yaml file. You should see something like this because the tuna-app is based on fabcar from the fabric-samples:
./../chaincode/:/opt/gopath/src/github.com/

If you see this declaration, copy in your local machine the folder /hyperledger/fabric/core/chaincode/lib/cid into your chaincode folder. You should find it in chaincode/abac if you are using the last version of fabric samples (https://github.com/hyperledger/fabric-samples).

A: I think you should not create a new goshim.tar.bz2. If you think it is easier make sure cid is in the correct path within the archive, e.g. github.com/hyperledger/fabric/core/chaincode/lib/cid
To test this you can make a debug output:
ADD payload/goshim.tar.bz2 $GOPATH/src/
RUN ls $GOPATH/src/github.com/hyperledger/fabric/core/chaincode/lib/cid

I would recommend to download cid within the Dockerfile:
RUN go get -d github.com/hyperledger/fabric/core/chaincode/lib/cid


text:
Q: How to make sure elements land on full pixel boundaries in a StackLayout? I have a StackLayout holding some elements for a custom cell in a ListView. The problem I am running in to is that my images are not landing on full pixel boundaries. This is causing the straight lines in my graphics to become blurry as they are not landing on pixel boundaries. Is there a way for me to easily prevent this behavior, perhaps in a custom renderer?
    public InputEditCell()
    {
        image = new Image { HorizontalOptions = LayoutOptions.Start };
        image.SetBinding(Image.SourceProperty, new Binding("Image.ImageNameSelect"));
        image.BindingContext = _tempInputViewModel;
        var tappedImageGesture = new TapGestureRecognizer
        {
            Command = new Command(OnImageTapped),
            CommandParameter = image
        };
        image.GestureRecognizers.Add(tappedImageGesture);

        nameEntry = new Entry()
        {
            TextColor = Color.FromHex("E60006"),
            FontSize = Device.GetNamedSize(NamedSize.Medium, typeof(Entry)),
            VerticalOptions = LayoutOptions.Center,
            HorizontalOptions = LayoutOptions.FillAndExpand
        };
        nameEntry.SetBinding(Entry.TextProperty, "Name");
        nameEntry.BindingContext = _tempInputViewModel;

        var acceptImage = new Image
        {
            Source = ResourceHandler.GetAcceptImage(),
            VerticalOptions = LayoutOptions.Center,
            HorizontalOptions = LayoutOptions.End,
        };
        var tappedAcceptGesture = new TapGestureRecognizer
        {
            Command = new Command(OnAcceptTapped),
            CommandParameter = acceptImage
        };
        acceptImage.GestureRecognizers.Add(tappedAcceptGesture);

        var cancelImage = new Image
        {
            Source = ResourceHandler.GetCancelImage(),
            VerticalOptions = LayoutOptions.Center,
            HorizontalOptions = LayoutOptions.End,
        };
        var tappedCancelGesture = new TapGestureRecognizer
        {
            Command = new Command(OnCancelTapped),
            CommandParameter = cancelImage
        };
        cancelImage.GestureRecognizers.Add(tappedCancelGesture);

        var viewLayout = new StackLayout {
            Orientation = StackOrientation.Horizontal,
            Children = { image, nameEntry, acceptImage, cancelImage },
            Padding = new Thickness(10, 10, 10 ,10)
        };

        View = viewLayout;
        View.GestureRecognizers.Clear();
        View.GestureRecognizers.Add(new TapGestureRecognizer());
    }


text:
Q: Appending elements to datatables column I currently utilize the createdRow callback to append buttons (with link) into one of the columns in a datatables.
But this doesn't work when the window is resized (smaller) and that column is hidden (only shown when expanded), since createdRow will no longer be called.
Is there any way to cater for this situation?
Updated:
Column 7 initially contains Id of the respective item (data[7]).
In the createdRow callback, I replace the Id with 3 clickable icons (view/Update/Delete).
createdRow: function (row, data, dataIndex) {
$(row).children().eq(7).html("")
    .append($("<i>").addClass("fa fa-eye mr5").attr("title", "Details").css("cursor", "pointer")
        .click(function () {
            window.location.href = self.urlViewCam + "/?id=" + encodeURIComponent(data[7]);
        }))
    .append($("<i>").addClass("fa fa-pencil mr5").attr("title", "Update").css("cursor", "pointer")
        .click(function () {
            window.location.href = self.urlUpdateCam + "/?id=" + encodeURIComponent(data[7]);
        }))
    .append($("<i>").addClass("fa fa-trash-o").attr("title", "Delete").css("cursor", "pointer")
        .click(function () {
            if (self.confirmationModal) {
                $('#divConfirmMsg').text("Do you want to delete \"" + data[0] + "\"?");
                $('#btnConfirmDelete').click(function () { deleteCamera(data[7]) });
                self.confirmationModal.modal("show");
            } else if (confirmDelete(data[0])) {
                deleteCamera(data[7]);
            }
        }));
}

Current workaround: When details are expanded, search for the next 'tr' (the expanded row), and modify its content.
$(self.detailedTableElem).on('click', 'tr', function () {
    var camName = $(this).children().eq(0).text();
    if (self.table.row($(this)).child.isShown()) {
        $(this).next('tr').find('li > span.dtr-title').each(function () {
            if ($(this).text() == functionColName + ":") {
                appendIcons(camName, $(this).next('span.dtr-data'));
            }
        });
    }
});


text:
Q: how to render html format in node.js (openweathermap.api) This is my code below. What I want to do is when I render, I'd like to render a html format to index.pug without using res.send(body);
When I put a zipcode, a result like the below link will show under text in index.pug.
body is this link. this link is designed in html not image.
link I want to use
topic.js
 router.post('/weather', function(req,res){
      let url = `http://api.openweathermap.org/data/2.5/weather?zip=${req.body.zipcode}&mode=html&units=imperial&appid=${apiKey}`
      request(url, function (err, response, body) {
//this below code works but not what I wanna do
res.send(body);
//this is something I'd like to use
res.render('index',text:body);
          }
       });
    })

index.pug
h1= text

A: The first issue you're seeing is calling the OpenWeather API and fetching only one zip code at a time.  Let's fix that first, then we need to address getting the data efficiently into the pug template where you can generate your table.
1. Fetching Multiple Values
The API spec says that you can string multiple city ID's together but not zip codes.  If you want to keep this easy in the route you should switch to city ID:
http://api.openweathermap.org/data/2.5/group?id=524901,703448,2643743&units=metric

Otherwise you will need to make multiple calls to the api in the route, something that is possible using a library such as async but you say you're just starting out with programming so that's probably not a good first step.
Hopefully your app can use City ID instead, or at the very least you can start with that.
2. Sending the results to the template
The results from a multi-city query look like this:
{"cnt":3,"list":[{"coord":{"lon":37.62,"lat":55.75},"sys":{"type":1,"id":7323,"message":0.0036,"country":"RU","sunrise":1485753940,"sunset":1485784855},"weather":[{"id":800,"main":"Clear","description":"clear sky","icon":"01n"}],"main":{"temp":-10.5,"pressure":1028,"humidity":66,"temp_min":-11,"temp_max":-10},"visibility":10000,"wind":{"speed":5,"deg":200},"clouds":{"all":0},"dt":1485793175,"id":524901,"name":"Moscow"},{"coord":{"lon":30.52,"lat":50.45},"sys":{"type":1,"id":7358,"message":0.0268,"country":"UA","sunrise":1485754480,"sunset":1485787716},"weather":[{"id":800,"main":"Clear","description":"clear sky","icon":"01n"}],"main":{"temp":-11.04,"pressure":1033,"humidity":61,"temp_min":-15,"temp_max":-9},"visibility":10000,"wind":{"speed":3,"deg":150},"clouds":{"all":0},"dt":1485793175,"id":703448,"name":"Kiev"},{"coord":{"lon":-0.13,"lat":51.51},"sys":{"type":1,"id":5091,"message":0.0034,"country":"GB","sunrise":1485762036,"sunset":1485794875},"weather":[{"id":701,"main":"Mist","description":"mist","icon":"50d"},{"id":300,"main":"Drizzle","description":"light intensity drizzle","icon":"09d"}],"main":{"temp":7,"pressure":1012,"humidity":81,"temp_min":5,"temp_max":8},"visibility":10000,"wind":{"speed":4.6,"deg":90},"clouds":{"all":90},"dt":1485793175,"id":2643743,"name":"London"}]}

You'll need to loop through every entity in the list property and extract the data you want.  Here's an example using for...of, it loops through the results, creates a new simpler object for each city, then adds that to the weatherData array.  Just pass weatherData into your template using res.render and you'll find it very easy to create your table.
var weatherData = [];

for(var city in body.list){
  var cityWeather = {
    "name": city.name,
    "temperature": city.main.temp,
    "weather": city.weather[0].description
  };

  weatherData.push(cityWeather);

}

res.render('topic/weather', {"cities": weatherData});


text:
Q: How to extract "executable" strings from a string containing valid python? I'd like to parse a string such as:
code_str = """
def foo(a, b):
    return a + b

foo(
    a=1,
    b=2
)
"""

To get a list of "executable" strings (multi-lined or not)
code_snippets = extract_executable_strings(code_str)
assert code_snippets = [
    "def foo(a, b):\n\treturn a + b\n",
    "foo(\n\ta=1\n\tb=2\n)\n"
]

So that I can do such things as execute the snippets one by one, or produce an equivalent doctest string such as:
"""
>>> def foo(a, b):
...     return a + b
>>>
>>> foo(
...     a=1,
...     b=2
... )
"""

Of course, the simple cases can be covered by regular expressions, but to cover all valid python it seems like I should tap into python's parser itself instead of rewriting (a bad) one myself.

A: Here's the function that does the exact job described by the question.
from ast import parse as ast_parse

try:
    # Try ast.unparse (3.9+)
    from ast import unparse as ast_unparse
except ImportError:
    try:
        from astunparse import unparse as ast_unparse
    except ModuleNotFoundError:
        raise ModuleNotFoundError(
            "Can't find a ast unparse function -- you'll need python 3.9+ or (pip/conda) install astunparse")

def extract_executable_strings(code_str: str):
    """Extract code blocks from code_str

    >>> code_str = '''
    ... def foo(a, b):
    ...     return a + b
    ...
    ... foo(
    ...     a=1,
    ...     b=2
    ... )
    ... '''
    >>> blocks = list(extract_executable_strings(code_str))
    >>> len(blocks)
    2
    >>> print(blocks[0])
    def foo(a, b):
        return (a + b)
    >>> print(blocks[1])
    foo(a=1, b=2)

    """
    for ast_obj in ast_parse(code_str).body:
        yield ast_unparse(ast_obj).strip()


text:
Q: Using JQuery to remove large HTTP requests from DOM on document(ready) I am using a video background for a website, and I'm hoping to reduce the load time on a mobile site by removing this element for mobile.  If I do something like this:
$(document).ready(function() {
    var windowWidth = $(window).width();
    if(windowWidth < 481) {
        $('.video').remove();
    }
});

to measure the screen width on load, assume it is mobile, and then remove this element from the DOM, am I saving any performance with this method?
I'm guessing that is has already made an HTTP request, but if it is immediately removed, the site would "load faster" wouldn't it?
I'm hoping to avoid external libraries aside from JQuery, and I don't want to change the HTML mark up if possible.


text:
Q: multiple phrases connected with comma
I aspire to help organizations achieve their goals by solving the
  issues in the areas of customer focus, employee engagement, adapting
  for change, managing in complex environment and work-life balance

Question :- Are last 3 points "adapting for change", "managing in complex environment" and "work-life balance" fitting well with rest of the sentence?

A: You're mixing verb phrases and noun phrases, which is a problem with parallelism.
Really, each item should be of one form or the other.
For instance:

I aspire to help organizations achieve their goals by solving [] issues in the [area] of customer focus, engaging employees, adapting for change, managing [complex environments], and balancing work [and] life.

I made some additional tweaks in the areas with square brackets, but the main point is that all of the items now start with an -ing-formed verb.
Now it doesn't have any problems with grammar.

As some comments have said, however, you might want to do something to make it easier to parse.
You could use a vertical list:

I aspire to help organizations achieve their goals by

*

*solving issues in the area of customer focus,

*engaging employees,

*adapting for change,

*managing complex environments, and

*balancing work life.

Or, you could keep everything horizontal but help the items stand out like this:

I aspire to help organizations achieve their goals by (1) solving issues in the area of customer focus, (2) engaging employees, (3) adapting for change, (4) managing complex environments, and (5) balancing work and life.


text:
Q: how do i get subtext source code without Web platform installer? I check all over the net and i can't find a way to get the new version of subtext without using the Web platform installer? Why do we need to install a installer in order to get the source code? what's the purpose of this additional hoop? does anyone know how to get any of the web app on the web gallery without using the web platform installer?
edit: ok, i find it on the link text
still what is the purpose of the web installer? why not just give us the source?

A: The Web Platform Installer is used to download and install the product on your machine. It can handle things like applying the appropriate IIS settings, setting permissions on the file system, etc...
So it's great for getting a running instance of Subtext or other web software working on a server.
If you want the source code, go to http://code.google.com/p/subtext


text:
Q: How would I divide a string after a specific character in Python EDIT: Thank you for so many responses and apologies for ambiguous question, and poorly constructed example. I didn't mean to split the word by the uppercase character. I literally mean to split the string after a specific character like 'X', 'r', or 'o'.
I'm trying to split a long string of repeating words like "FooXXBarBazXBar ..." into a list of words ['Fo', 'o', 'X', 'X', 'Bar', 'Baz', 'X', 'Bar' ...].
In c I would create a new array of characters and copy characters one by one, inserting a delimiter after a specific character, to later split on the delimiter like this:
{
    char *newString = malloc(sizeof(char)*200);
    int offset=0;

    //copy characters from old string to the new one, inserting ';' after a specific character

    for (int i = 0, n = strlen(string); i < n; i++)
    {
        newString[i+offset] = string[i];
        if ((string[i] == 'o') || (string[i] == 'r') || (string[i] == 'z') || (string[i] == 'X'))
        {
            offset += 1;
            newString[i+offset] = ';';
        }
    }

    //split the string into an array of strings on the delimiter ';'
    split_string(newString);
}

I'm still a beginner, so it's probably also not that great, but it works.
I'm trying to work around this in python, but cannot come up with a good approach.
How would you go about it? Thanks :)

A: If i understand correctly, and what you want to do is to split each word on an uppercase letter ("HelloWorldPython" -> ["Hello", "World", "Python"]
I would use regex:
import re
text = "FooXXBarBazXBar"
re.findall(r'[A-Z][^A-Z]*', text) # Uppercase letter followed by 0 or more non-uppercased character
['Foo', 'X', 'X', 'Bar', 'Baz', 'X', 'Bar']

A: Your quesiton is kind of ambiguous. It's not clear at which characters you wanna split the string but if these are ['o','r','X','z'] then the following code will do:
string = input()
word = ''
words_list = []
for char in string: # iterate through the string
    word += char # add the character to the word
    if(char in ['o','r','X','z']): # check if the character at current iteration is one of the characters in the list
        words_list.append(word) # add the word formed by now to the list
        word = '' # re-initialize the word variable to an empty string so as to start the next word
print(words_list)

This would output:
['Fo', 'o', 'X', 'X', 'Bar', 'Baz', 'X', 'Bar', 'xxX']

Warning: As you have specified 'o' as a splitting cahracter it will never give you 'Foo' in order to get 'Foo' instead of 'Fo' in the list you will have to add more code within the loop.

A: Splitting a string into parts starting with an uppercase.
like splitting "ThisIsALineAsAnExample" to ['This','Is','A','Line','As','An','Example']
if this is what you want to do then this may help
i=0
j=1
final=[]
s="ThisIsALineAsAnExample"
while(i<len(s)):
    if(s[i].isupper()):
        new_str=s[i]
        j=i+1
        while(j<len(s) and s[j].islower()):
            new_str=new_str+s[j]
            j=j+1
        print(new_str)
    i=j
    final.append(new_str)

print(final)

A: The example input and the ouput suggests that you want to split every word that starts with an uppercase letter.
For Python, a solution with this approach can be found here.
If you want to apply it to your solution in C too,you can check if a char is uppercase by:
if(string[i] >= 'A' && string[i] <= 'Z') {
    offset += 1;
    newString[i+offset] = ';';
}


text:
Q: Assign a value depending on window width using jQuery I am using the bigSlide.js (http://ascott1.github.io/bigSlide.js/) plugin to create a slide-in menu.
I'm able to enter my own value for the width of the menu, which I've set to 250px, this is then used later in the code. The site is responsive so what I would like to happen is for the value to change depending on the window width, ie. window width 600px or less - the menu width be 100px, and if the window width is larger than 600px - the menu width be 250px.
Is this possible to do? If so, would someone be kind enough to show me how, thanks.
jQuery(function($) {
  'use strict';

  $.fn.bigSlide = function(options) {

    var settings = $.extend({
      'menu': ('#menu'),
      'push': ('.push'),
      'side': 'right',
      'menuWidth': '250px',
      'speed': '300'
    }, options);

    var menuLink = this,
        menu = $(settings.menu),
        push = $(settings.push),
        width = settings.menuWidth;

    var positionOffScreen = {
      'position': 'fixed',
      'top': '0',
      'bottom': '0',
      'settings.side': '-' + settings.menuWidth,
      'width': settings.menuWidth,
      'height': '100%'
    };

    var animateSlide = {
      '-webkit-transition': 'all' + ' ' + settings.speed + 'ms ease',
      '-moz-transition': 'all' + ' ' + settings.speed + 'ms ease',
      '-ms-transition': 'all' + ' ' + settings.speed + 'ms ease',
      '-o-transition': 'all' + ' ' + settings.speed + 'ms ease',
      'transition': 'all' + ' ' + settings.speed + 'ms ease'
    };

    menu.css(positionOffScreen);
    push.css(settings.side, '0');
    menu.css(animateSlide);
    push.css(animateSlide);

    menu._state = 'closed';

    menu.open = function() {
      menu._state = 'open';
      menu.css(settings.side, '0');
      push.css(settings.side, width);
    };

    menu.close = function() {
      menu._state = 'closed';
      menu.css(settings.side, '-' + width);
      push.css(settings.side, '0');
    };

    menuLink.on('click.bigSlide', function(e) {
      e.preventDefault();
      if (menu._state === 'closed') {
        menu.open();
      } else {
        menu.close();
      }
    });

    return menu;

  };

}(jQuery));

A: You can use $(window).resize to detect when the window is resized.
Working example of window resize with width change using bigSlide.js
jsfiddle
------------------ UPDATED --------------------
You can probably add the resize code right before line
return menu;
-But what would be kind of an issue is updating the value of menuWidth because it passes its value to other variables. So you need to update whatever lines of code are affected by it.
// examples from plugin code
width = settings.menuWidth;

var positionOffScreen = {
      'settings.side': '-' + settings.menuWidth,
      'width': settings.menuWidth
};

menu.css(positionOffScreen);

To keep from repeating the same code, you should encapsulate the code into a function. Then you can call the function when .bigSlide() is instantiated and again whenever the window.resize event is fired.
-I updated the JSFIDDLE  with the resize event integrated with the plugin. Try to optimize it if you can.
-jQueryLearning-Plugins can help you get a basic understanding of plugin development.
// TEST
$(window).resize(function(){
    // Get window width
    var window_width = $(window).width();

    // Determine width
    if (window_width <= 600) {
         settings.menuWidth = '100px';
    } else if (window_width > 600) {
         settings.menuWidth = '250px';
    }

    // Updating menu width
    positionOffScreen = {
          'settings.side': '-' + settings.menuWidth,
          'width': settings.menuWidth
    };
    menu.css(positionOffScreen);
}); // TEST


text:
Q: How to detect unclosed brackets in XML parsing In case the provider supplies a XML string that does not parse due to parse errors (and thet will not fix this for a while), I was wondering if it is possible to perform some validations to detect and correct the XML so it will be fail-proof.
Some examples of issues can be:
The rule of thumb is to get <> replaced for <>

*

*Lonely < replaced for <

*Words like <this> that are not XML tags (the criteria can be to replace the < and > symbols to ignore the unclosed tag.

*Math formulas like this: 5<x<10
I can't come with more scenarios at the moment, and I think I detected one o those with regex, but that is not enought.
I would like to read your comments.

A:
I was wondering if it is possible to perform some validations to
  detect and correct the XML so it will be fail-proof.

Your noble intentions are unfortunately misguided.  In a fundamental sense, communication mistakes cannot be repaired without relying upon some portion of the protocol being mistake-free.
You can only be so liberal in what you accept.  Even Postel's Law has its limits.
Standard practice in building XML-based systems is to require that messages be well-formed XML.  (In fact, non-well-formed XML is not XML; see Michael Kay's answer.)  Especially when you cannot trust your sender to follow protocol, you should check your input.  One of the benefits of XML is that there exist battle-tested parsers to use to perform these checks.
Pull the message off the wire and immediately parse it using a known-reliable parser such as Xerces2.  If there are errors, pass them back to the sender to repair and do not attempt to process the message further.  If you have a schema, the parse should be conducted with validation turned on against the schema to detect higher-level errors in the protocol as well.
Do not be tempted by the possibility of correcting "obvious" errors in an ad hoc manner.  The problem is theoretically unsolvable in the general case, and attempts at applying piecemeal corrections will actually make your system less robust, not more.

A: I would recommend using XML for data interchange. It's a great format. When people use XML, you have a wide choice of off-the-shelf parsers available which guarantee that everyone can read your data. By contrast, if you use home-brew formats that are not standardised and not documented then deciphering the data becomes a nightmare.
I would also recommend that if you are using a home-brew format for data interchange, you don't call it XML, because you will only confuse people.
If you want help here in how to parse a home-brew non-XML data interchange format, please don't tag the question as "XML", because you reach the wrong audience. And please provide a specification of the format. I know you don't have one, but writing a program to read data in an unspecified format is not something any competent programmer should ever attempt.


text:
Q: How can i use Cloud Firestore and Firebase Auth for windows i have a app both mobile and web in flutter so i want to create for desktop App, but base on the plugin does not support windows..
How can i use cloud Firestore and Firebase Auth in windows

A: Since the plugins don't support it, and there are no SDKs for Windows for either of the products, the most likely only option is to wrap the REST API that both provide. See: Auth REST API and the Firestore REST API.
It might also be worth checking out the Firestore gRPC API and its .NET client library, although I'm not sure if the latter is meant for use in client-side code or just for use in a trusted environment.

A: I had the same problem with desktop app in c#, there is not a lot of examples on the web. You are asking about flutter but I think my answer still should help you as the implementation is less important than concept.
You need to call your service and ask for custom_token, next with this custom_token you are calling google service and exchange custom_token for access_token. With this access_token you can call your service.
I created the the solution react.js+python+c#+firebase to have example for a future.

You can check the example on github

The firebase documentation regarding this topic is here


text:
Q: Capybara-webkit: not executing coffeescript properly I have a button which when being clicked, it triggers an ajax post, and renders an alert.
It works great, but when running a test, the coffeescript doesn't get executed well.
My files
app/views/alerts/index.html.haml
= link_to icon('plus', 'Show Alert'), new_alert_path, class: 'btn btn-with-icon btn-primary', remote: true

app/controllers/alerts_controller.rb
class AlertsController < BaseController
  def new
    @alert = Alert.new
  end
end

app/views/alerts/new.js.coffee
console.log "1" # => This is being executed
AlertComponent.show "show this message" # Here it breaks I think
console.log "2" # => It never arrives here

app/assets/javascript/alert_component.js.coffee
class AlertComponent
  @show: (description) ->
    console.log "3" # => This is not being executed
    # => Does some other stuff

end

window.AlertComponent = AlertComponent

My test
click_link 'Show Alert' # => This is executed because I added a binging.pry in the controller and it arrives properly
wait_for_ajax
p page.driver.console_messages # => Below is what it returns
expect(page).to have_css '.alert-div'

The result
The test fails, and the page.driver.console_messages returns this:

{:line_number=>0, :message=>"ReferenceError: Can't find variable: AlertComponent", :source=>"undefined"}

As I already said, it works great on development and production. The problem is with the tests.
My setup
I am using Capybara-webkit:

*

*capybara (2.9.2)

*capybara-webkit (1.1.0)

spec/rails_helper.rb
ENV['RAILS_ENV'] ||= 'test'
require File.expand_path('../../config/environment', __FILE__)
# Prevent database truncation if the environment is production
abort("The Rails environment is running in production mode!") if Rails.env.production?
require 'spec_helper'
require 'rspec/rails'

Capybara.javascript_driver = :webkit

# more stuff

Any ideas about why isn't this working as expected?

A: The big difference between development and test/production, when talking about the rails asset pipeline, is that in development each JS file is served separately, while in test/production they get concatenated together and served as one file.  This means that a JS error in one file doesn't stop the other files from being processed in development mode, but it can in test/production mode. It looks like it's probably aborting evaluation of the concatenated file before the AlertComponent class is created.
Check your browsers developer console when running the app in dev mode and fix any JS errors that are being logged.


text:
Q: Can't determine the user's config path I'm using the svn library as part of my web application to rerteive text files. I'm getting the following error:

Can't determine the user's config path

The weird thing is that I can access other command line tools and checkout my files without any problem.
Has anyone encountered this problem?

A: This post is old, but for me it was the AppPool identity user. I changed it to localsystem and it worked. The AppPool user should have the proper permissions to access the file.


text:
Q: R: sort contents of a column I am trying to sort a contents of a data frame column alphabetically in R, e.g., I have joined two columns
col_1, col_2, col_joined
A, B, A_B,
A, B, A_B,
B, A, B_A,

I would like to have it like:
A, B, A_B,
A, B, A_B,
B, A, A_B,

Not really sure how to do that. Many thanks for your help.

A: We can use pmin/pmax to get the rowwise 'min/max' values and paste them together with str_c
library(dplyr)
library(stringr)
df1 %>%
     mutate(col_joined = str_c(pmin(col_1, col_2), pmax(col_1, col_2), sep="_"))
#  col_1 col_2 col_joined
#1     A     B        A_B
#2     A     B        A_B
#3     B     A        A_B

data
df1 <- structure(list(col_1 = c("A", "A", "B"), col_2 = c("B", "B",
"A")), row.names = c(NA, -3L), class = "data.frame")


text:
Q: bootloader works on qemu but not on real machine i have been writting an os for the last weeks and its going fine i decided to try it on a real machine but it doesnt jump to kernel
i have tried to use an hdd instead of an usb stick and it doesnt even get the bootloader as it gets on the usb stick
ive tried to search on the web and use other code but it just doesnt jump to kernel
here is the boot code
[ORG 0x7c00]

[BITS 16]

CODE_SEG EQU gdt_code - gdt_start
DATA_SEG EQU gdt_data - gdt_start

jmp short biosBlock
nop

biosBlock:
    jmp 0:start

start:
    ;umas checkagens
    cli ;clear interrupts
    mov ax, 0x00
    mov ds, ax
    mov es, ax

    mov ss, ax
    mov sp, 0x7c00
    sti ;enables interrupts

.load_protected:
    cli
    lgdt[gdt_descriptor]
    mov eax, cr0
    or eax, 0x1
    mov cr0, eax
    jmp CODE_SEG:load32

;just using gdt so we can use all the memory :D 4GB
gdt_start:
gdt_nul:
    dd 0x0
    dd 0x0

;offset 0x8
gdt_code:  ;cs should point to this
    dw 0xffff
    dw 0
    db 0
    db 0x9a
    db 11001111b
    db 0
;offset 0x10
gdt_data:
    dw 0xffff
    dw 0
    db 0
    db 0x92
    db 11001111b
    db 0

gdt_end:

gdt_descriptor:
    dw gdt_end - gdt_start - 1
    dd gdt_start

[BITS 32]
 load32:
    mov eax, 1
    mov ecx, 100
    mov edi, 0x0100000
    call ata_lba_read
    jmp CODE_SEG:0x0100000

ata_lba_read:
    mov ebx, eax, ; Backup the LBA
    ; Send the highest 8 bits of the lba to hard disk controller
    shr eax, 24
    or eax, 0xE0 ; Select the  master drive
    mov dx, 0x1F6
    out dx, al
    ; Finished sending the highest 8 bits of the lba

    ; Send the total sectors to read
    mov eax, ecx
    mov dx, 0x1F2
    out dx, al
    ; Finished sending the total sectors to read

    ; Send more bits of the LBA
    mov eax, ebx ; Restore the backup LBA
    mov dx, 0x1F3
    out dx, al
    ; Finished sending more bits of the LBA

    ; Send more bits of the LBA
    mov dx, 0x1F4
    mov eax, ebx ; Restore the backup LBA
    shr eax, 8
    out dx, al
    ; Finished sending more bits of the LBA

    ; Send upper 16 bits of the LBA
    mov dx, 0x1F5
    mov eax, ebx ; Restore the backup LBA
    shr eax, 16
    out dx, al
    ; Finished sending upper 16 bits of the LBA

    mov dx, 0x1f7
    mov al, 0x20
    out dx, al

.next_sector:
    push ecx

.try_again:
    mov dx, 0x1f7
    in al, dx
    test al, 8
    jz .try_again

; We need to read 256 words at a time
    mov ecx, 256
    mov dx, 0x1F0
    rep insw
    pop ecx
    loop .next_sector
    ; End of reading sectors into memory
    ret

times 510 - ($- $$) db 0
dw 0xAA55

make file code:
        dd if=./bin/boot.bin >> ./bin/os.bin
    dd if=./bin/kernel.bin >> ./bin/os.bin
    dd if=/dev/zero bs=1048576 count=32 >> ./bin/os.bin

im using
dd if=os.bin of="the_usb"

A: The most likely problem is that (for real hardware but not emulators) the ATA controller got replaced by SATA/AHCI about 20 years ago (and then got replaced by NVMe about 10 years ago); and you have no sanity checks to determine if the ATA controller you think you're talking to exists (or is faulty, or has a hard drive plugged into it, or if that hard drive is faulty, or if the commands you sent worked and didn't just return a "read error") and no code to handle any of the many possible problems (not even displaying the absolute worst possible "Sorry, something went wrong" error message).
This is why it's a good idea to use the firmware to access devices (e.g. BIOS "int 0x13") during early boot, until the OS is able to detect which devices are present (e.g. starting with PCI bus enumeration) and set up the right device drivers for whatever devices were detected.
To be more general; (for both BIOS and UEFI) its best to split "boot" into 4 phases:
a) Early boot. During this phase the firmware owns all the hardware and you only use the firmware to do things. The purpose of early boot code is to gather information from firmware (e.g. get a memory map that you need later), setup temporary memory management (including disabling A20 using the relevant BIOS function), load "kernel plus drivers and whatever else will be needed later" (possibly kernel plus "initial RAM disk"), setup a default video mode, etc. This typically involves switching between real mode (to use BIOS functions) and either protected mode or long mode (to be able to access more memory); to avoid the "kernel and/or initial RAM disk is many MiB but real mode can only access about 640 KiB of RAM" problem (by loading into a temporary buffer in real mode and then moving data where you actually want it  using protected/long mode). This phase ends when the OS either figuratively (for BIOS) or literally (for UEFI, via. its "ExitBootServices()") takes control of all hardware from firmware.
b) Kernel initialization. This is where you set up things like physical memory management, virtual memory management, scheduler, device driver interfaces, etc. Note that during this phase nothing needs to access any device. Also, some work can be done (e.g. decompressing kernel's file, setting up paging and mapping kernel into the right place in virtual memory) before passing control to kernel (not all of "kernel initialization" is done by kernel itself).
c) Setting up devices (detecting which devices are present, loading their device drivers from "initial RAM disk", letting device drivers test their device and see what is connected to them, etc). Note that this can be conceptually recursive and can end with "non-device services". E.g. PCI bus enumeration detects network card and starts network card driver, then network card driver initializes (and checks for faulty hardware) and detects network connection/s and starts TCPI/IP stack (if not already started); or PCI bus enumeration detects USB controller and starts relevant USB controller driver, USB controller driver detects sound device and starts relevant USB sound device driver; USB sound device driver detects speakers/microphones and starts some kind of sound service (if not already started). In the same way a hard disk controller could (after initialization, detecting attached disks, etc) start a RAID layer and/or start file systems.
d) Pass control to user-space for more initialization. This could be an "init script" (ancient Unix), or could be something a user can use to log in (followed by a GUI); and will probably include various other things (starting services/daemons).
Note that (especially in early phases where you can't just say "LOL, if something is wrong kernel or device drivers will handle it") maybe half of your code will exist to deal with things that should never happen. This means that it's impossible to have acceptable early boot code that fits in 512 bytes, even if you do none of the thing that are necessary (e.g. get a memory map).


text:
Q: Power-Pivot:500 Internal Server Error I am importing the ssrs report from .automsvc extension and I am facing the below issue as .Can any one help me how can I solve this issue
Tablix1: The remote server returned an error: (500) Internal Server Error.

A: If you have any date columns delete them from the SSRS report and see if the PowerPivot connection works.  You may need to play with formatting if you want to add the columns back.  Trial and error.

A: Yea, took me a bit to find, but the issue is simple and also stupid. Power Pivot has issues with importing "Calculated Fields" - But I think these are Sharepoint created and might still work with Infopath created Calculated fields, hope this helps someone. Once I removed the calculated fields I stopped getting this error immediately.