text:
Q: Must declare the scalar variable "@historyId" exception I have a working raw Sql command execution
using (var cmd = SqlUtils.CreateSqlCommand(cmdText, sqlConn))
    {
      cmd.Parameters.Add(new SqlParameter("historyId", SqlDbType.Int)).Value = AAverage.CashFlowRelevantHistoryId;
      cmd.Parameters.Add(new SqlParameter("nodeId", SqlDbType.Int)).Value = AAverage.CashNodeId;
      cmd.Parameters.Add(new SqlParameter("denomId", SqlDbType.Int)).Value = AAverage.DenominationId;
      cmd.Parameters.Add(new SqlParameter("dayId", SqlDbType.Int)).Value = AAverage.CashFlowDayCategoryId;
      cmd.Parameters.Add(new SqlParameter("hour", SqlDbType.Int)).Value = AAverage.Hour;
      cmd.Parameters.Add(new SqlParameter("type", SqlDbType.Int)).Value = AAverage.ValueType;
      cmd.Parameters.Add(new SqlParameter("average", SqlDbType.Real)).Value = AAverage.AverageDerivative;

      using (var reader = cmd.ExecuteReader())
        if (reader.HasRows && reader.Read())
        {
          IDataRecord record = (IDataRecord)reader;
          AAverage.Id = record.GetInt32ByName("Id");
        }
    }

but if I've changed it to use SqlQuery method, I get the error in the subject:
  StringBuilder cmdText = new StringBuilder();
  cmdText.AppendLine("INSERT INTO CashFlowAverageDerivatives");
  cmdText.AppendLine("  (CashFlowRelevantHistoryId, CashNodeId, DenominationId, CashFlowDayCategoryId, Hour, ValueType, AverageDerivative)");
  cmdText.AppendLine("VALUES");
  cmdText.AppendLine("  (@historyId, @nodeId, @denomId, @dayId, @hour, @type, @average)");
  cmdText.AppendLine("SELECT Id FROM CashFlowAverageDerivatives WHERE @@ROWCOUNT > 0 and Id = scope_identity()");
  AAverage.Id = ADbContext.Database.SqlQuery<int>(
    cmdText.ToString(),
    new SqlParameter("historyId", SqlDbType.Int).Value = AAverage.CashFlowRelevantHistoryId,
    new SqlParameter("nodeId", SqlDbType.Int).Value = AAverage.CashNodeId,
    new SqlParameter("denomId", SqlDbType.Int).Value = AAverage.DenominationId,
    new SqlParameter("dayId", SqlDbType.Int).Value = AAverage.CashFlowDayCategoryId,
    new SqlParameter("hour", SqlDbType.Int).Value = AAverage.Hour,
    new SqlParameter("type", SqlDbType.Int).Value = AAverage.ValueType,
    new SqlParameter("average", SqlDbType.Real).Value = AAverage.AverageDerivative
  ).First<int>();

and I have no idea why. If I tried to rename "historyId" in Sql text to something else, exception reports this new name. It seems like parameter definition was missing or misspelled, but list of parameters has been copy&pasted, VS IDE search command finds it, prefix "@" does not matter...
Sure I can live with my working version, but I'm learning EF and it tease me I'm not able to solve this

A: You were sending the sql parameter as value directly.
When you did this
new SqlParameter("historyId", SqlDbType.Int).Value = AAverage.CashFlowRelevantHistoryId

You actually sent a value of AAverage.CashFlowRelevantHistoryId, not a SqlParameter.
Try changing it with this and see if it works.
AAverage.Id = ADbContext.Database.SqlQuery<int>(
  cmdText.ToString(),
  new SqlParameter("historyId", AAverage.CashFlowRelevantHistoryId),
  new SqlParameter("nodeId", AAverage.CashNodeId),
  new SqlParameter("denomId", AAverage.DenominationId),
  new SqlParameter("dayId", AAverage.CashFlowDayCategoryId),
  new SqlParameter("hour", AAverage.Hour),
  new SqlParameter("type", AAverage.ValueType),
  new SqlParameter("average", AAverage.AverageDerivative)
).First<int>();

Or this
AAverage.Id = ADbContext.Database.SqlQuery<int>(
  cmdText.ToString(),
  new SqlParameter("historyId", SqlDbType.Int) { Value = AAverage.CashFlowRelevantHistoryId },
  new SqlParameter("nodeId", SqlDbType.Int) { Value = AAverage.CashNodeId },
  new SqlParameter("denomId", SqlDbType.Int) { Value = AAverage.DenominationId },
  new SqlParameter("dayId", SqlDbType.Int) { Value = AAverage.CashFlowDayCategoryId },
  new SqlParameter("hour", SqlDbType.Int) { Value = AAverage.Hour },
  new SqlParameter("type", SqlDbType.Int) { Value = AAverage.ValueType },
  new SqlParameter("average", SqlDbType.Real) { Value = AAverage.AverageDerivative }
).First<int>();


text:
Q: How do I validate data mapping between 2 data frames in pandas I am trying to validate a data mapping between two data frames for specific columns. I need to validate the following:

*

*if values in a specific column in df1 matches the mapping in a specific column in df2.

*if values in a specific column in df1 does not match the specified mapping in a specific column in df2 - a different value in df2.

*if values in a specific column in df1 does not have a match in in df2.

df1 looks like this:

cp_id
cp_code

2A23
A

2A24
D

3A45
G

7A96
B

2A30
R

6A18
K

df2 looks like like:

cp_type_id
cp_type_code

2A23
8

2A24
7

3A45
3

2A44
1

6A18
8

4A08
2

The data mapping constitutes of sets of values where the combination could match any values within the set, as following:

*

*('A','C','F','K','M') in df1 should map to (2, 8) in df2 - either 2 or 8

*('B') in df1 should map to 4 in df2

*('D','G','I') in df1 should map to 7 in df2

*('T','U') in df1 should map to (3,5) in df2 - either 3 or 5

Note that df1 has a cp_code as R which is not mapped and that 3A45 is a mismatch. The good news is there is a unique identifier key to use.
First, I created a list for each mapping set and created a statement using merge to check for each mapping. I ended up with 3 lists and 3 statements per set, which I am not sure if this is the right way to do it.
At the end I want to combine the matches into one df that I call match, all no_matches into another df that I call no_match, and all no_mappings into another df that I call no_mapping, like the following:
Match

cp_id
cp_code
cp_type_id
cp_type_code

2A23
A
2A23
8

2A24
D
2A24
7

6A18
K
6A18
8

Mismatch

cp_id
cp_code
cp_type_id
cp_type_code

3A45
G
3A45
3

No Mapping

cp_id
cp_code
cp_type_id
cp_type_code

7A96
B
NaN
NaN

NaN
NaN
2A44
1

2A30
R
NaN
NaN

NaN
NaN
4A08
2

I am having a hard time to make the no_match to work.
This is what I tried for no match:

*

*filtered df1 based on the set 2 codes

*filtered df2 based on not in map 2 codes

*for the no mapping, I did a df merge with on='cp_id'

    no_mapping_set2 = df1_filtered.merge(df2_filtered, on='cp_id', indicator = True)

With the code above, for cp_id = 'B', for example, instead of getting only 1 row back, I get a lot of duplicate rows with cp_id = 'B'.
Just to state my level, I am a beginner in Python. Any help would be appreciated.
Thank you so much for your time.
Rob

redpajama_set_name: RedPajamaStackExchange


text:
Q: nginx config for same server but different ports I recently upgraded from nginx 1.9.2 to 1.14.0 and something that worked in our old configuration is no longer working. I have our normal website on standard SSL configuration, but I also have an http version running with the same domain name but on port 8888 (let's call this the alternate site). The sample configuration below no longer works, it results in my alternate site being redirected to https (but still on port 8888).
What is even more strange is that if I open a private browsing window, and go directly to the alternate url (http://my_domain.com:8888) it will work. But the moment I browse to our normal https site, the alternate site has this issue.
The relevant portion of my nginx.conf is below. Does anyone see what the issue might be?
# Configuration for "alternate" website
server {
  listen <ip>:8888;
  server_name my_domain.com;
  location / {
    proxy_pass http://127.0.0.1:8889
    ...
  }
}

# Redirect normal http traffic (port 80) to https
server {
  listen <ip>:80;
  server_name my_domain.com;
  return 301 https://my_domain.com$request_uri;
}

# Configuration for standard https site
server {
  listen <ip>:443 ssl http2;
  server_name my_domain.com;
  ... SSL configuration ...
  location / {
    proxy_pass http://localhost:127.0.0.1:12345;
    ...
  }
}


text:
Q: Cannot write dynamic xpath for element in page This is the Url: http://automationpractice.com/index.php
I want to select "casual dresses", but when I tried the "Women" WebElement is selected instead.
How can I write the dyanmic xpath to select "casual dresses"?

A: You have to wait until page is loaded, then hover over Women title, the wait until the menu is open and then click on the Casual Dress item.
It's best practice to keep variables in the top of class, not inside the code hardcoded.
Try this:
//Define expected conditions explicitly wait
WebDriverWait wait = new WebDriverWait(driver, 30);
//Define Actions object instance
Actions action = new Actions(driver);
//define locators
String womenTitleXpath = "//a[@title='Women']";
String up = "/..";
String womenCasualDressXpath = womenTitleXpath + up + "//a[@title='Casual Dresses']";
//Wait until the element is visible
wait.until(ExpectedConditions.visibilityOf(By.xpath(womenTitleXpath)));
WebElelemnt womenTitle = driver.findElement(By.xpath(womenTitleXpath));
//Hover over the Menu to open it
action.moveToElement(womenTitle).build().perform();
//Wait until the menu item is visible
wait.until(ExpectedConditions.visibilityOf(By.xpath(womenCasualDressXpath)));
//Finally click on the desired element
driver.findElement(By.xpath(womenCasualDressXpath)).click();

A: You can find by reading the <li> items,this is my result:
xpath:
//*[@id="block_top_menu"]/ul/li[1]/ul/li[2]/ul/li[1]/a

full xpath:
/html/body/div/div[1]/header/div[3]/div/div/div[6]/ul/li[1]/ul/li[2]/ul/li[1]/a

A: Here is a quick python script that clicks that "Casual Dresses" button. You have to use ActionChains to hover over "Women", then identify and click "Casual Dresses":
from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
import time
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.action_chains import ActionChains

driver = webdriver.Chrome(ChromeDriverManager().install())
driver.get("http://automationpractice.com/index.php")

womenElement = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.CSS_SELECTOR, 'a[title="Women"]')))
ActionChains(driver).move_to_element(womenElement).perform()
casualDressesElement = WebDriverWait(driver, 10).until(EC.element_to_be_clickable((By.CSS_SELECTOR, 'a[title="Casual Dresses"]')))
casualDressesElement.click()
time.sleep(5)
driver.quit()


text:
Q: Update values in MYSQL with concat from another table I've been trying to update values of a field from another table's field with comma separators.
This is my current code:
update programs set registered = (select user_id from users where reg_prog != 0)

I am getting #1242 mysql error.
I would like to have a list like this: Registered users: 47, 97, 10, 618, 5 (these are the ids of the users that are registered to the program).
Any help?

A: Don't do it like this. Use a normalized data model. Having any kind of comma-separated list in a database field usually is a very bad idea. You have no way of properly working with these values, because you always need messy string manipulation to do anything with this.
If you need to record the users that registered to a program, create separate tables for users, programs and a relation table for both of them:
 _________          ______________          _________
| program |        | user2program |        | program |
+---------+        +------------  +        +---------+
| id      |  <-->  | user_id      |        | name    |
| name    |        | program_id   |  <-->  | id      |
 ---------          --------------          ---------

It takes a little more programming effort, to keep these tables filled properly, but you will see that it works much better this way.
There is no single SQL statement that can do what you are looking for in your question. If you have a proper data model, you need to first insert your program, then your user and afterwards add the releation between the two:
INSERT INTO program (id, name) VALUES (1, "My Program");
INSERT INTO user (id, name) VALUES (1, "John Doe");
INSERT INTO user2program (user_id, program_id) VALUES (1, 1);

To get all users that are registered for a program, you can then use a SELECT statement with JOINs:
SELECT p.name AS program_name, u.name AS user_name
FROM   program AS p
JOIN   user2program AS u2p ON p.id = u2p.program_id
JOIN   user AS u ON u.id = u2p.user_id
WHERE  p.id = 1 -- ID of the program


text:
Q: Why is python import not working in VS code? I have downloaded a pip package 'xlrd' to read an excel file. When I try and run the module, the program shows that I have not downloaded that pip. I have not been able to find answers as I did not know what question to ask. How can I fix this?
Message when downloading the pip:
'Requirement already satisfied: xlrd in c:\users\thecodeadd\appdata\local\programs\python\python310\lib\site-packages (2.0.1)'
What it shows in 'Problems' for the program:
[{
    "resource": "/c:/Users/thecodeadd/Documents/Stuff/Program/Programs/Python/Trialxlrd.py",
    "owner": "_generated_diagnostic_collection_name_#0",
    "code": {
        "value": "reportMissingImports",
        "target": {
            "$mid": 1,
            "external": "https://github.com/microsoft/pylance-release/blob/main/DIAGNOSTIC_SEVERITY_RULES.md#diagnostic-severity-rules",
            "path": "/microsoft/pylance-release/blob/main/DIAGNOSTIC_SEVERITY_RULES.md",
            "scheme": "https",
            "authority": "github.com",
            "fragment": "diagnostic-severity-rules"
        }
    },
    "severity": 4,
    "message": "Import \"xlrd\" could not be resolved",
    "source": "Pylance",
    "startLineNumber": 1,
    "startColumn": 8,
    "endLineNumber": 1,
    "endColumn": 12

}]

A: for xlrd python module , you need 2 libraries.

*

*pip install jinja2

*pip install xlrd

This should solve your problem


text:
Q: how to loop on a set of animations with velocity.js Hello,
I'm trying to make a string appear and disappear char by char.
First I use lettering.js which split my string in as much span element as my string length.
Second I use velocity to put some effects on them.
So for example

Rainbow

It works well and my 2 first caracters move and disappear yiha! But there is no way to loop on all of this. If you look at the doc of velocity, the only way to put several effects on something is to call as much .velocity as you want to add effects...A loop attribute exists but you can't put all of your velocity call in a row.
Does anyone has a clue of how i can do this with velocity? I actually don't want to use animate.
Thanks for your help!
Thomas

A: Ok, i just found a solution
$("#demo1 h1").lettering('words').children('span').lettering().find('span').velocity({opacity: 0}, 0);

        var titles = ['First title', 'Second title', 'Third title'];
        var titleIndex = 0;

        var transitionsIn = ["flipXIn","slideDownIn","perspectiveLeftIn"];
        var transitionsOut = ["flipXOut","slideUpOut","perspectiveRightOut"];

        function animateText() {
            var transIn = transitionsIn[Math.floor(Math.random()*transitionsIn.length)];;
            var transOut = transitionsOut[Math.floor(Math.random()*transitionsOut.length)];;
            $('#demo1 h1 span span')
                    .velocity("transition." + transIn, {stagger: 100})
                    .delay(2000)
                    .velocity("transition." + transOut, {
                        complete: function(elements) {
                            console.log(elements);
                            titleIndex++;
                            if (titleIndex > titles.length) {
                                titleIndex = 0;
                            }
                            $("#demo1 h1").hide().html(titles[titleIndex]).lettering('words').children('span').lettering().find('span').velocity({opacity: 0}, {
                                complete: function(els) {
                                    $("#demo1 h1").show();
                                    animateText();
                                }});

                        }
                    })
                    ;
        }
        animateText();

Hope it will help!


text:
Q: Conclude $\left|\sum_{n = 0}^{100} \frac{e^{-n^2/10000}}{100} -\int_{0}^{1}e^{-x^2}dx\right|\le 0.05$ Conclude $$\left|\sum_{n = 0}^{100} \frac{e^{-n^2/10000}}{100} -\int_{0}^{1}e^{-x^2}dx\right| \le 0.05$$
Ok so this is a question by parts for integrals according to the definion, meaning upper and lower sums and we are not allowed to use the fundemental theorem of calculus for definite integrals. This is the last part of the question and I need to showcase this.
I want to say that the left part (the sum) and the right part are equal and this their difference is $=0 < 0.05$ but I dont know how to explain it formally. I am not even sure its the right direction in which case I am definitely bit lost
I can say $P$ is a partition for $f(x) = e^{-x^2/10000}$ for which $x_k = 1/100$ for every $x$ in the range but I am not sure how to say that the sum which is also the lower sum is equal to the upper integral and reach that conclusion any help would be appreciated

A: Since the function $e^{-x^2}$ is decreasing on the interval $[0,1]$, a right hand Riemann sum will be smaller than the integral, which will be smaller than a left hand Riemann sum. Therefore
$$
\sum_{n=1}^{100}\frac{e^{-(n/100)^2}}{100}
\le \int_0^1 e^{-x^2}\ dx
\le \sum_{n=0}^{99} \frac{e^{(n/100)^2}}{100}
\le \sum_{n=0}^{100} \frac{e^{(n/100)^2}}{100}.
$$
For $n=0$ we have $\frac{e^{-n^2/10000}}{100}=\frac{1}{100}<.05.$
So
$$
\sum_{n=0}^{100}\frac{e^{-n^2/10000}}{100}-.05<
\sum_{n=1}^{100}\frac{e^{-n^2/10000}}{100}
\le \int_0^1 e^{-x^2}\ dx
\le \sum_{n=0}^{100} \frac{e^{n^2/10000}}{100}.
$$
Then
$$
\Bigg\lvert\sum_{n=0}^{100} \frac{e^{n^2/10000}}{100} - \int_0^1 e^{-x^2}\ dx
\Bigg \rvert<.05
$$
follows.

A: Notice that
$$D:=\Big|\sum^{100}_{k=0}\frac{e^{-(k/100)^2}}{100}-\int^1_0e^{-t^2}\,dt\Big|\leq\frac{1}{100}+\Big|\sum^{100}_{k=1}\int^{k/100}_{(k-1)/100}e^{-(k/100)^2}-e^{-t^2}\,dt\Big|$$
By the mean value theorem, for $t\in[(k-1)/100,k/100]$ there is $t<\xi_t<k/100$ such that
$$|e^{-t^2}-e^{-(k/100)^2}\big|= 2\xi e^{-\xi^2}\big|t-\tfrac{k}{100}\big|\leq \frac{2k}{100}\frac{1}{100}$$
$$\int^{k/100}_{(k-1)/100}\big|e^{-t^2}-e^{-(k/100)^2}\big|\,dt\leq\int^{k/100}_{(k-1)/100}\frac{2k}{100}\frac{1}{100}dt=\frac{k}{500000}$$
$$\frac{1}{500000}\sum^n_{k=1}k=\frac{5050}{500000}=.0101$$
Putting things together $D\leq .01+.0101=.0201<0.05$.


text:
Q: Probability of flipping four coins Flip 4 coins, when you see a head, you get \$1. What is the expected return of this game? What if you can reflip (meaning reflip all coins) as many times as you want? What if you have to pay $1 each time to reflip? What is the best strategy?
For this problem, the EV of the first flip would be 2. So if I can choose to either reflip or keep the coins I'd choose to reflip if I get 0,1,2, if not then I'd keep the coins if they are 3,4. So the expected value for the first flip is $\frac{4}{16}(3) + \frac{1}{16}(4)=1$, and then for the second flip, we flip the four coins again to get an EV of 2. Multiplied by the respective probabilities, it's $1+ (2) \frac{11}{16} = 2.375$, which is better than the original 2.
But what happens when the game continues and you can reflip as many times as you want or if I need to pay \$1? Do I keep this strategy? I would assume if the game continues, then this strategy would work as well since I have a better chance of getting more than EV of first flips. But if I need to pay \$1 then I would have to accept a lower number the first flip (since $(1)\frac{5}{16} + (2) \frac{11}{16} < 2$). So say I accept 2,3,4 the first flip, I'd get $\frac{6}{16}(2) + \frac{4}{16}(3) + \frac{1}{16}(4)=1.75$ and reflip for 0 and 1 only. So $\frac{11}{16}(1.75)+\frac{5}{16}(1)=1.515 < 2$. So I go lower and reflip only when I get 0 heads. So the first flip EV is still 2 for $\frac{15}{16}$ of times and the second flip EV is 1 after paying 1 dollar, which is also worse than if I keep the flip the first round. So I keep the first flip.
Is this solution correct? I still don't know how to account for the scenario where I get infinite flips instead of 2.

A: You want to determine the maximum value $n \in \{0,1,2,3,4\}$ so that if you flip exactly $n$ heads, you do pay the $1\$$ to re-flip.  This means that if you flip $(n+1)$ heads, you do not re-flip.
Let $E(n)$ denote your overall expected value as a function of $n$, where $n$ is as defined in the previous paragraph.  You want to find all values of $n$ such that $E(n) \geq (n+1).$
This is because if you get $n$ heads, and decide to reflip, you are paying $1\$$ and forfeiting the $n\$$, for a total expenditure of $(n+1)\$$.  You want to identify those values of $n$,where this expenditure is not greater than your expected value on a re-flip.

Consider $E(1).$
You are paying (in effect) $2\$$.
In exchange, $(5/16)$ of the time, you will be in the same position that you were in, $(6/16)$ of the time you get $2\$$, $(4/16)$ of the time you get $3\$$, and $(1/16)$ of the time you get $4\$$.
Therefore,
$$E(1) = (5/16)E(1) + (1/16)[25] \implies $$
$$(11/16)E(1) = (25/16) \implies E(1) > 2.$$
So, if you only get $1$ head, you should re-flip.

Consider $E(2).$
You are paying (in effect) $3\$$.
In exchange, $(11/16)$ of the time, you will be in the same position that you were in, $(4/16)$ of the time you get $3\$$, and $(1/16)$ of the time you get $4\$$.
Therefore,
$$E(2) = (11/16)E(2) + (1/16)[13] \implies $$
$$(5/16)E(2) = (13/16) \implies E(2) < 3.$$
So, if you only get $2$ heads, you should not re-flip.


text:
Q: Compiling opencv simple program results in conflict with windows sdk This is my first experience with opencv. I downloaded it and set the visual studio 2010 (pro) include directories like this:
C:\opencv\build\include\opencv
C:\opencv\build\include

The "inherited" values are:
$(VCInstallDir)include
$(VCInstallDir)atlmfc\include
$(WindowsSdkDir)include
$(FrameworkSDKDir)\include

But when I compile I get errors regarding the windows sdk...
1>c:\program files (x86)\microsoft sdks\windows\v7.0a\include\ws2def.h(212): error C2011: 'sockaddr' : 'struct' type redefinition
1>c:\program files (x86)\microsoft sdks\windows\v7.0a\include\winsock.h(485) : see declaration of 'sockaddr'
1>c:\program files (x86)\microsoft sdks\windows\v7.0a\include\ws2def.h(390): error C2059: syntax error : 'constant'
1>c:\program files (x86)\microsoft sdks\windows\v7.0a\include\ws2def.h(443): error C2143: syntax error : missing ';' before '}'
1>c:\program files (x86)\microsoft sdks\windows\v7.0a\include\ws2def.h(443): error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
1>c:\program files (x86)\microsoft sdks\windows\v7.0a\include\ws2def.h(443): error C4430: missing type specifier - int assumed. Note: C++ does not support default-int
1>c:\program files (x86)\microsoft sdks\windows\v7.0a\include\ws2def.h(524): warning C4005: 'IN_CLASSA' : macro redefinition
1>c:\program files (x86)\microsoft sdks\windows\v7.0a\include\winsock.h(287) : see previous definition of 'IN_CLASSA'
...

There is some conflict with the sdk include files. Does anyone know how can I fix this?
Thank you

A: Was using winsock2.h and it conflicts for some reason with opencv. changed it to winsock.h


text:
Q: Computed value not display until I click component in Vue Devtools I have problems with my computed value. If I add item to cart, the totalPrice will remain 0, until I click the component in Vue Devtools, it will display the value. However, the Item Count working normally. Why is that happening? :/
data() {
    return {
      totalPrice: 0,
    };
  },

computed: {
    calcTotal() {
        this.cart.forEach((item) => {
            this.totalPrice += item.price * item.quantity
        });
        return this.totalPrice;
    }
  }

I am using it to display the total price for whole cart.

 0">
      Item count ({{this.cart.length}})

      Net Payable
      {{ totalPrice }}

A: Do not mutate your data properties inside a computed property. It's a great way to end up in an infinite loop. They should be as close to pure functions as possible.
totalPrice should be your computed property that reduces the cart items to a number (the sum of price * quantity)
// Adjust locale and currency code accordingly
const currencyFormatter = Intl.NumberFormat("en", { style: 'currency', currency: 'USD' })

export default {
  data: () => ({
    cart: []
  }),
  filters: {
    currency: (value) => currencyFormatter.format(value)
  },
  computed: {
    totalPrice: ({ cart }) =>
      cart.reduce((total, item) => total + item.price * item.quantity, 0)
  }
}

{{ totalPrice | currency }}

See also ~ Filters


text:
Q: How to update an outputted value on an Angular template driven form page? I am trying to extend the Angular template driven form given in the tutorial at angular.io/guide/forms. I have added a select control whose values are based on the following model:

export class Power {
  constructor(
    public val: string,
    public txt: string,
  ) { }
}

When the form is completed, the output is sent to both the console and the page. I can update the values of input fields and they are immediately updated on the page (specifically, to div class="output") and in the console, but the select element does not update. I have a feeling I'm not binding to the right elements, or perhaps my overall model is incorrect. The code is included below. I'd appreciate any input; TIA!
hero-form.component.ts:

import { Component } from '@angular/core';
import { Hero } from '../_models/hero';
import { Power } from '../_models/power'

@Component({
  selector: 'app-hero-form',
  templateUrl: './hero-form.component.html',
  styleUrls: ['./hero-form.component.css']
})

export class HeroFormComponent {
  powers = [
    new Power('Strong', 'Really strong'),
    new Power('Smart', 'Really smart'),
    new Power('Hot','Really hot'),
    new Power('Cold','Really cold'),
    new Power('Weather','Weather changer'),
    new Power('Time','Time traveller'),
  ];

  model = new Hero('', this.powers[0], '');

  submitted: boolean = false;

  onSubmit: Function = () => {
    console.log(this.model);
    this.submitted = true;
  }

  constructor() { }
}

hero-form.component.html:

Hero Form

<form #HeroForm="ngForm" (ngSubmit)="onSubmit(HeroForm)">

    Name
    <input
      class="form-control"
      type="text"
      name="Name"
      id="Name"
      [(ngModel)]="model.name"
      #name="ngModel"
      required>

        Name is required!

    Alias
    <input
      class="form-control"
      type="text"
      name="Alias"
      id="Alias"
      [(ngModel)]="model.alias"
      required
      #alias="ngModel">

        Alias is required!

    Hero Power
    <select
      class="form-control"
      id="power"
      name="power"
      required
      [(ngModel)]="model.power"
      #power="ngModel">
      <option
        *ngFor="let pow of powers;"
        [ngValue]="pow.val">
        {{pow.txt}}
      </option>
    </select>

<button type="submit" [disabled]="!HeroForm.valid">Submit</button>

</form>

{{model.name}}

{{model.alias}}

    ***
    {{model.power.val}}
    ***

{{HeroForm.value | json}}

A: You need to assign the whole power object as the value of each select option. Otherwise it will just save the val string in the model.power property .
<option
    *ngFor="let pow of powers;"
    [ngValue]="pow"> // <------
    {{pow.txt}}
  </option>

Cheers


text:
Q: Difficulty Creating a Set of Variance Data I am trying to create a series of data that plots the variance in a data point. The difficulty I am having is that the statement depends not just on subtracting the previous row's data point. The data points are mixed with each other randomly.
I have a list of wells and each well has the temperature reading for each date. For a given day, there are about 100 temperature recordings, one for each well. I want the variance plot to be the data of the current day minus the previous day temperature of that specific well.
Currently I have two index columns that I use to subtract the current index from the previous. However, the mistake it makes is that the index columns don't line up correctly with the well and its date. For example, X1A on June 1 is index 0 in the first index column, but is then October 14th in index 1. The variance plot will record the temperature difference between these two dates, rather than June 2 minus June 1.
I think to fix it will require a specific setting before declaring my two index columns, but I'm not sure how to do so. Currently, the index columns are aligned just per well, so it is subtracting the wells data, just not in the correct order. Any help will be greatly appreciated. I have included a screenshot just for extra clarity.
The code for my column that calculates the temperature variance looks like this:
      TempVariation = Var Diff = 'Zone 2 Max'[Zone 2 Max Temp] -
      Calculate(SUM('Zone 2 Max'[Zone 2 Max Temp]),FILTER('Zone 2 Max','Zone
      2 Max'[Index.1] = EARLIER('Zone 2 Max'[Index]))) return
      IF(Diff=Value('Zone 2 Max'[Zone 2 Max Temp]),0,Diff)

Attached Screenshot of Table and How It Currently is Wrong
This is how I want my table to look so that I can make a graph of the change in temperature when a user selects a certain well.
| Date | Well | Temp | Change in Temp From Previous Day |
|:------|:------:|:------:|----------------------------------:|
|July 1| A1P  | 74   |               0                  |
|July 1| A2P  | 78   |               0                  |
|July 1| A3P  | 41   |               0                  |
|July 2| A1P  | 75   |               1                  |
|July 2| A1P  | 70   |              -8                  |
|July 2| A1P  | 38   |              -3                  |
|July 3| A1P  | 72   |               -3                 |
|------|------|------|----------------------------------|

A: I've found an answer to my own problem using what I currently already have created:
I sorted my wells firstly by well name ascending, then by date ascending and from there added two index columns starting at 0 and 1. The sorting of the rows corrected my previous mistake, as now the first index starts on July 1 on the first well, and it increments for the one well per day. From there, the calculation shown in the question remained the same, just subtracting the earlier value from the current to get change in temperature.


text:
Q: Define macros based on endianness of machine I want to define variables in structure based on endianness of machine , This is what I tried
#define IS_BIG_ENDIAN (!(union { uint16_t u16; unsigned char c; }){ .u16 = 1 }.c)
//#define IS_BIG_ENDIAN (!*(unsigned char *)&(uint16_t){1})
struct A {
    #if IS_BIG_ENDIAN
    char a:4;
    char b:4;
    #else
    char b:4;
    char a:4;
    #endif
}

The above code is giving error , is this possible to achieve. My Main aim is to achieve reverse order of structure variables.

A: From https://sourceforge.net/p/predef/wiki/Endianness/
You don't have standard way to have it.
but custom headers <sys/param.h> or <endian.h> might provide MACRO such as:
Type                            Macro           Value
Big endian                      __BYTE_ORDER    __BIG_ENDIAN
Little endian                   __BYTE_ORDER    __LITTLE_ENDIAN
Little endian (word-swapped)    __BYTE_ORDER    __PDP_ENDIAN

A: That test cannot work for a pre-processor if-directive.
The upcoming C++20 is proposed to have std::endian. It can be used without the pre processor.
static_assert(std::endian::native == std::endian::big
           || std::endian::native == std::endian::little);

struct ABig {
    char a:4;
    char b:4;
};

struct ALit {
    char b:4;
    char a:4;
};

using A = std::conditional_t<std::endian::native == std::endian::big, ABig, ALit>;

Prior to C++20, there is no standard way of getting the endianness.
A portable solution is to use pre-defined macros to detect the system. Some systems are little endian (Windows), while others provide a header with macro definitions (<endian.h> in Linux, <sys/endian.h> in BSD and so on) and others may be different in some other way. The GCC compiler provides macros:
__BYTE_ORDER__
__ORDER_LITTLE_ENDIAN__
__ORDER_BIG_ENDIAN__
__ORDER_PDP_ENDIAN__

That said, pretty much every aspect of the representation of bit fields is implementation defined, and if it is important for the order to be exact - as it appears to be - then you're going to have to rely on particular implementation anyway, so portability is not achievable. Decide your target system and once you've decided, consult the documentation of that system for how to get the endianness.
It's best to not rely on the representation of bit fields.

A: Wait until C++20 (or use experimental features of your compiler) and you will be able to use C++ standard std::endian for this:

Indicates the endianness of all scalar types:
If all scalar types are little-endian, std::endian::native equals
  std::endian::little If all scalar types are big-endian,
  std::endian::native equals std::endian::big

A: Thanks @Jarod42 , following code is working for me
#define IS_BIG_ENDIAN (__BYTE_ORDER__ == __BIG_ENDIAN)
struct A {
    #if IS_BIG_ENDIAN
    char a:4;
    char b:4;
    #else
    char b:4;
    char a:4;
    #endif
};


text:
Q: GCC can't find headers on Windows I'm new in winAPI and I was learning how code programs with some special functions and such, so I downloaded the Windows's SDK.
Problem is, GCC decided to put the blind glasses and say:
Documents_path.c:6:25: fatal error: KnownFolders.h: No such file or directory
#include<KnownFolders.h>
                        ^
compilation terminated.

I said "OK, next one then" and there's another header with the same problem:
thread.c:3:30: fatal error: processthreadsapi.h: No such file or directory
#include<processthreadsapi.h>
                             ^
compilation terminated.

I checked if these headers are even in my PC and here they are setting with windows.h, which it was working when I tried basic functions with it.
I searched an answer for this problem but didn't find any, either it was a external\binary libraries problem, is it local or not or a macro fix (which it didn't work).
How can I fix the problem?
EDIT:
I'm using VS Code
EDIT2:
This is the code of "Documents_path.c" example:
#include<stdio.h>
#include<stdlib.h>
#include<Windows.h>
#include<ShlObj.h>
#include<initguid.h>
#include<KnownFolders.h>
#pragma comment(lib, "user32.lib")
int main(){
    int a;
    PWSTR path = NULL;
    HRESULT hr = SHGetKnownFolderPath(&FOLDERID_Documents, 0, NULL, &path);
    if(SUCCEEDED(hr)){
        printf("path for Documents is: %ls", path);
    }
    scanf("%d",&a);
    CoTaskMemFree(path);
    return 0;
}

And I'm reading the basics of winAPI from this website:
https://zetcode.com/gui/winapi/
as for structure of project folder:
C:\Users\ %USER%\Documents\C\dawd

A: MSVC uses Windows SDK while GCC does not.
On Windows GCC uses MinGW or MinGW-w64 as standard library, which is an open source implementation of Windows API.
So GCC+MinGW will use its own headers and will not look for any Windows SDK. So GCC+MinGW on Windows works without having any Microsoft developer tools installed at all.
MinGW-w64 - which is more recent than MinGW and which supports both Windows 32-bit and 64-bit - exists in a standalone package that can be downloaded from https://winlibs.com/. But you can still use it from an IDE like VSCode or Code::Blocks.
MinGW-w64 has the files like knownfolders.h and processthreadsapi.h which you had issues with.
But be aware that #pragma comment(lib, "user32.lib") is MSVC-specific and will not work in other compilers like GCC. Instead you must use linker flag -luser32. Because you call CoTaskMemFree() you will also need to add -lole32.
I tried your code on my system and it compiles and links fine with:
gcc -c -o Documents_path.o Documents_path.c
gcc -o Documents_path.exe Documents_path.o -luser32 -lole32


text:
Q: How to pass mapped array to PageMethods? I've been trying to pass a data array to c# web method with using jquery. I have a table which has selectable rows. And my function must pass the id's of selected data. But i can't pass the object array with PageMethods.
Here is my jquery function;
function DeleteQuestions()
    {
        var table = $('#questTable').DataTable();
        var data = (table.rows('.selected').data()).map(function (d) { return d.q_id; });
        PageMethods.Delete(data);
    }

When i debug it with firebug, veriable data looks like : Object["543","544","546"] as i wanted.
And here is my Web Method:
[WebMethod]
    public static void Delete(List<string> questId)
    {
        DB_UserControl carrier = new DB_UserControl(); //break pointed here
    }//and looks it doesn't come here

It doesn't work, and the error is : Cannot serialize object with cyclic reference within child properties. I've searced for error but i couldn't figured it out. So need some help. Thanks in advance.
Note:Error throws at script function's last line: PageMethods.Delete(data);
And i think it might be about mapped data causes some kind of loop behavior.

A: Problem solved with changing syntax. I use
var data = $.map(table.rows('.selected').data(), function (d) {
            return d.q_id;
        });

instead of given line. I don't know what caused the error but this code works fine and i get data in c#. Thank you all


text:
Q: Unknown Exception with Code: 13 I have created a new project, then went to VM Instances. It says "enabling compute engine". After some time, it throws the following error:
Unknown Exception with Code: 13.

Why am I receiving this error? Do I have to set up permissions or anything else?

A: In some cases that error occurs because your project doesn't have a billing account assigned. You can check if this is your problem in the left menu Billing ->  Manage Billing Accounts from drop down box.


text:
Q: Dequeue an array in perl with thread::queue I am trying to process data with a set of threads and enqueue it with another, currently the enqueueing and dequeueing process doesn't seem to be working
Any thoughs??
sub process() {
    while (my @DataElement = $DataQueue->dequeue()) {
        print "\t".$DataElement[0]."\n";
    }
}

I use the following to enqueue the data

my @l;
push(@l, $directories.$suffix);
push(@l, "testclass");
push(@l, $eachFile);
$DataQueue->enqueue(\@l);

A: Are you accessing an array reference without dereferencing it? Try
while (my $DataElementRef = $DataQueue->dequeue()) {
    my @DataElement = @$DataElementRef;
    print "\t".$DataElement[0]."\n";
}

A: @l is not shared, so you can't pass it's reference to another thread. Use threads::shared.


text:
Q: Why Apache Spark ML on Dataproc Trains Only on Single Node? I'm new to distributed ML and currently doing my personal project
I train my model using PySpark on Cloud Dataproc and build the pipeline like the code below
spark = SparkSession.builder.appName('sparkify-train').getOrCreate()
df = spark.read.parquet(path)

gbt = GBTClassifier()

paramGrid = ParamGridBuilder() \
    .addGrid(gbt.maxDepth, [4,8,12]) \
    .addGrid(gbt.maxIter, [5,10,15]) \
    .addGrid(gbt.featuresCol, ["features_1", "features_2"]) \
    .build()

tvs = TrainValidationSplit(estimator=gbt,
                           estimatorParamMaps=paramGrid,
                           evaluator=BinaryClassificationEvaluator(),
                           trainRatio=0.75)
tvs.fit(df)

Note: I don't show feature extraction and other stuff on the code above
But on CPU utilization chart, the master node is the only busy node instead of three workers node

I create Dataproc cluster using cloud shell with command below. This command is generated from Dataproc create cluster UI.
gcloud beta dataproc clusters create sparkify --enable-component-gateway --region asia-southeast2 --subnet default --zone asia-southeast2-c
--master-machine-type custom-1-3840 --master-boot-disk-type pd-ssd --master-boot-disk-size 50 --num-workers 3 --worker-machine-type custom-1-3840 --worker-boot-disk-type pd-ss
d --worker-boot-disk-size 30 --image-version 2.0-ubuntu18 --optional-components JUPYTER,ZEPPELIN --project wskt-trek

and this is the cluster properties from command above:

I just wondering is there anything wrong in my code? Or are there any settings I miss? I thought all of the workers CPU should have high utilization. Thanks!

A: The cluster is well configured , in your case you are using  a notebbok , a client mode is established in this case, I advice you either:

*

*You create a spark cluster with more than one master (2 masters and 3 workers for examle ) which is not a good practice (you will understant in the 3 rd point why ).

*You can use spark-tensorflow-distributor which is an open-source native package in TensorFlow that helps users do distributed training with TensorFlow on their Spark clusters. It is built on top of tensorflow.distribute.Strategy, which is one of the major features in TensorFlow 2. For detailed API documentation, see docstrings. For general documentation about distributed TensorFlow, see Distributed training with TensorFlow.

*The most import point is this: don't limit your vision in this level , I mean at the level of  working with notebook and see the behavior of spark cluster, why ? Well after  trainning your model you need to save it as a pmml file then  deploy it , spark will work fine. You can refer to this simple example  and try to deploy your model and compare spark cluster behavior in Dataproc to the previous one when using notebbok client mode.


text:
Q: LD_LIBRARY_PATH not working One of my binaries requires libfoo.so (which resides in /dir/libfoo) and I can't figure out how to link against it by setting an environment variable. I tried the two following solutions:
export LD_FLAG='-L/dir/libfoo/'
export LD_LIBRARY_PATH='-L/dir/libfoo/'
but when I run ldd ./mybin I see libfoo.so.0 => not found among other libs that are found.
I can, however, successfully link when I use this: /lib/ld-linux.so.2 --library-path /dir/libfoo ./mybin
I'm running Ubuntu 13.10 server x86
What am I doing wrong here?

A: -L is a gcc flag, and gcc is not involved in this process. Just do
export LD_LIBRARY_PATH='/dir/libfoo/'

A: You have passed -L flag to LD_LIBRARY_PATH this is wrong instead remove -L from LD_LIBRARY_PATH
export LD_LIBRARY_PATH=/dir/libfoo/

Also refer http://man7.org/linux/man-pages/man8/ld.so.8.html for linker/loader specification


text:
Q: pandas - how to create multiple columns in groupby with conditional? I need to group a dataframe, but I need to create two columns, one that is a simple count and another that is a count with conditional, as in the example:

The qtd_ok column counts only those that have 'OK'

I tried this, but I do not know how to add the total count in the same groupby:
df.groupby(['column1', 'column2', 'column3']).apply(lambda x : x['status'].sum() == 'OK')

A: First create helper column A with assign and then aggregate by agg functions sum for count only OK values and size for count all values per groups:
df = (df.assign(A=(df['status']== 'OK'))
        .groupby(['column1', 'column2', 'column3'])['A']
        .agg([('qtd_ok','sum'),('qtd','size')])
        .astype(int)
        .reset_index())

Sample:
df = pd.DataFrame({
        'column1':['a'] * 9,
        'column2':['a'] * 4 + ['b'] * 5,
        'column3':list('aaabaabbb'),
        'status':list('aabaaabba'),
})

print (df)
  column1 column2 column3 status
0       a       a       a      a
1       a       a       a      a
2       a       a       a      b
3       a       a       b      a
4       a       b       a      a
5       a       b       a      a
6       a       b       b      b
7       a       b       b      b
8       a       b       b      a

df = (df.assign(A=(df['status']== 'a'))
        .groupby(['column1', 'column2', 'column3'])['A']
        .agg([('qtd_ok','sum'),('qtd','size')])
        .astype(int)
        .reset_index())
print (df)
  column1 column2 column3  qtd_ok  qtd
0       a       a       a       2    3
1       a       a       b       1    1
2       a       b       a       2    2
3       a       b       b       1    3

A: Just an idea to count with groupby with lambda  which can further be enhanced ..
>>> df
  colum1    colum2    colum3 status
0  unit1  section1  content1     OK
1  unit1  section1  content1     OK
2  unit1  section1  content1  error
3  unit1  section1  content2     OK
4  unit1  section2  content1     OK
5  unit1  section2  content1     OK
6  unit1  section2  content2  error
7  unit1  section2  content2  error
8  unit1  section2  content2     OK

using groupby with lambda..
 >>> df.groupby(['colum1','colum2', 'colum3'])['status'].apply(lambda x: x[x.str.contains('OK', case=False)].count()).reset_index()
  colum1    colum2    colum3  status
0  unit1  section1  content1       2
1  unit1  section1  content2       1
2  unit1  section2  content1       2
3  unit1  section2  content2       1

Also can use case=False for ignorecase for ok.

A: pd.crosstab
You can use pd.crosstab with margins=True:
# data from @jezrael

list_of_lists = df.iloc[:, :-1].values.T.tolist()
condition = df['status'].eq('a')

res = pd.crosstab(list_of_lists, condition, margins=True)\
        .drop('All', level=0).reset_index()

print(res)

status column1 column2 column3  False  True  All
0            a       a       a      1     2    3
1            a       a       b      0     1    1
2            a       b       a      0     2    2
3            a       b       b      2     1    3


text:
Q: What should we do with comments posted as answers by low-rep users?
Possible Duplicate:
Comments incorrectly submitted as an answer instead: what should we do?
What to do about low-rep users requesting more information in answers?
What to do with self-aware rule breaking posts?

What should we do when users who haven't earned the privilege of leaving comments post comment-level content as answers? Should we flag as "not an answer" and let the mods clean things up?
In particular, the cases that interest me are when the users know that they don't have the ability to leave a comment and say "I can't post a comment yet but..." in their "comment-answer".
Should we up-vote to get the posters closer to being able to leave real comments?
My gut says to just flag as NAA, but I am curious about what others think.

Note to the delete voter(s): Since I did't find the other 3 questions linked as duplicates with what I searched on, leaving this undeleted may serve as a useful signpost for future users.

A: I think that the best thing you can do is just flag them as "not an answer".
Why would somebody want to upvote them ? That makes no sense. I know it does get to the top of answers, but I do not think that affects something


text:
Q: How to react on failed transaction (Django) How to react on failed Django transaction? For example return some kind of error page or reload the page etc.
There is with transaction.atomic() in the code so in case that user has been saved but the problem occured during saving userprofile, everything will be rolled back.
But how to detect and react on situations, when transaction failed so it was rolled back?
if request.method == 'POST':
        if register_as_translator_form.is_valid():
            cleaned = register_as_translator_form.cleaned_data

            with transaction.atomic():
                request.user.first_name = cleaned['first_name']
                request.user.last_name = cleaned['last_name']
                request.user.userprofile.IBAN = cleaned['IBAN']
                languages = cleaned['languages']
                language_levels = get_or_create_unknown_language_levels(languages)
                request.user.userprofile.language_levels.add(*language_levels)
                request.user.save()
                request.user.userprofile.is_translator = True
                request.user.userprofile.save()

            return HttpResponseRedirect('/register-translator-success')

A: You can catch the exception (except-try) and return an error message/page.
   try:
        with transaction.atomic():
            request.user.first_name = cleaned['first_name']
            request.user.last_name = cleaned['last_name']
            request.user.userprofile.IBAN = cleaned['IBAN']
            languages = cleaned['languages']
            language_levels = get_or_create_unknown_language_levels(languages)
            request.user.userprofile.language_levels.add(*language_levels)
            request.user.save()
            request.user.userprofile.is_translator = True
            request.user.userprofile.save()

        return HttpResponseRedirect('/register-translator-success')
    except:
        return HttpResponseRedirect('/register-translator-failure')


text:
Q: T4 template multiple outputs I want to use another t4 template to give input instead of this.WriteLine("Hello, World!"); .Is that possible?
 <#@ template language="C#" hostspecific="True" debug="True" #>

<#@ output extension="txt" #>
<#@ include file="T4Toolbox.tt" #>

Sample Content

<#    for(int i=7;i<9;i++){

        SampleTemplate template = new SampleTemplate();
        template.Output.File = @"SubFolder\SampleOutput"+i+".txt";
        template.Output.Project = @"..\ClassLibrary2\ClassLibrary2.csproj";
        template.Render();
    }
#>

<#+
    public class SampleTemplate : Template
    {
        public override string TransformText()
        {
            this.WriteLine("Hello, World!");

            return this.GenerationEnvironment.ToString();
        }
    }
#>

A: Make a T4 function that redirects the current template output to a file you specify - save this as SaveOutput.tt:
<#@ template debug="false" hostspecific="true" language="C#" #>
<#@ import namespace="System.IO" #>
<#

void SaveOutput(string outputFileName)
{
  string templateDirectory = Path.GetDirectoryName(Host.TemplateFile);
  string outputFilePath = Path.Combine(templateDirectory, outputFileName);
  File.WriteAllText(outputFilePath, this.GenerationEnvironment.ToString());
  this.GenerationEnvironment.Remove(0, this.GenerationEnvironment.Length);
}

#>

And when generating your output code, call the function:
<#@ include file="SaveOutput.tt" #>
<#
    GenerateFile1();
    SaveOutput("File1.txt");

    GenerateFile2();
    SaveOutput("File2.txt");
#>
<#
    void GenerateFile1()
    {
#>
This is file 1
<#
    }

    void GenerateFile2()
    {
#>
This is file 2
<#+
    }
#>

Note: I took this code from Oleg Sych's blog as he posted a now-dead link to his blog showing the steps required as an answer to this question. Since SO doesn't like link only answers, I re-posted the relevant code from that blogpost. You can find a copy of his blogpost on the wayback machine here. The only difference is that I have removed the '+' characters after each T4 code block starts - they don't appear to be necessary.


text:
Q: meteor js how to write a file to local disk from the server? I want to know how to save file in local disk? Like i want to save file in c: drive using meteor. Help me to achieve this.
Thanks in advance.

A: You can pass the data on the server methods than use file system you can write the file to a local disk.
Client side code :
Template code:
<template name="example">
    <input type=file />
</template>

Template event code:
Template.example.events({
  'change input': function(ev) {
    _.each(ev.srcElement.files, function(file) {
      Meteor.saveFile(file, file.name);
    });
  }
});

Meteor.saveFile function code:
/**
 * @blob (https://developer.mozilla.org/en-US/docs/DOM/Blob)
 * @name the file's name
 * @type the file's type: binary, text (https://developer.mozilla.org/en-US/docs/DOM/FileReader#Methods)
 *
 * TODO Support other encodings: https://developer.mozilla.org/en-US/docs/DOM/FileReader#Methods
 * ArrayBuffer / DataURL (base64)
 */
Meteor.saveFile = function(blob, name, path, type, callback) {
  var fileReader = new FileReader(),
    method, encoding = 'binary', type = type || 'binary';
  switch (type) {
    case 'text':
      // TODO Is this needed? If we're uploading content from file, yes, but if it's from an input/textarea I think not...
      method = 'readAsText';
      encoding = 'utf8';
      break;
    case 'binary':
      method = 'readAsBinaryString';
      encoding = 'binary';
      break;
    default:
      method = 'readAsBinaryString';
      encoding = 'binary';
      break;
  }
  fileReader.onload = function(file) {
    Meteor.call('saveFile', file.srcElement.result, name, path, encoding, callback);
  }
  fileReader[method](blob);
}

Server side code :
/**
 * TODO support other encodings:
 * http://stackoverflow.com/questions/7329128/how-to-write-binary-data-to-a-file-using-node-js
 */
Meteor.methods({
  saveFile: function(blob, name, path, encoding) {
    var path = cleanPath(path), fs = __meteor_bootstrap__.require('fs'),
      name = cleanName(name || 'file'), encoding = encoding || 'binary',
      chroot = Meteor.chroot || 'public';
    // Clean up the path. Remove any initial and final '/' -we prefix them-,
    // any sort of attempt to go to the parent directory '..' and any empty directories in
    // between '/////' - which may happen after removing '..'
    path = chroot + (path ? '/' + path + '/' : '/');

    // TODO Add file existance checks, etc...
    fs.writeFile(path + name, blob, encoding, function(err) {
      if (err) {
        throw (new Meteor.Error(500, 'Failed to save file.', err));
      } else {
        console.log('The file ' + name + ' (' + encoding + ') was saved to ' + path);
      }
    });

    function cleanPath(str) {
      if (str) {
        return str.replace(/\.\./g,'').replace(/\/+/g,'').
          replace(/^\/+/,'').replace(/\/+$/,'');
      }
    }
    function cleanName(str) {
      return str.replace(/\.\./g,'').replace(/\//g,'');
    }
  }
});


text:
Q: Why is my AutoCompleteTextView not working? This feels strange as normally the widgets work as they are supposed to. I have an AutoCompleteTextView that I want to populate with a list of city names. It seems simple but doesn't work as I intend to. Here is the resulting output:

Here is the layout in picture:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity1">

    <AutoCompleteTextView
        android:id="@+id/autocomptv_city_list"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginStart="20dp"
        android:layout_marginLeft="20dp"
        android:layout_marginTop="12dp"
        android:layout_marginEnd="20dp"
        android:layout_marginRight="20dp"
        android:background="@drawable/bg_edittext_rect_opd"
        android:hint="Select City"
        android:text=""
        android:inputType="text"
        android:maxLines="1"
        android:completionThreshold="0"
        android:padding="10dp"
        android:singleLine="true"
        android:textColor="#000000"
        android:textSize="15sp"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</android.support.constraint.ConstraintLayout>

And below is the java code for the same:
public class MainActivity1 extends AppCompatActivity {

    AutoCompleteTextView mAutCompleteTextViewSelfCity;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main1);

        mAutCompleteTextViewSelfCity = ((AutoCompleteTextView) findViewById(R.id.autocomptv_city_list));

        setupCityDropdownwidget();
    }

    private void setupCityDropdownwidget() {
        Type listType = new TypeToken<List<CityName>>() {}.getType();
        List<CityName> citiesList = Singletons.getGsonInstance().fromJson(TestData.cityDataJson, listType);

        CityArrayAdapter adapter = new CityArrayAdapter(this, R.layout.item_spinner_city, citiesList);
        mAutCompleteTextViewSelfCity.setAdapter(adapter);
        adapter.notifyDataSetChanged();

        mAutCompleteTextViewSelfCity.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                CityName selectedCitySelf = ((CityName) parent.getItemAtPosition(position));
                mAutCompleteTextViewSelfCity.setText(selectedCitySelf.getCityName());
            }
        });
    }
}

Problem:
Well, I want the view to be such that as soon as the user taps on it, it shows a dropdown of cities and when the user starts typing their city for filtering, the view keeps showing narrowed down suggestions for the same.
Currently, the only time it is able to suggest is when I type in something and empty out the text view. If I change the completion threshold to 1, no suggestions are shown ever.
What's wrong with my code?
Here is the complete source for reference: https://wetransfer.com/downloads/ce4017f5f2488288ef7494dc029e033420191019092536/7afa9a3e64afb257293533bd634d6c3220191019092536/dc2341

A: So ultimately, it turned out to be about the basics - The data item that ArrayAdapter works with, should provide a meaningful toString() override. That is what had been missing from my implementation.
From the docs:

By default, the array adapter creates a view by calling
  Object#toString() on each data object in the collection you provide,
  and places the result in a TextView.

I did end up wasting up some time but the experience and knowledge would surely come in handy some day.

A: YOu don't need to set adapter.notifyDataSetChanged();, just set your adapter and everything goes fine.


text:
Q: Where is the network in memory networks? The paper Weston, Jason, Sumit Chopra, and Antoine Bordes. "Memory networks." arXiv preprint arXiv:1410.3916 (2014). introduces memory networks.
The given definition is as follows:

Where is the network? I can see that one might use a (artificial neural) network in I, G, O, or R, but it does not sounds like a necessity.

A: I think the authors concede to that as well. Quoting them,

One particular instantiation of a memory network is where the components are neural networks.

Memory Networks are essentially some kind of a lookup table if you will. But for Memory Networks to work well, it is crucial that there is some kind of a generalization across different memory cells. In this work, that generalization is achieved by using Vector Embeddings, which is technically one layer of a neural network. The following are the Artificial Neural Network (ANN) components that can be used in tandem with the 4 main functions that they define.

*

*$I:$ (Input feature map) - This component can use any sort of input embedding. Word2vec vectors of the words could be one example. You could alternatively use a matrix $U$ which maps the bag of words representation to a more dense representation. In this work, they just use the bag of words representation as the input and leave the embedding part to the other modules, as will be clear in a moment.

*$G:$ (Generalization) - This component is responsible for reflecting changes in the memory, given a new input. If each input has it's own slot, it does not lead to much generalization. The Hashing function mentioned in section 3.3 is not a generalization because it is just a trick to ensure less computation. Whenever generalization is required, there should be lesser parameters (degrees of freedom) than the number of instances. Updating other memory cells based on current input may lead to generalization and may involve Neural Networks in terms of Forget and Input gates used in LSTMs.

*$O:$ (Output feature map) - As is clear from the work, weight matrices are used for linear transformations and these are essentially single layer neural networks.

*$R:$ (response) - After choosing which memory cells to base the answer on, an RNN (or LSTM) is used to generate natural language answers.

I agree with the OP that all these components can be used without Neural Networks as well. But these single layer NNs used throughout can be used as a justification. There should be further work in improving the generalization ($G$) and I think there is scope for using ANNs there as well.


text:
Q: How to prevent ARKit app to place object if I click on the button (How to detect if I click on UI element)? How can I prevent ARKit app (initially made in Unity) from placing an object on the surface when I'm clicking on the UI button on the screen?
The solution from this tutorial doesn't work:
if ((touch.phase == TouchPhase.Began || touch.phase == TouchPhase.Moved) && !EventSystem.current.IsPointerOverGameObject(0))

Is there any other way to detect if I'm clicking on the UI element for IOS?
Here is the full code for placing objects using ARKit:
using System;
using System.Collections.Generic;
using UnityEngine.EventSystems;

namespace UnityEngine.XR.iOS
{
    public class UnityARHitTestExample : MonoBehaviour
    {
        public Transform m_HitTransform;

        bool HitTestWithResultType (ARPoint point, ARHitTestResultType resultTypes)
        {
            List<ARHitTestResult> hitResults = UnityARSessionNativeInterface.GetARSessionNativeInterface ().HitTest (point, resultTypes);
            if (hitResults.Count > 0) {
                foreach (var hitResult in hitResults) {
                    Debug.Log ("Got hit!");
                    m_HitTransform.position = UnityARMatrixOps.GetPosition (hitResult.worldTransform);
                    m_HitTransform.rotation = UnityARMatrixOps.GetRotation (hitResult.worldTransform);
                    Debug.Log (string.Format ("x:{0:0.######} y:{1:0.######} z:{2:0.######}", m_HitTransform.position.x, m_HitTransform.position.y, m_HitTransform.position.z));
                    return true;
                }
            }
            return false;
        }

        // Update is called once per frame
        void Update () {
            if (Input.touchCount > 0 && m_HitTransform != null)
            {
                var touch = Input.GetTouch(0);
                if ((touch.phase == TouchPhase.Began || touch.phase == TouchPhase.Moved) && !EventSystem.current.IsPointerOverGameObject(0))
                {
                    transform.localPosition = Vector3.zero;
                    var screenPosition = Camera.main.ScreenToViewportPoint(touch.position);
                    ARPoint point = new ARPoint {
                        x = screenPosition.x,
                        y = screenPosition.y
                    };

                    // prioritize reults types
                    ARHitTestResultType[] resultTypes = {
                        ARHitTestResultType.ARHitTestResultTypeExistingPlaneUsingExtent,
                        // if you want to use infinite planes use this:
                        //ARHitTestResultType.ARHitTestResultTypeExistingPlane,
                        ARHitTestResultType.ARHitTestResultTypeHorizontalPlane,
                        ARHitTestResultType.ARHitTestResultTypeFeaturePoint
                    };

                    foreach (ARHitTestResultType resultType in resultTypes)
                    {
                        if (HitTestWithResultType (point, resultType))
                        {
                            return;
                        }
                    }
                }

                if (noShoesPlaced) {
                    UIController.GetComponent<ShoeUIController2>().showShoe1
                    noShoesPlaced = false;
                }
            }

            //if (placeFirstTime) {
            //  UIController.GetComponent<ShoeUIController> ().firstTimePlace = true;
            //  placeFirstTime = false;
        //  }

        }

    }
}


text:
Q: python Regex- get match based on condition I have the below text string
text = "\n1.2.2. ROAD LOAD PARAMETERS \nf0 \n227.4 \nf1 (N/(km/h)) \n0.149"

I am trying to write a regex match pattern to get values (consecutive 2 values) that follows '1.2.2. ROAD LOAD PARAMETERS'.
Expected output:
1.2.2. ROAD LOAD PARAMETERS : f0 227.4 # (only 2 values after the match)

Tried the below regex:
ec = re.search(r'(1.2.2. ROAD LOAD PARAMETERS)\s*(.+)', text)

ec.groups()

which gives me the following
('1.2.2. ROAD LOAD PARAMETERS', 'f0 ')

A: If the 1.2.2. ROAD LOAD PARAMETERS is always fixed you can use this:
ec = re.search(r'(1.2.2. ROAD LOAD PARAMETERS)\s+(\w+)\s+([\w\.]+)', text)

I replaced the .+ with \w+ in the first case to prevent matching the space, and also used [\w\.]+ in the second case because you have alphanumerical plus a ..

A: You can use the str.split() method:
import re

text = "\n1.2.2. ROAD LOAD PARAMETERS \nf0 \n227.4 \nf1 (N/(km/h)) \n0.149"

i = "1.2.2. ROAD LOAD PARAMETERS"

val1, val2 = text[text.index(i) + len(i):].split()[:2]
print(i, ":", val1, val2)

Output:
1.2.2. ROAD LOAD PARAMETERS : f0 227.4

A: You need two of the \s*(.+) if you want to match two numbers.
Using
ec = re.search(r'(1.2.2. ROAD LOAD PARAMETERS)\s*(.+)\s*(.)', text)

gives you
('1.2.2. ROAD LOAD PARAMETERS', 'f0 ', '227.4 ')

A: You can use
import re
text="\n1.2.2. ROAD LOAD PARAMETERS \nf0 \n227.4 \nf1 (N/(km/h)) \n0.149"
m = re.search(r'\b(1\.2\.2\. ROAD LOAD PARAMETERS).*((?:\n.*){2})', text)
d = {}
if m:
    d[m.group(1).strip()] = m.group(2).replace('\n', '').strip()

print(d)
## => {'1.2.2. ROAD LOAD PARAMETERS': 'f0 227.4'}

See the Python demo.
The \b(1\.2\.2\. ROAD LOAD PARAMETERS).*((?:\n.*){2}) regex matches

*

*\b - a word boundary

*(1\.2\.2\. ROAD LOAD PARAMETERS) - Group 1: a fixed string

*.* - any zero or more chars other than line break chars as many as possible

*((?:\n.*){2}) - Group 2: two occurrences of a line feed char followed with any zero or more chars (two lines after the line containing 1.2.2. ROAD LOAD PARAMETERS).

When building the dictionary you need to remove all line feeds from Group 2.


text:
Q: Unable to switch to GNOME on Ubuntu Budgie 18.04 I'm using Ubuntu 18.04 with Budgie preinstalled (default for Tuxedo computers), and I'm trying to use GNOME desktop environment.
I installed ubuntu-desktop meta-package using
sudo apt install ubuntu-desktop

but even after restarting I can't see the gear icon to switch desktop.
After the first restart, I got some "GNOME welcoming message" (asking for keyboard setup and online accounts) and I suppose I have more gnome-applications than before, but that's all.
I have the GNOME 'settings' application, but I suppose it's also the default one for Budgie. In the 'about' section it mentions GNOME version : 3.28.2
I had to install GNOME on my last Tuxedo too, but I can't remember what I did differently.


text:
Q: HTTP Components encoding problem When using HTTP Components (java library for http) the response I get has ' displayed as Æ and - displayed as ȗ.

A: Ok, so basically you are getting a response without Content-Type from a server you are not in control of, and you're having encoding issues.
In java every string is internally handled as Unicode strings, despite the format they come in.
So I'm guessing your problem is where you are displaying this characters, either to the console or to a file.
The console will use the default charset to print the chars there. In my machine for example is MacRoman, not utf-8.
So what you need is to get the raw bytes from the response and do something like this:
System.out.println(new String(raw_byte_array, "utf-8"));

Also, this might shed some light in the matter:
http://download.oracle.com/javase/tutorial/i18n/text/string.html

A: With the latest version 4.x, you would use something like below to be Charset agnostic -
HttpEntity entity = response.getEntity();
Charset charset = ContentType.getOrDefault(entity).getCharset();


text:
Q: It Happened That, As It Happened Is there a difference here:

*

*It happened that he did not go to work today.

*As it happened, he did not go to work today.

Do "it happened that" and "as it happened" have different meanings?

A: Yes, they (can) have different meanings, depending on context.
As it happened, or as it happens, normally describes a single occurrence of a situation.

We always went to the candy store after school, but as it happened, that fateful day, the store was closed.

It happened or it happens can be used to describe something that occurs more than once. It is maybe not the most common thing, but it does occur from time to time.

We always went to the candy store after school, but it happened that the store would be closed. Then we would sit at the coffee shop next door.

A: Maulik and user3169 have sketched the difference.

*

*It happened that introduces a new event to a narrative, usually one that turns the narrative in a new direction and launches a new phase of the action.

*As it happened reports an event whose occurrence was previously in doubt or not expected, often in contrast to what was expected.
As it happened may also be an ordinary temporal clause, introducing an account of what was happening at the same time as 'it'.


text:
Q: NullPointerException in AsyncTask OnPostExecute with google maps When debugging I get this
After the line 'httpURLConnection.connect();' my code goes to the catch block and gives me this output:
output catch
part 2
I know there are several post on this topic but I don't seem to find a solution to it.  I don't understand why I am getting this error. I know that I most likely get a null object from my 'doInbackground()' method but I don't get why. Can someone help me understand this so I know how to fix it. Thank you !
My code :
    private  class PlaceRequest extends AsyncTask<String, Integer, JSONArray> {

        @Override
        protected JSONArray doInBackground(String... params) {
            try {
                URL url=new URL(params[0]);

                HttpURLConnection httpURLConnection=(HttpURLConnection) url.openConnection();
                httpURLConnection.setRequestMethod("GET");
                httpURLConnection.connect();

                String line;
                StringBuilder stringBuilder = new StringBuilder("");
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(httpURLConnection.getInputStream()));
                while ((line = bufferedReader.readLine()) != null) {
                    stringBuilder.append(line);
                }
                JSONObject jsonObject=new JSONObject(stringBuilder.toString());
                if (jsonObject.has("next_page_token")) {
                    nextPageToken =jsonObject.getString("next_page_token");
                } else {
                    nextPageToken="";
                }
                return jsonObject.getJSONArray("results");
            } catch (Exception e) {
                e.printStackTrace();
            }
            return new JSONArray();
        }

        @Override
        protected void onPostExecute(JSONArray jsonArray) {
            progressBar.setVisibility(View.GONE);
            requestCount++;
            try {
                for (int i = 0; i < jsonArray.length(); i++) {
                    JSONObject jsonObject = jsonArray.getJSONObject(i);
                    JSONObject location = jsonObject.getJSONObject("geometry").getJSONObject("location");

                    String placeId = jsonObject.getString("place_id");
                    String name = jsonObject.getString("name");
                    LatLng latLng = new LatLng(location.getDouble("lat"), location.getDouble("lng"));

                    GooglePlace googlePlace = new GooglePlace(name, placeId, latLng);
                    listPlaces.add(googlePlace);
                    MarkClusterItem markerClusterItem = new MarkClusterItem(latLng, name);
                    clusterManager.addItem(markerClusterItem);
                }
                clusterManager.cluster();
            } catch (Exception e) {
                e.printStackTrace();
            }

            if (requestCount < REQUEST_LIMIT && !nextPageToken.equals("")) {
                progressBar.setVisibility(View.VISIBLE);
                String url=PLACES_REQUEST+"&pagetoken="+nextPageToken;
                new Handler().postDelayed(() -> new PlaceRequest().execute(url), 2000);
            }
        }
    }

}

the error:
2018-12-09 23:59:51.168 13210-13210/com.example.flow E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.flow, PID: 13210
    java.lang.NullPointerException: Attempt to invoke virtual method 'boolean java.lang.String.equals(java.lang.Object)' on a null object reference
        at com.example.flow.displayClasses.WebscrapingScreens.GoogleMapsFragment$PlaceRequest.onPostExecute(GoogleMapsFragment.java:271)
        at com.example.flow.displayClasses.WebscrapingScreens.GoogleMapsFragment$PlaceRequest.onPostExecute(GoogleMapsFragment.java:218)
        at android.os.AsyncTask.finish(AsyncTask.java:695)
        at android.os.AsyncTask.access$600(AsyncTask.java:180)
        at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:712)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:193)
        at android.app.ActivityThread.main(ActivityThread.java:6669)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:493)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
2018-12-09 23:59:51.204 1867-1881/? E/memtrack: Couldn't load memtrack module
2018-12-09 23:59:51.329 1867-1935/? E/InputDispatcher: channel '7cc9433 com.example.flow/com.example.flow.displayClasses.LoginScreens.Login (server)' ~ Channel is unrecoverably broken and will be disposed!
2018-12-09 23:59:51.329 1867-1935/? E/InputDispatcher: channel 'a9e800c com.example.flow/com.example.flow.Home (server)' ~ Channel is unrecoverably broken and will be disposed!
2018-12-09 23:59:52.005 1711-2262/? E/SurfaceFlinger: ro.sf.lcd_density must be defined as a build property
2018-12-09 23:59:52.059 1711-2050/? E/SurfaceFlinger: ro.sf.lcd_density must be defined as a build property
2018-12-09 23:59:54.394 1867-1983/? E/TaskPersister: File error accessing recents directory (directory doesn't exist?).
2018-12-09 23:59:57.468 5475-5549/? E/PlayCommon: [332] com.google.android.play.b.g.a(448): Failed to connect to server: java.net.UnknownHostException: Unable to resolve host "play.googleapis.com": No address associated with hostname
2018-12-09 23:59:58.360 1867-1881/? E/memtrack: Couldn't load memtrack module
2018-12-09 23:59:58.362 1867-1881/? E/memtrack: Couldn't load memtrack module
2018-12-09 23:59:58.362 1867-1881/? E/memtrack: Couldn't load memtrack module

The manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    package="com.example.flow">
    <!--
         The ACCESS_COARSE/FINE_LOCATION permissions are not required to use
         Google Maps Android API v2, but you must specify either coarse or fine
         location permissions for the 'MyLocation' functionality.
    -->
    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="Eazy-Split"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        tools:ignore="GoogleAppIndexingWarning"
        tools:replace="android:icon,android:label"
        >

        <uses-library android:name="org.apache.http.legacy" android:required="false" />

        <meta-data
            android:name="com.google.android.geo.API_KEY"
            android:value="AIzaSyApsuynhkRf3A7p3fgKQp01EEF8l4tggXQ" />

        <activity
            android:name=".MainActivity"
            android:theme="@style/AppTheme"
            >

            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <activity
            android:name=".Home"
            android:parentActivityName=".displayClasses.LoginScreens.Login"
            android:theme="@style/AppTheme.NoActionBar">
            <meta-data
                android:name="android.support.PARENT_ACTIVITY"
                android:value=".displayClasses.LoginScreens.Login" />
        </activity>

        <activity
            android:name=".displayClasses.LoginScreens.activity_signup"
            android:theme="@style/AppTheme"
            />

        <activity
            android:name=".displayClasses.LoginScreens.Login"
            android:theme="@style/AppTheme"
            />

    </application>

</manifest>

A: You are returning a new JSONArray() object that is pretty much empty and it has not been populated with any changes that you applied to your instances inside doInBackground.
Inside your doInBackground, make sure you create a local JSONArray object, and pass to it all of your instances that you would like to retrieve in your onPostExecute method. In your case, if you have a string named nextPageToken which will be updated during doInBackground. Then, you will be able to retrieve in  onPostExecute.
Do the following:
In doInBackground: create a local instance: JSONArray jsonArray;
Write to your object whenever its necessary. For example:
jsonArray = jsonObject.getJSONArray("results");
Then at the end of your method doInBackground, return it:
return jsonArray;

A: @Red M is right. You are returning an empty JSONArray.
You can create a JSONArray write to the object and return that JSONArray that have a value.
Example:
JSONObject jsonObject=new JSONObject(stringBuilder.toString());
JSONArray jsonArray = jsonObject.getJSONArray("your json value here");

then at the end of your code:
return jsonArray;


text:
Q: OUT Parameter Issue in DB2 Stored Procedure I am getting an error complaining about the OUT Parameter ID as an Undefined name when I try to set its value at the end of the procedure. Commenting it out the procedure executes fine.
What am I doing wrong?
CREATE PROCEDURE P3.CUST_CRT(IN NAME VARCHAR(15),
                             IN GENDER CHAR(1),
                             IN AGE INTEGER,
                             IN PIN INTEGER,
                             OUT ID INTEGER)
LANGUAGE SQL
P1: BEGIN
        --Check if Customer NAME is NULL.
        IF NAME IS NULL THEN
                SIGNAL SQLSTATE VALUE '20010'
                SET MESSAGE_TEXT = 'No NAME.';
        END IF;
        --Check if Customer NAME is an empty string.
        IF NAME = '' THEN
                SIGNAL SQLSTATE VALUE '20020'
                SET MESSAGE_TEXT = 'NAME cannot be an empty string.';
        END IF;
        --Check if Customer GENDER falls in either of the two acceptable categories.
        IF GENDER NOT IN ('M','F') THEN
                SIGNAL SQLSTATE VALUE '20030'
                SET MESSAGE_TEXT = 'GENDER can either be M or F';
        END IF;
        --Check if Customer AGE is not null.
        IF AGE IS NULL THEN
                SIGNAL SQLSTATE VALUE '20040'
                SET MESSAGE_TEXT = 'AGE cannot be NULL';
        END IF;
        --Check that AGE is not negative.
        IF AGE < 0 THEN
                SIGNAL SQLSTATE VALUE '20060'
                SET MESSAGE_TEXT = 'AGE cannot be negative.';
        END IF;
        --Check that the Customer is an adult.
        IF AGE < 18 THEN
                SIGNAL SQLSTATE VALUE '20070'
                SET MESSAGE_TEXT = 'You have to be over 18 years to have an account.';
        END IF;
        --Check that PIN is not null.
        IF PIN IS NULL THEN
                SIGNAL SQLSTATE VALUE '20080'
                SET MESSAGE_TEXT = 'PIN cannot be empty.';
        END IF;
        --Pin cannot be less than zero.
        IF PIN < 0 THEN
                SIGNAL SQLSTATE VALUE '20090'
                SET MESSAGE_TEXT = 'PIN cannot be less than 0.';
        END IF;

        INSERT INTO P3.CUSTOMER(Name, Gender, Age, Pin) VALUES(NAME, GENDER, AGE, P3.ENCRYPT(PIN));
        SET ID = ID.CURRVAL;
END P1 @

A: Always specify your Db2 Server version and operating-system when asking for help. Never write "getting an error" unless you specify the exact error message and error code. You code presumes that the sequence object you named "ID" is in the schema, and you should not allow an output parameter name to be the same as a sequence name. Give a sequence object a different name from the output parameter
For "Code: -204, SQL State: 42704] "DB2ADMIN.ID" is an undefined name.. SQLCODE=-204, SQLSTATE=42704, DRIVER=4.22.29",   Db2 is telling you that the output parameter (named ID) has the same name as the sequence object, and that Db2 cannot find the sequence object in the schema called DB2ADMIN - that is the schema that you are connecting to the database to do the compile.
So, either qualify your sequence object name (i.e. put the schema name before it for example P3.ID (if that is your sequence fully qualified name), or give the correct full name for your sequence object.  The sequence object needs to exist in the specified or implied schema before your code will compile.
It's unclear from your code where you consume the next value of the sequence (you only use its current value), but that is a separate matter from the -204 - in other words you may have other errors.
If you seek to return the most recently consumed sequence value, then one way (there are other ways, including more elegant ways) to do it is like this (in this example the sequence object is pre-created as P3.THEID ):
INSERT INTO P3.CUSTOMER(ID, Name, Gender, Age, Pin) VALUES( NEXT VALUE FOR P3.THEID , NAME, GENDER, AGE, P3.ENCRYPT(PIN));

SET ID = P3.THEID.CURRVAL;

A: Your ID variable is defined as INTEGER while in order to use the CURRVAL function it has to be defined as a SEQUENCE object.


text:
Q: Trouble saving C# WPF I am making an application for a 'Ski Resort' where you can add members and search members etc. So far I am having difficulty saving and loading these when the application closes. When I add a member, it saves, and then when I try to add another, the first member will not be saved anymore but the first one will have done.
Here is the code used to Save the members:
     public void Save(System.IO.TextWriter textOut)
    {
        textOut.WriteLine(number);
        textOut.WriteLine(name);
        textOut.WriteLine(address);
        textOut.WriteLine(score);
        textOut.Close();
    }

    public bool Save(string filename)
    {
        System.IO.TextWriter textOut = null;
        try
        {
            textOut = new System.IO.StreamWriter(filename);
            Save(textOut);
        }
        catch
        {
            return false;
        }
        finally
        {
            if (textOut != null)
            {
                textOut.Close();
            }
        }
        return true;
    }

A: The StreamWriter constructor you are using will overwrite the file each time. Use the constructor that also takes a boolean so you can make it append to the file. And you don't need the TextWriter.
try
{
   using(var textOut = new System.IO.StreamWriter(filename, true))
   {
       textOut.WriteLine("whatever..");
   }
}


text:
Q: Are the type system represented by XmlSchema and the CLS isomorphic Can someone please explain this question to me?

Are the type system represented by
  XmlSchema and the CLS isomorphic?

Link

A: Means every type defined by XML Schema can be defined in CLS (.NET type system) and vice versa.
For example, if we have xs:string in XML Schema, we have System.String in .NET. And If I define this class in C#:
public class Foo
{
   public string Bar{get;set;}
}

I can represent that in XML Schema:
<xs:complexType name="Foo">
    <xs:sequence>
      <xs:element name="Bar" type="xs:string" minOccurs="1" maxOccurs="1" />
    </xs:sequence>
</xs:complexType>

A: NO.
the question is a fancy way of asking if each member in the CLS has corresponding one in XmlSchema.
There are a  lot of matches but mismatches as well so the answer is no - they are not isomorphic.


text:
Q: Setting property to null in ViewModel? I have a Telerik RadDataForm, with a couple of DataFormDataField's that are bound to nullable properties:
<telerik:DataFormDataField Label="My Property">
    <telerik:RadNumericUpDown Value="{Binding Path=MyProperty}" />
</telerik:DataFormDataField>

And:
private double? myProperty;
public double? MyProperty
{
    get { return this.myProperty; }
    set
    {
        this.myProperty = value;
        this.onPropertyChanged(nameof(this.MyProperty));
    }
}

And:
public event PropertyChangedEventHandler PropertyChanged;

private void onPropertyChanged(string propertyName)
{
    PropertyChangedEventHandler handler = PropertyChanged;
    if (handler != null)
    {
        handler(this, new PropertyChangedEventArgs(propertyName));
    }
}

When the form loads, the property is null, so the control is empty. If the user types or uses the control to put a number into the property, the control displays the value and the property is set to the correct value.
I need to be able to reset the property to null in code and have the control cleared again. Unfortunately, when I set the property to null, the control does not change and continues to contain the prior value.
Any ideas as how to make this happen?
=== ADDENDUM ===
To clarify whether this was a problem in Telerik's RadNumericUpDown control, or in basic WPF binding, I replaced it with IntegerUpDown from Alex Titarenko's WPFControls:
<telerik:DataFormDataField>
    <xctk:IntegerUpDown Value="{KtWpf:IntegerBinding Path=mileageend}" />
</telerik:DataFormDataField>

I'm seeing exactly the same behavior.
=== OOPS ===
OK, the problem had nothing to do with the binding. Buried in the code for the view model that backed the control that contained this data form, we'd new up the object that the data form was bound to.
What was happening was that before we got to the code that set these fields to new, we'd new up a new object and point the view model's reference to it. So when I walked through in the debugger, I was looking at one object, and was setting its fields to null, but the data form was still bound to the original, which wasn't being changed.
When I null the fields of the object that the data form is actually bound to, everything works fine.
Sorry, everyone, for the distraction, and thanks for the help.
One bit of advice - when what is happening seems to make no sense, it may be that what is happening isn't what you think is happening.

A: Both variable and property must be nullable
private double? myProperty;
public double? MyProperty
{
    get { return this.myProperty; }
    set
    {
        this.myProperty = value;
        this.onPropertyChanged(nameof(this.MyProperty));
    }
}

Problem with nullable property's is that you'll have to cast them when you put the value into a other double
double d = (double)MyProperty;

Edit:
To check if a object or DependencyProperty is nullable see this question


text:
Q: Django admin breadcrumb for app Hardcoding a breadcrumb in a non-Admin template - with a model looks like this:
    {% trans 'MyModels' %}

Easy enough. My problem is in making a breadcrumb for just the app. I would expect something like:
{% trans 'MyApp' %}

Or
{% trans 'MyApp' %}

Or
 {% trans 'MyApp' %}

None of which work. As well as quite a few other things I've tried. Can someone put me out of my misery? Thanks.

A: The url name is actually just app_list, the application name is passed as an argument:
{% url 'admin:app_list' 'myapp' %}

See the source for reference.

A: URLs are based on paths to views, see https://docs.djangoproject.com/en/dev/ref/templates/builtins/#url


text:
Q: Syntax check on a java file For a given java file, I'd like to check if it's syntactically correct. ie. If it has semi-colons in the right places, matching parenthesis etc. Importantly, I need to check the file in isolation from all of its dependencies.
This other answer is promising, however it's really doing a semantic check rather than a syntactic check. It does what a compiler would do - check all the imports statements as well as verify external classes that are referenced in the code.
Is there a way to do a true syntax check? (A check that only inspects the raw text against Java's formal grammar)

A: Create or use a Java source code parser. For some parser generators there are public Java grammars available - you could use it to generate the parser.
E.g. Java 8 grammar for ANTLR (no idea about quality of that grammar though, you'd have to do your evaluation - but the grammar is written by the author of ANTLR, so should be OK I guess).

A: As Jiri suggested, use the ANTLR library to put together a syntax checker.

*

*Download and extract the ANTLR grammars from here

*Download the ANTLR4 jar from here

*Run the following command to generate classes from the Java 8 grammar:

java -jar antlr-4.5.3-complete.jar
  ~/Downloads/grammars-v4-master/java8/Java8.g4

*Copy the .java files that were created into your project
Then you can write your syntax checker:
public static void main(String[] args) throws SAXException, IOException {

    ANTLRInputStream input = new ANTLRFileStream(args[0]);
    Java8Lexer lexer = new Java8Lexer(input);
    CommonTokenStream tokens = new CommonTokenStream(lexer);
    Java8Parser parser = new Java8Parser(tokens);

    final StringBuilder errorMessages = new StringBuilder();
    parser.addErrorListener(new BaseErrorListener() {
        @Override
        public void syntaxError(Recognizer<?, ?> recognizer, Object offendingSymbol, int line, int charPositionInLine, String msg, RecognitionException e) {
            String err = String.format("Failed to parse at line %d:%d due to %s", line, charPositionInLine + 1, msg);
            errorMessages.append(err);
            errorMessages.append(System.lineSeparator());
        }
    });

    parser.compilationUnit();
    int syntaxErrors = parser.getNumberOfSyntaxErrors();

    if (syntaxErrors == 0) {
        System.out.println(args[0] + ": PASS");
    } else {
        System.out.println(args[0] + ": FAILED (" + syntaxErrors + " syntax errors");
    }
}

A: I was researching how to do a quick java syntax-checker for usage in vim. I inspired by @Fidel's answer (thanks for the example checker!) but it didn't suffice me as I needed it to work in a standalone way.
Here is a step by step process of what had to be done in order to have runnable command:

*

*Run:

# download and generate .java classes
wget https://repo1.maven.org/maven2/org/antlr/antlr4/4.5.3/antlr4-4.5.3.jar -O antlr4-4.5.3.jar
wget https://raw.githubusercontent.com/antlr/grammars-v4/master/java8/Java8.g4 -O Java8.g4
java -jar antlr4-4.5.3.jar ./Java8.g4

*

*Then write a syntax checker, perhaps similar to @Fidel's one and place it under package checker; place it directly under ./checker directory

*Also place all of the generated .java classes under that package (ie. put package checker; to the first line of all the files)

*Run:
# prepare directory structure and compile
mkdir -p checker && mv *.java ./checker/
javac -cp antlr4-4.5.3.jar ./checker/*.java

*

*Prepare a Manifest file that will look similarly to:

Class-Path: antlr4-4.5.3.jar
Main-Class: checker.<name-of-your-checker-class>

*

*Run:

# package into a jar file and run to test everything works
jar cfm checker.jar Manifest.txt checker/*.class
java -jar ./checker.jar <filename-you-want-to-run-syntax-check-against>

For my usage in vim I then created a simple shell script to wrap execution of the process of running the java jar that looks like this:
#!/bin/bash

DIR=$(readlink -f $0)
DIR=${DIR:0:(-3)}            # put the length of the script name here instead of '3'

java -jar ${DIR}checker.jar $@

Then make it executable and symlink it under $PATH:
chmod a+x <file-name>
sudo ln -s /path/to/the/script /usr/bin/java-syntax

And finally added a keybinding like this into a .vimrc file (ie. to map running the syntax-check when F10 key is pressed):
" java syntax validation
map <F10> :!java-syntax % <CR>

I also stored the process into a github repository, where all the commands are prepared in a makefile and it suffices to run make in order to build and package the checker. Feel free to use it as an inspiration.


text:
Q: how can i use binary search in c# for generic list I would like to sort my list and then use a binary search to find a name in the list and display it.
public abstract class animal {
  protected int age
  protected string name
  public print() {
    console.writeline({
      age
    } + {
     name
    });
  }
  animal() {}~animal() {}
}

public class pets {
  private List<animal> list = new List<animal>();

  public void search(string m) {
    int index = list.BinarySearch(m);
    if (index == 0)
      list[index].print();
  }
}

A: The built-in BinarySearch method does not let you pass in a value of a type other than the type of the list. To use the built-in BinarySearch you will need to either define a class that implements  IComparer<Animal> that compares by Name, or make Animal implement IComparable<Animal> so that two animals are compared by name by default. Then you Sort() the list and call BinarySearch, passing an Animal instance that has the name you want to search for.
You'd have to implement your own BinarySearch method to search for an object with a given property value (assuming, of course, that the list is sorted by that same property).
If you just want to use regular linear search methods to search for an animal with a given name, you can use a straight foreach loop, breaking when the item with that name is found, or use the First() Linq method (which basically does the same thing).


text:
Q: Sharepoint modal popup don't shown when the Infopath form are on the site I tried to add Infopath form on my project, but when I add the Infopath form some of the PopUp which is correlated with Infopath and shows errors od data didn't show What should I do to show A Modal Popup after used an Infopath form? Please help.
I putt this code, and nothing has shown When Infopath template is included. If it's included defoultTemplate Sharepoint all templates are shown:
   if (dzienStart > dzienStop)
           {
               System.Threading.Thread.Sleep((int)System.TimeSpan.FromSeconds(8).TotalMilliseconds);
               properties.Status = SPEventReceiverStatus.CancelWithRedirectUrl;
               properties.RedirectUrl = "/_layouts/Add4/OutOfRange.aspx";
               properties.ErrorMessage = "You cannot save this list item at this time";
               return;
           }

A: I cannot grasp what you are asking and in which context ("putts this code") but I shall try to make some comments:

*

*Infopath code-behind is client-side code and your code is server-side

*Published to Sharepoint Infopath form templates are available for use through IPFS - Sharepoint Server Infopath Form Service as an Infopath Web Part in ASPX Infopath Web Part pages;

*IPFS is available only on enterpse Sharepoint Server or enterprises Sharepoint online (Office 365) plans (but NOT through free Sharepoint Foundation)

*In order to use both default sharepoint form templates and Infopath from templates in dialog/popups, you should tweak and work around a little


text:
Q: VBA Entering userform data at next blank row correctly
*

*Created a userform

*Added a textBox and a comboBox

*Added a submit button

*When submit is clicked it adds the data to a spreadsheet

From what I have been told and what I have read this is wrong
ActiveCell.Value = TextBox3.Text
ActiveCell.Offset(0, 1).Select
ActiveCell.Value = ComboBox1.Text
ActiveCell.Offset(1, -1).Select

This works but I've been told I shouldn't use the .select keyword when possible. I've read that to make my code reusable I should create variables. How would a professional developer write this code, can it be written in less lines and how can I refer to the activecell offset without using select?

A: I am assuming you want TextBox3 in column A and ComboBox1 in column B.  If you want different columns just change the letter references.
Sub OnClick() 'whatever your current sub is called.

    Dim LastRow As Long, ws As Worksheet

    Set ws = Sheets("Name of Sheet where data is going")

    LastRow = ws.Range("A" & Rows.Count).End(xlUp).Row + 1 'Finds the last blank row

    ws.Range("A" & LastRow).Value = TextBox3.Text 'Adds the TextBox3 into Col A & Last Blank Row
    ws.Range("B" & LastRow).Value = ComboBox1.Text 'Adds the ComboBox1 into Col B & Last Blank Row

End Sub

If you want a method using Offset():
Sub OnClickwithOffset() 'whatever your current sub is called.

    Dim LastRow As Long, ws As Worksheet

    Set ws = Sheets("Name of Sheet where data is going")

    LastRow = ws.Range("A" & Rows.Count).End(xlUp).Row + 1 'Finds the last blank row

    ws.Range("A" & LastRow).Value = TextBox3.Text 'Adds the TextBox3 into Col A & Last Blank Row
    ws.Range("A" & LastRow).Offset(0, 1).Value = ComboBox1.Text 'Adds the ComboBox1 into next cell to the right of TextBox3 data.

End Sub

A: The main reason why you want to avoid using ActiveCell is that it may produce unexpected results should the user select another cell while the code is executing.
If your goal is to always write the contents of your controls to the same cells, you may wish to start by defining a variable of type Range and set your offsets relative to that variable.
E.g.:
Dim myCell as Range

Set myCell = ThisWorkbook.Sheets(1).Range("C4")
myCell.Value = TextBox3.Text
myCell.Offset(0, 1).Value = ComboBox1.Text

'[...]


text:
Q: Getting no array key Hey I'm trying to get the key of my array in a foreach.
But got this error
Warning:  array_keys() expects parameter 1 to be array, string given on line 10
Here is my array:
$status_de = array
(
    '1' => 'Anfrage',
    '2' => 'Angebot',
    '3' => 'Abgeschlossen'
);

Here is my code:
<select name="land">
    <?php foreach ($status_de as $status) {
      echo "<option value='" . array_keys($status) . "'>" . $status . "</option>";
    }
    ?>
</select>

A: You should use:
<?php foreach ($status_de as $key=>$status) {
  echo "<option value='" . $key . "'>" . $status . "</option>";
}
?>

as array_keys() will return array containing all keys (so not applicable to use with strings operators)

A: Try this:
foreach loop will get key and value pair, so you can directly use it. No need any function to get those.
<select name="land">
    <?php foreach ($status_de as $key => $value) {
      echo "<option value='" . $key . "'>" . $value . "</option>";
    }
    ?>
</select>

A: You can't do like this because array_keys expected an array. In your scenario you give a string.
try like this:
<select name="land">
    <?php foreach ($status_de as $k =>$v) {
      echo "<option value='" . $k . "'>" . $v . "</option>";
    }
    ?>
</select>