Q:

SQLERRM - like function for other error types

This is a continuation from this question.
My Question: I'm looking for a function like SQLERRM which will give me a description for all Oracle error codes.
From this website, I found this list of oracle error types:
AMD, AUD, CLS, DBV, DGM, DRG, EXP, IMG, IMP, KUP, LCD, LFI, LPX, LRM,
LSX, NCR, NID, NMP, NNC, NNF, NNL, NNO, NPL, NZE, O2F, O2I, O2U, OCI,
ORA-CODE, PCB, PCC, PLS, PLW, PRO, QSM, RMA, SQL, TNS, UDE, UDI, VID

Am I misunderstanding something or is this possible?

A:

Something like
SQL> !oerr ora 04043
04043, 00000, “object %s does not exist”
// *Cause: An object name was specified that was not recognized by the system.
// There are several possible causes:
// – An invalid name for a table, view, sequence, procedure, function,
// package, or package body was entered. Since the system could not
// recognize the invalid name, it responded with the message that the
// named object does not exist.
// – An attempt was made to rename an index or a cluster, or some
// other object that cannot be renamed.
// *Action: Check the spelling of the named object and rerun the code. (Valid
// names of tables, views, functions, etc. can be listed by querying
// the data dictionary.)

This is the error lookup utility in Oracle.
Usage: oerr facility error

facility is any of the error types like ora, amd etc. and error is the code. But you need to make sure that you have access privilege to all installed directories.
This is what you need in PDF format.


Q:

code igniter database (Trying to get property of non-object) on server

On my local machine I access my application using

http://localhost/index.php

on the server i publish it its

http://myserver:8888/alias/index.php

I've updated this in code igniter config and also replicated my local database on the server. Now something screwy is happening on the server when it reaches

$this->db->query($queryStr)->row()->ID;

I tried to manually run the query inside $queryStr and it gives me back data from the command line however when I ran it like above on the server

$this->db->query($queryStr)->row()
   returns an empty array

I get

Severity: Notice
Message: Trying to get property of
  non-object
Filename: models/model_mymodel.php

Am I overlooking something why is the exact same code not working on the server?

A:

Check you code to capitalization (case) errors. If your development machine is windows based, it then it does not care about case. You linux server does however.


Q:

C++ - Error with iteration of vector

struct user
{
    vector<size_t> follower;
    vector<size_t> following;
};

int main ()
{
    vector< user > node ( 100 );

    // Pushing back some indices of other nodes in some node[x].follower and node[x].following

    size_t i = 2;

    for ( size_t const& j : node[i].follower )
        node[j].following.erase( remove( node[j].following.begin(), node[j].following.end(), i ), node[j].following.end() );

}

In C++, I created the struct user, where vectors follower and following store indices to some other users belonging to the vector node. With the last for loop I would like to destroy all the indices i (which refer to the specific user i) from the vector follower and following of other users; unluckily, with gcc/4.7.2, using C++11, I obtain this error:
error: cannot convert 'std::vector<long unsigned int>::iterator {aka __gnu_cxx::__normal_iterator<long unsigned int*, std::vector<long unsigned int> >}' to 'const char*' for argument '1' to 'int remove(const char*)'

I also tried with a for loop of iterators, for ( vector<size_t>::iterator it = node[i].follower.begin(); it != node[i].follower.end(); ++it ), using *it in the code of the loop, but I still obtain a similar error.
I don't know what to do.

A:

#include <algorithm>

Otherwise, compiler tries to use other remove function which is for deleting files and accepts a C-style strings (By including <iostream>).


Q:

Error: "Expected an identifier and instead saw '<'"

I am writing this in JS and trying to figure out what my editor is complaining about. Here is what I have:
document.write('

');
  var widgetHTML =

Send deals directly to my inbox - Sign up now!

What is missing because my editor has 4 errors all for one line but I cannot figure this out. The errors are:

Expected an identifier and instead saw '<'
  Missing semicolon
  Expected an assignment or function call and instead saw an expression
  Missing semicolon

A:

You start off just fine:
var widgetHTML =

what follows that = should be a Javascript expression. Strings ("..."), numbers, variable names, function calls, any of those things combined with operators -- all would be fine.
But a bunch of HTML is not a Javascript expression.

Send deals directly to my inbox - Sign up now!

If you want to set widgetHTML to that HTML text, you'll need to make a string out of it:
var widgetHTML = '
' +
  '
' +
  '
Send deals directly to my inbox - Sign up now!
';


Q:

How can I totally remove TFS bindings from a solution?

We have a large solution with many projects. Some of the projects were outsourced, and the vendor used TFS. When they commited into our SVN repo, some of the bindings are still hanging around.
When I open the sln, VS2008 says "The source control provider associated with the solution cannot be found, do you want to remove them". I hit yes, save and exit, and then next time it does it all again :)
So - anyone know how I cam get rid of any TFS bindings from the sln once and for all? Do I need to manually search the csproj files for any "scc" references and remove?
Thanks!

A:

Some PDA deployment projects(.vddproj) had some bindings hanging around.
Just removed them manually :)


Q:

HTML parsing unknown selector needed

Using Jsoup an html parsing java library, i have located this from a website:

                Cafe staff wanted!

using: Elements Jobs = doc.select("div.jobCardListingTitle a");
however i want to retrieve "cafe staff wanted" but i only know how to retrieve href System.out.println(Job.attr("href")); and id... System.out.println(Job.attr("id"));
How do i find this string?
Thanks

A:

Sounds like you are looking for <ElementsObject>.html().
In your case:
System.out.println(Job.html());

There also is the <ElementsObject>.text() property, that may worth a look.


Q:

Remove punctuation but keeping emoticons?

Is that possible to remove all the punctuations but keeping the emoticons such as
:-(
:)
:D
:p
structure(list(text = structure(c(4L, 6L, 1L, 2L, 5L, 3L), .Label =     c("ãããæããããéãããæãããInappropriate announce:-(",
"@AirAsia your direct debit (Maybank) payment gateways is not working. Is it something     you are working to fix?",
"@AirAsia Apart from the slight delay and shortage of food on our way back from Phuket, both flights were very smooth. Kudos :)",
"RT @AirAsia: ØØÙØÙÙÙÙ ÙØØØ ØØØÙ ÙØØØØÙ ØØØØÙÙÙí í Now you can enjoy a #great :D breakfast onboard with our new breakfast meals! :D",
"xdek ke flight @AirAsia Malaysia to LA... hahah..:p bagi la promo murah2 sikit, kompom aku beli...",
"You know there is a problem when customer service asks you to wait for 103 minutes and your no is 42 in the queue. X-("
), class = "factor"), created = structure(c(5L, 4L, 4L, 3L, 2L,
1L), .Label = c("1/2/2014 16:14", "1/2/2014 17:00", "3/2/2014 0:54",
"3/2/2014 0:58", "3/2/2014 1:28"), class = "factor")), .Names = c("text",
"created"), class = "data.frame", row.names = c(NA, -6L))

A:

1. A working pure-regex solution (a.k.a. Edit#2)
This task can be done purely with regular expressions (many thanks to @Mike Samuel)
First we build a database of emoticons:
(emots <- as.character(outer(c(":", ";", ":-", ";-"),
+                c(")", "(", "]", "[", "D", "o", "O", "P", "p"), stri_paste)))
## [1] ":)"  ";)"  ":-)" ";-)" ":("  ";("  ":-(" ";-(" ":]"  ";]"  ":-]" ";-]" ":["  ";["  ":-[" ";-[" ":D"  ";D"  ":-D" ";-D"
## [21] ":o"  ";o"  ":-o" ";-o" ":O"  ";O"  ":-O" ";-O" ":P"  ";P"  ":-P" ";-P" ":p"  ";p"  ":-p" ";-p"

An exemplary input text:
text <- ":) ;P :] :) ;D :( LOL :) I've been to... the (grocery) st{o}re :P :-) --- and the salesperson said: Oh boy!"

A helper function that escapes some special characters so that they may be used in a regex pattern (using the stringi package):
library(stringi)
escape_regex <- function(r) {
   stri_replace_all_regex(r, "\\(|\\)|\\[|\\]", "\\\\$0")
}

A regular expression to match the emoticons:
(regex1 <- stri_c("(", stri_c(escape_regex(emots), collapse="|"), ")"))
## [1] "(:\\)|;\\)|:-\\)|;-\\)|:\\(|;\\(|:-\\(|;-\\(|:\\]|;\\]|:-\\]|;-\\]|:\\[|;\\[|:-\\[|;-\\[|:D|;D|:-D|;-D|:o|;o|:-o|;-o|:O|;O|:-O|;-O|:P|;P|:-P|;-P|:p|;p|:-p|;-p)"

Now, as @Mike Samuel suggested below, we just match (emoticon)|punctuation
(note that emoticons are in a capturing group) and then replace the matches
with the result of capturing group 1 (so if it's an emoticon, we have replacement=this emoticon, if it's a punctuation char, we have replacement=nothing). This will work because the alternation with | in ICU Regex (which is the regex engine used in stri_replace_all_regex) is greedy and left-biased: emoticons will be matched earlier than the punctuation characters.
stri_replace_all_regex(text, stri_c(regex1, "|\\p{P}"), "$1")
## [1] ":) ;P :] :) ;D :( LOL :) Ive been to the grocery store :P :-)  and the salesperson said Oh boy"

BTW, if you want to get rid only of a selected set of characters, put e.g. [.,] instead of [\\p{P}] above.
2. Regex solution hint - my first (not wise) attempt (a.k.a. original answer)
My very first idea (left here mainly for "historical reasons") was to approach this problem by using look-aheads and look-behinds, but - as you see - that's far from perfect.
To remove all : and ; not followed by ), (, D, X, 8, [, or ] use negative look-behind:
stri_replace_all_regex(text, "[:;](?![)P(DX8\\[\\]])", "")
## [1] ":) :8 ;P :] :) ;D :( LOL :) I've been to... the grocery store :P -) --- and the salesperson said Oh boy!"

Now we can add some old-school emoticons (with noses, e.g. :-), ;-D etc.)
stri_replace_all_regex(text, "[:;](?![-]?[)P(DX8\\[\\]])", "")
## [1] ":) :8 ;P :] :) ;D :( LOL :) I've been to... the grocery store :P :-) --- and the salesperson said Oh boy!"

Now the hyphens removal (negative look behind and look ahead)
stri_replace_all_regex(text, "[:;](?![-]?[)P(DX8\\[\\]])|(?!<[:;])[-](?![)P(DX8\\[\\]])", "")
## [1] ":) :8 ;P :] :) ;D :( LOL :) I've been to... the grocery store :P :-)  and the salesperson said Oh boy!"

and so on. Of course, first you should build your own database of emoticons (to leave as they are) and punctuation marks (to remove). The regex will highly depend on these two sets, so it will be difficult to add new emoticons --- it's definitely not worth applying (and may twist your brain).
3. The second attempt (regex-dumb friendlier, a.k.a. Edit#1)
On the other hand, if you're allergic to complex regexes, try this. This approach has some "didactic benefits" - we have full insight on what's being done in each of the following steps:

Locate all emoticons within text;
Locate all the punctuation characters within text;
Find positions of the punctuation characters that are not parts of emoticons;
Remove the characters located in step 3.

An exemplary input text - 1 string only - a generalized case is left as an exercise ;)
text <- ":) ;P :] :) ;D :( LOL :) I've been to... the (grocery) st{o}re :P :-) --- and the salesperson said: Oh boy!"

A helper function that escapes some special characters so that they may be used in a regex:
escape_regex <- function(r) {
   library("stringi")
   stri_replace_all_regex(r, "\\(|\\)|\\[|\\]", "\\\\$0")
}

A regular expression to match the emoticons:
(regex1 <- stri_c("(", stri_c(escape_regex(emots), collapse="|"), ")"))
## [1] "(:\\)|;\\)|:-\\)|;-\\)|:\\(|;\\(|:-\\(|;-\\(|:\\]|;\\]|:-\\]|;-\\]|:\\[|;\\[|:-\\[|;-\\[|:D|;D|:-D|;-D|:o|;o|:-o|;-o|:O|;O|:-O|;-O|:P|;P|:-P|;-P|:p|;p|:-p|;-p)"

Locate the start and end positions of all the emoticons (i.e. locate the first OR the second OR ... emoticon):
where_emots <- stri_locate_all_regex(text, regex1)[[1]] # only for the first string of text
print(where_emots)
##       start end
##  [1,]     1   2
##  [2,]     4   5
##  [3,]     7   8
##  [4,]    10  11
##  [5,]    13  14
##  [6,]    16  17
##  [7,]    23  24
##  [8,]    64  65
##  [9,]    67  69

Locate all the punctuation chars (Here \\p{P} is the Unicode character class representing punctuation characters):
where_punct <- stri_locate_all_regex(text, "\\p{P}")[[1]]
print(where_punct)
##       start end
##  [1,]     1   1
##  [2,]     2   2
##  [3,]     4   4
##  [4,]     7   7
##  [5,]     8   8
## ...
## [26,]    72  72
## [27,]    73  73
## [28,]    99  99
## [29,]   107 107

As some punctuation chars occur within the emoticons, we should not stage them for removal:
which_punct_omit <- sapply(1:nrow(where_punct), function(i) {
   any(where_punct[i,1] >= where_emots[,1] &
        where_punct[i,2] <= where_emots[,2]) })
where_punct <- where_punct[!which_punct_omit,] # update where_punct
print(where_punct)
##       start end
##  [1,]    27  27
##  [2,]    38  38
##  [3,]    39  39
##  [4,]    40  40
##  [5,]    46  46
##  [6,]    54  54
##  [7,]    58  58
##  [8,]    60  60
##  [9,]    71  71
## [10,]    72  72
## [11,]    73  73
## [12,]    99  99
## [13,]   107 107

Each punctuation mark surely consists only of 1 character, thus always where_punct[,1]==where_punct[,2].
Now the final part. As you see, where_punct[,1] contains the positions of characters to be removed. IMHO the easiest way to do that (without loops) is by converting a string to UTF-32 (each character == 1 integer), remove undesired elements, and then go back to the textual representation:
text_tmp <- stri_enc_toutf32(text)[[1]]
print(text_tmp) # here - just ASCII codes...
## [1]  58  41  32  59  80  32  58  93  32  58....
text_tmp <- text_tmp[-where_punct[,1]] # removal, but be sure that where_punct is not empty!

And the result is:
stri_enc_fromutf32(text_tmp)
## [1] ":) ;P :] :) ;D :( LOL :) Ive been to the grocery store :P :-)  and the salesperson said Oh boy"

Here you are.

A:

Here's an approach that is less sophisticated and likely slower than @gagolews's solution.  It requires you feed it an emoticon dictionary.  You can create that or use the one in the qdapDictionaries package.  The basic approach converts the emoticons to text that couldn't be mistaken for anything else (I use dat$Temp <- prefix to ensure this).  Then you strip out punctuation using qdap::strip and then convert the placeholders back into emoticons via mgsub:
library(qdap)
#reps <- emoticon
emos <- c(":-(", ":)", ":D", ":p", "X-(")
reps <- data.frame(seq_along(emos), emos)

reps[, 1] <- paste0("EMOTICONREPLACE", reps[, 1])
dat$Temp <- mgsub(as.character(reps[, 2]), reps[, 1], dat[, 1])
dat$Temp <- mgsub(reps[, 1], as.character(reps[, 2]),
    strip(dat$Temp, digit.remove = FALSE, lower.case=FALSE))

View it:
truncdf(left_just(dat[, 3, drop=F]), 50)

##   Temp
## 1 RT AirAsia ØØÙØÙÙÙÙ ÙØØØ ØØØÙ ÙØØØØÙ ØØØØÙÙÙí í No
## 2 You know there is a problem when customer service
## 3 ãããæããããéãããæãããInappropriate announce:-(
## 4 AirAsia your direct debit Maybank payment gateways
## 5 xdek ke flight AirAsia Malaysia to LA hahah:p bagi
## 6 AirAsia Apart from the slight delay and shortage o

EDIT: To keep the ? and ! as requested pass the char.keep argument in strip function:
dat$Temp <- mgsub(reps[, 1], as.character(reps[, 2]),
    strip(dat$Temp, digit.remove = FALSE, lower.case=FALSE, char.keep=c("!", "?")))


Q:

Insert two arrays in tableView - Error connecting

Edited:
I'm trying to insert two arrays into one tableview with two cell labels. But not really sure how I can convert it all and make it work. Here is my code so far.
In the top of the main ViewController (Where the tableView is)
class ScoreBoardViewController: UIViewController, UITableViewDelegate, UITableViewDataSource

    var countedArray: [String] = []
    var nameArray: [String] = []

    @IBOutlet weak var tableView: UITableView!
    var list: [pointsTxt] = []

Additional info: I've added the self.tableView.delegate = self

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int
    {
        return list.count

    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
    {
        let listPath = list[indexPath.row]
        let cell = tableView.dequeueReusableCell(withIdentifier: "pointsCell") as! ScoreCell
        cell.setCell(list: listPath)

        return cell
    }

    func createArray() -> [pointsTxt]
    {
        var tempTxt: [pointsTxt] = []

        let txt = pointsTxt(person: nameArray, points: countedArray)

        tempTxt.append(txt)

        self.list = tempTxt
        self.tableView.reloadData()

        return list
    }

Class for the cell
class ScoreCell: UITableViewCell
{

    @IBOutlet weak var person: UILabel!
    @IBOutlet weak var points: UILabel!

    func setCell(list: pointsTxt)
    {
        person.text = list.person
        points.text = list.points
    }
}

ERROR: Cannot assign value of type '[String]' to type 'String?'

Class for the array
class pointsTxt
{
    var person: [String] = []
    var points: [String] = []

    init(person: [String] = [], points: [String] = [])
    {
        self.person = person
        self.points = points
    }
}

I hope you understand what I need. Thanks in advance!

A:

You have to follow the following steps when creating a custom tableViewCell:

Subclass UITableViewCell
Add your Outlets to that subclass
register your subclass to the TableView
code Example for your rowAtIndexPath function:

.
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    if indexPath.row < nameArray.count {

        // load from customerDetails array
        let names = nameArray[indexPath.row]

        let cell = tableView.dequeueReusableCell(withIdentifier: "listCell", for: indexPath) as! UITableViewSubclassCell
        cell.person.text = names

        return cell
    } else {
        // load from customerDetails2 array
        let points = countedArray[indexPath.row - nameArray.count]

        let cell = tableView.dequeueReusableCell(withIdentifier: "listCell", for: indexPath) as! UITableViewSubclassCell
        cell.person.text = points
        return cell
    }
}


Q:

Sink argument implementation of assignment operator and language defect

In his key note lecture at the C++now Conference 2012, Sean Parent introduced the notion of “sink arguments”. His recommendation is to pass arguments by value if they are “consumed” by a function. The sink argument is then moved or copied, dependent on its R- or L-valueness.
He explicitly mentioned the assignment operator as an instance of an operation that has a sink argument.
He therefore gave this implementation as an example in the talk:
object_t& operator = (object_t x)
{ object_ = move(x.object_); return *this;  }

In later talks e.g. at the Going Native 2013, he repeated the guidelines but mentioned that a separate move assignment operator needs to be implemented due to a language defect:
This is a citation from his slides:

Pass sink arguments per value and move or swap into place.
A sink argument is any argument consumed of passed by the function.

The argument to assignment is a sink argument.
However, due to a language defect, you must write a move assignment operator.

I searched for information about this specific language defect but did not find any.

Can anybody explain what this language defect is and why an assignment operator using a sink argument is not working.
Will this language defect persist in C++14?

Thanks in advance,
Joachim

A:

Sean Parents answers this question in a comment of his in this link.

Lets say that you have a class Foo with an assignment operator as the example below:
class Foo {
  Foo& operator=(Foo o) noexcept {
    member = move(o.member);
    return *this;
  }
};

And wrap a Foo object in a struct, say struct wrap like in the example below:
struct wrap { Foo m_ };

Then wrap will not get a default move assignment. For wrap to get a default noexcept move assignment, all members must have a noexcept move assignment - this determination is made by signature. That is the standard says that for wrap to get a default noexcept move assignment all members must have a move assignment with the signature T& operator=(T&&) noexcept.
The fix is to rephrase the requirement so it says that a struct or class will get a default noexcept move assignment if all members satisfies  is_nothrow_move_assignable<T> - which the above does. That is, we want to define the requirement in terms of the concept, or operation semantics, and not in terms of matching an exact signature.


Q:

MySQL subquery select first row for each group

I need to create a MySQL stored procedure it selects each User SUM of all the Points they've earned.
The query should group Game by StartTime and only select the first row of each group ordered by Points. I'm trying to ignore duplicate StartTime values for each User but still keep the first one. This should avoid cheating if the User saves the same game twice.
If the User hasn't been in any Game, it should still return NULL.
CREATE PROCEDURE `spGetPoints`(
    IN _StartDate DATETIME,
    IN _EndDate DATETIME,
    IN _Limit INT,
    IN _Offset INT
)
BEGIN
    SELECT `User`.`UserId`, `User`.`Username`,
        (SELECT SUM(`Game`.`Points`)
            FROM `Game`
            WHERE `Game`.`UserId` = `User`.`UserId` AND
            `Game`.`StartDate` > _StartDate AND `Game`.`StartDate` < _EndDate
            GROUP BY `Game`.`StartDate`
            ORDER BY `Game`.`Points` DESC
            LIMIT 1
        ) AS `Value`
    FROM `User`
    ORDER BY `Value` DESC, `User`.`Username` ASC
    LIMIT _Limit OFFSET _Offset;
END

Sample User Table
+--------+----------+
| UserId | Username |
+--------+----------+
|      1 | JaneDoe  |
|      2 | JohnDoe  |
+--------+----------+

Sample Game Table
+--------+--------+-------------------------+--------+
| GameId | UserId |        StartDate        | Points |
+--------+--------+-------------------------+--------+
|      1 |      1 | 2019-01-09  12:43:00 AM |   1789 |
|      2 |      1 | 2019-01-09  11:35:00 AM |   1048 |
|      3 |      1 | 2019-01-09  9:22:00 AM  |    900 |
|      4 |      1 | 2019-01-09  12:43:00 AM |   1789 |
|      5 |      1 | 2019-01-09  11:35:00 AM |   1048 |
|      6 |      1 | 2019-01-09  9:22:00 AM  |    900 |
|      7 |      1 | 2019-01-09  12:43:00 AM |   1789 |
|      8 |      1 | 2019-01-09  11:35:00 AM |   1048 |
|      9 |      2 | 2019-01-17  12:05:00 AM |    552 |
|     10 |      2 | 2019-01-24  12:08:00 AM |    512 |
|     11 |      2 | 2019-01-27  5:13:00 PM  |      0 |
+--------+--------+-------------------------+--------+

Current Result
+--------+----------+-------+
| UserId | Username | Value |
+--------+----------+-------+
|      1 | JaneDoe  |  5367 |
|      2 | JohnDoe  |   552 |
+--------+----------+-------+

Expected Result
+--------+----------+-------+
| UserId | Username | Value |
+--------+----------+-------+
|      1 | JaneDoe  |  3737 |
|      2 | JohnDoe  |  1064 |
+--------+----------+-------+

I was able to get the expected result with the following statement by selecting the SUM from a subquery and hardcoding the UserId.
SELECT SUM(`x`.`Points`) FROM
(SELECT `Points`
    FROM `Game`
    WHERE `Game`.`UserId` = 1 AND
    `Game`.`StartDate` > STR_TO_DATE('01/09/2019', '%m/%d/%Y') AND `Game`.`StartDate` < STR_TO_DATE('02/09/2019', '%m/%d/%Y')
    GROUP BY `Game`.`StartDate`
    ORDER BY `Game`.`Points` ASC) AS `x`;

When I try to put that statement in a subquery like in the following statement, I get this error message Error Code: 1054. Unknown column 'User.UserId' in 'where clause'. I'm getting this error because the UserId isn't visible in the second subquery.
SELECT `User`.`UserId`, `User`.`Username`,
        (SELECT SUM(`x`.`Points`) FROM (SELECT `Game`.`Points`
            FROM `Game`
            WHERE `Game`.`UserId` = `User`.`UserId` AND
            `Game`.`StartDate` > STR_TO_DATE('01/09/2019', '%m/%d/%Y') AND `Game`.`StartDate` < STR_TO_DATE('02/09/2019', '%m/%d/%Y')
            GROUP BY `Game`.`StartDate`
            ORDER BY `Game`.`Points` DESC) AS `x`
        ) AS `Value`
    FROM `User`
    ORDER BY `Value` DESC, `User`.`Username` ASC;

A:

I changed the query to use LEFT JOIN on Game. I also added GROUP BY 'Game'.'UserId', 'Game'.'StartDate' and GROUP BY 'User'.'UserId'.
CREATE PROCEDURE `spGetPoints`(
    IN _StartDate DATETIME,
    IN _EndDate DATETIME,
    IN _Limit INT,
    IN _Offset INT
)
BEGIN
    SELECT `User`.`UserId`, `User`.`Username`,
        SUM(`Game`.`Points`) AS `Value`
        FROM `User`
        LEFT JOIN (SELECT *
            FROM `Game`
            WHERE `Game`.`StartDate` > _StartDate AND `Game`.`StartDate` < _EndDate
            GROUP BY `Game`.`UserId`, `Game`.`StartDate`
            ORDER BY `Game`.`Points`
        ) AS `Game` ON `User`.`UserId` = `Game`.`UserId`
        GROUP BY `User`.`UserId`
        ORDER BY `Value` DESC, `User`.`Username` ASC
        LIMIT _Limit OFFSET _Offset;
END

This link also helped. Select first row in each GROUP BY group?


Q:

Calling images in another directory

I'm really not sure what the fancy jargon for this stuff is so Im sorry if I dont use the right terminology.
Im working with a script where the images are located in a subdirectory than where the html is located.
This is the snippet of code:
eval("document.hm.src=\"hm" + wrong_guesses + ".gif\"");

In the world of html the image path would normally look like: games/word/hm01.gif
How do I modify that line of javascript to reflect that the images are in the subdirectory? I'm lost and I'm sure it's something simple but I'm not a programmer, I just lightly tweak stuff :\

A:

It would be : eval("document.hm.src=\"games/word/hm" + wrong_guesses + ".gif\"");.
Hope it helps.


Q:

Question on upper bounds of two numbers

If $a =5000$ to $1$ significant figure and $b=400$ to $1$ significant figure, calculate:
the upper bound of $$a-b$$
I thought the answer would be $5500 - 350 = 5150$ but the answers say it is $5750$; which is right?

A:

So a=5000 to 1 significant figure. By definition, this is $a\in [4500,5500)$. The same holds for $b$, i.e. $b\in [350,450)$.
Now we want an upper bound for $a-b$. As $a$ has a positive sign, we need to consider the biggest value of $a$ which is $a_{max} = 5500$. As $b$ has a negative sign, we need the least value of $b$, i.e. $b_{min} = 350$. Thus, $$a-b \leq a_{max} - b_{min} = 5150.$$
I think you were right, if my definition of significant figure is the right one.


Q:

BigQuery GUI - CPU Resource Limit

Is there a way to set the CPU Resource Limit on the BigQuery with Python and GUI?
I'm getting an error of:
Query exceeded resource limits. 2147706.163729571 CPU seconds were used, and this query must use less than 46300.0 CPU seconds.

Looking at the BigQuery's Python reference page: http://google-cloud-python.readthedocs.io/en/latest/bigquery/reference.html
It looks like there's:
1. maximum_billing_tier
2. maximum_bytes_billed

That can be set, but there is no CPU second options.

A:

You cannot set anymore maximum_billing_tier - it is obsolete and as soon as you are lower than tier 100 you are billed as if it were 1. if you exceed 100 - query just failes.
As of CPU - check concept of slots

Maximum concurrent slots per project for on-demand pricing — 2,000
  The default number of slots for on-demand queries is shared among all queries in a single project. As a rule, if you're processing less than 100 GB of queries at once, you're unlikely to be using all 2,000 slots.
To check how many slots you're using, see Monitoring BigQuery Using Stackdriver. If you need more than 2,000 slots, contact your sales representative to discuss whether flat-rate pricing meets your needs.

See more at https://cloud.google.com/bigquery/quotas#query_jobs


Q:

javascript multiple conditions don't work

I have a dropdown list ,every option of the list have a year and a month .
I want to sort a select options according to year or month or both that are  .
so I can display options sorted by year or month or year and month together or show everything .
I have the following event :
     $('#years,#months').bind('change', function () {
         y = $('#years').val();
         m = $('#months').val();
         $('#files > option').each(function () {
             $(this).show();
         });
         $('#files > option').each(function () {
             string = $(this).text();
              //first situation
             if (y == 'All' && m == 'All')
                $(this).show();
            // second situation
             else if ((y == 'All') && string.indexOf(m) == -1)
                    $(this).hide();
            //third situation
             else if ( string.indexOf(y) == -1 && m == 'All')
                  $(this).hide();
             // fourth situation
             else if (string.indexOf(y) == -1 || string.indexOf(m) == -1)
               $(this).hide();
         });
     });

with html code :
<select id='years'>
    <option value='All'>All</option>
    <option value='2013'>2013</option>
    <option value='2012'>2012</option>
</select>
<select id='months'>
    <option value='All'>All</option>
    <option value='Feb'>Feb</option>
    <option value='Jan'>Jan</option>
</select>

<select id='files' siz='10'>
    <option value='0'>sdgsdfsadfsd1-2013-Feb-1212</option>
    <option value='1'>fsadfadsfadsfadsf2-2012-Feb-123123</option>
    <option value='2'>fsadfadsfadsfadsf3-2012-Jan-123123</option>
    <option value='3'>fsadfadsfadsfadsf4-2013-Jan-123123</option>
    <option value='4'>fsadfadsfadsfadsf5-2012-Feb-123123</option>
    <option value='5'>fsadfadsfadsfadsf6-2013-Feb-123123</option>
    <option value='6'>fsadfadsfadsfadsf7-2013-Feb-123123</option>
    <option value='7'>fsadfadsfadsfadsf8-2013-Jan-123123</option>
    <option value='8'>fsadfadsfadsfadsf9-2012-Jan-123123</option>
    <option value='9'>fsadfadsfadsfadsf10-2013-Feb-123123</option>
    <option value='10'>fsadfadsfadsfadsf11-2012-Feb-123123</option>
</select>

second and third situations are not working !!
it deals with the two conditions (true && false) , (false && true ) as they are same values ! I have no idea why !
here's a Demo

A:

Your logic is wrong; the last condition is being evaluated when it shouldn't be. (For instance: if y == 'All' and also string.indexOf(m) >= 0). Try this instead:
$('#files > option').each(function () {
    var string = $(this).text();
    var show;
    if (y == 'All') {
        show = m == 'All' || string.indexOf(m) >= 0;
    } else if (m == 'All') {
        show = string.indexOf(y) >= 0;
    } else {
        show = string.indexOf(y) >= 0 && string.indexOf(m) >= 0;
    }
    if (show) $(this).show();
    else $(this).hide();
});


Q:

RecyclerView not showing anything, although there not seem to be any problems

I am a bit comfused at this moment. In order to save time I used Android Studio's template for Navigation Drawer Activity. I was planning to create a Navigation Drawer and pass it through the rest of the activities. The first Activity did go well. The problem is with the second one, as I want to have the Navigation Drawer and create a RecyclerView.
So my code is:
Content_main2.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context="com.sparrowred.sendcard.Main2Activity"
    tools:showIn="@layout/activity_main2">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/imageRecycleView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:scrollbars="vertical">
    </android.support.v7.widget.RecyclerView>

</RelativeLayout>

app_bar_main2.xml:
<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout 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"
    android:fitsSystemWindows="true"
    tools:context="com.sparrowred.sendcard.Main2Activity">

    <android.support.design.widget.AppBarLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="?attr/colorPrimary"
        app:popupTheme="@style/AppTheme.PopupOverlay" />

    </android.support.design.widget.AppBarLayout>

    <include layout="@layout/content_main2" />

    <android.support.design.widget.FloatingActionButton
        android:id="@+id/fab"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|end"
        android:layout_margin="@dimen/fab_margin"
        android:src="@android:drawable/ic_menu_add" />

</android.support.design.widget.CoordinatorLayout>

nav_header_main2.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="@dimen/nav_header_height"
    android:background="@drawable/side_nav_bar"
    android:gravity="bottom"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:theme="@style/ThemeOverlay.AppCompat.Dark">

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:paddingTop="@dimen/nav_header_vertical_spacing"
        android:src="@android:drawable/sym_def_app_icon" />

    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingTop="@dimen/nav_header_vertical_spacing"
        android:text="Android Studio"
        android:textAppearance="@style/TextAppearance.AppCompat.Body1" />

    <TextView
        android:id="@+id/textView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="android.studio@android.com" />

</LinearLayout>

activity_main2.xml:
<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout 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:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:openDrawer="start">

    <include
        layout="@layout/app_bar_main2"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <android.support.design.widget.NavigationView
        android:id="@+id/nav_view"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:fitsSystemWindows="true"
        app:headerLayout="@layout/nav_header_main"
        app:menu="@menu/activity_main_drawer" />

</android.support.v4.widget.DrawerLayout>

image_list_row:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:focusable="true"
    android:paddingLeft="16dp"
    android:paddingRight="16dp"
    android:paddingTop="10dp"
    android:paddingBottom="10dp"
    android:clickable="true"
    android:background="?android:attr/selectableItemBackground">

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:padding="8dp"
        android:contentDescription="@string/image_descrprtion"
        android:layout_gravity="center_horizontal"
        android:id="@+id/imageId"
        android:src="@drawable/profile"/>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/title"
        android:textStyle="bold"
        android:padding="8dp"
        android:layout_gravity="center_horizontal"
        android:text="dummy"/>

</LinearLayout>

imageAdapter.java:
package com.sparrowred.sendcard;

public class imageAdapter {
    private String title;
    private int imageId;

    public imageAdapter() {
    }

    public imageAdapter(String title, int imageId) {
        this.title = title;
        this.imageId = imageId;
    }

    public void setTitle(String title){
        this.title = title;
    }

    public String getTitle(){
        return this.title;
    }

    public void setImageId(int imageId){
        this.imageId = imageId;
    }

    public int getImageId(){
        return this.imageId;
    }
}

imageDescriptionArray.java (I need to change the name :P):
package com.sparrowred.sendcard;

import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import java.util.List;

public class imageDescriptionArray extends RecyclerView.Adapter<imageDescriptionArray.MyViewHolder> {

    private LayoutInflater layoutInflater;
    private List<imageAdapter> imageAdapterList;

    public imageDescriptionArray(List<imageAdapter> imageAdapterList) {
        this.imageAdapterList = imageAdapterList;
    }

    @Override
    public MyViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View itemView = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.image_list_row, parent, false);

        return new MyViewHolder(itemView);
    }

    @Override
    public void onBindViewHolder(MyViewHolder holder, int position) {
        imageAdapter iva = imageAdapterList.get(position);
        holder.title.setText(iva.getTitle());
        holder.image.setImageResource(iva.getImageId());
    }

    @Override
    public int getItemCount() {
        return imageAdapterList.size();
    }

    public class MyViewHolder extends RecyclerView.ViewHolder {
        public TextView title;
        public ImageView image;

        public MyViewHolder(View view) {
            super(view);
            title = (TextView) view.findViewById(R.id.title);
            image = (ImageView) view.findViewById(R.id.imageId);
        }
    }

}

and finally Main2Activity.java:
package com.sparrowred.sendcard;

import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.support.design.widget.NavigationView;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.ViewGroup;

import java.util.ArrayList;
import java.util.List;

import jp.wasabeef.recyclerview.animators.SlideInUpAnimator;

public class Main2Activity extends AppCompatActivity
    implements NavigationView.OnNavigationItemSelectedListener {

    private RecyclerView mImageRecycleView;
    private List<imageAdapter> imageAdapterList;
    private imageDescriptionArray mAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.fab);
        fab.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            }
        });

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
                this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.setDrawerListener(toggle);
        toggle.syncState();

        NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setNavigationItemSelectedListener(this);

        mImageRecycleView = (RecyclerView) findViewById(R.id.imageRecycleView);
        mImageRecycleView.setHasFixedSize(true);
        imageAdapterList = new ArrayList<>(12);
        mAdapter = new imageDescriptionArray(imageAdapterList);
        LinearLayoutManager mLayoutManager = new  LinearLayoutManager(this);
        mLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        mImageRecycleView.setLayoutManager(mLayoutManager);
        mImageRecycleView.setItemAnimator(new SlideInUpAnimator());
        mImageRecycleView.setAdapter(mAdapter);
        prepareData();
    }

    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main2, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();

        if (id == R.id.nav_camera) {
            // Handle the camera action
        } else if (id == R.id.nav_gallery) {

        } else if (id == R.id.nav_slideshow) {

        } else if (id == R.id.nav_manage) {

        } else if (id == R.id.nav_share) {

        } else if (id == R.id.nav_send) {

        }

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }

    private void prepareData(){
        List<imageAdapter> data = new ArrayList<>();
        int[] images = {R.drawable.birthday_image_1,R.drawable.birthday_image_2,R.drawable.birthday_image_3,R.drawable.birthday_image_4,
              R.drawable.birthday_image_5,R.drawable.birthday_image_6,R.drawable.birthday_i    mage_7,R.drawable.birthday_image_8,
               R.drawable.birthday_image_9,R.drawable.birthday_image_10,R.drawable.birthday_    image_11,R.drawable.birthday_image_12};
        String[] description = {"ballons","a lot of cakes","ballons with cakes","presents","presents with hat","cup-cake",
                "retro","perspective","flying presents","empty card","giving a present","tasty cake"};
        for(int i = 0; i<images.length && i<description.length; i++){
            imageAdapter current = new imageAdapter();
            current.setTitle(description[i]);
            current.setImageId(images[i]);
            data.add(current);
        }
        mAdapter.notifyDataSetChanged();
    }
}

This the code for my second activity.It's not fully implemented but for sure the recyclerView doesn't work. Can anyone help me out with this. I believe that the problem is within my xmls .... but I cannot find anything.
PS. My code, when compiled shows no errors....

A:

Try with the following code. Replace your prepareData() with mine
private void prepareData(){

    int[] images = {R.drawable.birthday_image_1,R.drawable.birthday_image_2,R.drawable.birthday_image_3,R.drawable.birthday_image_4,
          R.drawable.birthday_image_5,R.drawable.birthday_image_6,R.drawable.birthday_i    mage_7,R.drawable.birthday_image_8,
           R.drawable.birthday_image_9,R.drawable.birthday_image_10,R.drawable.birthday_    image_11,R.drawable.birthday_image_12};
    String[] description = {"ballons","a lot of cakes","ballons with cakes","presents","presents with hat","cup-cake",
            "retro","perspective","flying presents","empty card","giving a present","tasty cake"};
    for(int i = 0; i<images.length && i<description.length; i++){
        imageAdapter current = new imageAdapter();
        current.setTitle(description[i]);
        current.setImageId(images[i]);
        imageAdapterList.add(current);
    }
    mAdapter.notifyDataSetChanged();
}


Q:

How to order chicken at the supermarket?

If I'm at the supermarket and want to order a piece of chicken breast, do I say

Ich möchte ein stück Hähnchen bitte.

A:

If I would sell chicken and parts of chicken, and you say to me:

Ich hätte bitte gerne ein Stück Hähnchen/Huhn.
  I'd like to have a piece of chicken.

Then I would ask you:

Was für ein Stück?
  Which piece?

Because I would think you don't want a whole chicken, but just a part of it, but you didn't tell me if you want a leg, a wing, a breast or whatever.
If you want a whole chicken, order it like this:

Ich hätte bitte gerne ein Huhn.
  I'd like to have a chicken, please.

or, even better, and to make it sure:

Ich hätte bitte gerne ein ganzes Huhn.
  I'd like to have a whole chicken, please.

You also can order a half chicken:

Ich hätte bitte gerne ein halbes Huhn.
  I'd like to have half of a chicken, please.

If you want one complete breast, order it this way:

Ich hätte bitte gerne eine Hühnerbrust.
  I'd like to have one breast of a chicken, please.

Maybe you want just 100 grams of the chicken breast:

Ich hätte bitte gerne 100 Gramm Hühnerbrust.
  I'd like to have 100 grams of chicken breast, please.

Addendum
I give you some more information about Huhn/Hähnchen/Hendl/Güggeli. (You did not ask for it, but maybe you want to know it if you travel to Austria or Switzerland)
The female adult chicken is called »Henne«, and the adult male chicken is called »Hahn«. Since chicken are small animals, you often use a diminutive. But the diminutive is built different in different regions:
Austria and Bavaria:
In Austria, the diminutive is built from the female name, and there is a kind of dimutive that is only used in Austria and Bavaria: You add »erl« to the noun to build the diminutive (Sack -> Sackerl, Krug -> Krügerl, Kind -> Kinderl), and so you get: »Henderl«. But due to sloppy speaking, the e and the r got lost, only the l is left, and so Chicken is in Austria and southern parts of Germany (Bavaria):

das Hendl

Germany, north of Bavaria:
In Germany the diminutive is built from the male form, by adding »chen« to the noun. This a way of building diminutives, that is used everywhere where German is spoken. So in most parts of Germany it is:

das Hähnchen

Switzerland:
In Switzerland you will find a very different word, that also is a diminutive (Swiss and Swabian style diminutive: adding li to the noun), but derived from an old and outdated Swizz word for Chicken (»Gugg«). But this diminutive is only used for roast chicken. It is:

das Güggeli

Note, that all three diminutives are used for male and female chicken, although the Austrian and German variations are derived from words for just one of both genders.
Note also, that all this words are not dialect words, but part of standard German, but with regional usage (there are many of such regional variations in standard German).
Everywhere:
If you want to be understood everywhere, don't use a diminutive for chicken. You'd better use the normal noun for chicken of any biological gender instead:

das Huhn

A:

"Stück" needs to be uppercase because it's a noun, and if you specifically want chicken breast, it's "Hähnchenbrust". Also, the "bitte" should be separated by a comma because it's not an actual part of the main clause. These three are pretty minor mistakes though (two of them inaudible), so your order would be well understood already. This is the correct version:

Ich möchte ein Stück Hähnchenbrust, bitte.

For even more politeness (yours is already polite enough, don't worry), you could also say:

Ich hätte gerne ein Stück Hähnchenbrust, bitte.

A:

That depends on what exactly you want to order, I usually go with

Ich hätte gern x Gramm Hähnchenbrust, bitte.


Q:

Best practice for lining up PHP syntax in HTML page

I'm using Codeigniter but this goes for any project in PHP. Let's say I have the following code in my view. I've been struggling, trying to figure out how best to indent and display PHP code within standard HTML code.
...
...

    <?php
        if ($this->session->flashdata('message')) {
            ...
            ...
    ?>

            ...
            ...

    <?php
        }
    ?>

So notice how I nested HTML within the PHP code by escaping w/ the PHP syntax. This can get out of hand if you have lines and lines of code. I'm using Komodo and I've enabled "Indentation Guidelines" but even with that, most of my code doesn't line up. So my question is, how best to handle this?
I've actually resorted to keeping the PHP marker <?php ?> to the far left and not indenting them. Seems to work so far ...

A:

You can use other kind of syntax:
...
...

    <?php if ($this->session->flashdata('message')): ?>

            ...
        ...

    <?php endif; ?>

So, <?php ?> can be in 1 line and I think it's beauty:)
Anyway, There are no any 'right' way to do it. You can(and should) choose your own one


Q:

textbox is stretching and moving upside once we click on button

please visit link
this is e commerce site where we can buy products.
please click on "Add to cart" button , than you can see :

this is cloth product, we have to select "color" and "charactar" first than we have to click on "add to cart" .
if we select "color" and "charactar" first, than there will be no problem. but if we click directly on Add to cart than only problem, textbox next to "color" will stretch and move little upside.
What i want is if we click on "Add to cart"  directly than also it should display as like before only [css part ]

A:

You will need to do the following changes to the styles.css
line no: 282
.validation-advice { clear:both; min-height:13px; margin:5px 0; padding-left:13px; padding-top:2px; line-height:13px; background:url(../images/validation_advice_bg.png) 0px 3px no-repeat; color:#e70808; float:left; width:70%; text-align:left}

line no: 1953 where the comments are /vikas/
  #product-options-wrapper dl dt {
       display: inline-block;
      margin-top: 13px;
  }

 #product-options-wrapper dl dd {
   display: inline-block;
   vertical-align: top;
  }

 #product-options-wrapper dl dd { width: 35%; }

line no: 1036
.product-options dd select { /*width:100%;*/ margin-bottom:5px; height:auto}

Let me know if this works for you.
Happy Coding...


Q:

What is the right way to compare two strings in SoapUI with groovy script assertion?

I need to compare two strings in SoapUI. The first one is from a text file stored in my local directory, and the second one is from an XML response I get from a REST API operation. Before comparing the two strings, I use some methods on them to remove the header because they contain information like Dates and Processing Time which is sure to be different each time.
Below is what I've tried.
def xml = messageExchange.responseContentAsXml
String fileData = new File("C://Users/362784/project/outputPGB123.txt").text

String responseContent = new XmlSlurper().parseText(xml)

String fileDataFiltered = fileData.substring(fileData.indexOf("PASSED :"))
String responseContentFiltered = responseContent.substring(responseContent.indexOf("PASSED :"))

log.info(fileDataFiltered)
log.info(responseContentFiltered)

assert fileDataFiltered == responseContentFiltered

Here is the error I received
SoapUI error message
and my two identical log.info
log.info
Here's what the XML response looks like
I am new to SoapUI and I'm not sure what those two are actually comparing but I've checked the log.info of them on https://www.diffchecker.com/diff and the contents are identical. However, this assertion returns an error.
Can anyone point out what I did wrong and how do I get the result as passed?

A:

In Java/Groovy you compare string values for equality like this:
assert fileDataFiltered.equals(responseContentFiltered)

See if that solves your problem.
The == comparator could, for example, compare object instances which could fail even if the text values are identical. See here for a more in-depth explanation.
EDIT:
Having seen your sample, it looks like the value you are comparing is inside XML character data (CDATA).
Consider the following example from here:
Some XML:
def response = '''<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"
   xmlns:sam="http://www.example.org/sample/">
   <soapenv:Header/>
   <soapenv:Body>
      <sam:searchResponse>
         <sam:searchResponse>
            <item><id>1234</id><description><![CDATA[<item><width>123</width><height>345</height><length>098</length><isle>A34</isle></item>]]></description><price>123</price>
            </item>
         </sam:searchResponse>
      </sam:searchResponse>
   </soapenv:Body>
</soapenv:Envelope>
'''

Then access the CDATA node with XmlSlurper:
def Envelope = new XmlSlurper().parseText(response)
def cdata = Envelope.Body.searchResponse.searchResponse.item.description
log.info cdata
log.info cdata.getClass()
assert cdata instanceof groovy.util.slurpersupport.NodeChildren

As you can see, the value returned is of object NodeChildren. You can convert it to a string with:
log.info cdata.toString()
log.info cdata.toString().getClass()

So let's do a comparison (as per cfrick's comment, you can use == or .equals())
def expectedCdata = '<item><width>123</width><height>345</height>length>098</length><isle>A34</isle></item>'

if (cdata.toString().equals(expectedCdata)) { log.info 'Equal' }
else {log.info 'Different'}

It still fails ???
Well, that is because of a residual newline that isn't obvious from printing with log.info, if you remove whitespace it works in this case:
if (cdata.toString().replaceAll("\\s","").equals(expectedCdata)) { log.info 'Equal' }
else {log.info 'Different'}

As you can see, there are many levels of possible failure. You have to work through it.


Q:

Using scanf to read a file in C

I'm in my first-ever class about C, and I'm having some trouble with a program we're writing. Here's the program:
#include <stdio.h> //printf
#include <stdlib.h>

//Prototypes
void readScores(int* scores, int* actualCount);
void displayScores(int* scores, int* actualCount);

int main() {
int arrayCount = 100;
int scores[arrayCount];
int actualCount = 0;

readScores(scores, &actualCount);
displayScores(scores, &actualCount);
}

void readScores(int* scores, int* actualCount) {
    for(int i = 0; i <= 10; i++) {
    *actualCount = *actualCount + 1;
    scanf("%d", scores);
    }
}

void displayScores(int* scores, int* actualCount) {
    for(int i = 1; i < *actualCount; i++) {
        printf("score %d: \t%d\n", i, *scores);
    }
}

My goal is to simply read scores from the scores.txt text file and add them to the scores[] array. Our goal in this assignment is to learn more about pointers, so don't bother trying to make my code more "efficient" or anything.
My problem is that when I compile the code with
gcc histogram.c -std=c99 -o histogram

and run it with
./histogram <scores.txt

my output looks like this:
score 1: 7
score 2: 7
score 3: 7
score 4: 7
score 5: 7
score 6: 7
score 7: 7
score 8: 7
score 9: 7
score 10: 7

How can I modify my code so that it reads the text file correctly? This problem has been bothering me all week and a solution would be much appreciated!
Thanks!

A:

Since scores is an array, you can use more than the first element:
void readScores(int* scores, int* actualCount) {
    for(int i = 0; i <= 10; i++) {
    *actualCount = *actualCount + 1;
    scanf("%d", scores + i);  // Read into element i of array scores
    }
}

void displayScores(int* scores, int* actualCount) {
    for(int i = 1; i < *actualCount; i++) {
        printf("score %d: \t%d\n", i, *(scores + i));  // Print element i of array scores
    }
}


Q:

Difference between "remedy", "heal", "cure" and "treat"

These words relates to Health category. I think these words are really confusing and I don't know how to use them correctly. Can you show me what are the differences between these words?

A:

These terms are used with more precision by healthcare professionals than by the general public.  The dictionary definitions reflect general usage of the terms.
Remedy as a noun is often applied to health, but the verb isn't commonly used in that context.  It means to relieve a problem, which is very imprecise if you apply it to health matters.
Heal and cure are related:
Heal: to make free from injury or disease; to make sound or whole; to restore to health
Cure: to restore to health, soundness, or normality; to bring about recovery from a disease
Heal and cure refer to the patient, although "cure" is often used in the broad sense of eradicating a class of illness from the population at large, like "curing cancer".  But if a person has an illness, you cure the patient, not the illness.
Also note that heal and cure refer to accomplishing the result rather than the nature of the process.  The "curing" or "healing" done by the doctor might be little more than keeping you comfortable while your own body does the work, but they are said to have cured or healed you because they provided the conditions to bring about recovery.
The difference between the terms focuses on the nature of the problem.  Health problems that are not based on a deficiency of something the body needs (and can be fixed by providing that), are broadly categorized as injury or disease.  Injury is physical damage.  Disease is a condition that impairs normal functioning.  This isn't medical school, so I won't get into the weeds with rigorous definitions.
"Cure" refers to disease (you don't cure injury).  In common usage, "heal" is applied to disease or injury, but it more accurately applies to injury or the physical manifestations of a disease.
Treat means to care for or deal with medically or surgically, or give medical care or attention to; try to heal or cure..
It refers to the application of treatments, not the results.  Again, you treat the patient, not the problem.  In common usage, people say things like "treat a cold" or "treat a broken arm", but that's shorthand for treating a patient for a cold or for a broken arm.  There is no guarantee that treatment will result in healing or cure.


Q:

AngularJS ng-click Directive Not Calling Function

I'm trying to use ng-click to call a function in my controller, but I haven't been able to get that to work. I've stripped everything down to its simplest form, so that I now have this:
<button id="submitBtn" type="submit" class="btn btn-default"
  ng-click="count = count + 1; count = count + 2; alert('hello');" >Submit</button>

The first two statements (count = count + 1; count = count + 2;) execute just fine, but it won't call the alert function. When I take out the two count incrementing statements, the alert still won't work. Anytime I try to call a function, it fails, but plain old Javascript works.
(Just an FYI, I have Javascript down the page that prevents the form from submitting and triggering a postback).
Edit:
I'll include my controller's code for this:
myApp.controller('LawSearchController', ['$scope', function ($scope) {

    $scope.alert = function (text) {
        alert(text);
    };
}]);

A:

All functions you call in an ng-expression are in the context of $scope.
So when you say alert() it compiles to scope.alert() which is undefined, and fails silently.
In your controller, include the code
$scope.alert = alert


Q:

Conditional Logic to show or hide fields in the admin?

I'm looking for a way to show or hide fields when editing an entry based on items selected.
I need to manage a list of businesses and my plan is to have a channel to hold them all. But based on the type of business, there are different pieces of information I need to collect.

They all have common attributes (Name, Description, Location, Phone, etc.)
There are many types (Restaurant, Recreation, Venue, etc.)

Many types have subtypes, but not all (Restaurant: American, Chinese, Casual)
Some have additional Info based on their type (Venu includes a list of meeting rooms with Names, Dimensions, Amenities, etc.)
Businesses can have more than one type (Restaurant, Venu)

What I'd like to do is be able to show different sets of inputs based on what categories are selected.

Check Restaurant

Reveal a list of Restaurant types, because that is relevant only to restaurants.

Check Venue

Reveal a table field type so you can enter a list of room names with corresponding features and amenities.

Is there a way in Craft, or is there a plugin that lets you run logic based on inputs to show or hide other inputs?

A:

Check out the Reasons plugin... sounds like exactly what you need:

https://github.com/mmikkel/Reasons-Craft/


Q:

Unable to move element from one parent to another in magento 2.1 layout

I am trying to move minicart-wrapper into page-wrapper, right now it is in the parent(header). What i have done so far,

Path where i am over riding magento core module in my extended theme, my parent theme is luma:

Magento/app/design/frontend/classic/classic_theme/Magento_Checkout/layout/default.xml
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>
        <move element="minicart.wrapper" destination="page.header" after="-"/>
    </body>
</page>

Path of the default module that i am over riding in my theme:
  Magento/vendor/magento/module-checkout/view/frontend/layout/default.xml

I am following this (Rearrange elements)
http://devdocs.magento.com/guides/v2.0/frontend-dev-guide/layouts/xml-manage.html
I am confused how if they are referring to element by class or something else. I am doing it using class in my code.
Please help!!! Thanks in advance.

A:

check

../app/code/Magento/Checkout/view/frontend/layout/default.xml

here you find:
<block class="Magento\Checkout\Block\Cart\Sidebar" name="minicart" as="minicart" after="logo" template="cart/minicart.phtml">

I suspect this is the element you want to move.
To find the element you want it to move to check:

../app/code/Magento/Checkout/view/frontend/page_layout/checkout.xml

Here you will find the element:
<layout xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_layout.xsd">
    <update handle="empty"/>
    <referenceContainer name="page.wrapper">
        <container name="checkout.header.container" as="checkout_header_container" label="Checkout Page Header Container" htmlTag="header" htmlClass="page-header" before="main.content">
            <container name="checkout.header.wrapper" label="Checkout Page Header" as="checkout_header_wrapper" htmlTag="div" htmlClass="header content"/>
        </container>
    </referenceContainer>
</layout>

So you should be able to change it like:
<?xml version="1.0"?>
<!--
/**
 * Copyright © 2013-2017 Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */
-->
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>
        <move element="minicart" destination="checkout.header.container" />
    </body>
</page>

How I found the elements generally speaking:
You can enable layout hints in the admin backend. But I never found this useful so far.
So typically I just search in my IDE over all of the magento source code for some unique element like ie. a html class name or similar. You will then often find the code either in a layout xml, phtml or html.
If you found it in xml it should be simple to see the name of the element where the htmlClass is set.
If it's in an html or phtml file you need to search this file name in the layout(.xml) instruction files so you can find at what element it is attached. That gives you the element name then you can use for further actions.
To finally see if I got the right element I add a remove instruction into the appropriate layout file.


Q:

How to set custom template for HTML formatter in Behat

I tried in my behat.yml and put the template inside my /support dir, but no help.
    default:
      formatter:
        name:  html
        parameters:
          template_path: html.tpl

Any ideas?

A:

You can extend a custom class from the existing HtmlFormatter to explicitly set your html template.
PHP
namespace Behat\Behat\Formatter;
use Behat\Behat\Formatter\HtmlFormatter;

class MyHtmlFormatter extends HtmlFormatter {

    /**
     * The HTML template to use for formatting.
     * @return string
     */
    protected function getHtmlTemplate()
    {
        return '
          <div id="behat">
            {{content}}
          </div>
        ';
    }

    // You can override any other methods of HtmlFormatter that you want
    // to define custom behavior.
}

Then update your behat.yml file to point to your custom class.
behat.yml (Optional - Only needed if you don't use --format in your behat command line.)
default:
    formatter:
        name: Behat\Behat\Formatter\MyHtmlFormatter

Behat
Finally, run behat with the following command:
behat --out out.html your_feature.feature

If you want to specify this formatter directly then do:
behat --format Behat\\Behat\\Formatter\\MyHtmlFormatter --out o.html

Note that you need the \\ to properly send the class name.


Q:

Constructing Proxy type given the input

Given the code below which looks up type-specific information in Data.HashMap for a type, is it possible to define a new function getMapVal2 as documented in the comments, to build the TypeKey argument given the type?
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE DataKinds #-}

import Data.Monoid ((<>))
import Data.Proxy (Proxy(Proxy))
import GHC.TypeLits (KnownSymbol, Symbol, symbolVal)
import qualified Data.HashMap.Strict as Map (HashMap, empty, insert, lookup)
import Data.Dynamic
import GHC.Generics
import Data.Maybe (fromJust, isNothing, maybe)

type family TypeKey (a :: *) :: Symbol where
    TypeKey Int = "int"
    TypeKey T = "trec"

data T = T { aInt :: Int} deriving (Show, Generic, Typeable)

extract ::(s ~ TypeKey a, Typeable a, KnownSymbol s) => Maybe Dynamic -> Maybe a
extract dyn = if (isNothing dyn) then Nothing else fromDynamic . fromJust $ dyn

getMapVal :: (s ~ TypeKey a, Typeable a, KnownSymbol s) => Map.HashMap String Dynamic -> String -> Maybe a
getMapVal m k = extract $ Map.lookup k m

{-- How do we get the TypeKey lookup for type a?
getMapVal2 :: (s ~ TypeKey a, Typeable a, KnownSymbol s) => Map.HashMap String Dynamic -> a -> Maybe a
getMapVal2 m ty = extract $ Map.lookup (symbolVal (Proxy :: Proxy (TypeKey ???))) m
--}

main = do
  let map = Map.insert (symbolVal (Proxy :: Proxy (TypeKey T))) (toDyn $ T {aInt=5}) Map.empty -- we insert some value in hashmap for type T - it is of same type
      val = getMapVal map (symbolVal (Proxy :: Proxy (TypeKey T))) :: Maybe T -- now let us retrieve the value in map for Type T. We pass the SymbolVal ourselves
    --val =  getMapVal2 map (T {aInt = 2}) -- now we want to lookup map value given something of a type T. Need getMapVal2 to build symbolval given the input type
  print $ maybe "" show val -- prints value stored in Hashmap for type T which is: T {aInt=5}

This is just a toy code to test passing type specific configuration at run-time via Data.HashMap to a polymorphic function that acts on types of a typeclass.

A:

Use the ScopedTypeVariables extension. This allows you to refer to forall-bound type variables in the body of the definition in which they are bound.
{-# LANGUAGE ScopedTypeVariables #-}

getMapVal2 :: forall a s. (s ~ TypeKey a, Typeable a, KnownSymbol s) => Map.HashMap String Dynamic -> a -> Maybe a
getMapVal2 m ty = extract $ Map.lookup (symbolVal (Proxy :: Proxy (TypeKey a))) m


Q:

create a generic method that sorts List collections

What I used to do is create a case switch that sorts my LINQ in this format:
List<products> productList = GetAllLists();

switch (sortBy)
{
  case "name":
     return productsList.OrderBy(pl => pl.Name);
  case "date":
     return productsList.OrderBy(pl => pl.DateCreate);
}

which, in the long run, becomes cumbersome.
I wanted to have a generic method that you simply use to sort out List collections like these and will help you toggle which property to sort by.. something like this:
return SortListCollection(productsList, Name);

A:

You don't need to use reflection for this, you can do it using expression trees, which will be much faster. Here's a blog post that describes the process, but a cut'n'paste sample is:
public static IQueryable<T> SortBy<T>(this IQueryable<T> source, string propertyName)
{
    var parameter = Expression.Parameter(source.ElementType, String.Empty);
    var property = Expression.Property(parameter, propertyName);
    var lambda = Expression.Lambda(property, parameter);

    var methodCallExpression = Expression.Call(typeof(Queryable), "OrderBy",
        new Type[] { source.ElementType, property.Type },
        source.Expression, Expression.Quote(lambda));

    return source.Provider.CreateQuery<T>(methodCallExpression);
}

A:

Solved:
private List<T> SortList<T>(List<T> collection, SortOrder order, string propertyName) where T : class
        {
            if (order == SortOrder.Descending)
            {
                return collection.OrderByDescending(cc => cc.GetType().GetProperty(propertyName).GetValue(cc, null)).ToList();
            }

            return collection.OrderBy(cc => cc.GetType().GetProperty(propertyName).GetValue(cc, null)).ToList();
        }


Q:

iTextSharp - Merging a Batch of PDF Byte Arrays

I am using iTextSharp to fill a few fields on a pdf.  I need to be able to combine a series of these pdfs into one single batch pdf file.  Below I am looping through a SQL result set, filling the fields of the pdf with values corresponding to the current record, storing that as a byte array, and consolidating all of those into a list of byte arrays.  I am then attempting to merge each byte array in that list into a single byte array, and serve that as a pdf to the user.
It seems to work, generating a single file containing presumably as many individual pages as were in my result set, but with all the fields blank on each page.  It works as expected when using FillForm() to serve a single pdf.  What am I doing wrong?
byte[] pdfByteArray = new byte[0];
List<byte[]> pdfByteArrayList = new List<byte[]>();
byte[] pdfByteArrayItem = new byte[0];

foreach (DataRow row in results.Rows)
{
    certNum = row[1].ToString();
    certName = row[2].ToString();
    certDate = row[3].ToString();
    pdfByteArrayItem = FillForm(certType, certName, certNum, certDate);
    pdfByteArrayList.Add(pdfByteArrayItem);

}

using (var ms = new MemoryStream()) {
    using (var doc = new Document()) {
        using (var copy = new PdfSmartCopy(doc, ms)) {
            doc.Open();

            //Loop through each byte array
            foreach (var p in pdfByteArrayList) {

                //Create a PdfReader bound to that byte array
                using (var reader = new PdfReader(p)) {

                    //Add the entire document instead of page-by-page
                    copy.AddDocument(reader);
                }
            }

            doc.Close();
        }
    }

pdfByteArray = ms.ToArray();
context.Response.ContentType = "application/pdf";
context.Response.BinaryWrite(pdfByteArray);
context.Response.Flush();
context.Response.End();

private byte[] FillForm(string certType, string certName, string certNum, string certDate)
{
    string pdfTemplate = string.Format(@"\\filePath\{0}.pdf", certType);

    PdfReader pdfReader = new PdfReader(pdfTemplate);

    MemoryStream stream = new MemoryStream();
    PdfStamper pdfStamper = new PdfStamper(pdfReader, stream);

    AcroFields pdfFormFields = pdfStamper.AcroFields;

    // set form pdfFormFields
    pdfFormFields.SetField("CertName", certName);
    pdfFormFields.SetField("CertNum", certNum);
    pdfFormFields.SetField("CertDate", certDate);

    // flatten the form to remove editting options, set it to false
    // to leave the form open to subsequent manual edits
    pdfStamper.FormFlattening = false;

    // close the pdf
    pdfStamper.Close();
    stream.Flush();
    stream.Close();

    byte[] pdfByte = stream.ToArray();

    return pdfByte;
}

A:

Adding the line below after setting the value for the fields seems to have fixed it:
pdfFormFields.GenerateAppearances = true;


Q:

Volumetrics in a pixel shader

I have this shadertoy at:
                          https://www.shadertoy.com/view/4sVfz1
I seem to get most of the routines of volume ray marching but I am missing something in my ray marching function that computes transparency according to the accumulated density at a point.
Here is my ray marching function:
float ray( vec3 ro, vec3 rd, out float d, out float den )
{

    float t = 0.0; d = EPS; den = 0.0;

    for( int i = 0; i < STEPS; ++i )
    {

        vec3 p = ro + rd * t;
        d = 0.3 * map( p, den ).x;
        if( d < EPS || den > 1.0 || t > FAR ) break;
        t += d;
        den = fbm( p + TWA );
        den += clamp( den, -1.0, 0.0 ) * t * t;

    }

    return t;
}

A:

The proper ray marching function is this one:
float ray( vec3 ro, vec3 rd, out float den )
{

    float t = 0.0, maxD = 0.0; den = 0.0;

    for( int i = 0; i < STEPS; ++i )
    {

        vec3 p = ro + rd * t;

        den = map( p );
        maxD = maxD < den ? den : maxD;

        if( maxD > 0.99 || t > FAR ) break;

        t += 0.05;

    }

    den = maxD;

    return t;

}


Q:

String and char in Java

How can I take a return value which is a char, and check if the char is contained within a String?  I've been told that I should be able to work with the char as is, w/o converting to String. SO I have something like:
String answer = "JAVA IS THE BEST";
char guess = getUserInput(); //Returns a char
if (answer.contains(Character.toString(guess))){
    //DO SOMETHING
}

I was told this is "incorrect" and should be able to work with the char return value as is?!
Thanks

A:

you can use : str.contains(Character.toString(ch));
Since you do not want to convert the char to string, you can convert string to char Array and iterate through the array to search for the character.
 char[] strChars = str.toCharArray();
 for(char val : strChars)
 {
   if(val == ch)
    {
     // do something
    }
 }


Q:

Mangling sk_buff data in a Netfilter module

I am building a module that does massive mangling of the protocol contained within. I am only mangling Layer 4 packets. I convert them back on the other end to how they should be.  The packet size is still 1:1, so there really isn't a need to reallocate skb...
That said, I change skb->data, and then return NF_ACCEPT from my NF_IP_LOCAL_OUT hook. I have another hook that shows me that the sk_buff is passed to NF_IP_POST_ROUTING, but the packet never actually leaves the host (as in I don't see it in Wireshark).  I can't figure out what is going on. Is the packet being dropped somewhere? I am not using any other kernel hooks other than the netfilter hooks and I am not manipulating the destination, so it should leave the machine without question.
Any ideas what might be causing it?  Do I need to register my custom IPPROTO with the kernel?  I have it in /etc/protocols I figured that would be enough.  Or am I just going down the wrong path entirely?  I tried working with the ESP and AH code that's in the kernel for IPsec, since it also mangles the packets, but all the transform code is more complicated than I need for what I am doing.

A:

Resolution
It would seem I was doing everything correctly with a single exception. I wasn't recalculating the IP header's checksum (since I was changing the protocol id itself, this is mandatory).
Code
iph->check = 0;
iph->check = ip_fast_csum(iph, iph->ihl);

And presto it worked.


Q:

Problem with NSOrderedSet addObject when unarchiving from file

I have been searching everywhere on the web and trying everything that I can think of so far to no avail. Here is my problem:
In my program I have a class called Scale, Scale has several properties. The user can add scales to a tableView by clicking a button called addScale. When addScale is pressed, I add it to a OrderedMutableSet. I use the set to store the scales and prevent duplicate scales. I had to override the isEqual method and the Hash method to fool the computer into thinking that two Scales with the same properties are exactly the same. This works fine. But when I open the app and have had previously some scales in the tableView, I have archiving implemented so these scales reappear, as expected. This time, when addScale is pressed, I get an exception:
    -[__NSOrderedSetI addObject:]: unrecognized selector sent to instance 0x746dbf0
    2011-08-29 13:20:49.095 MusicLog[678:f203]
    *** Terminating app due to uncaught exception 'NSInvalidArgumentException',
    reason: '-[__NSOrderedSetI addObject:]: unrecognized selector sent to instance 0x746dbf0'

Here is the code for my isEqual method and my Hash method:
(tonic, mode, rhythm, octaves, and tempo are all ints)
- (NSUInteger)hash
{
    NSUInteger prime = 31;
    NSUInteger result = 1;
    result = prime * result + tonic;
    result = prime * result + mode;
    result = prime * result + rhythm;
    result = prime * result + octaves;
    result = prime * result + tempo;
    NSLog(@"%u", result);
    NSLog(@"%u", NSUIntegerMax);

    return result;
}

- (BOOL)isEqual:(Scale *)object
{
    if ((tonic == [object tonic])
        && (mode == [object mode])
        && (rhythm == [object rhythm])
        && (octaves == [object octaves])
        && (tempo == [object tempo]))
        return YES;
    else
        return NO;
}

Here is the code for my addScale method:
- (IBAction)addScale:(id)sender
{
    Scale *chosenScale = [[Scale alloc] init];
    [chosenScale setTonic:[myPicker selectedRowInComponent:0]];
    [chosenScale setMode:[myPicker selectedRowInComponent:1]];
    [chosenScale setRhythm:[myPicker selectedRowInComponent:2]];
    [chosenScale setOctaves:[octavesSegmentedControl selectedSegmentIndex] + 1];
    [chosenScale setTempo: (int) [tempoStepper value]];
    [[ScaleStore defaultStore] addScale:chosenScale];
}

the addScale method of the ScaleStore just calls addObject from a NSOrderedMutableSet which is where all the scales are stored.
Any help you can give is greatly appreciated.
Thank you,
K

A:

When you unarchive, the objects are restored to an immutable version (NSMutableSet becomes NSSet, NSMutableArray becomes an NSArray, etc.)
Just create a new NSOrderedMutableSet with objects from the restored set.


Q:

How can i check if the Look Up Field User is the Same user in the Specific Queue using Formula Field

Thanx for helping,
I have a specific scenario which is used in the Approval Process
I have a LookUp to the user called Project Manager
I wan to check if the Project Manager is the same as the User Reside in Queue I have only one user in the Queue
Is there any way I can check

A:

Not in pure process builder. You could query this data. Queues are a type of Group object in Salesforce and they have a related list of Group Members. So something like that:
SELECT Group.Name, UserOrGroupId
FROM GroupMember
WHERE Group.Type = 'Queue' AND Group.DeveloperName= 'X'

Or
SELECT Id, Name
FROM User
WHERE Id IN (SELECT UserOrGroupId FROM GroupMember WHERE Group.DeveloperName = 'X')

Should give you some ideas.
If you have a simple process maybe you're willing to rewrite it into Flow? Should support queries nicely. (personally I'm not a fan of flows but hey, it's a valid option)
Or if you want to keep it in Process you can have some success with writing small piece of apex and calling InvocableMethod.
Or make a checkbox or (multi)picklist with Queue names? Or something like that on the User if it has to be a simple formula...


Q:

How do I export charts from Excel as graphics

I've got a series of Excel spreadsheets, each with at least one page of data and one page of a chart created from the data. I need to capture ( not regenerate from the data ) the existing chart as a web friendly image. Is this possible via Java or .Net? I know the POI stuff (Java) won't do it (or so I'm told, haven't tried it myself).

A:

Have you tried using the Chart.Export Method?
The example in help is:
Worksheets("Sheet1").ChartObjects(1).Chart. Export _
FileName:="current_sales.gif", FilterName:="GIF"

From memory, I think you can export to PNG as well.


Q:

XP Embedded attempts to start application as service

I'm having a lot of problems trying to start an application as administrator on an application I'm writing when running it on XP Embedded.
The application runs as the shell for a limited user account and is touch-screen and keyboard-less with one user command being to run the touch screen vendor's calibration tool. This must be run as administrator.
No problem I thought, add user and password information to the ProcessStartInfo and all should be fine. No. The error I get is:
System.ComponentMode.Win32Exception: The specified service does not exist as an installed service.

From some investigation, I've found that:

My Process starting code is correct:

any application can be started successfully on XP Embedded when run as the limited user
any application can be run as Administrator on my own laptop

on XP Embedded, any application is regarded as being a service in the same way, including notepad
if I attempt to start a program from within process explorer, I simply get "Unable to execute process: Access is Denied"

I'm not an XP Embedded expert in anyways so I'd very much appreciate some help. I suspect that there's a configuration setting that has been set when building the XP image that specifically denies access to process creation and that the errors I'm being reported are actually mis-reports from software that's not assuming XP Embedded error codes.
Unfortunately, the people who make the base image aren't around right now so I can't get the current settings.
Thanks in advance if anyone's ever seen this before!
Kev

A:

For the record, it turned out that the "Secondary Logon" service wasn't installed in the image.
The code I had reached down eventually into either CreateProcessWithLogonW or CreateProcessAsUser which ultimately depend on this service running. The "specified service" error was spot on, but not about what I thought it was about. No idea why I got that particular error from Process Explorer.


Q:

SonarQube: Log to Console

Is this rule applied to console applications? If yes, how can we log to the conosle then? Or why shouldn't you do it?
http://dist.sonarsource.com/plugins/csharp/rulesdoc/0.10.0-RC/S2228.html

A:

You can disable this rule on Console Applications. Nevertheless, even for console applications, it can be a good idea to limit the number of Console.WriteLine() calls for instance to make it easier to later on change your application. For example, you don't want to see Console.* calls spread to the whole codebase, but see it perhaps contained in a single class. If that is the case, feel free to mark those issues as Won't Fix in SonarQube, to indicate that you have reviewed them and that they are expected and accepted.


Q:

Meaning of the word "may"

I'm struggling a bit with the meaning of "may".
Does "You may eat that apple." mean any of these?:

"You are able to eat that apple."
"You are allowed to eat that apple."
"I want you to eat that apple."

I think it's probably the middle one but I'm not quite sure. Same for the negative version of the above-mentioned sentence.
Does "You may not eat that apple." mean any of these?:

"You are unable to eat that apple."
"You aren't allowed to eat that apple."
"Whether you eat that apple, is up to you."
"I want you to eat that apple but you don't have to do it."
"I wish you won't eat that apple."
"I'd prefer if you won't eat that apple but you are able to and allowed to if you want to." (Side note: Is that sentence grammatically correct?)

If none of the proposed meanings quite cut it, please let me know what would.

A:

May can express permission or authority, and conditionality (in the present perfect) or potentiality.
We use the modal may to talk about the possibility of doing something, or about permission to do something.
In your sentence You may eat that apple, depending on context, may could convey either of these meanings:

It is possible that you will eat that apple. (Potentiality)
You are allowed to eat that apple. (Permission)

In the negative form You may not eat that apple, (depending again on context) may not could convey one of the following meanings:

You are not allowed to eat that apple.  (Permission)
It is possible that you will not eat that apple.  (Potentiality)


Q:

SQL query GROUP BY colA and ORDER by ColB issue

What I am trying to do is to do a Distinct on only 1 Column with Access.
Access is unfortunately limited and we have to use an aggregate function.
SELECT ColB, max(ColA), Max(ColC)...
FROM Table1
WHERE blabalba
GROUP BY ColB

the query is working fine but what I would need is to have the result ORDER BY ColA and I can't if I add ORDER BY ColA at the end, I get the exeption You tried to execute a query that does not include the specified expression 'CSR' as part of an aggregate function.
How can we have this query order by ColA?
Also I don't know if this one is possible but I would need for the results to have ColA in the first position so basically we do a kind of a DISTINCT on ColB only and we order by ColA
ColA            ColB          ColC
1                A              @
1                A              #
1                B              #
2                C              %
2                D              &
3                E              *
3                E              !
3                E              @
3                F              $

Results
ColA           ColB            ColC
1               A               @
1               B               #
2               C               %
2               D               &
3               E               *
3               F               $

Thank you!!

A:

To order by ColA, could you try this query?
SELECT colb, maxcola, maxcolc
FROM (
  SELECT ColB, max(ColA) AS maxcola, Max(ColC) AS maxcolc
  FROM Table1
  WHERE blabalba
  GROUP BY ColB
) AS sub
ORDER BY maxcola;

Or, if that doesn't work in Access, could you save the first query as a View and then query from the view using an ORDER BY?


Q:

How can I get a unknown number from a string within a certain part of the string?

My string:
How would you rate the ease and comfort required to undertake the session?@QUESTION_VALUE_0

How would I be able to get this value specifically from the above string? I don't know what this value will be (apart from that it will be an integer):
(some question)@QUESTION_VALUE_X where X is an integer, I want to get X.
I looked into Regex, but I suck at regular expressions, so I'm at a loss, cheers guys!
About as far as I got with regex
/@QUESTION_VALUE_[0-9]+/

But I can't get the number out of the string. How can I only grab the number?

A:

This should work for you:
Just put the escape sequence \d (which means 0-9) with the quantifier + (which means 1 or more times) into a group (()) to capture the the number which you then can access in the array $m.
<?php

    $str = "How would you rate the ease and comfort required to undertake the session?@QUESTION_VALUE_0";
    preg_match("/@QUESTION_VALUE_(\d+)/", $str, $m);
    echo $m[1];

?>

output:
0

If you do print_r($m); you will see the structure of your array:
Array
(
    [0] => @QUESTION_VALUE_0
    [1] => 0
)

And now you see ^ that you have the full match in the first element and then first group ((\d+)) in the second element.


Q:

python Pandas: transform dataframe adding grouped columns

I have the following dataframe:
    n   startdate     enddate  count
0   1  2014-02-01  2014-02-01   6069
1   1  2014-02-01  2014-03-01   1837
2   1  2014-02-01  2014-04-01    107
3   1  2014-02-01  2014-05-01     54
4   1  2014-03-01  2014-03-01  10742
5   1  2014-03-01  2014-04-01   2709
6   1  2014-03-01  2014-05-01   1387
7   1  2014-04-01  2014-04-01   5584
8   1  2014-04-01  2014-05-01   1103
9   1  2014-05-01  2014-05-01   2970

Is it possible to transform it into something similar to:
    n  startdate   2014-02-01  2014-03-01 2014-04-01   2014-05-01
0   1  2014-02-01  6069        1837       107          54
1   1  2014-03-01  0           10742      2709         1387
2   1  2014-04-01  0           0          5584         1103
3   1  2014-05-01  0           0          0            2970

Thanks!

A:

without recreating your dataframe, i think it's going to be something like:
df.groupby(['n', 'startdate', 'enddate']).sum().unstack()

you might need to fill some nan values as well:
df.fillna(0, inplace=True)


Q:

Detecting if any values are within a certain value of each other - MATLAB

If I have:
a = [5000 8000 20000 22000 30000]';

Is there any quick way to detect if a given number is within - for example 5000 - of another and then remove both and replace them with the midpoint? Ideally I want to attach this to an IF statement but I really have no idea what sort of function or mathematical method could be used to do this.
The desired output would be for a:
   = [6500 21000 30000];

A:

accumarray based approach might be best suited to solve it -
th = 5000      %// threshold to choose next elements (edit to specific input)
a = sort(a(:)) %// sort elements
matches = diff(a)>th
idx = cumsum([0 ; matches])+1 %// index each element with their group IDs
out = (accumarray(idx,a,[],@min) + accumarray(idx,a,[],@max))./2
   %// outputs are the midpoints of the min-max boundaries within each group


Q:

Why is P(A⋃B) ⊄ P(A)⋃P(B)?

I had a question in my 11th grade Mathematics book : Prove that P(A⋃B) ⊄ P(A)⋃P(B)
I did a proof for why P(A⋃B) ⊂ P(A)⋃P(B)
Which step in the following proof is wrong?
Let y be an arbitrary element of a set Y
Let Y be an element of P(A⋃B)
So, Y ⊂ (A⋃B)
So, y ∈ (A⋃B)
So, y ∈ A  or  y ∈ B
So, Y ⊂ A  or  Y ⊂ B
So, Y ∈ P(A)  or  Y ∈ P(B)
So, Y ∈ P(A)⋃P(B)
And, thus :-  every element of P(A⋃B) is an element of P(A)⋃P(B)
So, P(A⋃B) ⊂ P(A)⋃P(B)

I suspect a mistake in the 6th line because, just wanted confirmation
Thank You...

A:

The 6th line is wrong. What you have shown is that an arbitrary $y\in Y$ is in $A$ or is in $B$ but this doesn't mean ALL $y\in Y$ satisfy this for same set $A$ or $B$. You might have some $y\in Y$ who are in $A$ and some $y'\in Y$ who are in $B$. Then, $Y$ is not an element of $P(A)$ or of $P(B)$ but is an element of of $P(A\cup B)$.


Q:

Как правильно отобразить треугольник при верстке?

Всем доброго времени суток) Возник вопрос, как будет правильно отобразить треугольник (на фото в нижнем углу) при верстке страницы: с помощью позиционирования картинки, или нарисовать его свойствами CSS???

A:

При условии, что ширина контейнера всегда меньше высоты, можно градиентом в псевдоэлементе. Работает адаптивно.

.container {
  display: flex;
  min-height: 100vh;
}

.intro {
  flex: 2;
}

.right {
  flex: 1;
  background: #f2f2f2;
  position: relative;
}

.right:before {
  content: '';
  display: block;
  position: absolute;
  bottom: 0;
  width: 100%;
  padding-top: 100%;
  background: linear-gradient(135deg, transparent, transparent 50%, pink 50%, pink);
}


Q:

Assign product category to specific store

I've been trying for a while now to assign a product to a new category. We are running multiple store views, but when i try to assign the products to the new category IDs the original product is also affected.
$newProduct = Mage::getModel('catalog/product')->setStoreId($this->_targetStoreId)->load($productId);
$newProduct->setCategoryIds($newCategoryIds);
$newProduct->getResource()->save($newProduct);

Can anyone see the bug?
For some products i get this error:

SQLSTATE[23000]: Integrity constraint violation: 1062 Duplicate entry '47893-0-6-8' for key 'FA0D1FDA369EC09AFFDA36F11B04E66B'

A:

The product - category relation s global.
It does not depend on the store view or website.
What you can do is to have a different category tree on the second
website.
But this will result in duplicate categories.

When you see catalog_category_product table, and it only has category_id and product_id not store_id


Q:

Audacity: Show track names in compact view

My Problem
I am using audacity to merge multiple short audio files to a log one, with some overlaps. The tracks disaply their waveform, which is not important to me, but without their name (that appears on the far left).

I've seen audacity screenshots in which the track name appears instead of the waveform, which makes editing way easier for my use case.
What Have I Tried
I Googled "Compact view" and alike, and browsed the menus.
My Question
How can I view the tracks names without their waveform in Audacity, like this example ?

A:

Although I am not sure that it will solve your issue, the screen capture you are linking to :

Screen capture from Twitter user @ohcybermycyber
actually shows a label track :

Screen from Audacity documentation


Q:

What are the different ways of handling 'Enumerations' in SQL server?

We currently define a list of constants (mostly these correspond to enumerations we have defined in the business layer) at the top of a stored procedure like so:
DECLARE @COLOR_RED INT = 1
DECLARE @COLOR_GREEN INT = 2
DECLARE @COLOR_BLUE INT = 3

But these often get repeated for many stored procedures so there is a lot of duplication.
Another technique I use if the procedure needs just one or two constants is to pass them in as parameters to the stored procedure. (using the same convention of upper case for constant values). This way I'm sure the values in the business layer and data layer are consistent. This method is not nice for lots of values.
What are my other options?
I'm using SQL Server 2008, and C# if it makes any difference.
Update Because I'm using .Net is there any way that user defined (CLR) types can help?

A:

This might be controversial: my take is don't use enumerations in T-SQL. T-SQL isn't really designed in a way that makes enums useful, the way they are in other languages. To me, in T_SQL, they just add effort and complexity without the benefit seen elsewhere.


Q:

How can I stop Silverlight DataForm immediately saving changes back to underlying object?

I have a Silverlight master-details DataForm where the DataForm represents a street address.
When I edit the Address1 textbox, the value gets automatically committed to the bound Address object once focus leaves the textbox.
If I hit the Cancel button, then any changes are undone because Address implements IEditableObject and saves its state.
The problem is that since any change is immediately propagated to the underlying object it will be shown in the master grid before the user has actually hit Save. I also have other locations where this data is shown. This is not a very good user experience.
I've tried OneWay binding but then I can't commit back without manually copying all the fields over.
The only thing I can think of doing is to create a copy of the data first or using OneWay binding, but they both seem a little clumsy.
Does DataForm support this way of working?

A:

The copy of the object feels a little clumsy, but I would use that: it's coming back into style with systems like ASP.NET MVC.
You then also have a good opportunity to do any level of validation you want before commiting it to what will be propagated to other bound controls.