text:
Q: Password Protect Winforms Application I have a simple WinForms application that runs in the system tray. Is it possible to password protect the program from closing if a user tries to close it from task manager?
Ideally I want to keep a user from closing the process but if windows is restarted, I want it to close without being prompted. Much like antivirus programs.

A: If a user has the correct permissions they will be able to kill your process from the Task Manager.
That said as @fujiFX mentions in his comment the FormClosing event is a good start and better than nothing.

The FormClosing event occurs as the form is being closed. When a form is closed, it is disposed, releasing all resources associated with the form. If you cancel this event, the form remains opened. To cancel the closure of a form, set the Cancel property of the FormClosingEventArgs passed to your event handler to true.

A: It's hard to do, but you can create two applications, one is main program and two is helper. If helper is killed, then main app restarts it. If main app is killed, then helper restarts main app.

A: You can make this verification on YourService.Stop method (assuming you're using a Windows Service thus inheriting from ServiceBase), but as far as I know you cannot prevent the user from killing the proccess, just to close the app (two different things in Windows).


text:
Q: Ember.js History with Fullscreen API It is possible to use History API with Ember.js, simply by:
App.Router.reopen
  location: 'history'

But when operating in a fullscreen, any URL modifications breaks fullscreen mode in Chrome (it's well-known bug https://code.google.com/p/chromium/issues/detail?id=171670).
Is it possible to queue History API changes in EmberJS, and fire all of them only when the app exits the fullscreen?
P.S. Looks like YouTube do the same – you can watch multiple consecutive videos in the fullscreen, and URL stays the same just until you exit the fullscreen mode.

A: You can probably do this by reopening Ember.HistoryLocation. I would try to modify the method pushState to queue paths when in fullscreen. On exiting fullscreen call the pushState method manually with the queued paths.
Source code for Ember.HistoryLocation

redpajama_set_name: RedPajamaStackExchange


text:
Q: recursion without base case and statements following recursion function When are the statements after the recursion executed if there is no base case ?
              void fun(int x,int y){
               statement 1;
               statement 2;
               fun(x',y');
               statement 3;
               statement 4;
               }

Here statement 1 and 2 are not the base cases.When will the statements 3 and 4 executed if every recursion sends the control back to the recursive function ?
My question is in reference with this code  https://ideone.com/lEKxW5 .In the link that i have  given, when is the statement after line 24 or say after recursion executed ?
             LOOK AT THE LINK OF THE CODE BEFORE ANSWERING .

               void dfsBipartiteColor(int x, int y, int c)
              {
               // If we got to paint the cell:
                  if ( (board[x][y] == 'X') && (color[x][y] == -1) ) {
                   // Color it:
                  color[x][y] = c;
                   // Special case: We have foudn that there is at least one X:
    result = std::max(result, 1);

    // Try the adjacent hexagons:
    for (int nx = max(0, x-1); nx <= min(n-1, x+1); nx++) {
        for (int ny = max(0, y-1); ny <= min(n-1, y+1); ny++) {
            // The hexagon is adjacent and has an X:
            if ( (nx - x != ny - y) && (board[nx][ny] == 'X') ) {
                // continue the DFS, negate the color:
                dfsBipartiteColor(nx,ny, !c);//
                // Special case: We now know there are two adjacent X:
                result = std::max(result, 2);
                // If the color is not consistent, the graph is not bipartite:
                if (color[nx][ny] == c) {
                    result = 3;
                }
            }
        }
    }
}

When are the statements after recursion executed in the code above ?

A: You have simplified the code too much, there is also a condition:
void fun(int x,int y){
    statement 1;
    statement 2;
    if(condition) fun(x',y');
    statement 3;
    statement 4;
}

So when the condition is not met, the calls return.

A: The base case seems invisible because it doesn't do anything and occurs when the entry condition is false.
(You left out the entry condition when you simplified.)
Simplifying the code you posted as much as possible:
void function()
{
    if (condition)
    {
        function();
        statement;
    }
}

If you still can't see the base case, consider the equivalent
void function()
{
    if (condition)
    {
        function();
        statement;
    }
    else
    {
        // Do nothing.
    }
}

A: They will never be executed, and the program will crash fairly quickly, as soon as it runs out of stack space, due to infinite recursion.


text:
Q: Ambiguous column name error When executing the following (complete) SQL query on Microsoft SQL Server 2000:
SELECT B.ARTIFACTTNS, B.ARTIFACTNAME, B.ARTIFACTTYPE, B.INITIALBYTES, B.TIMESTAMP1, B.FILENAME, B.BACKINGCLASS,
       B.CHARENCODING, B.APPNAME, B.COMPONENTTNS, B.COMPONENTNAME, B.SCAMODULENAME, B.SCACOMPONENTNAME
FROM (SELECT DISTINCT A.ARTIFACTTYPE, A.ARTIFACTTNS, A.ARTIFACTNAME
      FROM (SELECT DISTINCT ARTIFACTTYPE, ARTIFACTTNS, ARTIFACTNAME
            FROM CUSTPROPERTIES WHERE PNAME = 'AcmeSystemName' AND PVALUE = 'MyRuleGroup'
                  UNION SELECT DISTINCT ARTIFACTTYPE, ARTIFACTTNS, ARTIFACTNAME
                          FROM CUSTPROPERTIES WHERE PNAME = 'AcmeSystemDisplayName' AND PVALUE = 'MyRuleGroup') A,
           (SELECT DISTINCT ARTIFACTTYPE, ARTIFACTTNS, ARTIFACTNAME
            FROM CUSTPROPERTIES WHERE PNAME = 'AcmeSystemTargetNameSpace' AND PVALUE = 'http://MyModule') B
WHERE A.ARTIFACTTYPE = B.ARTIFACTTYPE AND A.ARTIFACTTNS = B.ARTIFACTTNS AND A.ARTIFACTNAME = B.ARTIFACTNAME) A, BYTESTORE B
    WHERE (A.ARTIFACTTYPE = 'BRG') AND A.ARTIFACTTYPE = B.ARTIFACTTYPE AND A.ARTIFACTTNS = B.ARTIFACTTNS AND A.ARTIFACTNAME = B.ARTIFACTNAME
    ORDER BY ARTIFACTTYPE, ARTIFACTTNS, ARTIFACTNAME

I get the following exception:
java.sql.SQLException: [Acme][SQLServer JDBC Driver][SQLServer]
    Ambiguous column name 'ARTIFACTTYPE'.

What am I doing wrong here and how can I correct it?

A: Because ARTIFACTTYPE can refer to either A.ARTIFACTTYPE or B.ARTIFACTTYPE and the server needs to know which one you want, just change it to A.ARTIFACTTYPE and you should be okay in this case.
To clarify, you need to specify the alias prefix any time the column name is ambiguous.  It isn't bad practice to always use alias prefixes as it makes it clear which columns are coming from which tables when you read the query, and eliminates issues like this one.
One might wonder why you need to distinguish between which of two columns you want when they both refer to the same column in the same table.  The answer is that when you join a table to itself, the values from A.column and B.column may be different depending on the join criteria (such as may be the case with an outer join where values in one of the columns may be null).

A: If that's the exact query you're running, I have no idea why it would find anything ambiguous.
I wrote what I think is an equivalent query and ran it in my database (Oracle) with no problem.
EDIT Adding exact output of a new experiment in Oracle.  The query executed in this experiment is the exact query given by the OP, with the table name filled in.  NO OTHER CHANGES.  There's nothing ambiguous in this query.  So, either that is not the exact query that is being executed, or SQL Server has a parser bug.
SQL> create table props (pname varchar2(100),
  2                       pvalue varchar2(100),
  3                       artifacttype number,
  4                       artifacttns number,
  5                       artifactname number);

Table created.

SQL> SELECT
  2    DISTINCT A.ARTIFACTTYPE, A.ARTIFACTTNS, A.ARTIFACTNAME
  3  FROM
  4   (SELECT DISTINCT
  5      ARTIFACTTYPE,
  6      ARTIFACTTNS,
  7      ARTIFACTNAME
  8    FROM props
  9    WHERE PNAME = 'AcmeSystemName'
 10        AND PVALUE = 'MyRuleGroup'
 11    UNION
 12    SELECT DISTINCT
 13      ARTIFACTTYPE,
 14      ARTIFACTTNS,
 15      ARTIFACTNAME
 16    FROM props
 17    WHERE PNAME = 'AcmeSystemDisplayName'
 18        AND PVALUE = 'MyRuleGroup') A,
 19  (SELECT DISTINCT
 20      ARTIFACTTYPE,
 21      ARTIFACTTNS,
 22      ARTIFACTNAME
 23   FROM props
 24   WHERE PNAME = 'AcmeSystemTargetNameSpace'
 25      AND PVALUE = 'http://mymodule') B
 26  WHERE A.ARTIFACTTYPE = B.ARTIFACTTYPE
 27      AND A.ARTIFACTTNS = B.ARTIFACTTNS
 28      AND A.ARTIFACTNAME = B.ARTIFACTNAME
 29  /

no rows selected

End Edit
My suggestion for getting around the error is to give the table in each select clause a unique alias and qualify all column references.  Like this:
SELECT
  DISTINCT A.ARTIFACTTYPE, A.ARTIFACTTNS, A.ARTIFACTNAME
FROM
 (SELECT DISTINCT
    P1.ARTIFACTTYPE,
    P1.ARTIFACTTNS,
    P1.ARTIFACTNAME
  FROM {PROPERTIES_TABLE_NAME} P1
  WHERE PNAME = 'AcmeSystemName'
      AND PVALUE = 'MyRuleGroup'
  UNION
  SELECT DISTINCT
    P2.ARTIFACTTYPE,
    P2.ARTIFACTTNS,
    P2.ARTIFACTNAME
  FROM {PROPERTIES_TABLE_NAME} P2
  WHERE PNAME = 'AcmeSystemDisplayName'
      AND PVALUE = 'MyRuleGroup') A,
(SELECT DISTINCT
    P3.ARTIFACTTYPE,
    P3.ARTIFACTTNS,
    P3.ARTIFACTNAME
 FROM {PROPERTIES_TABLE_NAME} P3
 WHERE PNAME = 'AcmeSystemTargetNameSpace'
    AND PVALUE = 'http://mymodule') B
WHERE A.ARTIFACTTYPE = B.ARTIFACTTYPE
    AND A.ARTIFACTTNS = B.ARTIFACTTNS
    AND A.ARTIFACTNAME = B.ARTIFACTNAME

A: Are you listing the complete query?
Perhaps you have also ORDER BY clause - that could cause that problem
I would support Dave on that that there should be no problem with the posted query

A: To be clear, it is lines 13, 14 and 15 that have the ambiguous columns.

A: You need to specify the tables in the ORDER BY clause, like this:
ORDER BY A.ARTIFACTTYPE, A.ARTIFACTTNS, A.ARTIFACTNAME


text:
Q: Find, from the first principle, the derivative of $\textrm {ln} x$
Find, from the first principle, the derivative of $\ln x$.

My Attempt:
\begin{align}f(x)&=\ln (x)\\
f(x+\Delta x)&= \ln (x+\Delta x)\end{align}
Now, by formula:
\begin{align}f'(x)&=\lim_{\Delta x\to 0} \dfrac {f(x+ \Delta x)-f(x)}{\Delta x}\\
&=\lim_{\Delta x\to 0} \dfrac {\ln(x+\Delta x) -\ln(x)}{\Delta x}\\
&=\lim_{\Delta x\to 0} \dfrac {\ln\left(\dfrac {x+\Delta x}{x}\right)}{\Delta x}\\
&=\lim_{\Delta x\to 0} \dfrac {1}{\Delta x} \ln \left(1+\dfrac {\Delta x}{x}\right)\end{align}
How do.I proceed further?

A: If you can use the fact that $e^{\ln x} = x$ then call
$$
f(x) = \ln x
$$
Such that
$$
e^{f(x)} = e^{\ln x} = x
$$
and
$$
\frac{de^{f(x)}}{dx} = e^{f(x)}\frac{df(x)}{dx} = 1 = x\frac{d\ln x}{dx}
$$
Therefore
$$
\frac{d\ln x}{dx} = \frac{1}{x}
$$


text:
Q: Css not linked to html I have a html file and my css file. After searching for a lot of Suggestions I put them in seperate folders but I can't link the index.css with the index.html. My code is provided Below:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>App</title>
    <link rel="stylesheet" href="styles/index.css" type="text/css" />

Welcome

and my css file:
#Come{
    font-size: xx-large;
}

My file structure:
App
  |
   index.html
   styles
        |
         index.css

Pls Help

A: Can you try replacing the href value to "./styles/index.css"
and also try to remove spaces from id = 'Come'
it should look something like this: id="Come"

A: There was a Glitch guys. I restarted my computer and CSS loaded


text:
Q: Google Spreadsheets API batch insert How can I make a batch insert with big data to Google Spreadsheets using API?
I found the batch request in the api, but:

insert and delete are not supported because the cells feed cannot be
  used to insert or delete cells.

(https://developers.google.com/google-apps/spreadsheets/)


text:
Q: How to use libusb to transfer bytes from android host to another machine which runs on windows I am developing android application where I need to transfer bytes from android device (host) to another device which runs on windows via USB.
I came across libusb library which only works on host mode, so I am developing an android application for android tablet which will act as host and need to communicate with a machine where windows OS runs.
Machine which runs windows always act as host, correct me If I am wrong?
So in my case both are host so things are not going to work. Afaik, in a communication one need to be a host and rest peripherals.
Does anyone have any idea how I can make it work ?


text:
Q: Python class using large lookup tables I've been tinkering with Python (v3) on and off for the past few years.  As a learning exercise, I decided a couple weeks ago to refactor a collection of bash scripts I wrote.  I also think some features of the language will dramatically speed up the processing.  These bash scripts typically run for 5 or 6 days processing huge data files.  The Python version also significantly improves the readability and maintainability of the code.
First I got the algorithms working as a program in one file.  The algorithm uses several large lookup tables, implemented variously as lists and dictionaries.  Now I want to break it up - the core logic going into one file, and a second file containing a class(es?) holding the lookup tables and their associated functions.  The data tables take about 350 lines of code, and the functions are about the same size.
Q: What is the preferred way of structuring the class module file?
For example, I started doing it this way, let's call it case 1:
class Zebra:
    _stripe_keys = [ ....... ]
    _stripe_info = [ [.....], [.....], ... [.....] ]
    _stripes = [ dict(zip( stripe_keys, info )) for info in stripe_info ]
    <<< many such tables >>>
    def __init__(self, name):
        self.name = name
    def function_one(self):
        do something
    def function_two(self):
        do something
    <<< etc... >>>

Then I realized this might be better, case 2:
_stripe_keys = [ ....... ]
_stripe_info = [ [.....], [.....], ... [.....] ]
_stripes = [ dict(zip( stripe_keys, info )) for info in stripe_info ]
<<< many such tables >>>
class Zebra:
    def __init__(self, name):
        self.name = name
    def function_one(self):
        do something
    def function_two(self):
        do something
    <<< etc... >>>

And then I saw yet another possibility, case 3, but somehow I'd have to pass the data class into the function class:
class ZebraTables:
    _stripe_keys = [ ....... ]
    _stripe_info = [ [.....], [.....], ... [.....] ]
    _stripes = [ dict(zip( stripe_keys, info )) for info in stripe_info ]
    <<< many such tables >>>
    def __init__(self, name):
        self.name = name
class Zebra:
    def __init__(self, name):
        self.name = name
    def function_one(self):
        do something
    def function_two(self):
        do something
    <<< etc... >>>

The data tables are essentially constant.  If there was ever a reason to make two instances of this class, the data should be shared and not duplicated.  The static data in the source code takes tens of MB of memory, combined with additional data read from disk at startup brings the total to about 600MB).  I think this means case 2 is what I want, but I'm not certain.  I come from an embedded background using primarily C, so Object Oriented techniques aren't my specialty - yet!

A: Personally, I would not store large lists inside the same module with the class. What about saving them in some format in an external python module, that manages them and load them when you need it?
Depending on the size and needs you can use pickle, pandas, csv, or directly an SQL/NoSQL DB.

A: Thanks for the suggestions, they helped steer me to a workable solution and a better grasp of module vs class vs instance variables.  I decided to put everything into one class within the module.
class Zebra:
    stripe_keys = []
    stripe_info = []
    stripes = defautdict(list)
    <<< many such tables >>>
    def __init__(self, name):
        self.name = name
        self.init_stripes()
    def function_one(self):
        do something
    def function_two(self):
        do something
    def init_stripes(self):
        Zebra.stripe_keys.extend([.........])
        Zebra.stripe_info.extend([ [...], [...], ..., [...] ])
        Zebra.stripes.extend([ dict(zip( Zebra.stripe_keys, info ))
                               for info in Zebra.stripe_info ])
    <<< etc... >>>

This arrangement, where I define empty tables at the top and extend/update them with data at the bottom, was necessary to solve a circular reference issues. One of the lists is a jump table referencing functions in the class, so I couldn't define the tables first, nor could I define the functions first.


text:
Q: User login null error I am using cakephp 2.1 and I used login action in UsersController as follows.
public function login() {
    if ($this->request->is('post')) {
        if ($this->Auth->login()) {
            $this->redirect($this->Auth->redirect());
        } else {
            $this->Session->setFlash('Invalid email or password, try again', 'default/flash_error');
        }
    }
}

And the login.ctp code is as follows.
<?php echo $this->Form->create('User', array('class' => 'form')); ?>

                Email

                    <?php echo $this -> Form -> text('email', array('id' => 'inputEmail', 'placeholder' => 'Email')); ?>
                    <?php echo $this -> Form -> error('email', null, array('wrap' => 'span', 'class' => 'help-block')); ?>

                Password

                    <?php echo $this -> Form -> password('password', array('id' => 'inputPassword', 'placeholder' => 'Password')); ?>
                    <?php echo $this -> Form -> error('password', null, array('wrap' => 'span', 'class' => 'help-block')); ?>

                        <input type="checkbox"/>
                        Remember me
                    <?php echo $this->Form->button('Sign in', array('type' => 'submit', 'class' => 'btn')); ?>

            <?php echo $this->Form->end(); ?>

When the form get submitted with email and password, the user is not able to login so its showing an error 'Invalid email or password, try again'. Even I am passing the $this->request->data['User'] into $this->Auth->login() method and debugged $this->Session->read(Auth.User.id). Its giving me null. Please give me a solution for this.

A: You can try passing $this->request->data into the $this->Auth->login() method. It's not a great way to do it (see this post: CakePHP Auth Component Not logging in when using $this->Auth->login();), but it works for me. Have you debugged $this->Auth->login()?


text:
Q: Java Pack200 library output different from command line tool output I'm dealing with some gzipped pack200 files and have no trouble unpacking them with the command line tool. I only run into problems when I attempt to unpack the files with the pack200 library.
For reference, this is the method I am using to unpack the files:
//Output from this can be properly unpacked with command line tool
InputStream in = new GZIPInputStream(new ByteArrayInputStream(compressed));

//This is where things go awry
Pack200.Unpacker unpacker = Pack200.newUnpacker();
JarOutputStream out = new JarOutputStream(new FileOutputStream("file.jar"));
unpacker.unpack(in, out);

Here is the output of unpacker.properties():
com.sun.java.util.jar.pack.default.timezone: false
com.sun.java.util.jar.pack.disable.native: false
com.sun.java.util.jar.pack.verbose: 0
pack.class.attribute.CompilationID: RUH
pack.class.attribute.SourceID: RUH
pack.code.attribute.CharacterRangeTable: NH[PHPOHIIH]
pack.code.attribute.CoverageTable: NH[PHHII]
pack.deflate.hint: keep
pack.effort: 5
pack.keep.file.order: true
pack.modification.time: keep
pack.segment.limit: -1
pack.unknown.attribute: pass

Some other relevant information:

*

*The jar files output by the library are consistently smaller than those unpacked by the command line tool.

*The library generated files use a newer version of the .zip format (0x14 vs 0x0A).

*unpack200.exe version 1.30, 07/05/05

*jdk version 1.7.0_21

So to reiterate, the jar files generated by the command line tool function properly while those generated by the library do not.
I very much appreciate any help or guidance.

A: It was something very simple, but I'm happy to have found the problem. Here is the solution I was able to use:
//Output from this can be properly unpacked with command line tool
InputStream in = new GZIPInputStream(new ByteArrayInputStream(compressed));

//This is where things go awry
Pack200.Unpacker unpacker = Pack200.newUnpacker();
JarOutputStream out = new JarOutputStream(new FileOutputStream("file.jar"));
unpacker.unpack(in, out);
out.close();

Don't forget your JarOutPutStream.close();, kids.


text:
Q: How to make sure capturing group is more than 5 characters? I'm using this code:
(?i)(?<!see )(?<!\d)(?<!")(?<!")ITEM.*?1A.*?\n*(?<!")(?<!")RISK.*?FACTORS(?<!")\n*([\s\S]*?)\n*ITEM.*?1B
It is grabbing text that are between ITEM 1A. RISK FACTORS and ITEM 1B., but how can I only grab the capturing group with more than 5 characters?
Full string:
ITEM 1A.    RISK FACTORS

123

ITEM 1B.

ITEM 1A.    RISK FACTORS

In addition to other information in this Form 10-K, the following risk factors should be carefully considered in evaluating us and our business because these factors currently have a significant impact or

ITEM 1B.

So, desired capturing group would be:
In addition to other information in this Form 10-K, the following risk factors should be carefully considered in evaluating us and our business because these factors currently have a significant impact or

and not:
123

A: Counting is done close to the data like this.
Can significantly shorten the regex replacing [^\S\r\n] with \h if needed.
Group 1 contains the trimmed data.
(?sm)^[^\S\r\n]*ITEM[^\S\r\n]+1A[^\S\r\n]*\.[^\S\r\n]+RISK[^\S\r\n]+FACTORS[^\S\r\n]*\r?\n\s*(\S(?:(?!^[^\S\r\n]*ITEM).){3,}?\S)\s*^[^\S\r\n]*ITEM[^\S\r\n]+1B[^\S\r\n]*\.
https://regex101.com/r/ChQseo/1
Expanded
 (?sm)
 ^ [^\S\r\n]* ITEM [^\S\r\n]+ 1A [^\S\r\n]* \.
 [^\S\r\n]+ RISK [^\S\r\n]+ FACTORS [^\S\r\n]* \r? \n

 \s*
 (                             # (1 start)
      \S
      (?:
           (?! ^ [^\S\r\n]* ITEM )
           .
      ){3,}?
      \S
 )                             # (1 end)
 \s*

 ^ [^\S\r\n]* ITEM [^\S\r\n]+ 1B [^\S\r\n]* \.

A: I'm guessing that maybe,
(?i)(?<!see )(?<!\d)(?<!")(?<!")ITEM.*?1A.*?\n*(?<!")(?<!")RISK.*?FACTORS(?<!")\n*([^\r\n]{5,}?)\s*\n*ITEM.*?1B

might be somewhat close to what you have in mind, not sure though.
It is likely to work with re.DOTALL flag too:
import re

regex = r'(?i)(?<!see )(?<!\d)(?<!")(?<!")ITEM.*?1A.*?\n*(?<!")(?<!")RISK.*?FACTORS(?<!")\n*([^\r\n]{5,}?)\s*\n*ITEM.*?1B'
string = '''

ITEM 1A.    RISK FACTORS

123

ITEM 1B.

ITEM 1A.    RISK FACTORS

In addition to other information in this Form 10-K, the following risk factors should be carefully considered in evaluating us and our business because these factors currently have a significant impact or

ITEM 1B.

'''

print(re.findall(regex, string, re.DOTALL))

Output

['In addition to other information in this Form 10-K, the following
  risk factors should be carefully considered in evaluating us and our
  business because these factors currently have a significant impact
  or']

If you wish to simplify/modify/explore the expression, it's been explained on the top right panel of regex101.com. If you'd like, you can also watch in this link, how it would match against some sample inputs.


text:
Q: Need to access data from xlsx file public class fileReader {

    public static void main (String[] args) throws IOException {
        String excelFilePath = "sample.xlsx";
        InputStream inputStream = new FileInputStream(new File(excelFilePath));

        XSSFWorkbook workbook = new XSSFWorkbook();
        Sheet firstSheet = workbook.getSheetAt(0);
        Iterator<Row> iterator = firstSheet.iterator();

        while (iterator.hasNext()) {
            Row nextRow = iterator.next();
            Iterator<Cell> cellIterator = nextRow.cellIterator();
        ...

In the XSSFWorkbook line the error has been showing
Exception in thread "main" org.apache.poi.ooxml.POIXMLException: org.apache.xmlbeans.XmlOptions.setEntityExpansionLimit(I)Lorg/apache/xmlbeans/XmlOptions;
    at org.apache.poi.ooxml.POIXMLFactory.createDocumentPart(POIXMLFactory.java:66)
    at org.apache.poi.ooxml.POIXMLDocumentPart.read(POIXMLDocumentPart.java:657)
    at org.apache.poi.ooxml.POIXMLDocument.load(POIXMLDocument.java:180)
    at org.apache.poi.xssf.usermodel.XSSFWorkbook.<init>(XSSFWorkbook.java:282)
    at org.apache.poi.xssf.usermodel.XSSFWorkbook.<init>(XSSFWorkbook.java:303)
    at fileReader.main(fileReader.java:20)

A: You are not reading your file. You are creating a new workbook. SO I suspect your are getting an exception because your are asking for a Sheet where there is none.
Provide your file to the instance using XSSFWorkbook(File)
String excelFilePath = "sample.xlsx";
File f = new File(excelFilePath);
XSSFWorkbook workbook = new XSSFWorkbook(f);

Or XSSFWorkbook(InputStream)
String excelFilePath = "sample.xlsx";
File f = new File(excelFilePath);
InputStream inputStream = new FileInputStream(f);
XSSFWorkbook workbook = new XSSFWorkbook(inputStream);

If File is given to the workbook instance then there occurs an error showing File cannot be resolved to a type

Just need to import java.io.File


text:
Q: How to hide certain on SQL Reporting Services 2005 I created a report in SQL Report Services 2005 and everything is coming out right but on my comments field I am getting bunch of HTML Tags which I dont want to show. See below the sample of my report comments field data. I really appreciate somebody let me know how to hide these tags not to show on the output of the report in my comment field. Thanks and appreciate your quick response.

Meet with low bidder Hill York on site to go over each item in the scope of work.

Met with Richard Waugh, Joe Charles of Hill Pines, Jim Rogers, Ed Chris, Dwayne Right on site and both parties agreed that everything in the scope of work was covered in the bid. Awaiting approval from Council on August 6th 2010.

A: The values must be coming from the source.  I've not ever seen this in SSRS.
You'll need to use an expression to remove them and depending on how many are in your data this could become burdensome.  The expression
Replace(Replace(Fields!Comment.Value,"
",""),"
","") will remove them from a field name Comment.

A: Use string.replace in the eypressions field to strip out the tags, perhaps.
The tags are most likely not coming from SSRS but are in your data. At least, I've never seen it SSRS add HTML tags...

A: If you want to hide any comment that uses
, then try putting this in the Hidden property:
=iif(instr(Fields!Comment.Value,"
") > 0, True, False)


text:
Q: Не отображается форма django У меня не отображается поле text на странице. Передаю в контекст. Вывожу через {{ form.text }}. Ссылка гитхаб, ютуб
forms.py
from django.forms import ModelForm
from .models import Entry

class EntryForm(ModelForm):
    class Meta:
        model = Entry
        fields = ('text', )

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.fields['text'].widget.attrs.update({'class' : 'textarea', 'placeholder' : 'О чем ты думаешь?'})

views.py
from django.shortcuts import render, redirect
from .models import Entry
from .forms import EntryForm
from django.views import *
from django.views import View

def add(request):
    if request.method == 'POST':
        form = EntryForm(request.POST)

        if form.is_valid():
            form.save()
            return redirect('index')
    else:
        form = EntryForm()

    context = {'form' : form}

    return render(request, 'entries/add.html', context)

add.html
<!DOCTYPE html>

    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Дневник</title>
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bulma@0.9.2/css/bulma.min.css" />

                    Дневник

      <form method="POST" action="{% url 'add' %}">
               {% csrf_token %}

                       {{ form.text }}

                       <button class="button is-link">Submit</button>

       </form>

urls.py
from django.urls import path
from .views import (
    PostListView,
    PostDetailView,
    PostCreateView,
    PostUpdateView,
    PostDeleteView,
    UserPostListView
)
from . import views

urlpatterns = [
    path('', PostListView.as_view(), name='blog-home'),
    path('user/<str:username>', UserPostListView.as_view(), name='user-posts'),
    path('post/<int:pk>/', PostDetailView.as_view(), name='post-detail'),
    path('post/new/', PostCreateView.as_view(), name='post-create'),
    path('post/<int:pk>/update/', PostUpdateView.as_view(), name='post-update'),
    path('post/<int:pk>/delete/', PostDeleteView.as_view(), name='post-delete'),
    path('about/', views.about, name='blog-about'),
    path('calendar/', views.calendar, name='blog-calendar'),
    path('rukovoditelya/', views.rukovoditelya, name='blog-rukovoditelya'),
    path('biography/', views.biography, name='blog-biography'),
    path('diary/', views.diary, name='blog-diary'),
    path('struktura/', views.struktura, name='blog-struktura'),
    path('contact/', views.contact, name='blog-contact'),
    path('index/', views.index, name='index'),
    path('add/', views.add, name='add'),
]

base.html
{% load static %}
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.5.3/dist/css/bootstrap.min.css" integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2" crossorigin="anonymous">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/mdbootstrap/4.19.1/css/mdb.min.css" rel="stylesheet">
    <link rel="stylesheet" type="text/css" href="{% static 'blog/main.css' %}">
    <link rel="stylesheet" href="{% static 'blog/fc/lib/main.css' %}">

    {% if title %}
        <title>Блог - {{ title }}</title>
    {% else %}
        <title>Блог</title>
    {% endif %}

          Блог руководителя управления транспорта и автодорог области
          <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarToggle" aria-controls="navbarToggle" aria-expanded="false" aria-label="Toggle navigation">

          </button>

              {% if user.is_authenticated %}
              Создать пост
              Профиль
              Выйти
              {% else %}
              Авторизоваться
              Регистрация
              {% endif %}

          {% if messages %}
            {% for message in messages %}

                {{ message }}

            {% endfor %}
          {% endif %}
          {% block content %}{% endblock %}

Меню

                Последние новости

                Дневник

                Календарь

                Контакты

                Обратная связь

Об управлении

Уважаемые посетители сайта! Мы рады приветствовать вас, и надеемся, что информация, представленная на сайте, будет для Вас полезной.
              Подробнее →

Присоединяйтесь к нам в социальных сетях!

Наша компания

Полезные ссылки

              Задать вопрос

              Вакансия

              Обратная связь

Аккаунт

              Войти

              Регистрация

Контакты

© 2021 Copyright:

urls.py
from django.contrib import admin
from django.contrib.auth import views as auth_views
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static
from users import views as user_views

urlpatterns = [
    path('admin/', admin.site.urls),
    path('register/', user_views.register, name='register'),
    path('profile/', user_views.profile, name='profile'),
    path('login/', auth_views.LoginView.as_view(template_name='users/login.html'), name='login'),
    path('logout/', auth_views.LogoutView.as_view(template_name='users/logout.html'), name='logout'),
    path('password-reset/',
         auth_views.PasswordResetView.as_view(
             template_name='users/password_reset.html'
         ),
         name='password_reset'),
    path('password-reset/done/',
         auth_views.PasswordResetDoneView.as_view(
             template_name='users/password_reset_done.html'
         ),
         name='password_reset_done'),
    path('password-reset-confirm/<uidb64>/<token>/',
         auth_views.PasswordResetConfirmView.as_view(
             template_name='users/password_reset_confirm.html'
         ),
         name='password_reset_confirm'),
    path('password-reset-complete/',
         auth_views.PasswordResetCompleteView.as_view(
             template_name='users/password_reset_complete.html'
         ),
         name='password_reset_complete'),
    path('', include('blog.urls')),
]

if settings.DEBUG:
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

A: Это должно работать, но лучше отдельно определить методы POST и GET. Используйте  https://docs.djangoproject.com/en/3.2/ref/class-based-views/base/
def add(request):

    form = EntryForm()
    context = {'form' : form}
    if request.method == 'POST':
        form = EntryForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect('index')
    else:
        return render(request, 'entries/add.html', context)
    return render(request, 'entries/add.html', context)


text:
Q: InvalidOperation in T4 Generated Helper Method SelfTrackingModel.Context.Extensions I have a project whereby I'm using STE's (EF4.1) and I'm hitting a reproducable issue when I call the auto generated ApplyChanges() method on one of my object sets, passing in an object graph I have held in memory, and I'm getting the following error:
InvalidOperationException:
    Collection was modified; enumeration operation may not execute.

This is originating from within a call to ObjectContext.AddObject() method, which is being called by the T4 auto generated ApplyChanges() method. My method to call ApplyChanges looks something like this:
// Extension to auto generated Session : IObjectWithChangeTracker
public partial class Session
{
    public void SaveToDatabase(String myConnectionString)
    {
        using (MyContext DbContext = new MyContext(myConnectionString))
        {
            DbContext.Sessions.ApplyChanges(this);
            DbContext.SaveChanges();
        }
    }
}

The call stack when I hit the error looks something like this:
at System.ThrowHelper.ThrowInvalidOperationException(ExceptionResource resource)
at System.Collections.Generic.List`1.Enumerator.MoveNextRare()
at System.Collections.Generic.List`1.Enumerator.MoveNext()
at System.Data.Objects.DataClasses.RelatedEnd.WalkObjectGraphToIncludeAllRelatedEntities(IEntityWrapper wrappedEntity, Boolean addRelationshipAsUnchanged, Boolean doAttach)
at System.Data.Objects.DataClasses.RelatedEnd.AddGraphToObjectStateManager(IEntityWrapper wrappedEntity, Boolean relationshipAlreadyExists, Boolean addRelationshipAsUnchanged, Boolean doAttach)
at System.Data.Objects.DataClasses.RelatedEnd.IncludeEntity(IEntityWrapper wrappedEntity, Boolean addRelationshipAsUnchanged, Boolean doAttach)
at System.Data.Objects.DataClasses.EntityReference`1.Include(Boolean addRelationshipAsUnchanged, Boolean doAttach)
... // The below 4 lines are pretty much repeated as it iterates through the object graph
at System.Data.Objects.DataClasses.RelatedEnd.WalkObjectGraphToIncludeAllRelatedEntities(IEntityWrapper wrappedEntity, Boolean addRelationshipAsUnchanged, Boolean doAttach)
at System.Data.Objects.DataClasses.RelatedEnd.AddGraphToObjectStateManager(IEntityWrapper wrappedEntity, Boolean relationshipAlreadyExists, Boolean addRelationshipAsUnchanged, Boolean doAttach)
at System.Data.Objects.DataClasses.RelatedEnd.IncludeEntity(IEntityWrapper wrappedEntity, Boolean addRelationshipAsUnchanged, Boolean doAttach)
at System.Data.Objects.DataClasses.EntityCollection`1.Include(Boolean addRelationshipAsUnchanged, Boolean doAttach)
at System.Data.Objects.DataClasses.RelatedEnd.WalkObjectGraphToIncludeAllRelatedEntities(IEntityWrapper wrappedEntity, Boolean addRelationshipAsUnchanged, Boolean doAttach)
at System.Data.Objects.DataClasses.RelatedEnd.AddGraphToObjectStateManager(IEntityWrapper wrappedEntity, Boolean relationshipAlreadyExists, Boolean addRelationshipAsUnchanged, Boolean doAttach)
at System.Data.Objects.DataClasses.RelatedEnd.IncludeEntity(IEntityWrapper wrappedEntity, Boolean addRelationshipAsUnchanged, Boolean doAttach)
at System.Data.Objects.DataClasses.EntityReference`1.Include(Boolean addRelationshipAsUnchanged, Boolean doAttach)
at System.Data.Objects.DataClasses.RelationshipManager.AddRelatedEntitiesToObjectStateManager(Boolean doAttach)
at System.Data.Objects.ObjectContext.AddObject(String entitySetName, Object entity)
at MyNamespace.SelfTrackingEntitiesContextExtensions.AddHelper.AddAllEntities(ObjectContext context, String entitySetName, IObjectWithChangeTracker entity)
at MyNamespace.SelfTrackingEntitiesContextExtensions.ApplyChanges[TEntity](ObjectContext context, String entitySetName, TEntity entity)
at MyNamespace.SelfTrackingEntitiesContextExtensions.ApplyChanges[TEntity](ObjectSet`1 objectSet, TEntity entity)
at MyNamespace.Transaction.SaveToDatabase(String transactionDbConnectionString)

I'm not modifying the object graph at all whilst the operation is in progress, so I'm really stumped as to the issue. Anybody got any ideas?
Thanks

A: We had the same problem.
We could solve it with removing Navigation properties so that they cannot run in circles.
So if A has B as a Navigation Property, B should not hav A as a Navigation property.
It is not possible under all circumstances but in our case, it solved the problem.

A: Had the same problem. Looks like a bug that was fixed in .net 4.5.


text:
Q: How to connect component in html props in react-tippy to redux form I have got a problem with react-tippy component. I would like to pass in html props react component with redux form, but I receive an error like this:
Uncaught Error: Could not find "store" in either the context or props of "Connect(Form(AssignDriverForm))". Either wrap the root component in a <Provider>, or explicitly pass "store" as a prop to "Connect(Form(AssignDriverForm))".

Here is code of react tippy component:
class AssignDriverToolTip extends Component {
    state = { open: false }
    setIsOpen = () => this.setState({ open: true });
    setIsClose = () => this.setState({ open: false });

    render() {
        return (
            <CustomTooltip
                theme="light"
                open={this.state.open}
                arrow={false}
                html={(
                    <AssignDriverForm/>
                )}
                position='right'
                trigger="click" >
                <CustomButton infoSmallWithIcon onClickHandler={() => this.setIsOpen()}>
                    <SVGComponent icon="pen" color="white" width="12px" height="12px" />
                    {strings.assignDriver}
                </CustomButton>
            </CustomTooltip>
        )
    }
}
export default AssignDriverToolTip;

And also here is an AssignDriverForm component:
class AssignDriverForm extends Component {
    handleSubmit = (data) => {
        console.log(data);
    }
    render() {
        return (
            <form onSubmit={this.handleSubmit}>
                <Field
                    name="message"
                    type="textarea"
                    autoComplete="off"
                    component="textarea" />
            </form>
        )
    }
}

AssignDriverForm = reduxForm({
    form: 'assignDriver'
})(AssignDriverForm)

export default AssignDriverForm;

When I change it to component without redux-form everything works fine. But I really dont know how to fix it. Could you help me ?

A: As the error message says: find the root component where you create your store. (Something like this in index.jx)
const store = createStore(reducer)

Then make sure you wrap your component in the <Provider> wrapper.
// render app
ReactDOM.render(
  <Provider store={store}>
    <App />
  </Provider>,
  document.getElementById('app')
)

Redux form uses a normal Redux store, so somewhere you need to add that reducer to your main reducer. You may have something like this:
// combine reducers
const reducer = combineReducers({
  myReducer,
  ...
  form: formReducer // for redux-form
})


text:
Q: Why can't i call props in this Method? (react) My Codeblocks are as follows:
class Buerger extends React.Component {
  constructor() {
    super();
    this.gehaltHandler = this.gehaltChange.bind(this)
  }
  render() {

    return(
      <div style={{textAlign:"right", marginTop:'-103', marginRight:'900px'}}>
        <Anzeige stand = {"Bargeld: " + this.props.stand}/>
        <Arbeit gehalt = {this.props.gehalt} gehaltChange = {this.gehaltChange} arbeitenFunc = {this.props.arbeitenFunc}/>
      </div>
   )
  }

  gehaltChange(inputWert) {
   const test = this.props.gehalt
    alert(test)
  }

So I'm passing the prop "gehalt" from the parent class and you can see i pass it again to a child of the child class called "Arbeit" .
The Funktion gehaltChange is working as checked with an alert('click'), but with this code i get a "Cannot read property 'props' of undefined".
The passing of gehalt to "Arbeit" is working too as i have tested it as a button name and it shows the right value no problem.
I dont get it. Somebody seeing what i'm doing wrong? Is it that i cant pass props that have been passed before and use them at the same time? I would be thankful for any help.

A: Because you need to pass the constructor the props and also call super with them.
class Buerger extends React.Component {
  constructor(props) {
    super(props);
    this.gehaltHandler = this.gehaltChange.bind(this)
  }

A: because you changed names
this.gehaltHandler = this.gehaltChange.bind(this)

vs
gehaltChange={this.gehaltChange}

so you bind it into a new name and then pass the original unbound function.
gehaltChange={this.gehaltHandler} or this.gehaltChange = this.gehaltChange.bind(this)

A: I think you aren't binding in a correct way.
Replace this line:
this.gehaltHandler = this.gehaltChange.bind(this);

For this one:
this.gehaltChange = this.gehaltChange.bind(this);

And pass props as someone replied above.

A: Just change this:
   constructor() {
    super();
    this.gehaltHandler = this.gehaltChange.bind(this)
  }

to this:
  constructor(props) {
    super(props);
    this.gehaltHandler = this.gehaltChange.bind(this);
  }

You missed the props argument in both constructorand super methods :)


text:
Q: How can I respond to a keyUp event? I am writing a simple menu bar application for MacOS using SwiftUI. I would like the application to respond to the escape key. Using what I have pieced together so far, I have something like this:
extension NSWindow {
    open override func keyDown(with event: NSEvent) {
        print("keyDown: \(event.keyCode)")
    }
    open override func keyUp(with event: NSEvent) {
        print("keyUp: \(event.keyCode)")
    }
}

class AppDelegate: NSObject, NSApplicationDelegate {
    func applicationDidFinishLaunching(_ aNotification: Notification) {

    //  etc

    }
}

The AppDelegate creates and launches a NSPopover.
When I run the application, I do get the keyUp messages, but, not the keyDown for some reason.
The question is how can I respond to the key from within the AppDelegate? Ultimately, I want to close the popover using the escape key, but I would also like to explore other possibilities.


text:
Q: Trying to implement full view in windows 10 mobile through code but it gives Unhandled exception while deploying on desktop view in windows 10 I'm trying to implement full view in Windows 10 mobile view through code. It's working fine in mobile, but when deploying the same code for desktop view I get the following error:

Unhandled exception at 0x00007FFCB9BFD1C4 (twinapi.appcore.dll) in
  L_c_uwp.exe: 0xC000027B: An application-internal exception has
  occurred (parameters: 0x000000C517DFECF0, 0x0000000000000001)

How to resolve this? Any suggestion would be appreciated.
XAML
<Grid>
    <MediaElement x:Name="myMediaElement"
        Source="/Video/splash_3.mp4" AutoPlay="True"
        CurrentStateChanged="MediaElement_CurrentStateChanged"/>
</Grid>

C# code
public MainPage()
{
    this.InitializeComponent();
    RemoveGap();
}

private void MediaElement_CurrentStateChanged(object sender, RoutedEventArgs e)
{
    if (myMediaElement.CurrentState == MediaElementState.Paused)
    {
        this.Frame.Navigate(typeof(Home));
    }
}

public async void RemoveGap()
{
    await StatusBar.GetForCurrentView().HideAsync();
}

A: Windows 10 Desktops does not have Status Bar so calling await StatusBar.GetForCurrentView().HideAsync(); causes error.
Instead, we need use the ApiInformation class to check for the presence of StatusBar as this class only exists in Mobile Device (See Requirements →  Device family).
if (ApiInformation.IsTypePresent("Windows.UI.ViewManagement.StatusBar"))
     await StatusBar.GetForCurrentView().HideAsync();

For more info, please see Dynamically detecting features with API contracts


text:
Q: assumeRole in airflow container I'm trying to run local docker containers as airflow cluster for local testing. My DAG needs to run some code like sts_client.assume_role. It works with ECS. However in local containers, it only gets my identity as arn:aws:sts::xxx:assumed-role/okta-dev/xxxx.com, which is not listed in the trust relationship of the role DAG code to assume.
Questions are:

*

*I think we can try to add the arn:aws:sts::xxx:assumed-role/okta-dev/xxxx.com to the trust relationship of assume role, but is there a better way to make it work? In ECS, the identity is like arn:aws:sts::xxx:assumed-role/xxx-container/xxx which has been added to target roles.

*If we have to add the okta arn to the role, each of the team members needs to do that. In that case, can we make all okta arn to assume one role in, say, <middle_role>, and use add that middle role to target role DAG needs to assume? That is:
Add all okta arns to trust relationship of middle_role => add middle_role to trust relationship of target roles.

Thanks

A: This might be more a question for an IAM/AWS expert but from the Airflow side there is a way to mount the local credentials in local containers by using a docker-compose.override.yml.
So you if you can assume the role you need (in your case the arn:aws:sts::xxx:assumed-role/xxx-container/xxx role) with the aws cli locally to have the correct credentials in .aws you can then you mount your credentials in docker-compose.override.yml (this is for Mac, so you might need to adjust the path to .aws):
version: "3.1"
services:
    scheduler:
        volumes:
        - /Users/<username>/.aws:/usr/local/airflow/.aws:ro
    webserver:
        volumes:
        - /Users/<username>/.aws:/usr/local/airflow/.aws:ro
    triggerer:
        volumes:
        - /Users/<username>/.aws:/usr/local/airflow/.aws:ro

and set the following ENV variables in your Dockerfile:
ENV AWS_CONFIG_FILE=/usr/local/airflow/.aws/config
ENV AWS_SHARED_CREDENTIALS_FILE=/usr/local/airflow/.aws/credentials

When you run Airflow, all AWS connections without defined credentials automatically fall back to these user credentials when connecting to AWS.
Might be worth trying. :)


text:
Q: Interfacing with BME280 via STM8L101F3 via SPI I'm trying to use the BME280 via an STM8L101F3. However I cannot seem to get any data from the sensor. As a start I would like to read the chip ID to verify that everything is working. However, I have not found a suitable library that works with the STM8L10x and I have been unable to create my own. I have the following code but all I receive are zero's. I have tried everything I could find online but I haven't progressed. I have checked that the sensor is functioning with an arduino and I'm using 4-wire spi.
#include "stm8l10x.h"
#include "bme280.h"

void DelayS(uint16_t sec) {
  uint32_t freq = 400000;
  for (; sec != 0; sec--) {
    freq = 400000;
    for (; freq != 0; freq--) {
    }
  }
}

static void SPI_Config(void)
{
  /*Set the MOSI,MISO and SCK at high level*/
  GPIO_ExternalPullUpConfig(GPIOB,GPIO_Pin_5|GPIO_Pin_6|GPIO_Pin_7, ENABLE);
  // Disable SPI before configuration
  SPI_DeInit();
  /* Initialize SPI in Slave mode  */
  SPI_Init(SPI_FirstBit_MSB, SPI_BaudRatePrescaler_8, SPI_Mode_Master, SPI_CPOL_Low,
           SPI_CPHA_1Edge, SPI_Direction_2Lines_FullDuplex, SPI_NSS_Soft);
}

void main(void)
{
  volatile uint8_t received = 33;
  volatile uint8_t sendByte = 0xD0; // ChipID register
  /* High speed internal clock prescaler: 1*/
  CLK_MasterPrescalerConfig(CLK_MasterPrescaler_HSIDiv1);
  // Disable SPI for configuration
  SPI_Cmd(DISABLE);
  /* Enable SPI clock */
  CLK_PeripheralClockConfig(CLK_Peripheral_SPI, ENABLE);
  SPI_Config();
  // Init CSB
  GPIO_DeInit(GPIOB);
  GPIO_Init(GPIOB, GPIO_Pin_1, GPIO_Mode_Out_PP_High_Fast);
  // Enable SPI
  SPI_Cmd(ENABLE);
  // Wait for SPI to be idle
  while (SPI_GetFlagStatus(SPI_FLAG_BSY)) {};
  DelayS(5);
  // Begin Transaction, pull CSB low
  GPIO_WriteBit(GPIOB, GPIO_Pin_1, RESET);
  // Write to ChipId register
  SPI_SendData(sendByte);
  // Wait for buffer to be empty
  while (SPI_GetFlagStatus(SPI_FLAG_TXE) == RESET) {};
  // Wait for the register to be filled
  while (SPI_GetFlagStatus(SPI_FLAG_RXNE) == RESET) {};
    // Receive the data
    received = SPI_ReceiveData();
  // End transaction, pull CSB high
  GPIO_WriteBit(GPIOB, GPIO_Pin_1, SET);
}

#ifdef  USE_FULL_ASSERT
/**
  * @brief  Reports the name of the source file and the source line number
  *   where the assert_param error has occurred.
  * @param file: pointer to the source file name
  * @param line: assert_param error line source number
  * @retval : None
  */
void assert_failed(uint8_t* file, uint32_t line)
{
  /* User can add his own implementation to report the file name and line number,
     ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */

  /* Infinite loop */
  while (1)
  {
  }
}
#endif


text:
Q: How to change facet labels? I have used the following ggplot command:
ggplot(survey, aes(x = age)) + stat_bin(aes(n = nrow(h3), y = ..count.. / n), binwidth = 10)
  + scale_y_continuous(formatter = "percent", breaks = c(0, 0.1, 0.2))
  + facet_grid(hospital ~ .)
  + theme(panel.background = theme_blank())

to produce

I'd like to change the facet labels, however, to something shorter (like Hosp 1, Hosp 2...) because they are too long now and look cramped (increasing the height of the graph is not an option, it would take too much space in the document). I looked at the facet_grid help page but cannot figure out how.

A: Note that this solution will not work nicely in case ggplot will show less factors than your variable actually contains (which could happen if you had been for example subsetting):
 library(ggplot2)
 labeli <- function(variable, value){
  names_li <- list("versicolor"="versi", "virginica"="virg")
  return(names_li[value])
 }

 dat <- subset(iris,Species!="setosa")
 ggplot(dat, aes(Petal.Length)) + stat_bin() + facet_grid(Species ~ ., labeller=labeli)

A simple solution (besides adding all unused factors in names_li, which can be tedious) is to drop the unused factors with droplevels(), either in the original dataset, or in the labbeler function, see:
labeli2 <- function(variable, value){
  value <- droplevels(value)
  names_li <- list("versicolor"="versi", "virginica"="virg")
  return(names_li[value])
}

dat <- subset(iris,Species!="setosa")
ggplot(dat, aes(Petal.Length)) + stat_bin() + facet_grid(Species ~ ., labeller=labeli2)

A: Both facet_wrap and facet_grid also accept input from ifelse as an argument. So if the variable used for faceting is logical, the solution is very simple:
facet_wrap(~ifelse(variable, "Label if true", "Label if false"))

If the variable has more categories, the ifelse statement needs to be nested.
As a side effect, this also allows the creation of the groups to be faceted within the ggplot call.

A: The EASIEST way to change WITHOUT modifying the underlying data is:

*

*Create an object using as_labeller(). If the column names begin with a number or contain spaces or special characters, don't forget to use back tick marks:

# Necessary to put RH% into the facet labels
hum_names <- as_labeller(
     c(`50` = "RH% 50", `60` = "RH% 60",`70` = "RH% 70",
       `80` = "RH% 80",`90` = "RH% 90", `100` = "RH% 100"))

*Add to the ggplot:

    ggplot(dataframe, aes(x = Temperature.C, y = fit)) +
        geom_line() +
        facet_wrap(~Humidity.RH., nrow = 2, labeller = hum_names)

A: Here's how I did it with facet_grid(yfacet~xfacet) using ggplot2, version 2.2.1:
facet_grid(
    yfacet~xfacet,
    labeller = labeller(
        yfacet = c(`0` = "an y label", `1` = "another y label"),
        xfacet = c(`10` = "an x label", `20` = "another x label")
    )
)

Note that this does not contain a call to as_labeller() -- something that I struggled with for a while.
This approach is inspired by the last example on the help page Coerce to labeller function.

A: This is working for me.
Define a factor:
hospitals.factor<- factor( c("H0","H1","H2") )

and use, in ggplot():
facet_grid( hospitals.factor[hospital] ~ . )

A: Here is a solution that avoids editing your data:
Say your plot is facetted by the group part of your dataframe, which has levels control, test1, test2, then create a list named by those values:
hospital_names <- list(
  'Hospital#1'="Some Hospital",
  'Hospital#2'="Another Hospital",
  'Hospital#3'="Hospital Number 3",
  'Hospital#4'="The Other Hospital"
)

Then create a 'labeller' function, and push it into your facet_grid call:
hospital_labeller <- function(variable,value){
  return(hospital_names[value])
}

ggplot(survey,aes(x=age)) + stat_bin(aes(n=nrow(h3),y=..count../n), binwidth=10)
 + facet_grid(hospital ~ ., labeller=hospital_labeller)
 ...

This uses the levels of the data frame to index the hospital_names list, returning the list values (the correct names).

Please note that this only works if you only have one faceting variable. If you have two facets, then your labeller function needs to return a different name vector for each facet. You can do this with something like :
plot_labeller <- function(variable,value){
  if (variable=='facet1') {
    return(facet1_names[value])
  } else {
    return(facet2_names[value])
  }
}

Where facet1_names and facet2_names are pre-defined lists of names indexed by the facet index names ('Hostpital#1', etc.).

Edit: The above method fails if you pass a variable/value combination that the labeller doesn't know. You can add a fail-safe for unknown variables like this:
plot_labeller <- function(variable,value){
  if (variable=='facet1') {
    return(facet1_names[value])
  } else if (variable=='facet2') {
    return(facet2_names[value])
  } else {
    return(as.character(value))
  }
}

Answer adapted from how to change strip.text labels in ggplot with facet and margin=TRUE

edit: WARNING: if you're using this method to facet by a character column, you may be getting incorrect labels. See this bug report. fixed in recent versions of ggplot2.

A: I have another way to achieve the same goal without changing the underlying data:
ggplot(transform(survey, survey = factor(survey,
        labels = c("Hosp 1", "Hosp 2", "Hosp 3", "Hosp 4"))), aes(x = age)) +
  stat_bin(aes(n = nrow(h3),y=..count../n), binwidth = 10) +
  scale_y_continuous(formatter = "percent", breaks = c(0, 0.1, 0.2)) +
  facet_grid(hospital ~ .) +
  opts(panel.background = theme_blank())

What I did above is changing the labels of the factor in the original data frame, and that is the only difference compared with your original code.

A: The labeller function defintion with variable, value as arguments would not work for me. Also if you want to use expression you need to use lapply and can not simply use arr[val], as the argument to the function is a data.frame.
This code did work:
libary(latex2exp)
library(ggplot2)
arr <- list('virginica'=TeX("x_1"), "versicolor"=TeX("x_2"), "setosa"=TeX("x_3"))
mylabel <- function(val) { return(lapply(val, function(x) arr[x])) }
ggplot(iris, aes(x=Sepal.Length, y=Sepal.Width)) + geom_line() + facet_wrap(~Species, labeller=mylabel)

A: Since I'm not yet allowed to comment on posts, I'm posting this separately as an addendum to Vince's answer and son520804's answer . Credit goes to them.

Son520804:
using Iris data:
I assume:
  You have installed the dplyr package, which has the convenient mutate command, and
  your dataset is named survey.
  survey %>% mutate(Hosp1 = Hospital1, Hosp2 = Hospital2,........)
  This command helps you to rename columns, yet all other columns are kept.
  Then do the same facet_wrap, you are fine now.

Using the iris example of Vince and the partial code of son520804, I did this with the mutate function and achieved an easy solution without touching the original dataset.
The trick is to create a stand-in name vector and use mutate() inside the pipe to correct the facet names temporarily:
i <- iris

levels(i$Species)
[1] "setosa"     "versicolor" "virginica"

new_names <- c(
  rep("Bristle-pointed iris", 50),
  rep("Poison flag iris",50),
  rep("Virginia iris", 50))

i %>% mutate(Species=new_names) %>%
ggplot(aes(Petal.Length))+
    stat_bin()+
    facet_grid(Species ~ .)

In this example you can see the levels of i$Species is temporarily changed to corresponding common names contained in the new_names vector. The line containing
mutate(Species=new_names) %>%

can easily be removed to reveal the original naming.
Word of caution: This may easily introduce errors in names if the new_name vector is not correctly set up. It would probably be much cleaner to use a separate function to replace the variable strings. Keep in mind that the new_name vector may need to be repeated in different ways to match the order of your original dataset. Please double - and - triple check that this is correctly achieved.

A: If you have two facets hospital and room but want to rename just one, you can use:
facet_grid( hospital ~ room, labeller = labeller(hospital = as_labeller(hospital_names)))

For renaming two facets using the vector-based approach (as in naught101's answer), you can do:
facet_grid( hospital ~ room, labeller = labeller(hospital = as_labeller(hospital_names),
                                                 room = as_labeller(room_names)))

A: Here's another solution that's in the spirit of the one given by @naught101, but simpler and also does not throw a warning on the latest version of ggplot2.
Basically, you first create a named character vector
hospital_names <- c(
                    `Hospital#1` = "Some Hospital",
                    `Hospital#2` = "Another Hospital",
                    `Hospital#3` = "Hospital Number 3",
                    `Hospital#4` = "The Other Hospital"
                    )

And then you use it as a labeller, just by modifying the last line of the code given by @naught101 to
... + facet_grid(hospital ~ ., labeller = as_labeller(hospital_names))

A: Just extending naught101's answer -- credit goes to him
plot_labeller <- function(variable,value, facetVar1='<name-of-1st-facetting-var>', var1NamesMapping=<pass-list-of-name-mappings-here>, facetVar2='', var2NamesMapping=list() )
{
  #print (variable)
  #print (value)
  if (variable==facetVar1)
    {
      value <- as.character(value)
      return(var1NamesMapping[value])
    }
  else if (variable==facetVar2)
    {
      value <- as.character(value)
      return(var2NamesMapping[value])
    }
  else
    {
      return(as.character(value))
    }
}

What you have to do is create a list with name-to-name mapping
clusteringDistance_names <- list(
  '100'="100",
  '200'="200",
  '300'="300",
  '400'="400",
  '600'="500"
)

and redefine plot_labeller() with new default arguments:
plot_labeller <- function(variable,value, facetVar1='clusteringDistance', var1NamesMapping=clusteringDistance_names, facetVar2='', var1NamesMapping=list() )

And then:
ggplot() +
  facet_grid(clusteringDistance ~ . , labeller=plot_labeller)

Alternatively you can create a dedicated function for each of the label changes you want to have.

A: I think all other solutions are really helpful to do this, but there is yet another way.
I assume:

*

*you have installed the dplyr package, which has the convenient mutate command, and

*your dataset is named survey.
survey %>%
  mutate(Hosp1 = Hospital1, Hosp2 = Hospital2,........)
This command helps you to rename columns, yet all other columns are kept.
Then do the same facet_wrap, you are fine now.

A: I feel like I should add my answer to this because it took me quite long to make this work:
This answer is for you if:

*

*you do not want to edit your original data

*if you need expressions (bquote) in your labels and

*if you want the flexibility of a separate labelling name-vector
I basically put the labels in a named vector so labels would not get confused or switched. The labeller expression could probably be simpler, but this at least works (improvements are very welcome). Note the ` (back quotes) to protect the facet-factor.
n <- 10
x <- seq(0, 300, length.out = n)

# I have my data in a "long" format
my_data <- data.frame(
  Type = as.factor(c(rep('dl/l', n), rep('alpha', n))),
  T = c(x, x),
  Value = c(x*0.1, sqrt(x))
)

# the label names as a named vector
type_names <- c(
  `nonsense` = "this is just here because it looks good",
  `dl/l` = Linear~Expansion~~Delta*L/L[Ref]~"="~"[%]", # bquote expression
  `alpha` = Linear~Expansion~Coefficient~~alpha~"="~"[1/K]"
  )

ggplot() +
  geom_point(data = my_data, mapping = aes(T, Value)) +
  facet_wrap(. ~ Type, scales="free_y",
             labeller = label_bquote(.(as.expression(
               eval(parse(text = paste0('type_names', '$`', Type, '`')))
               )))) +
  labs(x="Temperature [K]", y="", colour = "") +
  theme(legend.position = 'none')

A: A one liner from mishabalyasin
:
facet_grid(.~vs, labeller = purrr::partial(label_both, sep = " #"))
See it in action
library(reprex)
library(tidyverse)

mtcars %>%
  ggplot(aes(x="", y=gear,fill=factor(gear), group=am)) +
  geom_bar(stat="identity", width=1) +
  coord_polar("y", start=0) +
  facet_grid(.~vs, labeller = purrr::partial(label_both, sep = " #"))

Created on 2021-07-09 by the reprex package (v2.0.0)

A: Adding another solution similar to @domi's with parsing mathematical symbols, superscript, subscript, parenthesis/bracket, .etc.
library(tidyverse)
theme_set(theme_bw(base_size = 18))

### create separate name vectors
# run `demo(plotmath)` for more examples of mathematical annotation in R
am_names <- c(
  `0` = "delta^{15}*N-NO[3]^-{}",
  `1` = "sqrt(x,y)"
)

# use `scriptstyle` to reduce the size of the parentheses &
# `bgroup` to make adding `)` possible
cyl_names <- c(
  `4` = 'scriptstyle(bgroup("", a, ")"))~T~-~5*"%"',
  `6` = 'scriptstyle(bgroup("", b, ")"))~T~+~10~degree*C',
  `8` = 'scriptstyle(bgroup("", c, ")"))~T~+~30*"%"'
)

ggplot(mtcars, aes(wt, mpg)) +
  geom_jitter() +
  facet_grid(am ~ cyl,
             labeller = labeller(am  = as_labeller(am_names,  label_parsed),
                                 cyl = as_labeller(cyl_names, label_parsed))
             ) +
  geom_text(x = 4, y = 25, size = 4, nudge_y = 1,
            parse = TRUE, check_overlap = TRUE,
            label = as.character(expression(paste("Log"["10"], bgroup("(", frac("x", "y"), ")")))))

### OR create new variables then assign labels directly
# reverse facet orders just for fun
mtcars <- mtcars %>%
  mutate(am2  = factor(am,  labels = am_names),
         cyl2 = factor(cyl, labels = rev(cyl_names), levels = rev(attr(cyl_names, "names")))
  )

ggplot(mtcars, aes(wt, mpg)) +
  geom_jitter() +
  facet_grid(am2 ~ cyl2,
             labeller = label_parsed) +
  annotate("text", x = 4, y = 30, size = 5,
           parse = TRUE,
           label = as.character(expression(paste("speed [", m * s^{-1}, "]"))))

Created on 2019-03-30 by the reprex package (v0.2.1.9000)

A: Simple solution (from here):
p <- ggplot(mtcars, aes(disp, drat)) + geom_point()
# Example (old labels)
p + facet_wrap(~am)

to_string <- as_labeller(c(`0` = "Zero", `1` = "One"))
# Example (New labels)
p + facet_wrap(~am, labeller = to_string)

A: Change the underlying factor level names with something like:
# Using the Iris data
> i <- iris
> levels(i$Species)
[1] "setosa"     "versicolor" "virginica"
> levels(i$Species) <- c("S", "Ve", "Vi")
> ggplot(i, aes(Petal.Length)) + stat_bin() + facet_grid(Species ~ .)

A: This solution is very close to what @domi has, but is designed to shorten the name by fetching first 4 letters and last number.
library(ggplot2)

# simulate some data
xy <- data.frame(hospital = rep(paste("Hospital #", 1:3, sep = ""), each = 30),
                 value = rnorm(90))

shortener <- function(string) {
  abb <- substr(string, start = 1, stop = 4) # fetch only first 4 strings
  num <- gsub("^.*(\\d{1})$", "\\1", string) # using regular expression, fetch last number
  out <- paste(abb, num) # put everything together
  out
}

ggplot(xy, aes(x = value)) +
  theme_bw() +
  geom_histogram() +
  facet_grid(hospital ~ ., labeller = labeller(hospital = shortener))

A: Have you tried changing the specific levels of your Hospital vector?
levels(survey$hospital)[levels(survey$hospital) == "Hospital #1"] <- "Hosp 1"
levels(survey$hospital)[levels(survey$hospital) == "Hospital #2"] <- "Hosp 2"
levels(survey$hospital)[levels(survey$hospital) == "Hospital #3"] <- "Hosp 3"

A: After struggling for a while, what I found is that we can use fct_relevel() and fct_recode() from forcats in conjunction to change the order of the facets as well fix the facet labels. I am not sure if it's supported by design, but it works! Check out the plots below:
library(tidyverse)

before <- mpg %>%
  ggplot(aes(displ, hwy)) +
  geom_point() +
  facet_wrap(~class)
before

after <- mpg %>%
  ggplot(aes(displ, hwy)) +
  geom_point() +
  facet_wrap(
    vars(
      # Change factor level name
      fct_recode(class, "motorbike" = "2seater") %>%
        # Change factor level order
        fct_relevel("compact")
    )
  )
after

Created on 2020-02-16 by the reprex package (v0.3.0)

A: My approach to this issue these days is to use dplyr::case_when to produce a labeler within the facet_grid or facet_wrap function. This is an extension of the solution proposed by @lillemets
ggplot(survey, aes(x = age)) + stat_bin(aes(n = nrow(h3), y = ..count.. / n), binwidth = 10)
  + scale_y_continuous(formatter = "percent", breaks = c(0, 0.1, 0.2))
  + facet_grid(case_when(hospital == "Hospital #1" ~ "Hosp1",
                         hospital == "Hospital #2" ~ "Hosp2") ~ .)
  + theme(panel.background = theme_blank())

What's nice is that if you have a second facet label to change you just use the same approach on the other side of the ~ within facet_grid

A: Found a simple way to assign the values to an existing vector without the need for c=(`1`="first name",`2`="second name") etc.
First create a labeller function
title_labeller_function <- function(nuisance_parameter) {
  return(vector_of_labels)
}

,where vector_of_labels are your labels, eg. c("first label", "second label")
Then just assign this in your facet_grid/facet_wrap
facet_grid(.~ hospital,labeller=as_labeller(title_labeller_function))

For more info, see as_labeller-documentation.


text:
Q: Evaluating Default Return Destination From A @MessageMapping Method TLDR
When using

*

*spring boot

*spring websocket

*@EnableWebSocketMessageBroker
How to evaluate the default return destination for a return value which is returned from a handler method annotated with @MessageMapping inside a @Controller class?
Details

*

*Source Code Attempts' Snippets

*Docs

*

*Spring Framework - Reference Documentation - Spring Web Servlet - WebSocket - STOMP - Annotated Controllers - @MessageMapping - Return Values

The destination of the outbound message is the same as that of the inbound message but prefixed with /topic

*Spring Framework - API Documentation - @MessageMapping

STOMP over WebSocket -- the value is turned into a message and sent to a default response destination or to a custom destination specified with an @SendTo or @SendToUser annotation

*I have guessed and subscribed to a number of possible destinations and none of those destinations' subscriptions' StompFrameHandlers` handleFrame methods was triggered


text:
Q: Heroku building app fail: error to load gem 'graphicsmagick' when I push my rails app to heroku it always fails. On the stage "Build App" the logs show me following message:

checking for gm... no
   !     rake aborted!
   !     Bundler::GemRequireError: There was an error while trying to load the gem 'graphicsmagick'.

I have required this gem in the Gemfile and I don't know why building app on heroku always fails.
Local running and running on CircleCI are ok.
Did someone have similar issue?
Please let me know what I've missed. Thank you.

A: Do you have the graphicsmagick Buildpack included?
Go to the settings tab on Heroku dashboard and add this url to your buildpacks: https://github.com/mcollina/heroku-buildpack-graphicsmagick.git


text:
Q: Changing "a" into "the" in case of providing more info for a noun Do I need to change the indefinite article "a" before a noun into the definite "the" if I provide some definitive information for that noun right after it?

I brought this trinket from a workshop.
I brought this trinket from (a/the?) workshop built by our neighbor Billy
  Brown right in the center of our village in 1925.

EDIT:
There are several workshops built by Billy Brown in the center of the village. There is a possibility that only this one was built in 1925, but nobody knows for sure

A: The OP asks "Do I need to change the indefinite article "a" before a noun into the definite "the" if I provide some definitive information for that noun right after it?"
In my view the answer is yes - it is necessary to change the indefinite article if some definite information is provided. However, at all times context is key.
In this case there are three pieces of information provided, but the challenge is to establish which is truly definitive. We are told:

*

*the workshop was built by Billy Brown

*the workshop was in the center of town, and

*the workshop may or may not have been built in 1925.

I suggest that it is only the age of the building that is the truly
  definitive piece of information. Where the age is critical to
  determining the sense of the text, then the use of the definite
  article is required.

In this scenario, our context is the knowledge that Billy Brown built several workshops over the years, and that this workshop is thought to have been the only one built in 1925, but no one knows for sure.
"I brought this trinket from a workshop."
This is indiscriminate; the characteristics of the workshop are unknown.
"I brought this trinket from a workshop built by our neighbor Billy Brown right in the center of our village in 1925."
We know Billy Brown built many workshops in the center of town; however we don't know whether there are also other workshops of a similar age in the town center.
Accordingly, one might interpret the use of "a" as to imply that the trinket was bought from a "Billy Brown" workshop as opposed to one not built by Brown. Rather like saying "I bought this at a Nike store", or "I bought this at a Walmart".
Though the age attributed to the workshop is false, it is also irrelevant since the age of the workshop is irrelevant to the meaning of the sentence.
The text might just as reasonably read "I brought this trinket from a workshop. The workshop was built by our neighbor Billy Brown right in the center of our village in 1925."
However, let's assume that there are no workshops in the town other than those built by Billy Brown.
In this case, the use of the indefinite article is still justified because, in this context, the additional information is merely descriptive. The writer provides more information about the workshop.
"I brought this trinket from the workshop built by our neighbor Billy Brown right in the center of our village in 1925."
We know that i) Billy Brown built several workshops, 2) one workshop was built in 1925, and iii) it is possible, but uncertain, that this particular workshop was built in 1925. As before, we don't know whether there are other workshops of a similar age in the town center.
In this case, the age of the workshop is of significance and the use of "the" is essential to distinguish one Billy Brown workshop from another.
The text might just as reasonably read "I brought this trinket from a workshop. The workshop was built by our neighbor Billy Brown right in the center of our village. It's thought that this particular workshop might have been the one built in 1925."


text:
Q: Structure rails association[user -> one review -> single model] I have 3 models user, app and review
Current my models have the following associations
User -> has_many :reviews, has_many :apps
Review -> belongs_to :app, belongs_to :user
App -> has_many :reviews, belong_to :user
This allow user to create multiple reviews on a simple app model
My question: How to structure my models so that user can add only one review in a single app model?
How to ensure that user can not add review to app he/she created?

A: In your case just create a Form Object, that would control validations and creation process. Here you can find an example of form object:
http://blog.codeclimate.com/blog/2012/10/17/7-ways-to-decompose-fat-activerecord-models/

A: You have to create custom validation in review model.
validate :user_cannot_be_creator

def user_cannot_be_creator
  errors.add(:user_id, "You are not permited to review") unless user_id != App.find_by(id: app_id).user_id
end

I supose you have user_id foreign_key in app and review model and in review model you have app_id foreign_key.

A: When create the a review/before save you should check if the user do not own the app he/she is reviewing
Check rails cast reputation system from scratch


text:
Q: Show $\lim_{X \to -k}\:\prod_{j\neq k}\left(X+j \right)=(-1)^{k}k!\left(n-k \right).)$
I would like to know how to show that :
  $$\lim_{X \to -k}\:\prod_{j\neq k}\left(X+j \right)=(-1)^{k}k!\left(n-k \right).$$

This is came from solution of exercise that he said :

*

*what is Partial fraction decomposition of :

$$F(X)=\dfrac{n!}{\prod_{k=0}^{n}\left(X+k \right)}$$
indeed,
PFD of F:
$$F(X)=\sum_{k=0}^{n}\dfrac{a_k}{X+k} $$
$$\left(X+k\right)F(X)=\dfrac{n!}{\prod_{j\neq k}\left(X+j \right)}$$
and
$$\prod_{j\neq k}\left(X+j \right)=(-1)^{k}k!\left(n-k \right)$$ then :
$$a_k=(-1)^{k}{n \choose k} $$
Finaly:
$$F(X)=\sum_{k=0}^{n}(-1)^{k}{n \choose k}\dfrac{1}{X+k} $$

A: I guess you would rather like to prove

$$
\lim_{X \to -k}\:\prod_{j\neq k}\left(X+j \right)=(-1)^{k}k!\left(n-k \right).
$$

If this is the case, one may observe that
$$
\begin{align}
\lim_{X \to -k}\:\prod_{j\neq k}\left(X+j \right)&=\left.\prod_{j\neq k}\left(X+j \right)\right|_{X=-k}
\\\\&=\prod_{j\neq k}\left(-k+j \right)
\\\\&=\prod_{0\le j \le k,\,j\neq k}\left(-k+j \right)\prod_{k\le j \le n,\,j\neq k}\left(-k+j \right)
\\\\&=(-1)^{k}\prod_{0\le j \le k-1}\left(k-j \right)\prod_{k+1\le j \le n}\left(j-k \right)
\\\\&=(-1)^kk!(n-k)!
\end{align}
$$ as announced.

A: $\newcommand{\angles}[1]{\left\langle\,{#1}\,\right\rangle}
 \newcommand{\braces}[1]{\left\lbrace\,{#1}\,\right\rbrace}
 \newcommand{\bracks}[1]{\left\lbrack\,{#1}\,\right\rbrack}
 \newcommand{\dd}{\mathrm{d}}
 \newcommand{\ds}[1]{\displaystyle{#1}}
 \newcommand{\expo}[1]{\,\mathrm{e}^{#1}\,}
 \newcommand{\half}{{1 \over 2}}
 \newcommand{\ic}{\mathrm{i}}
 \newcommand{\iff}{\Longleftrightarrow}
 \newcommand{\imp}{\Longrightarrow}
 \newcommand{\Li}[1]{\,\mathrm{Li}_{#1}}
 \newcommand{\mc}[1]{\mathcal{#1}}
 \newcommand{\mrm}[1]{\mathrm{#1}}
 \newcommand{\ol}[1]{\overline{#1}}
 \newcommand{\pars}[1]{\left(\,{#1}\,\right)}
 \newcommand{\partiald}[3][]{\frac{\partial^{#1} #2}{\partial #3^{#1}}}
 \newcommand{\root}[2][]{\,\sqrt[#1]{\,{#2}\,}\,}
 \newcommand{\totald}[3][]{\frac{\mathrm{d}^{#1} #2}{\mathrm{d} #3^{#1}}}
 \newcommand{\ul}[1]{\underline{#1}}
 \newcommand{\verts}[1]{\left\vert\,{#1}\,\right\vert}$
\begin{align}
\color{#f00}{\mrm{F}\pars{X}} & =
{n! \over \prod_{k = 0}^{n}\pars{X + k}} =
{n! \over \prod_{k = 0}^{n}\pars{k + X}} =
{n! \over \pars{X}_{n + 1}}
\end{align}
where $\ds{\pars{a}_{m}}$ is the Pochhammer Symbol.

Also,
\begin{align}
\prod_{j \not= k}\pars{X + j} & = {n! \over \pars{X + k}\,\mrm{F}\pars{X}} =
{n! \over \pars{X + k}\bracks{n!/\pars{X}_{n + 1}}} =
{\pars{X}_{n + 1} \over X + k} =
{\Gamma\pars{X + n + 1} \over \pars{X + k}\Gamma\pars{X}}
\\[5mm] & =
{\pars{X + n}! \over \pars{X + k}\pars{X - 1}!} =
{\pars{X + n}\ldots X \over X + k} =
\pars{X + n}\ldots\pars{X + k + 1}\pars{X + k - 1}\ldots X
\end{align}

\begin{align}
\lim_{X \to -k}\,\,\,\prod_{j \not= k}\pars{X + j} & =
\pars{-k + n}\pars{-k + n - 1}\ldots 1\bracks{\pars{-1}\ldots\pars{-k}}
\\[5mm] & =
\pars{n - k}!\bracks{\pars{-1}^{k}\,1 \times 2 \ldots k} =
\color{#f00}{\pars{-1}^{k}\,k!\pars{n - k}!}
\end{align}


text:
Q: How can I retrive other values of form 1 when returning data from form2? Code of form1,
Picklist f2 = new Picklist(Query, this.Text);
f2.Show();

Code of form2,
DataGridViewRow Row = dgvPicklist.Rows[index];
this.Hide();
ItemMaster f2 = new ItemMaster(Row);
f2.Show();

A: Okay, to send values from form1 to form2:
In form1:
form2 F = new form2(something);  // something is the value you need to send
F.show();

In form2:
public form2(string x)  //Considering the type of your value is string, you can replace that with the required data type.
{
    string something = x;  //sets the value of x to something. Just like it was in form1.
    InitializeComponent();
}

I have considered the datatype of the value you wanted to transfer as string.
You could change it as required.

A: Use ShowModal() Instead of Show():
 Picklist f2 = new Picklist(Query, this.Text);
 f2.ShowModal();
 string valueFromForm1 = TextBox1.Text;

ShowModal() waits till the opened form closes, and then executes the rest of the code


text:
Q: Is it valid for an std::string to contain a null character '\0' not at its end? Consider the following code:
#include <iostream>
#include <string>
using namespace std;

int main() {
    string s = "Allie has a cat.";
    s[3] = '\0';
    cout << s << '\n';
    return 0;
}

Is this code valid? Are there any pitfalls that would make it invalid if in addition to what is above we would do some other operations on this string?

*

*In C, the '\0' character was used as a string terminator. std::string still seems to follow this tradition. THerefore, it wouldn't be unreasonable to suppose that under certain circumstances a premature '\0' might break methods like std::string::size().

*It wouldn't be unreasonable to suppose that some routines like cout might use the underlying std::string::c_str() for their operation, perhaps entering some sort of UB when this null-terminated string is "prematurely terminated".

But suppose that, as on ideone, couting such a std::string works fine and prints out this:
Alle has a cat.

I've compiled and run this program locally and confirmed that it does print out 0x00 in between of l and e. Is it valid to print out null characters to the console? Is it valid for text files to contain null characters? gedit refuses to open the file to which this program's output has been redirected.


text:
Q: Entity Relationship Diagram, can someone check for my erd whether its correct or not? Can someone check my ERD, because I don't know whether I'm doing it correctly or not. I'm not sure about the difference between strong and weak entity, what I'm sure is that strong entity has their own primary key.
Other than that, is it correct i need to take Payment_ID as foreign key in my order table ? and what other attribute that i could have in my ORDER TABLE
Maybe some suggestion on what to add or improve on my ERD. Here i have a image for my ERD. Thank You
Entity Relationship Diagram

A: PAYMENT has an ORDER_ID and ORDER has a PAYMENT_ID. Having both fields is redundant, I would remove ORDER.PAYMENT_ID which would be a nullable field if customers don't pay immediately.
ORDER_DETAILS requires a PK, either a surrogate key ORDER_DETAIL_ID or the combination of ORDER_ID, ITEM_ID.
Can a PAYMENT use only one or more than one COUPON? The cardinality on the crow's foot line says more than one, but the PAYMENT.COUPON_ID field would allow only one. A nullable PAYMENT_ID in the COUPON table would be a better choice.
You have some doubtful minimum cardinalities. A CUSTOMER must place at least one ORDER? Ok, I can accept that. An EMPLOYEE must take at least one ORDER? So everyone in the company must take orders, and you're not going to record employees until they've taken an order? Also, every ITEM must be referenced in ORDER_DETAILS? Are you not going to want to record items on offer before they're ordered?
Finally, a note on terminology: your diagram is better called a table diagram, not an ERD. To be called an entity-relationship diagram, a diagram has to distinguish the concepts of the entity-relationship model. The style of diagram you used doesn't distinguish entity sets (i.e. ID fields) from value sets (non-ID fields) or entity relations (tables with single-field PK) from relationship relations (tables with composite PK, i.e. ORDER_DETAILS is a relationship relation).


text:
Q: CMake: Set ggc-min-expand and -heapsize with target_compile_options Minimal working example at the bottom.
Let's suppose I want to modify GCC garbage collection for a particular CMake target, call it foo. My instinct would be to try, for example:
target_compile_options(foo <PRIVATE|INTERFACE|PUBLIC> --param ggc-min-heapsize=32768)

This works fine. But if I try:
target_compile_options(foo <PRIVATE|INTERFACE|PUBLIC> --param ggc-min-expand=1 --param ggc-min-heapsize=32768)

or
target_compile_options(foo <PRIVATE|INTERFACE|PUBLIC> --param ggc-min-expand=1)
target_compile_options(foo <PRIVATE|INTERFACE|PUBLIC> --param ggc-min-heapsize=32768)

I get in response:
ggc-min-heapsize=32768: No such file or directory

Adding quotes around the arguments or around each argument doesn't help. I've tried this on CMake 3.5.1 and 3.11, GCC 4.8 and GCC 7, no changes.
Oddly, the old-style
SET(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} --param ggc-min-expand=1 --param ggc-min-heapsize=32768)

Seems to work just fine. Am I missing something about modern usage of target_compile_options?
Minimal Working Example
CMakeLists.txt
cmake_minimum_required(VERSION 3.5.1 FATAL_ERROR)
project(test)

add_executable(test main.cpp)
target_compile_options(test PRIVATE --param ggc-min-expand=1)
// Uncommenting the below causes compilation to fail
// target_compile_options(test PRIVATE --param ggc-min-heapsize=32768)

main.cpp
int main() {}

A: The issue is that CMake de-duplicates flags passed to target_compile_options, so it ends up passing "--param gcc-min-expand=1 gcc-min-heapsize=32768" to gcc.  This is obviously wrong.  There's an issue with people complaining about it.
To get around this, some new functionality was recently added.  You can wrap the options in quotes and prepend SHELL:.  The arguments will be treated as a single unit for de-duplication purposes, but will be passed to gcc as multiple arguments (as if split by your shell).  This change was released in CMake 3.12, so the version from your distro's package manager probably doesn't have it yet.
cmake_minimum_required(VERSION 3.12.1 FATAL_ERROR)
project(example)

add_executable(example main.cpp)
target_compile_options(example PRIVATE "SHELL:--param ggc-min-expand=1")
target_compile_options(example PRIVATE "SHELL:--param ggc-min-heapsize=32768")


text:
Q: Power consumption NeoPixels vs. direct control? At Maker Faire Berlin 2018, an electrical engineer looked at my
project which was shown with NeoPixel LEDs (WS2811). He mentioned
that the NeoPixels waste a lot of energy. It would be better to build
my own circuit with RGB LEDs and use the Arduino's (ATmega328P) PWM
functionality for brightness control.
Is there any truth in this?
According to the WS2811 spec sheet: "Gray level 256 can be
adjusted and scan frequency not less than 400Hz/s. [sic]" So the WS2811
driver chip is using PWM, of course. I don't see how it wastes
energy.

A: There's certainly truth in the WS2811 having a non-negligible stand-by current. You could, however, rather easily remedy that with a high-side switch that only powers the IC when needed.
Then, while PWM certainly is cleverer in perceived brightness per Joule than adjusting the sunk current, you still mustn't ignore the fact that this is essentially a linear power supply for each LED - all the difference between LED forward voltage (at the 18.5 mA that the WS2811 tends to sink) and the supply voltage will be converted to heat. So, if your LED forward was e.g. 2V, and your battery is a 6V source (2× CE2032=3V+3V), you'll get an efficiency of only 33%, as two thirds of the voltage are dropped over the regulator.
In that case, using a switch-mode step-down (voltage) converter to get the supply voltage down to close to the minimum necessary voltage would work better here. One could then argue that if you can do that in the first place, simply having a switch-mode constant current supply that can be en- and disabled with a PWM would even safe the energy for the WS2811; but considering you're still driving a full set of LEDs at 18.5 mA, that 1 or 2 mA wasted is peanuts.
By the way, your CR2032 are definitely not meant to source currents up to ~60 mA; you'll probably see that during high-load times, the battery voltage drops below 4V.
And: an Arduino isn't the most power-saving choice, either, especially not with the 5V-based Atmega MCUs. I'd recommend going for one of the ARM-based arduinos. Especially the STM32Lxxx ("L" like low-power) series would be a good choice. Then again, the Arduino environment itself isn't meant for very low-power designs (making it hard to impossible to use lower-power modes) and energy-efficiently addressing the WS2811 (where you'd want a series of automated DMA transfers to happen while the CPU sleeps rather than using the CPU in idle loops to bitbang out the WS2811 "protocol").
Detailed information on how to save energy in your overall design, however, would require a different question with a different background – I think we'd all like to advise you if you can ask based on a project description including a schematic!

A: It's not so much the waste in using the WS2811.  More important is to use high  efficacy (lumens per watt) LEDs.
When you use high efficacy LEDs, they may cost a little more, but the increased battery life will more than make up the cost difference.  10X increased battery life is possible.  If I knew what LEDs you are using I could recommend replacements.  My choice for RGB projects are the Luxeon Color C line. You want to use LEDs that are sufficiently bright at 1 mA. Looking at the brightness of the LEDs in the picture of your project, I would estimate you can get that luminous intensity level at well below 1 mA.
When comparing LEDs the radiant distribution pattern (or view angle) makes a huge difference.  For example a 1000 mcd LED @ 120° emits over 3 lumen.  1000 mcd @ 15° emits only 0.05 lm.  If you don't need 120° you can put a 10° spot lens on the 3 lm 120° LED and get 100,000 mcd.
I much prefer the Texas Instruments TLC59731 run at 3V over the WS2811. A 3V supply for the LEDs is also ideal for the green and blue LEDs.  At low current, not too bad for the red.  Certainly much better than using a 5V supply for the LEDs. The problem is you will need to boost the CR2032 a tiny bit to maintain 3V to the TLC59731.  IF the current draw is less than 10 mA (hopefully it is) it may be more efficient to continue using two batteries and step down the voltage to 3V.
You should be able to run some bright RGB LEDs with about 15 mW of power.
TLC59731 3 mA x 3V
LEDs 1 mA x 3V x 3
MP28200 buck regulator 90% efficient @ 5 mA
You certainly do not need an ATmega when an ATtiny will do fine.


text:
Q: unused variable(s) warning in runjags model I am running JAGS models through the R package runjags. I just updated to JAGS 4.0.0 from JAGS 3.4, and have noticed some unexpected behavior that seems to be related to the update.
First, when I run a model, I now get a warning message WARNING: Unused variable(s) in data table: followed by a list of data objects that are referenced in the model and provided as data. It doesn't seem to affect the results (but it is very puzzling). I have, however, noticed a few times while playing around with this that for some variables the posteriors were virtually identical to the priors (indicating that no updating occured). I can't seem to recreate the update failure right now, but below is a reproducible code example illustrating the odd warning message. The code example on the run.jags help page also produces the same warning.
Second, I thought I'd check to see if the same message pops up if I use the R package R2jags instead of runjags, but R2jags won't load because apparently rjags (one of the dependencies) is not compatible with JAGS 4.0 (its looking for JAGS 3.X). Also, in the runjags function run.jags, the argument method="rjags" doesn't seem to work anymore, but method="parallel" does work.
I'm using runjags_2.0.1-4 and R 3.2.2.
So my questions are:
1) Is rjags really incompatible with JAGS 4.0? The motivation to go to 4.0 was to use vectors as indices (see https://martynplummer.wordpress.com/2015/08/16/whats-new-in-jags-4-0-0-part-34-r-style-features/).
2) What is up with the unused variable(s) warning, and should I be concerned about it?
Thanks,
Glenn
Code:
#--- GENERATE DATA ------------------------
rm(list=ls())
# Number of sites and observations per site
N <- 200
nobs <- 3
# generate covariates and standardize (where appropriate)
set.seed(123)
forest <- rnorm(N)
# relationship between occupancy and covariates
b0 <- 0.5
b.for <- 0.5
psi <- plogis(b0 + b.for*forest)
# draw occupancy for each site
z <- rbinom(n=N, size=1,prob=psi)
# specify detection probablility
p <- 0.5
pz <- p*z
# generate the observations
Y <- rbinom(n=N, size=nobs,prob=pz)
#---- BUGS model ------------------------
model1 <- "model {
for (i in 1:N){
    logit(eta[i]) <- b0 + b.for*forest[i]
    z[i] ~ dbern(eta[i])
    pz[i] <- z[i]*p
    y[i] ~ dbin(pz[i],nobs)
} #i
b0.0 ~ dunif(0,1)
b0 <- log(b0.0/(1-b0.0))
b.for ~ dnorm(0,0.01)
p ~ dunif(0,1)
}"
occ.data1 <-list(y=Y,N=N,nobs=nobs,forest=forest)
inits1 <- function(){list(b0.0=runif(1),b.for=rnorm(1),p=runif(1),z=as.numeric(Y>0))}
parameters1 <- c("b0","b.for","p")
#---- RUN MODEL ------------------------
library(runjags)
ni <- 2000
nt <- 1
nb <- 1000
nc <- 3
ad <- 100
out <- run.jags(model=model1,data=occ.data1,monitor=parameters1,n.chains=nc,inits=inits1,burnin=nb,
    sample=ni,adapt=ad,thin=nt,modules=c("glm","dic"),method="parallel")

A: To answer your questions:
1)  rjags and JAGS used linked (non-interchangable) versions, and CRAN systems are still using JAGS_3.4.0 so the version of rjags on CRAN matches.  This will be updated soon, and in the meantime you can grab the correct version of rjags from the sourceforge page as @jbaums notes.
2)  This is a helpful message from JAGS/rjags telling you that you have specified something as data that the model isn't using.  Remember that variable names are case sensitive i.e.
library('runjags')
model <- "model {
    m ~ dunif(-1000,1000)
    #data# M
    #inits# m
    #monitor# m
}"
M <- 0
m <- list(-10, 10)

results <- run.jags(model, method="interruptible", n.chains=2)
results <- run.jags(model, method="rjags", n.chains=2)

... gives you a warning because M does not match m.  Also note that the warning looks a bit different from the two function calls - in the first it comes half-way down the JAGS output and in the second it comes as a warning in R after the function is completed.
As for 'should I be concerned' - yes if you think these variables should be in your model.  If you can't find the problem try posting the code you are using - it got cut off from your original post.
Matt


text:
Q: trying to find iframe that wraps email Id field I want to switch my webdriver to iframe before entering email id in the email id box. I am not able to locate the iframe that surrounds the email id box.
How do i locate iframe in order to make below code work?
Below is the java webdriver code,
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

public class HandlingIframes {

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

        WebDriver driver = new FirefoxDriver();

        driver.navigate().to("http://www.firstcry.com/");

        Thread.sleep(3000);

        driver.switchTo().frame(driver.findElement(By.xpath(".//*[@id='amt']/div[2]"))); //This locator is not working.

        driver.findElement(By.xpath(".//*[@id='Email']")).sendKeys("happita@gmail.com");

        Thread.sleep(4000);

    }

}

A: I went to the page source and found the id of the iframe and used it. Below code is working fine now.
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

public class HandlingIframes {

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

        WebDriver driver = new FirefoxDriver();

        driver.navigate().to("http://www.firstcry.com/");

        Thread.sleep(3000);

        driver.switchTo().frame("iframe_Login");

        driver.findElement(By.xpath(".//*[@id='Email']")).sendKeys("happita@gmail.com");

        Thread.sleep(4000);

    }

}


text:
Q: Left Ideals and Two-Sided Ideals of Rings of Matrices This is a question I posted in this topic: Pathologies in "rng".  However, I decided that the question deserves its own thread, and I want to know if anybody can answer it.  For terminologies, please read my reply in that link.

Let $R$ be a (not necessarily unital) ring and $n\in\mathbb{N}$.  What
  are all left ideals and two-sided ideals of the ring of matrices
  $S:=\mathrm{Mat}_{n\times n}(R)$?

Assume that $R$ is unital. Then, there is a one-to-one correspondence between the set $\mathcal{L}\left(R^n\right)$ of all left $R$-submodules of the unitary $R$-module $R^n$ and the set $\mathcal{L}(S)$ of all left ideals of $S$ which associates each $V\in\mathcal{L}\left(R^n\right)$ with the left ideal of $S$ consisting of matrices $\left[v_{i,j}\right]_{i,j\in[n]}$, where $[n]:=\{1,2,\ldots,n\}$, and $\left(v_{i,1},v_{i,2},\ldots,v_{i,n}\right) \in V$ for every $i\in[n]$.  There is also a one-to-one correspondence between the set $\mathcal{T}(R)$ of two-sided ideal of $R$ and the set $\mathcal{T}(S)$ of two-sided ideals of $S$.  This correspondence associates $I\in\mathcal{T}(R)$ with $\text{Mat}_{n\times n}(I)$.
Now, what happens if $R$ is nonunital?  I don't know the answer, and I suspect that it is an open question.
EDIT: When $R$ is a trivial ring (i.e., an additive abelian group $R$ with the trivial multiplication: $r\cdot s:=0_R$ for all $r,s\in R$), we have a somewhat good characterization of left ideals and two-sided ideals of $\text{Mat}_{n\times n}(R)$.


text:
Q: Understanding Battery discharge rating Please find the attached image showing amaron quanta 12 V 100 Ah VRLA battery discharge chart at constant current rating.
I am bit confused that how should I calculate the battery capacity based on that.
In the table they shown end cut off voltage like 1.3 V, 1.55 V, 1.6 V, 1.7 V, 1.75 V and 1.8 V and corresponding ampere in table like 5 min, 10 min, ....5 hr, 10 hr, 20 hr etc.
If I simple take 10 hr reading then
1.6 V = 9.72 amp
1.7 V = 9.49 amp
1.75 V = 9.31 amp
1.8 V = 9.26 amp
Out of all this what parameter to be consider in discharge test. Most searches says that it should be 1.75X6=10.5 V is the cut off voltage and related to that constant current to be passed. but if that is the case why manufacturer is giving 1.3 V, 1.55 V, 1.6 V, 1.7 V, 1.75 V, and 1.8 V etc. and current parameter for that. If I take 1.6 V and related to that 9.72 amp as discharge current does it will show different capacity of battery or it will be the same regardless of the cut off voltage and current rating.

A: That table tells you two things.
1) The slower you discharge the battery, the more capacity you'll get. Compare the 20 hour figures, which give more or less the rated 100Ah capacity of the battery, and the 60 minute figures of around 60Ah.
2) The deeper you discharge the battery, the more capacity you'll get. Compare the 1.8v and 1.6v endpoint voltage figures on any column.
Now you get to choose what endpoint voltage you want to use in your application.
The deeper you discharge the battery, the fewer charge/discharge cycles it will deliver before wearing out. Do you want high capacity, or do you want a battery that lasts many charge/discharge cycles? You can't have both.
If you're lucky, the battery data sheet will have a graph or table of expected number of cycles versus endpoint voltage.
A battery like this is quite well suited to an application where you habitually use only 50% of the rated battery capacity, but occasionally need an emergency reserve that is not used all that often. You sacrifice a little bit of battery lifetime for high capacity when you must have it.


text:
Q: Table caption floating out of table I have a Table with caption, which I arrange using the caption package. In one longtable for which I decreased font size to 4.9pt (I know, small), the table caption is too far left, hanging out of the table.

When I increase the font to 5pt, the problem vanishes. Changing \captionsetup[..., margin=1em, ...] to 2em does not help at all, the caption is not even moving one bit. I cannot provide a full MWE but I do have the preamble of my table:
\begin{ThreePartTable}
\setlength{\tabcolsep}{0.5pt}
\fontsize{4.9}{4.9}\selectfont
\begin{TableNotes}
\item\textit{Notes:}  ...
\end{TableNotes}
\captionsetup[table]{labelsep=newline, textfont=it, margin=1em, font=tiny}
\begin{longtable}{lcccccccccccccccccc}
\caption{Some Table} \label{tab:some} \\
\toprule
...[headers]
\midrule
\endfirsthead
\caption*{Some Table (continued)} \\
\toprule
...
\midrule
\endhead
\bottomrule
\endfoot
\bottomrule
\insertTableNotes
\endlastfoot