An Angular2 app with karma & jasmine throws errors with multi-level directory structure

Question: I am building an Angular 2 app with the current 4.0.0-beta.1 release. After many hours of struggle, I got karma running. I'm now trying to get a jasmine tautology test (true=true) to run, but karma reports:

"Uncaught ReferenceError: describe is not defined"

Here are the relevant code sections:
karma.conf.js
module.exports = function(config) {
config.set({

basePath: '',
frameworks: ['jasmine'],
// these plugins seem to be necessary. Without them, an error about a missing require in app.component.js occurs in karma
plugins: [
  require('karma-jasmine'),
  require('karma-chrome-launcher'),
  require('karma-htmlfile-reporter')
],

files: [
  'src/client/app/*.js',
  'src/client/app/components/**/*.js'
],

1st.spec.ts
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { By }  from '@angular/platform-browser';
import { DebugElement } from '@angular/core';

////////  SPECS  /////////////
describe('1st tests', () => {
  it('true is true', () => expect(true).toBe(true));
});

The 1st.spec.ts file is in the 'src/client/app/*.js' folder, which is specified in the files: array of karma.conf.js
What is missing?  How do you get Angular2 to recognize jasmine functions?  I do not have any of the testing components imported into app.module.ts because I haven't seen any tutorials mention that.  Is that the secret? If so what goes in there?
Comment: Today, I added karma-typescript-preprocessor to the devDependencies. I now get the ReferenceError require is not defined in the app.component.js file. Also, one tutorial said to wrap the describe function with export function main() { . . . } When I do that, I get exports is not defined in the 1st.spec.js file. Where is a complete setup tutorial, not using a seed, with all the files for an Angular2 app?
Answer: After weeks of reading tutorials, karma docs, and buying ng-book2, I discovered that no one describes how to set test configs when app.component.ts is several levels down in the directory structure. Karma docs may explain this, but the docs are so verbose and abstract, without examples, I was not able to gain any meaning from them. I also found that Angular's quickstart apps have various 'secret sauces' to enable karma & jasmine testing, e.g., karma-test-shim.js (which you cannot get via npm).
With no help from the above docs, I re-started with Angular's Setup.  Setup uses systemjs. AngularCLI uses Webpack. Read about this. It makes a difference for my solution below and for your longer term actions.  Jasmine tests work off the shelf for Angular Setup's Quickstart. I nudged the directory structure to my multi-level and tweaked lots of things to find configs that kept karma & jasmine working. Bottom line - Systemjs and karma.config.js both have to change - together. A change in only 1 of them just creates new and novel console errors.
Systemjs - change app: in the map object to your path. In my case, its
map: {
  app: 'src/client/app',
  // the rest of map
}

karma.conf.js - change appBase and appSrcBase in the module.exports function
var appBase    = 'src/client/app/';  //originally appBase='app/';
var appSrcBase = 'src/client/app/';

The Console errors make it sound like the problem is in the @angular bundle paths. Changes there just created different errors. Don't get sucked in.
Hope this saves you lots of time in getting tests going on an app that has a real life directory structure.


BeanIO - How to detect multiple record with same type

Question: How to detect, in a fixed length file, the same record type?
BeanIO dected only first record header without the others two documents.
What I would like is to obtain wrapper class with the three documents and their item codes.
This is an example of fixed length txt file:
Unknown record
Unknown record
RH20210607A
RDitem1
RDitem2
Unknown record
RH20210607B
RDitem2
RDitem3
Unknown record
Unknown record
Unknown record
RH20210607C
RDitem1
RDitem4
RDitem5

I want to detect the header (RH) and detail (RD) record.
I designed a group list with another group for each subgroup.
Top group class:
@Group(name = "fixedFile")
public class ListDocumentWrapper {

    @Group(minOccurs=1, type=Document.class, collection = List.class)
    List<Document> documentList;
}

Subgroup class:
@Data
public class Document{

    @Record(order = 1, minOccurs=1, maxOccurs=1)
    private RH recordHeader;
    @Record(order = 2, minOccurs=1, type=RD.class, collection = List.class)
    private List<RD> recordDetails;
}

Single record class:
@Data
@Record
public class RH{

    @Field(ordinal = 0, required = true, length = 2, align = Align.LEFT, rid = true, literal = "RH")
    private String recordType;

    @Field(ordinal = 1, required = true, length=8, format = "yyyyMMdd")
    private LocalDate documentDate;

    @Field(ordinal = 2, required = true, length = 1, padding = ' ', align = Align.LEFT)
    private String documentCode;
}

@Data
@Record
public class RD{

    @Field(ordinal = 0, required = true, length = 2, align = Align.LEFT, rid = true, literal = "RD")
    private String recordType;

    @Field(ordinal = 1, required = true, length = 5, padding = ' ', align = Align.LEFT)
    private String itemCode;
}

Init of BeanReader:
// create a StreamFactory
StreamFactory factory = StreamFactory.newInstance();
// load the mapping file
String streamBuilderName = "fixedFile";
        factory.define(
                new StreamBuilder(streamBuilderName)
                        .format("fixedlength")
                        .parser(new FixedLengthParserBuilder())
                        .ignoreUnidentifiedRecords()
                        .addGroup(ListDocumentWrapper.class)
        );

BeanReader beanReader = factory.createReader(streamBuilderName, aFileReader, Locale.ITALIAN);

Thanks for help
Comment: Please also show how you constructed and initialized your `BeanReader` instance
Comment: I updated the initialization part. Thanks
Answer: I didn't find the right solution, but I found a workaround.
The desire is to make a single read and get a list of document
This is the workaround.
First I didn't understand that beanReader.read() extract the first element of stream. So it's no necessary to create ListDocumentWrapper but read all Document with a simple while loop.
This is the extract of code:
List<Document> documentList = new ArrayList<>();
Document documentMessage = null;
int documentIndex = 0;
        while ((documentMessage = (Document) beanReader.read()) != null) {
            // process the documentMessage...
            log.debug("Reading documentMessage ["+documentIndex+"]... => " + documentMessage);

            documentList.add(documentMessage);
            documentIndex++;
        }

Comment: Glad you found a solution


action when a cell is clicked

Question: H!
I am new to VBA.
This maybe a too simple of a question, but I am struggling to use VBA:
when a cell(1,1) is clicked as it has 1, the msgbox would show up saying "hi"
Sub test()
  'click action 'when cell(1,1) is clicked and if cells(1,1) is 1, msgbox saying "hi" will show up, if not nothing If Cells(1, 1) = 1 Then
  MsgBox "hi"
  Else
End If
End Sub

Comment: Can you add a button?  Those have events.
Answer: This code belongs in the worksheet module.
Right click on the sheet tab and select "View Code"
Paste this code there:
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    If Target.Address = "$A$1" Then
        If Target = 1 Then
            MsgBox "hi"
        End If
    End If
End Sub

Comment: This is not exactly the correct answer because it doesn't trigger if the cell is already (the only cell) selected.
Comment: @6diegodiego9, This is the answer the OP was looking for. Good thing you showed up 4 yrs later to make a comment.
Answer: The challenge for me was to distinguish between a "move on the cell via cursor movement" and "cell clicked by mouse". The Worksheet_SelectionChange() does not do this. I found something here (also late, but maybe still valuable).
In short, add the following code in the VBA editor to the concerning sheet:
Option Explicit

Private Type POINTAPI
    x As Long
    y As Long
End Type

Private Type MSG
    hwnd As Long
    Message As Long
    wParam As Long
    lParam As Long
    time As Long
    pt As POINTAPI
End Type

Private Declare Function PeekMessage Lib "user32" _
Alias "PeekMessageA" _
(ByRef lpMsg As MSG, ByVal hwnd As Long, _
ByVal wMsgFilterMin As Long, _
ByVal wMsgFilterMax As Long, _
ByVal wRemoveMsg As Long) As Long

Private Const PM_NOREMOVE = &H0
Private Const PM_QS_INPUT = &H20000

Private Sub Worksheet_SelectionChange(ByVal Target As Range)

    Dim Message As MSG

    'check for left-mouse button clicks.
    PeekMessage Message, 0, 0, 0, PM_NOREMOVE Or PM_QS_INPUT
    'if left-mouse clicked on cell F4 run macro
    If Message.Message = 512 Then
        If Selection.Address = Range("f4").Address Then
            MsgBox "You clicked cell: " & Selection.Address
        End If
    End If

End Sub

How it works: If the cell changed (however), the next message concerning mouse movement is queried. If it is 512 (WM_MOUSEMOVE) and the the position matches the interesting cell (in this case F4) the messagebox is displayed.

If you get an error about 64bit compatibility and the use of PtrSafe, you can enter the following (replace the definitions above):
Private Type MSG
    hwnd As LongLong
    Message As Long
    wParam As LongLong
    lParam As LongLong
    time As Long
    pt As POINTAPI
End Type

Private Declare PtrSafe Function PeekMessage Lib "user32" _
Alias "PeekMessageA" _
(ByRef lpMsg As MSG, ByVal hwnd As LongLong, _
ByVal wMsgFilterMin As Long, _
ByVal wMsgFilterMax As Long, _
ByVal wRemoveMsg As Long) As Long

action when a cell is clicked


Connecting to SQL Server with PDO_MSSQL in PHP

Question: I have a problem while trying to connect to my SQL Server 2000 database using pdo_mssql with this line:
<code>$connection = new PDO ('mssql:host=localhost;dbname=DNAME', 'user', 'password');
</code>
The exception is the following:
<code>PHP Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[HY000] General SQL Server error: Check messages from the SQL Server. (severity 5)' in C:\Inetpub\wwwroot\public\test.php:2 Stack trace: #0 C:\Inetpub\wwwroot\public\test.php(2): PDO->__construct('mssql:host=loca...', 'user', 'password') #1 {main} thrown in C:\Inetpub\wwwroot\public\test.php on line 2
</code>
If I make the connection using the function mssql_connect() as follows, I obtain no error and my connection is correctly made:
<code>$link = mssql_connect ('localhost', 'user', 'password');
</code>
Any idea? Where can I read the detailed error message? Thanks
Comment: Does your database name contain any non-alphanumeric characters?
Comment: Which version of PHP are you using?
Comment: PHP 5.2.17 with pdo_mssql and mssql extensions installed
Answer: My database name had the character "-", removing it solved the problem!
Comment: Same problem here... but cannot remove "-" from database name.
Tried connection on another DB and works very well.


How can we approximate a function by sampling a distribution proportial to it and making a histogram of samples?

Question: I've read the following (here on page 2):

Suppose that you want to approximate a function $f$. One way to do this is to produce a sampling distribution proportional to $f$ and then make a histogram of samples taken from the distribution. The resulting histogram will be proportional to $f$ (obviously), so it only needs to be scaled to approximate $f$.
The procedure can be summarized as follows:

Create a sampling distribution proportial to $f$
Make a histogram of samples taken from the sampling distribution
Scale the histogram to approximate $f$

The sacle factor $s$ needed to make the histogram approximate $f$ is the ratio of the average value $v$ of $f$ over the sampling domain to the average number $h$ of samples per bin in the histogram, i.e. $s=v/h$.

I'm not sure how seriously this has to be taken, but could anybody explain to me (in a more formal way) what the author is meaning to say?
Let's consider a example: Assume $f$ is the density of the standard normal distribution $\mathcal N_{0,\:1}$. We could divide an interval $[a,b]$ into $C$ "bins" of size $\delta$. Now we could draw $n$ samples from $\mathcal N_{0,\:1}$ and record for each bin $i$ the number $B(i)$ of samples falling into that bin (if $x\in[a,b)$ is a sample, it lies in the $\lfloor\frac{x-a}\delta\rfloor$-th bin).
Clearly, $$[a,b)\ni x\mapsto B\left(\lfloor\frac{x-a}\delta\rfloor\right)\tag1$$ is an approximation of the shape of $f$.
Now, let $v$ be the average value of $f$ on $[a,b]$, $h$ be the average number of samples per bin and $s:=v/h$. If I got it right, the desired approximation would be $$\tilde f(x):=sB\left(\lfloor\frac{x-a}\delta\rfloor\right)\;\;\;\text{for }x\in[a,b).$$ Here's a plot of the result for $a=-5$, $b=5$, $C=2000$, $\delta=(b-a)/C$ and $n=1000000$:

Obviously, the scale is not correct. Did I made any mistake or is there something wrong with the description in the paper?
Comment: You should definitely try a function that is not the normal density, i think it will be more illuminating
Comment: @GeorgeDewhirst I think so. Each time I draw a sample $sample$, I calculate the bin via $bin=\lfloor\frac{sample-a}\delta\rfloor$ and accumlate $avg=avg+f(a+(bin+\alpha)*\delta)$, where $\alpha\in[0,1]$ ($\alpha=0$ -> evaluate bin at left endpoint, $\alpha=0.5$ -> evaluate bin at the middle, $\alpha=1$ -> evaluate bin at right endpoint). At the end I divide $avg$ by the number of samples drawn.
Comment: You can also use the theoretical average for comparison, obtained by integrating the pdf
Comment: But it looks like you've done the right thing
Comment: @GeorgeDewhirst Could you elaborate on what exactly you mean? If I've done everything correctly, why is the result obviously not correct?
Comment: It is only incorrect up to scaling factor, the approximation of $f$ looks good otherwise, though you'd definitely expect it to be good. Have you computed the average of $f$ over the domain correctly? The mass of $f$ at 0 would be $\frac{1}{\sqrt{2\pi}}$. So you can deduce the correct factor
Comment: @GeorgeDewhirst Thank you for the suggestion (I didn't thought about that). With the theoretical average everything works fine. I've mistakenly computed the average in the wrong way. However, I still don't understand why this is a sensible approximation. I've asked for that here: https://math.stackexchange.com/q/3221016/47771. Maybe you can take a look.
Answer: It looks like you're taking $v$ to be the sample average of $f(x)$ where $x$ is drawn from $N_{0,1}$ (perhaps conditioned to $x\in[a,b]$ - this wouldn't make much difference). Instead,
$v$ should be the average of $f(x)$ for the uniform distribution on $[a,b]$ - this is what they mean by "selected at random from the sampling domain."
If you add up $f(x)$ at the points $a,a+\delta,\dots,a+(C-1)\delta,$ you should expect to get about $vC$ - the average of $f$ multiplied by the number of points. If you add up $\overline f(x)$ at these points, you get exactly $sn.$ So it makes sense to take $s=vC/n=v/h.$
Comment: What is $\overline f$ in your second to last comment? You're right, I've computed the $v$ in the wrong way. So, how should $v$ be computed? Seems like one needs to compute $v$ separately before running the actual algorithm.
Comment: @0xbadf00d: I meant the $\tilde{f}$ from your post - the approximation to $f.$ And yes, $v$ has to be computed separately, but this could be done in parallel to the histogram. Section 3.5 in the paper is the relevant bit
Comment: I'm still unsure why $\tilde f$ is a sensible approximation. Please take a look at this question: https://math.stackexchange.com/q/3221016/47771.
Comment: From your last equation, it seems like you're assuming $n=Ch$. But is that correct? $n$ is the total number of samples drawn from $\mathcal N_{0,\:1}$ in the example. Now $\mathcal N_{0,\:1}$ generates samples on its entire domain $\mathbb R$ (sure, the support of this distribution is much smaller, but suppose we don't know that), while we're only approximating $f$ on $(a,b]$. So, not all of the generated samples lie in the domain of interest $(a,b]$ and hence we only know that $Ch\le n$.
Comment: Oh and while it's clear to me what you're writing, we do not add up the values of $f(x)$ or $\tilde f(x)$ in the computation. So, I don't understand how you derived $s$.


Any tricks to adjust windows that are not collinear?

Question: I spent so much time making sure each window was level and plumb that I didn't think to make sure they were equal to each other. Now that they're flashed and nailed, they're about 3/8" off which I can tell when I look at it (not sure anyone can).
My plan is to vinyl side this shop and I'm worried the issue will be exacerbated once the siding goes on. I'm hoping I can tweak the windows so it's not noticeable without having to remove them and start over.
My initial thought was to add 3" trim around the windows and to cut the left one a little larger on the top and a smaller larger on the bottom to level it out. Would this work?
Comment: You won't notice it. The only reasons you do now are 1) it's fresh in your mind, and 2) there's a seam in the Tyvek right there. Unless you have a siding edge _right there_ it'll fade from memory before long. Almost no one else will ever see it.
Comment: Trick 1: live with it. Trick 2: rip out and redo. Trick 1 tends to be the winner unless you are contractor working for someone else and ignored the plans.
Comment: Ecnerwal & isherwood are correct. However, your idea of adjusting with the trim is a good one. But I think I would only do it if the trim is going to be a different color than the siding. That would make it a little more noticeable.
Comment: You could fiddle the trim (personally, I wouldn't), but if you don't, try to make sure the bottom/top of the windows is around the middle of the siding. (In other words, don't have a siding seam too close to the bottom/top planes.)
Comment: @isherwood every time the OP looks at it they will notice it, especially when the siding goes on and the window height to the next line of siding is different on each window.
Comment: Once nice, even horizontal lines have been drawn across the face of the wall with siding, it will be even more noticeable. Ignoring it will only drive the OP mad. Please do stop back by to tell us what you did!
Answer: You could grow vines on it. It's also excellent to keep it cool in summer.
Comment: On vinyl siding? Erm....
Comment: On _any_ building? Not good for the building...
Comment: You have to trim it at the top so it doesn't cause leaks in the roof.


iPhone SDK: Call tableview function anywhere

Question: I wanted to know if there was a way to call the tableview function anywhere throughtout the program. What I mean is I want to call this function:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

anywhere in my code. is there anyway of using the self function or anything or if its possible at all? Thanks.
Comment: Why? That method is only used by the table view to provide cells for the table. What are you trying to achieve by calling this from anywhere?
Comment: Are you trying to reloadData?
Comment: I'm trying to break down an error with the table view and when I put a breakpoint on this method it seems to only go through when you launch the app but not while its running, I'm looking for an alternative to calling this method from something like a void function so maybe I can break it down from there.
Comment: What's the error and where is the error coming from?
Answer: You sure can. You just have to be able to pass an NSIndexPath object to it, like this:
UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];

Once cellForRowAtIndexPath returns your cell object, you can access its properties, etc. like:
cell.backgroundView.alpha = 0.0;

Also, if you are using a custom UITableViewCell, you can get your custom cell returned by type casting the call:
MyCustomCellClass *cell = (MyCustomCellClass *)[self.tableView cellForRowAtIndexPath:indexPath];

Answer: You can just call [tableview reloadData];  this will call cell for row at index path.
Answer: You can do it this way:
  // First do modifications in the datasource for table
    // And then you can reload the specific row like this:

NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];

[self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];

And the reason your cellForRowAtIndexPath is not calling may be because you did not set the delegate OR there are no visible rows on the UI to display as Table calls this function for the rows which are visible on screen so check the frame of your table too.


How to insert multiple sections in collectionview at once?

Question: Actually i know how to insert one section at a time but i don't know
how to insert multiple section at once?.
collectionView.insertSections(IndexSet(integer: array.count + 1))

how to insert multiple section at once?.
ex
var array = [3,4,2,1,6] // one section for one element

func numberOfSections(in collectionView: UICollectionView) -> Int {
   return array.count
}

func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
    return array[section]
}

//now i want to add three new sections [8,5,9]

Api doc:

Use this method to insert one or more sections into the collection
  view. This method adds the sections,
Comment: @vadian now it make sence?
Comment: Please see the updated answer.
Answer: An IndexSet can contain multiple indexes
collectionView.insertSections(IndexSet([2, 4, 7]))

Edit:
To insert 3 new sections at end of
var array = [3,4,2,1,6]

use
let startIndex = array.count
array.append(contentsOf: [8,5,9])
let endIndex = array.count
collectionView.insertSections(IndexSet(startIndex..<endIndex))

Comment: thanks, but suppose i have 5 sections and i want to add 3 new section at the end


Python Lex-Yacc (PLY) Error recovery at the end of input

Question:
Problem
I am trying to implement an error tolerant parser using Python Lex-Yacc (PLY), but I have trouble using error recovery rules at the end of my input string.
How can I recover from an unexpected end of input?
Example
This example grammar produces strings of the form A END A END A END A END ...
Statement   : Expressions

Expressions : Expression Expressions
            |

Expression  : A END

I want to perform an error recovery if the END Token was omitted, so stings like A A A END or A A A will be recognized by the parser.
My approach
I added an error recovery rule, which allows me to accept input like A A A END
Expression : A END
           | A error

Which allows me to accept the following input:
A A A END
But if the last END token is omitted (A A A), I still get a syntax error and cannot recover.

Sample PLY code
from __future__ import print_function

# Tokens
tokens = ('A', 'END')

t_A   = r'A'
t_END = r'END'
t_ignore = " "

def t_error(t):
    print("Illegal character '%s'" % t.value[0])
    t.lexer.skip(1)

# Build the lexer
import ply.lex as lex
lex.lex()

# Rules
def p_statement_expr(p):
    '''statement : expressions'''
    print("parsed:", p[1])

def p_expressions(p):
    '''expressions : expression expressions'''
    p[0] = [p[1]] + p[2]

def p_expressions_empty(p):
    '''expressions : '''
    p[0] = list()

def p_expression_pharse(p):
    '''expression : A END
                  | A error'''
    p[0] = 'A'

def p_error(p):
    if p:
        print("Syntax error at '%s'" % p.value)
    else:
        print("Syntax error at EOI")

import ply.yacc as yacc
yacc.yacc()

while 1:
    try:
        s = raw_input('query > ')   # use input() on Python 3
    except EOFError:
        break
    yacc.parse(s)

Comment: You say you want to be tolerant. But to you want to just emit a warning and considere all A as valid even if there is no end, only keep first A and ignore the others until end, only keep last A and ignore previous ones. Same at end, do you want to reject the terminal A or process it as valid ?
Comment: I want to emit a warning and accept all `A`s as valid, even if there is no `END`.
Answer: I add it as a new answer (and do know it is too late for the bounty :-( ) because it is a very different approach. If we used flex, it would be much easier, since it has the notion of the <<EOF>> token that matches only at end of file. After thinking about that, I realized that it was very simple to add that functionality to PLY without any change to the original module by using a proxy  around the lexer. And Python allows easy implementation of proxies thanks the the __getattr__ special method.
I just add

a new token EOF that will be send at end of file
a proxy around the token method of the lexer that on end of file returns the special EOF token on first pass and then the normal None
the eof token to end statement rule

And still reverse the rule expressions : expressions expression instead of expressions : expression expressions to allow immediate reduce
The code becomes :
from __future__ import print_function

# Tokens
tokens = ('A', 'END', 'EOF')

t_A   = r'A'
t_END = r'END'
t_ignore = " "

def t_error(t):
    print("Illegal character '%s'" % t.value[0])
    t.lexer.skip(1)

# Build the lexer
import ply.lex as lex

orig_lexer = lex.lex()

class ProxyLexer(object):
    def __init__(self, lexer, eoftoken):
        self.end = False
        self.lexer = lexer
        self.eof = eoftoken
    def token(self):
        tok = self.lexer.token()
        if tok is None:
            if self.end :
                self.end = False
            else:
                self.end = True
                tok = lex.LexToken()
                tok.type = self.eof
                tok.value = None
                tok.lexpos = self.lexer.lexpos
                tok.lineno = self.lexer.lineno
        # print ('custom', tok)
        return tok
    def __getattr__(self, name):
        return getattr(self.lexer, name)

lexer = ProxyLexer(orig_lexer, 'EOF')

# Rules
def p_statement_expr(p):
    '''statement : expressions EOF'''
    print("parsed:", p[1])

def p_expressions(p):
    '''expressions : expressions expression'''
    p[0] = p[1] + [p[2]]

def p_expressions_empty(p):
    '''expressions : '''
    p[0] = list()

def p_expression_pharse(p):
    '''expression : A END
                  | A error'''
    p[0] = 'A'

def p_error(p):
    if p:
        print("Syntax error at '%s'" % p.value)
    else:
        print("Syntax error at EOI")

import ply.yacc as yacc
parser = yacc.yacc()

while 1:
    try:
        s = raw_input('query > ')   # use input() on Python 3
    except EOFError:
        break
    parser.parse(s, lexer = lexer)

That way :

the original grammar is unchanged
the error recovery method remains stupidly simple and has no dependance on the remaining of the grammar
it can be easily extended to complex parsers
Answer: As you want to accept all elements, you can explicitely declare a rule for a A not followed by a END and use the fact that yacc and PLY  friendly deal with ambiguous rules.
You can simply have a normal rule :
Expression : A END

and below a lower priority rule (as it comes later) that will issue a warning
Expression : A

That way, all A will be accepted, there won't be any syntax error, and the warning will be issued for any A not followed by a END including one at the end of the flow. In order to more easily find the offending A, I have added in the warning the position of the symbol in the flow.
Edit:
The script is modified to correctly deal with other syntax error (such as AENDENDAEND), and also to immediately reduce expressions by replacing expressions : expression expressions with expressions : expressions expression
Here is the modified script (tested in python 3.4 simply replacing raw_input with input):
from __future__ import print_function

# Tokens
tokens = ('A', 'END')

t_A   = r'A'
t_END = r'END'
t_ignore = " "

def t_error(t):
    print("Illegal character '%s'" % t.value[0])
    t.lexer.skip(1)

# Build the lexer
import ply.lex as lex
lex.lex()

# Rules
def p_statement_expr(p):
    '''statement : expressions'''
    print("parsed:", p[1])

def p_expressions(p):
    '''expressions : expressions expression'''
    p[0] = p[1] + [p[2]]

def p_expressions_err(p):
    '''expressions : expressions error'''
    p[0] = p[1]

def p_expressions_empty(p):
    '''expressions : '''
    p[0] = list()

def p_expression_pharse(p):
    '''expression : A END'''
    p[0] = 'A'

# add a separate rule BELOW previous one to display a warning
def p_expression_pharse_warn(p):
    '''expression : A'''
    print("Warning at absolute position %d (line %d)" % (p.lexpos(1), p.lineno(1)))
    p[0] = 'A'

def p_error(p):
    if p:
        print("Syntax error at '%s'" % p.value)
    else:
        print("Syntax error at EOI")

import ply.yacc as yacc
yacc.yacc()

while 1:
    try:
        s = raw_input('query > ')   # use input() on Python 3
    except EOFError:
        break
    yacc.parse(s)

Edit : the following is an incorrect attempt to avoid an additional rule : it is more complex and less efficient than the above version. Please see my conclusion below
Edit per comment :
I understand your point that you do not want to multiply grammar rules. It is possible to be fault tolerant, except for last token. If your last token is in error, it will not be followed by anything and will never be caught in rule expression : A error.
But here is a fault tolerant parser that keeps everything except last token if case of error on that one :
from __future__ import print_function

# Tokens
tokens = ('A', 'END')

t_A   = r'A'
t_END = r'END'
t_ignore = " "

def t_error(t):
    print("Illegal character '%s'" % t.value[0])
    t.lexer.skip(1)

# Build the lexer
import ply.lex as lex
lex.lex()

# Rules
def p_statement_expr(p):
    '''statement : expressions'''
    # print("parsed:", p[1])

def p_expressions(p):
    '''expressions : expressions expression'''
    p[0] = p[1] + [p[2]]
    result.append(p[2])

def p_expressions_empty(p):
    '''expressions : '''
    p[0] = list()

def p_expression_pharse(p):
    '''expression : A END
                  | A error'''
    p[0] = 'A'

def p_error(p):
    if p:
        global lasterr
        print("Syntax error at '%s' (%d)" % (p.value, p.lexpos))
    else:
        print("Syntax error at EOI")

import ply.yacc as yacc
yacc.yacc()

while 1:
    try:
        s = input('query > ')   # use input() on Python 3
    except EOFError:
        break
    result = []
    yacc.parse(s)
    print('Result', result)

The princip is to collate by expressions : expressions expression instead of expressions : expression expressions, and to keep all in a global variable.
With an input of  A END A A END A A A END it gives
Result ['A', 'A', 'A', 'A', 'A', 'A']

and with : A END A A END A A A END , it gives
Result ['A', 'A', 'A', 'A', 'A']

(all tokens but the last)
With a true flex - bison solution, it would be possible to make use of the special <<EOF>> token that matches at end of input, to always have another token after the last one. Unfortunately, it is not implemented in PLY, and the only real solution is to introduce a rule that accepts alone A token. For a real parser, it also guarantees that you are actually processing the correct token : I used
def p_expression_pharse(p):
    '''expression : A END'''
    p[0] = 1 + p.lexpos(1)

# add a separate rule BELOW previous one to display a warning
def p_expression_pharse_warn(p):
    '''expression : A'''
    print("Warning at absolute position %d (line %d)" % (p.lexpos(1), p.lineno(1)))
    p[0] = -1 - p.lexpos(1)

to uniquely identify tokens in resul string, and I get correct positions.
And ... the error processing is very simple ...
Discussion TL/DR :
I admit I missed the point of last token error recovery. It is because in all parsers I've seen in real use cases, the error recovery consisted in rejecting the part that was syntactically incorrect (and thus not directly useable) and re-synchonizing the parser on next correct group of token. In all what I have seen, if a partial sentence can be used, it must not be processed by the error recovery mechanizme but by a grammar rule, in which it is easy to describe the appropriate action.
If you just want to keep the offending input for later processing, I think it is not a problem of action depending of a syntax, and I would simply note the position of offending token, or at most note the position of last correctly analysed token (the end of a complete element), the begin of first error recovery token and say that what is between is incorrect.
But it would be much different than what is asked here ...
Comment: Thank you for your answer, but it misses the point a little bit. I do know, that I can augment my grammar to match this special case, but as the grammar grows bigger, there will be too many different error cases to define in the grammar.
Comment: `[...] But here is a fault tolerant parser that keeps everything except last token if case of error on that one`
But now it misses the point completely, as the main problem was the error recovery at the end of the input.
Comment: @Jen-Ya : if you want to accept a `A` as last token, you have to create a rule with A alone what was my first solution ! In fact, in a real parser, the solution would be to use a catchup for last token if one stay in the stack. But for such a simple example, it downgrades to my first solution ...
Comment: @Jen-Ya : I thought at what I did, and I really think that the correct solution is the first one. The only problem is that error processing is still mandatory. I've fixed it now. Please see my last edits.
Answer: This works for all examples I could imagine

from __future__ import print_function

# Tokens
tokens = ('A', 'END')

t_A   = r'A'
t_END = r'END'
t_ignore = " "

def t_error(t):
    print("Illegal character '%s'" % t.value[0])
    t.lexer.skip(1)

# Build the lexer
import ply.lex as lex
lex.lex()

# Rules
def p_statement_expr(p):
    '''statement : expressions'''
    #
    print("parsed:", p[1])

def p_expressions(p):
    '''expressions : expression expressions'''
    p[0] = p[1] + p[2]

def p_expressions_empty(p):
    '''expressions : '''
    p[0] = list()

def p_expression_pharse(p):
    '''expression : A END'''
    p[0] = ['A']

def p_expression_error(p):
    '''expression : A error'''
    p[0] = ['A']
    if p[2] is not None:
        p[0] += p[2]

def p_error(p):
    if p is None:
        print("Syntax error at EOI")
        e = yacc.YaccSymbol()
        e.type = 'error'
        e.value = None
        yacc.errok()
        return e
    elif p.type == 'error':
        yacc.errok()
        return
    elif hasattr(p, 'value'):
        print("Syntax error at '%s'" % p.value)
        e = yacc.YaccSymbol()
        e.type = 'error'
        e.value = p.value
        yacc.errok()
        return e

import ply.yacc as yacc
yacc.yacc()

while 1:
    try:
        s = raw_input('query > ')   # use input() on Python 3
    except EOFError:
        break
    yacc.parse(s)

Comment: @Jen-Ya Have you tried my edited version? For me it parses     A A A     to     ['A', 'A', 'A']    . I;m using ply 3.4 and python 2.7.3.
Comment: Thank you, this goes in the right direction. Why isn't it possible to set the token value to `error` instead of `END` on EOI? I would like to recover from different possible errors and cannot be sure, that the `END` token is needed in every case.
Comment: return error will cause p_expression_error(p) to execute. This will add two 'A' to output. Best thing to do would be to be able to return multiple tokens from p_error. Then we would be able to return 'error' and 'A'(p.value to be exact).
Comment: I have edited my answer to include suggestions from your comment. Hope this one suites you more.
Comment: Is anything missing from here? Can you help us with answering your own question?
Comment: Thank you for your adjustments, but the code you provided does not handle the syntax errors correctly. Example inputs `A A A` and `A A A END` are parsed as `['A', 'A']`.


.NET Service Repository Manager for SOA

Question: I'm searching a .NET service repository manager that manages all web services and ws-* - like authorization , auditing and logging,support service transactions , ...
Answer: There is a number of products that can apply runtime policies (e.g. security, auditing/logging), see http://www.soa.com/ for an example. Distributed transactions is rather more tricky as it requires that the backend systems have some way of supporting transactions or rolling back changes.
Answer: I'm not entirely sure of what you mean but...
Is it something like Jenkins/Hudson you are looking for?
http://jenkins-ci.org/
/J

.NET Service Repository Manager for SOA


JavaFX - Am I misunderstanding how to use KeyValues?

Question: KeyValue start = new KeyValue(enemy.translateXProperty(), 0);
KeyValue end = new KeyValue(enemy.translateXProperty(), 600);
KeyValue back = new KeyValue(enemy.translateXProperty(), 0);

KeyFrame startFrame = new KeyFrame(Duration.ZERO, start);
KeyFrame endFrame = new KeyFrame(Duration.seconds(5), end);
KeyFrame backFrame = new KeyFrame(Duration.seconds(5), back);

Timeline timeline = new Timeline(startFrame, endFrame, backFrame);
timeline.setCycleCount(Timeline.INDEFINITE);
timeline.play();

This is just some snippet from playing around since I'm on the animation section of the javafx book I've been reading, but I was wondering why it's not working. Basically, this is just supposed to make a circle goto the right and the left repeatedly. The KeyValue 'back' is supposed to take it back to the beginning, but it doesn't and the circle goes to the very right then spawns back to where it started instantly.
Am I misunderstanding something with KeyValues, or what? What's the problem here?
Comment: on the third ```KeyFrame``` the duration should probably be ```Duration.seconds(10)``` (i.e. a keyframe at 10 seconds) not 5?
Answer: The Duration time parameter of the KeyFrame constructor takes time relative to the start of the animation, not relative to the last KeyFrame.
If you want to animate the enemy.translateXProperty() property from 0 to 600 during the first 5 seconds of the animation and animate it back to 0 during the following 5 seconds, you need to use Duration.seconds(10) as parameter for the constructor of the back KeyFrame.
KeyFrame backFrame = new KeyFrame(Duration.seconds(10), back);

Note that for simply adding the reversed animation, you could also set autoReverse to true:
KeyValue start = new KeyValue(enemy.translateXProperty(), 0);
KeyValue end = new KeyValue(enemy.translateXProperty(), 600);

KeyFrame startFrame = new KeyFrame(Duration.ZERO, start);
KeyFrame endFrame = new KeyFrame(Duration.seconds(5), end);

Timeline timeline = new Timeline(startFrame, endFrame);
timeline.setAutoReverse(true);
timeline.setCycleCount(Timeline.INDEFINITE);
timeline.play();


htaccess, redirect to https for a specific file and to non-www https

Question: I've a site to work and trying to make redirect by htaccess for few days. I've searched the net and found good works, especially in this site, but altough I've tried almost every possibilities, I've could not achieve what I want to do.
My need is redirect all site to non-www http, including https, except for only one file. Let's say redirect
http ://www.example.com/.../....php?a=...
https ://www.example.com/.../....php?a=...
https ://example.com/.../....php?a=...
to
http ://example.com/.../....php?a=...
However, only one specific file
http ://www.example.com/.../theSpecificFile.php?a=...
https ://www.example.com/.../theSpecificFile.php?a=...
http ://example.com/.../theSpecificFile.php?a=...
should be redirected to
https ://example.com/.../theSpecificFile.php?a=...
To do these, I've wrote many htaccess files but in each case, I couldn't achieve my needs. e.g. At the last htaccess:
Options +FollowSymlinks
RewriteEngine on
RewriteBase /

ErrorDocument 404 http://example.com/404.php

#force https for certain pages
RewriteCond %{HTTPS} !=on
RewriteRule ^(theSpecificFile\.php)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R]

RewriteCond %{HTTPS} on
RewriteRule (.*) http://%{HTTP_HOST}%{REQUEST_URI} [R,L]

#redirect www.example.com to example.com (or any other subdomain)
RewriteCond %{HTTP_HOST} !^example.com$ [NC]
RewriteRule ^(.*)$ http://example.com/$1 [L,R=301]

By this htaccess file,
when I try to https ://www I get Unsecure or Untrusted connection (I'm translating from another language, hope it might be true translation) with  ssl_error_bad_cert_domainand when I try to access to the theSpecificFile.php I get error defining "infine loop" (again I hope this might be a true translation).
This is really frustrating for me, so, any help would be highly appreciated.
Thanks in advance
Answer: Look, here you redirect theSpecificFile.php to its https version, but then the second redirect rule triggers and redirects the browser back to http, and from there the first rule redirects back to https... That's why you're getting the infinite loop.
And ssl_error_bad_cert_domain means the certificate isn't for this domain, so you might need to check if you're using the right one.
Comment: Ok, after changing first and second "RewriteCond and RewriteRule" lines' places, when try to enter example.com, redirected to "https://example/com"
Answer: Please try:
RewriteCond %{HTTPS} on
RewriteConf %{REQUEST_URI} !=/theSpecificFile.php
RewriteRule (.*) http://%{HTTP_HOST}%{REQUEST_URI} [R,L]

Comment: `RewriteCond %{HTTPS} on
RewriteConf %{REQUEST_URI} !=/theSpecificFile.php
RewriteRule (.*) http://%{HTTP_HOST}%{REQUEST_URI} [R,L]

#force https for certain pages
RewriteCond %{HTTPS} !=on
RewriteRule ^(theSpecificFile\.php)$ https://%{HTTP_HOST}%{REQUEST_URI} [L,R]` tried htaccess with example.com and get https ://example/com
Answer: You can use that:
RewriteCond %{HTTPS} on
RewriteCond %{HTTP_HOST} ^www\. [NC,OR]
RewriteCond %{REQUEST_URI} !/theSpecificFile\.php [NC]
RewriteRule ^ http://example.com/%{REQUEST_URI} [L,R=302]

RewriteCond %{HTTPS} off
RewriteCond %{REQUEST_URI} /theSpecificFile\.php [NC]
RewriteRule ^ https://example.com/%{REQUEST_URI} [L,R=302]

Change [R=302,L] to [R=301,L] when everything works well


Securely store data for multiple party's in a single table

Question: I'm certainly no DBA and only a beginner when it comes to software development, so any help is appreciated. What is the most secure structure for storing the data from multiple parties in one database? For instance if three people have access to the same tables, I want to make sure that each person can only see their data. Is it best to create a unique ID for each person and store that along with the data then query based on that ID? Are there other considerations I should take into account as well?
Comment: read this: http://msdn.microsoft.com/en-us/library/aa479086.aspx . I would go tenant per schema (if using mysql, a mysql "database" is really just a database schema).
Answer: You are on the right track, but mapping the USER ID into the table is probably not what you want, because in practice many users have access to the corporations data.  In those cases you would store "CorpID" as a column, or more generically "ContextID".  But yes, to limit access to data, each row should be able to convey who the data is for, either directly (the row actually contains a reference to CorpID, UserID, ContextID or the like) or it can be inferred by joining to other tables that reference the qualifier.
In practice, these rules are enforced by a middle tier that queries the database, providing the user context in some way so that only the correct records are selected out of the database and ultimately presented to the user.
Answer:
...three people have access to the same tables...

If these persons can query the tables directly through some query tool like toad then we have a serious problem. if not, that is like they access through some middle tier/service layer or so then @wagregg's solution above holds.
coming to the case when they have direct access rights then one approach is:

create database level user accounts for each of the users.
have another table with row level grant information. say your_table has a primary key column MY_PK_COL then the structure of the GRANTS_TABLE table would be like {USER_ID; MY_PK_COL} with MY_PK_COL a foreign key to your_table.
Remove all privileges of concerned users from your_table
Create a view. SELECT * FROM your_table WHERE user_id=getCurrentUserID();
give your users SELECT/INSERT/UPDATE rights on this view.

Most of the database systems (MySQL, Oracle, SQLServer) provide way to get current logged user. (the one used in the connection string). They also provide ways to restrict access to certain tables. now for your users the view will behave as a normal table. they will never know the difference.
a problem happens when there are too many users. provisioning a database level uer account to every one of them may turn difficult. but then DBMS like MsSQLServer can use windows authentication, there by reducing the user/creation problem.
In most of the scenarios the filter at middle tier approach is the best way. but there are times when security is paramount. Also a bug in the middle tier may allow malicious users to bypass the security. SQL injection is one thing to name. then you have to do what you have to do.
Answer: It sounds like you're talking about a multi-tenant architecture, but I can't tell for sure.
This SO answer has a summary of the issues, and links to an online article containing details about the trade-offs.


Oracle - Compare sum() with a numeric value

Question: I'm having some troubles with some comparisons.
I have 3 tables:
Table 1 Project
Id - Budget

Table 2 Member
Id - Category - Hours

Table 3 Costs
Category - Salary/hour

I need to get all projects that have spent more money than they could. To get the money spent i use a sum() but it gives me an invald identifier error
select p.id, sum(m.hours*c.salary)as spent, max(p.budget) from member m
join project p on p.id=m.id
join costs c on m.category=c.category
where spent>max(p.budget)
group by p.id;

I can't find anything similar and I don't know how to compare those two columns.
Thanks for your time.
Answer: You can't use the spent alias in the where clause; column aliases are only valid in the order-by clause unless you use a subquery. You should also be checking with a having clause, not in the where:
select p.id, sum(m.hours*c.salary) as spent, max(p.budget)
from member m
join project p on p.id=m.id
join costs c on m.category=c.category
group by p.id
having sum(m.hours*c.salary) > max(p.budget);

Or if you don't want to repeat it, use an inline view:
select id, spent, budget
from (
  select p.id, sum(m.hours*c.salary) as spent, max(p.budget) as budget
  from member m
  join project p on p.id=m.id
  join costs c on m.category=c.category
  group by p.id
)
where spent > budget;

You don't really need the max() aggregate for budget, if p.id is unique anyway, you can include that in the group-by clause instead:
select id, spent, budget
from (
  select p.id, sum(m.hours*c.salary) as spent, budget
  from member m
  join project p on p.id=m.id
  join costs c on m.category=c.category
  group by p.id, p.budget
)
where spent > budget;


Drupal autocomplete limit number of character

Question: In Drupal 7 website. I don't want to call ajax for autocomplete if entered string length is less than 3 characters.
I have written the Jquery like this
<code>    $('#name').keyup( function( e ) {
        if( $.trim( $('#edit-enterprise-ids').val().length ) < 3){
            return false;
        }
    });
</code>
But it is not working, If I write alert(''); in place of return false it works.
But I don't want to have alert there.
Please help.
Comment: Try using this module: https://www.drupal.org/project/autocomplete_limit. What particular field are you trying to limit? Text autocomplete or a View autocomplete for example.
Comment: So what shoudl happen? Because right now your event handler function does just end. So nothing happening is to be expected.
Comment: @stevenw00 it works.. thak you :)
Comment: I've added it as an answer below. Mark it as an answer for future users.
Answer: Try using the Autocomplete Limit module here:
https://www.drupal.org/project/autocomplete_limit


Image from extension appears as broken link when referenced from content-script

Question: I wrote a small content-script for a Chrome extension which inserts an image in a webpage, but when I watch a processed webpage the image appears as if the link was broken.
The image is at the root of my Chrome extension. I am using the getURL function from the extension API:
$('
This is my image
');

When I inspect the webpage, I see that the URL is:

I can't figure out what I did wrong. Please help me, I am stuck and clueless.
EDIT: Note: the link is indeed correct because when I click on "Open Image in New Tab", the icon is displayed correctly.
Comment: Chrome version 18.0.1025.142 on MacOSX 10.7.3.
Comment: You dont happen to have `"manifest_version" : 2` in your manifest do you?
Comment: What's your Chrome version? When you watch the Network tab, does anything show up? Does any error show up in the console?
Comment: Thanks to you, I noticed a suspect error in the Network tab:

initiator is: chrome-extension://eccjgancceeifipagkhggplcohgcgloa/jquery-1.7.2.min.js

"url": "chrome-extension://invalid/",   <---- that's probably the source of the problem, but I don't know how to interpret this error.
Comment: Note: I am a total beginner with Javascript, I might have made a basic mistake in the way to use jquery. I just placed the latest version I found on the jquery's website in the root dir of the extension, and added it to the content-script list in the manifest:

  "content_scripts": [
    {
      "matches": ["http://*/*", "https://*/*"],
      "js": ["jquery-1.7.2.min.js", "content_script.js"]
    }
  ],
Comment: I had "manifest_version" : 2 in my manifest and if I remove it it fixes the problem ! ^_^

Please write your solution in the proper form (an answer) so I can mark it as solution to make it searchable for others. Thanks !
Answer: You CAN downgrade your manifest version to a deprecated version (using 1 instead of 2), but the way you're supposed to do it in the v2 world is by whitelisting the assets you intend to embed in the page using the web_accessible_resources, described here.
This is because of a change in the default availability of assets in manifest v2:

Default Availablility
Resources inside of packages using manifest_version 2 or above are blocked by default, and must be whitelisted for use via this property.
Comment: It's worst solution you can use.
Comment: I don't really follow -- I describe the same solution that you do and explain why it's necessary.
Answer: What kind of answer is that? "use old manifest and you are good to go", of course use newest!
Old is old. It's depreciated.
Read documentation:  https://developer.chrome.com/extensions/content_scripts#extension-files
you can use extension's files with manifest 2.
//Code for displaying <extensionDir>/images/myimage.png:
var imgURL = chrome.extension.getURL("images/myimage.png");
document.getElementById("someImage").src = imgURL;

also you have to add your images to web_accessible_resources, that you are going to use outside extension, e.g. content script inserts it into some user's website:
https://developer.chrome.com/extensions/manifest/web_accessible_resources
manifest.json:
{
  ...
  "web_accessible_resources": [
    "images/*.png",
    "style/double-rainbow.css",
    "script/double-rainbow.js",
    "script/main.js",
    "templates/*"
  ],
  ...
}


vertical margin massacre in HTML emails

Question: I know HTML email rendering is a vale of tears, but this is too weird.
I'm trying to get a consistent vertical spacing between my elements.   I have
 elements I'm using as dividers, and I'm trying to apply top/bottom margins to them.  However, even though I'm applying these margins inline, the css is being mangled when I inspect it in my gmail client.
For example,
Sent as:

Recieved as:

What??...
Sent as:

Recieved as:

Come on...
I thought that in-line styles would be safe, and that even if rendering was failing, at least the actual CSS wouldn't be mangled.  What am I dealing with here?
(I'm sending these out with standard PHP mail() functions out of a WordPress site)
Comment: "Received as" means the source code gets rewritten, or it gets rendered that way?
Comment: @Pekka- It's getting re-written!
Comment: What happens if you add a space behind the colon? What if you put the hr in a div container and add the styles to that container instead of the hr. So .
Comment: Also, which mail client are you using, please?
Answer: Different clients handle the margin property different. Some completely ignore it. The most common way to get even vertical spaces is by using a table layout for the entire e-mail and use an empty row of table cells and set a height to them to create the spaces. Place your hr's in the tablecells without adding margins to them.
An alternative way to this is to insert you hr's as an image and setting a height to them.
I would go with the first method, because this is tried and tested among most of the popular clients. The alternative is worth trying if you're not comfortable with using tables to set up a layout.
It's never a good idea to use shorthand properties in html e-mails, because some clients don't support shorthand properties.

vertical margin massacre in HTML emails


Omitting an optional parameter, which is before another optional parameter in React Router

Question: I'm new to React, so please forgive me if I'm making a mistake :)
I'm using React router dom version 4.2.2.
I'm defining a path in my BrowserRouter like this :
<Route exact path="/my-base-url/myForm/:formMode/:templateID?/:ruleID?" component={MyFormComponent}/>

And referring in MyFormComponent.jsx as :
let formMode = this.props.match.params.formMode;
let templateID = this.props.match.params.templateID;
let ruleID = this.props.match.params.ruleID;

My question is, In a case where templateID is not present, and only ruleID is present, Is there any possibility to omit the templateID and send only ruleID? (And how to read it?)
I found out that query-string makes this possible, but I would like to maintain the 'path parameters'.
Note that, the following are the possible scenarios for me :
formMode     CREATE    EDIT    DELETE
---------------------------------------
templateID    yes       no       no
ruleID        no        yes      yes

Thanks in advance
Answer: Try a path like /templateID/:templateID?/ruleID/:ruleID?
With /templateID/1/ruleID/1 you will have { params: { templateID:1, ruleID:1 }}
With /templateID/ruleID/1 you will have { params: { ruleID:1 }}
route tester
Comment: Thanks! This is the exact thing I was looking for!
Answer: why not simply add a second rule definition and stick it inside a <Switch>:
<Route exact path="/my-base-url/myForm/:formMode/:ruleID?" component={MyFormComponent}/>

please note that this assumes:

/my-base-url/myform/2 -> ruleId
/my-base-url/myform/1/2 -> templateId, ruleId

won't work as

/my-base-url/myform/1 -> templateId with ruleId optional.

alternatively, you can use the render={} prop instead of the component= and compose what you want so you don't have to change the API of the form guy
<Route exact path="/my-base-url/myForm/:formMode/:templateID?/:ruleID?"
    render={({match: { params }}) => params.templateId ?
      <MyFormComponent templateId={params.templateId} :
      <SomethingElse />
} />

Comment: I had an idea to use render={}, but it won't be suitable for the above mentioned requirement because I would have to put many short-hand if-else blocks to check whether the possible combinations of the two parameters can be there/not. Thanks for the answer anyhow :)


For repetitive "SELECT" query, does Linq access databsase each time or it gives you values from its in-memory Entity objects?

Question: By Linq, I mean Entity Framework and Linq. A further question, if the SELECT query is the same, but OEDER BY clause is different, does Linq have to access the database or the in-memory entities have enough information for the new SELECT query with different ORDER BY clause?
Comment: Write down a sample query to clarify what you mean.
Comment: @Aliostad: I mean like when you manually call the DataBind() method of the GridView control whose DataSource is EntityDataSource, you are essentially calling the same SELECT query to populate the GridView, I suspect Linq does not have to access the underlying database
Comment: It's going to hit the DB again, but there is no reason you can't cache your result set to use when rebinding your paging/sorting events.
Answer: The short answer is no, once the Entity is created, the Entity itself contains all the information that will be used for data binding, unless you explicitly instruct the Entity to requery the underlying data store.


Drilling rebar hole in 12" concrete footing

Question: My deck has 6"x6" wooden support posts sitting atop 12" diameter concrete footings.  The tops of the concrete footings are about 16" above grade.  When I inspected a little below grade, I discovered the 12" diameter footings end just 2-3 inches below grade, but they seem to be poured on top of 6" diameter concrete footings.  The 6" footings completely underground, and have an unknown depth.  The deck over the posts shows no sign of settling/heaving however, and the deck appears to be at least 10 years old.
The wooden posts appear to have no attachment to the 12" pillars: one of the posts has shifted to the edge of the 12" footing.  I would like to attach the posts to the footing using a rebar post holder by drilling a hole in the center of the footing, and using epoxy or some adhesive for the holder.
My concern is that the footing may crack during drilling.  Is this much of a risk for a concrete footing this size?
Comment: wood breathes. is it shifted as much in the winter as in the summer? if not, then you might be worse off locking it down tight; that tension will eventually find a release, probably warping the surface
Comment: Dou you even KNOW that it moved? Could be it was just built sloppy and has set right there for the past 10 years or so - you look and see it off-center, and assume it's moved - but if you didn't look and see it centered at some previous time, there's nothing to support that assumption.
Answer: Drilling with a rotary hammer at a high speed with low force should not crack the footing, assuming it's in good condition.
I wonder why the one post has moved, though, and the others haven't. Is the structure that loose? You might just repair and bolster the framing and not worry about anchoring the post at the footing.


Hat problem, finding the probability of no events occuring

Question: There's this thing called the Hatcheck. It states that each person gets a hat, without replacement.
So the problem I have is this (problem 5B):

So I know the probability of event A, B, and C are all the same; 5! and the sample size is 7! since it's without replacement. I also know the chance of that occurring is 1/7!
However, I can't figure out how to even begin part B of the problem. Any help would be appreciated! Thank you for your time!
Answer: Let $[21?????]$ Be the event that person one gets hat two and person two gets hat one and the other people get any permutation of the remaining hats. That is, it is event $A$.
You have determined that $\mathsf P(A) = \frac{5!}{7!}=\mathsf P(B)=\mathsf P(C)$ because of the $7!$ ways to permutate the hats, $5!$ are in the favoured arrangements.
Then $[215?3??]$ is $A\cap B$ and $[215634?]$ is $A\cap B\cap C$, and so likewise $\mathsf P(A\cap B)=\frac{3!}{7!}=\mathsf P(A\cap C)=\mathsf P(B\cap C)$ and $\mathsf P(A\cap B\cap C)=\frac{1}{7!}$
Now to find $\mathsf P(\neg A\cap \neg B\cap \neg C)=1-\mathsf P(A\cup B\cup C)$ use the Principle of Inclusion and Exclusion.

PS: Also, clearly if all three events occur, the seventh person surely gets their own hat. So $\mathsf P([??????7]\mid [215634?])= 1$
Comment: Can this also be right????
1- (A+B+C) - (A∩B) - (A∩C) - (B∩C) + (A∩B∩C) =
1 - {[(5!+5!+5!) / 7!] - [(3! + 3! + 3!) / 7!] + (1/7!)} = .93 = 93%
Comment: @Maru Yes, precisely
Comment: Yes, thank yuo, @JMoravitz
Comment: did you get a chance to read my comment?


Appcelerator Arrow error after nodeJS upgrade: Module version mismatch. Expected 47, got 46

Question: After I upgraded NodeJS and NPM to 3.x.x, when I run "Appc run" command for my Appcelerator Arrow application, I get the following error:
[Error: Module version mismatch. Expected 47, got 46.]
Interestingly, the console does NOT show any further details as to which module is throwing the error.
I have tried removing all node modules and then run "npm install" but this error won't go away. Any advice would be most appreciated.
Answer: This happens because different versions of node has different api compatibility (for node, not appc).
The easiest was to fix this is to re-install the appc command line tools again using the command: appc use latest --force.
Comment: Actually, `appc use latest` will only select the most recent version if its already installed. You need to add `--force` to force a fresh install.


ChartJS change monthly labels as time/date

Question: index.php
  <!DOCTYPE html>

<canvas id="myChart"></canvas>

script-java.js
var ctx = document.getElementById('myChart').getContext('2d');

var chart = new Chart(ctx, {
  // The type of chart we want to create
  type: 'line',

  // The data for our dataset
  data: {
      labels: ["January","Fberuary","March"],
      datasets: [{
          label: "My First dataset",
          backgroundColor: 'rgb(255, 99, 132)',
          borderColor: 'rgb(255, 99, 132)',
          data: [120, 10, 5, 2, 20, 30, 45],

      }]
  },

  // Configuration options go here
  options: {}
});

output:

Here are the code, as you can see,  my labels are Monthly names, how can I replace it with time/data? What I am trying to achieve is like stock market chart where you can see what date and time a data went it.
Thanks
EDIT: I just saw a documentation: https://www.chartjs.org/docs/latest/axes/cartesian/time.html
I tried it, the code script is now:
var ctx = document.getElementById('myChart').getContext('2d');

var chart = new Chart(ctx, {
  // The type of chart we want to create
  type: 'line',

  // The data for our dataset
  data: {
      datasets: [{
          label: "My First dataset",
          backgroundColor: 'rgb(255, 99, 132)',
          borderColor: 'rgb(255, 99, 132)',
          data: [120, 10, 5, 2, 20, 30, 45],

      }]

  },

  // Configuration options go here
    options: {
        scales: {
            xAxes: [{
                type: 'time',
                time: {
                    displayFormats: {
                        quarter: 'MMM YYYY'
                    }
                }
            }]
        }
    }
});

But now, nothing is showing.
Answer: var ctx = document.getElementById('myChart').getContext('2d');

var chart = new Chart(ctx, {
type: 'line',

// The data for our dataset
data: {
    datasets: [{
        label: "My First dataset",
        backgroundColor: 'rgb(255, 99, 132)',
        borderColor: 'rgb(255, 99, 132)',
        // data : [10,20]
        data: [{x: new Date(), y:15},{x: moment().add(10,'days'), y:50},
        {x : moment().add(15,'days'), y:20}],

    }]

},

// Configuration options go here
  options: {
      scales: {
          xAxes: [{
              type: 'time',
              time: {
                // unit: 'month',
                  displayFormats: {
                      quarter: 'MMM YYYY'
                  }
              }
          }]
      }
  }
});

Comment: Sorry, but that's a static code, like what I have said, the time/date will be based on when the data went it.
Comment: Are you referencing that the data that you acquire will have no date/time value just data only and you intend to take the system date/time for the labels?
Comment: Yes. I just saw ChartJS has some documentation on how to do it: https://www.chartjs.org/docs/latest/axes/cartesian/time.html, but still I couldnt figure it out
Comment: I just edited my question. Please check it, Thank you
Comment: Did you add moment.js? Add moment js above the chart js.
Comment: I have edited the answer in accordance to your change in post.
Comment: Thanks.Yes I already added moment.js ( i've already edited my index.php ). , then I replace my script and added yours, but still not working, the output is empty, nothing is showing. but i checked the console and there are some errors:  http://prntscr.com/ltc1g6
Comment: I checked everything and found out that the only difference between our codes is the CDN we both are using. Use  this cdn instead/


Excel sheet cut off trying to export

Question: Using c#, npoi
Basically I used npoi to create and export data to an excel sheet but I'm open to other ways other than npoi to fix it. The data still exports as intended but when I try to print using excel, the sheet looks like below. I want to fix it directly in the code so what went wrong?

    dataRow = (HSSFRow)sheet.CreateRow(31);
    dataRow.CreateCell(0).SetCellValue("Name");
    dataRow.GetCell(0).CellStyle = fontmaintoprightbotleft;
    for (int i = 1; i < 14; i++)                              //this only puts the border on top of the undeclared cells
    {
        dataRow.CreateCell(i).CellStyle = fontmaintoprightbotleft;
    }
    cra = new NPOI.SS.Util.CellRangeAddress(31, 31, 0, 5);
    sheet.AddMergedRegion(cra);
    dataRow.CreateCell(6).SetCellValue("Contact No. (Hp)");
    dataRow.GetCell(6).CellStyle = fontmaintoprightbotleft;
    cra = new NPOI.SS.Util.CellRangeAddress(31, 31, 6, 8);
    sheet.AddMergedRegion(cra);
    dataRow.CreateCell(9).SetCellValue("Relationship");
    dataRow.GetCell(9).CellStyle = fontmaintoprightbotleft;
    cra = new NPOI.SS.Util.CellRangeAddress(31, 31, 9, 13);
    sheet.AddMergedRegion(cra);

    dataRow = (HSSFRow)sheet.CreateRow(32);
    dataRow.CreateCell(0).SetCellValue(EmergNametxt.Text);
    dataRow.GetCell(0).CellStyle = fontmaintoprightbotleft;            //this only puts the border on top of the undeclared cells
    for (int i = 1; i < 14; i++)
    {
        dataRow.CreateCell(i).CellStyle = fontmaintoprightbotleft;
    }
    cra = new NPOI.SS.Util.CellRangeAddress(32, 32, 0, 5);
    sheet.AddMergedRegion(cra);
    dataRow.CreateCell(6).SetCellValue(EmergContactNoTextBox.Text);
    dataRow.GetCell(6).CellStyle = fontmaintoprightbotleft;
    cra = new NPOI.SS.Util.CellRangeAddress(32, 32, 6, 8);
    sheet.AddMergedRegion(cra);
    dataRow.CreateCell(9).SetCellValue(EmergRelationshiptxt.Text);
    dataRow.GetCell(9).CellStyle = fontmaintoprightbotleft;
    cra = new NPOI.SS.Util.CellRangeAddress(32, 32, 9, 13);
    sheet.AddMergedRegion(cra);

    dataRow = (HSSFRow)sheet.CreateRow(33);
    dataRow.CreateCell(0).SetCellValue("Education Profile");
    for (int i = 1; i < 14; i++)
    {
        dataRow.CreateCell(i).CellStyle = fontheader;
    }
    dataRow.GetCell(0).CellStyle = fontheader;
    cra = new NPOI.SS.Util.CellRangeAddress(33, 33, 0, 13);
    sheet.AddMergedRegion(cra);

    dataRow = (HSSFRow)sheet.CreateRow(34);

Comment: I don't know enough about npoi to provide an answer but this looks like normal Excel printing behavior to me -- You may need to either adjust column widths to fit on one page or set the "fit to page" or "fit to width" printing property.
Comment: Yea but unfortunately, npoi doesn't have a method to break page or fit.
Comment: Hey, it might be helpful to provide the code that can reproduce this circumstance, if applicable.
Comment: I added in the code but its pretty much just repeated making of rows and columns.
Answer: The documentation for the C# NPOI implementation seems to be poor, but I think you should have the POI methods for print settings
sheet.FitToPage = true;

There's another StackOverflow answer that suggests the above setting may override the following PrintSetup items:
sheet.PrintSetup.FitHeight = 1;
sheet.PrintSetup.FitWidth = 1;

Comment: @timetoquitcoding In that case I think you'll need to update the question with details about how you'd like it to print. I can take a look if you can provide more details.
Comment: The sheet.PrintSetup will fit the whole form into 1 page but mine is about 2 pages back to back so they just make everything really small. I'm not sure what the sheet.FitToPage changed when I tried implementing it.
Comment: Doubt there's an answer but I want both pictures to be on the same page because, as of now, it's separated to different pages because the rows are too long and thus excel is cutting it off. Thanks for helping though.

Excel sheet cut off trying to export


Joomla jQuery is not defined

Question: on my website http: //******.com/, when I upgrade to php 7 it gives me the error of Uncaught ReferenceError: jQuery is not defined when it is defined at the beginning of my index.php
The strange thing is that with version 5 of php everything is correct. What can be the failure?
<code>$jquery = '';
jimport('joomla.version');
$version = new JVersion();
if(version_compare($version->getShortVersion(), '3.0', '>=')){
    JHtml::_('jquery.framework');
} else {
    JHTML::_('behavior.mootools');
    JFactory::getDocument()->addScript($this->baseurl.'/templates/'.$this->template.'/js/jq.min.js');
}
</code>
Then inside of html of the index.php any jQuery code tells me that it is not defined. Why can it be?
Thank you!!
Comment: The first two steps you can take are: #1 Look in the output HTML source to see if the JQuery library is included; and #2 Open your browser's code debugger, look at the network activity, and see if the JQuery libraries are loaded.
Comment: The website is http://lcbikesmartorell.com/

the browser debugger tells me that it is not defined when I defined a block of php code that introduced the beginning of index.html before the html and head
Comment: The JQuery library is not being included in the head of your HTML document. You would expect to see something like `` (depending on location of your library) there. Since your post makes it clear that Joomla should have been generating this, I have no idea why it doesn't (I don't have much experience of Joomla I'm afraid).
Comment: @FelipeJiménezPrieto When you want to receive support from individuals with Joomla-specific expertise, please post your questions on [Joomla Stack Exchange](https://joomla.stackexchange.com/questions).
Comment: `` is in fact being written in the source code.  This means that your conditional is going to the `else` block.  If you want to load the jquery with `JHtml::_('jquery.framework');` put that in your `else` block.  Let us know how this goes.
Comment: What version are you actually on? and why aren't you upgrading?
Answer: You can update your core joomla jQuery, install this plugin jQuery easy
in plugin configurations you can change core joomla jQuery

Joomla jQuery is not defined


can't rearrange multiple rotated displays

Question: I'm trying to set up a computer with 3 HDTVs as one big screen, with each display being rotated 90 degrees to form a 3240x1920 desktop. I have them all hooked up and working, but when I try to rotate them to get the desired arrangement, suddenly I'm unable to drag the displays close to each other in the display manager. This forces there to be a gap between the 3 displays.
Has anyone else encountered this problem, and if so is there a workaround? And if not, is there a different program I can use to do this?
Answer: I use ARandR (a front-end to XRandR) for this.  ARandR is independent of your graphical environment; it is not a part of GNOME but should work fine if you are running GNOME or whatever else.  (I prefer a minimalist setup and run Xfce.)

To enable a display that is not currently on, go to the Outputs menu, hover your mouse over the connection type, and check the Active box.
Once you have your desired layout, save it to a file (e.g. ~/.screenlayout/triple-head.sh).  You can set this to load automatically by making the file executable (chmod +x ~/.screenlayout/triple-head.sh) and then adding it to Startup Applications Preferences in your Control Center (the saved layout is the Command, the Name is what you see in the menus, and the Comment is a description of what this does).  In certain(?) circumstances, the configuration is loaded automatically upon launching your X session.
You can also switch between saved layouts in the same kind of manner; just execute the saved layout, perhaps with a keyboard shortcut or even a script to recognize the different monitors as they are plugged in.
Comment: 2016 - Had the same issue and this tool saved me! I have 3 monitors plugged in, and with this tool I was able to simply generate a shell script that I run everytime my computer boots up. Thank you!
Comment: This tool is excellent. On Ubuntu 14.04 I didn't have to do anything special to have the layout preserved after a reboot, just laid it out and applied.
Comment: Thanks, I'll be trying this out hopefully later today. I'll report back on how it works.
Comment: Ok, apparently my original issue was that I hadn't updated to the most recent version of Ubuntu, as I thought I had. Unfortunately ARandR doesn't work for me, simply because it's too complicated for me to make heads or tails of. Even if I could figure it out, it would certainly be too much to expect our client to understand it whenever they turn the system on. Is there a way to set things up such that the computer automatically boots into using the three screens as a single desktop? And if so, a more detailed guide on how to accomplish that would be very much appreciated.
Comment: ARandR is merely a graphical interface to XRandR.  If you take a look at the "saved layout" all you will see is a one line shell script calling xrandr.  To use the saved layout automatically, you have to add it to your Startup Applications.  I'll adjust my post shortly.
Comment: Amazing tip, thanks, I could not get MATE linux mint 18.3 to rearrange properly, the snap feature was preventing them from being aligned due to some bad code, which has been fixed but not yet merged in. This solved it!
Answer: Running Ubuntu 14.04 LTS, I was able to reproduce your problem using both unity-control-center (the default "System Settings" manager for Ubuntu) and mate-display-properties (which implements "Monitor Preferences" for the MATE desktop alternative).  If you just rotate the displays, it won't let you simply drag them closer together -- seems like a bug, maybe this one.
I was able to work around the issue by just messing around a bit (after setting the desired orientation).  Here's a sequence that seems to work (given my particular starting arrangement):

Drag display 3 to sit below and diagonal to display 1.
Drag display 2 to sit adjacent to display 1.
Drag display 3 to sit adjacent to display 2.

It's like some kind of sliding puzzle, where you can't go directly from the beginning to the end, but instead have to transition through intermediate "legal" states.
Below is a screenshot after the first step is completed.

EDIT: 3+ years later, I can no longer reproduce the fix that I posted here.  There is clearly a bug in the MATE version of the tool.
ARandR is nice for multiple reasons:

It doesn't suffer from the rotation bug (it knows the correct geometries for each display).
It doesn't have the snapping feature, so you can put the displays where you want them.
It lets you save your layouts as a shell scripts -- giving you a quick way to restore prior states
Comment: I think that, despite drawing them reasonably,  when rearranging it doesn't know that the displays have been rotated.  Basically, it is wrong about the location of the right and bottom edges.  This bug (or similar) still exists in Ubuntu MATE 16.04.
Comment: as stated, this is workaround for bug, not  solution but second answer is
Comment: Is there a bug already filed for this?
Comment: Bug report: https://github.com/mate-desktop/mate-control-center/issues/198
Comment: Some of these utilities modify `monitors.xml`, which is subsequently used to configure your display layout when the computer is powered on (or comes out of sleep).  It seems that [ARandR/xrandr does not do this](https://askubuntu.com/q/884249/11522), so you may want to strategically run one of the utilities which does after making adjustments with ARandR/xrandr -- and click `apply` with no changes just to save your preferred configuration to `monitors.xml`.
Comment: For the record, the sliding-puzzle solution still applies -- that's how these tools work.  However, the rotated screen bug prevents it from working as expected if you want to place another display to the right of a rotated display -- that's where arandr/xrandr may be required.
Comment: As of 18.04, the gap bug is fixed.  The sliding-puzzle solution still applies.
Comment: In retrospect, I wonder if my workaround only appeared to me to work (I never actually tried to use three rotated displays).  In the image above, there appears to be some overlap (I guess I didn't notice this back then).  It may be that the OP's problem was, in fact, the rotation/gap bug that was fixed for Ubuntu MATE 18.04.  If so, I would expect that there was, somewhere, an overlap of 1080-(1920-1080)=240 pixels with my solution.
Answer: There is a very detailed and comprehensive post by Nicolas Bernaerts to rearrange a multiple-monitor setting using xrandr and make the changes persistent here.
The post mentions that it is for a dual-monitor setup but it can also be used for a triple-monitor setup.
Comment: The irony here is that because of the bounty I put on this, I'm unable to vote this answer up. :p
Comment: The proposed link tutorial worked like a charm thank you
Comment: I like the tip to delete `~/.config/monitors.xml` in order to get rid of extraneous configurations.


Cocompact & discrete lattice

Question: I don't understand a step in the proof of the following proposition:

Let $\Lambda$ be a subgroup of a real vector space $V$ of finite dimension. Then $\Lambda$ is a full lattice if and only if $\Lambda$ is discrete and $V/\Lambda$ is compact.
Proof.(the part I don't understand) Assume $\Lambda$ is discrete and $V/\Lambda$ is compact, let $W$ be the subspace of $V$ spanned by $\Lambda$, then the real vector space $V/W$ can't have positive dimension since $V/\Lambda$ is compact.

Why is $V/W$ a trivial vector space?
Answer: The first thing going on here is a sequence of equivalencies: $\Lambda$ does not span $V \iff W$ is a proper subspace of $V \iff V/W$ has positive dimension $\iff V/W$ is a nontrivial vector space.
But if all of that happens then $V/W$ is noncompact. The inclusion $\Lambda \subset W$ induces a surjective continuous function $V / \Lambda \mapsto V / W$, and therefore $V / \Lambda$ is noncompact, a contradiction.

Cocompact & discrete lattice


Problems with HWIOAuthBundle first example

Question: I am fighting against HWIOAuthBundle.
I am trying to make it work with twitter Oauth but I am not sure I am on the right road and I apologize from now if this question may appear trivial.
I am Following the few instructions reported on the doc.
I have this configuration:
<code>config.yml

hwi_oauth:
    firewall_name: secured_area;
    resource_owners:
      twitter:
        type: twitter
        client_id:      <consumer_key>
        client_secret:  <consumer-secret>

routing.yml

hwi_oauth_redirect:
    resource: "@HWIOAuthBundle/Resources/config/routing/redirect.xml"
    prefix:   /connect

hwi_oauth_login:
    resource: "@HWIOAuthBundle/Resources/config/routing/login.xml"
    prefix:   /login

security.yml
    firewalls:
       ...
        secured_area:
            anonymous: ~
            oauth:
                resource_owners:
                    twitter:            "/login/check-twitter"
                login_path:        /login
                use_forward:       false
                failure_path:      /login

                oauth_user_provider:
                    service: hwi_oauth.user.provider

    access_control:
        - { path: ^/login, roles: IS_AUTHENTICATED_ANONYMOUSLY }
</code>
In the oauth_user_provider I've understand I can use one of the three default implementations reported in the doc page https://github.com/hwi/HWIOAuthBundle/blob/master/Resources/doc/3-configuring_the_security_layer.md
If I try to access to a page covered from this configurations I receive :
ServiceNotFoundException in CheckExceptionOnInvalidReferenceBehaviorPass.php line 58: The service "hwi_oauth.security.oauth_utils" has a dependency on a non-existent service "hwi_oauth.resource_ownermap.secured_area;".
Please is there somebody can tell me what this error is caused from ? Is the service I've specified in oauth_user_provider a bad one and I've misunderstood the doc about the 3 default implementations of services implementating  the OAuthAwareUserProviderInterface ?
Answer: Hell it was a typo. It's in config.yml, "firewall_name: secured_area;".
I've loosed half afternoon for a damned ";"
@moderators : please feel free to delete this question if you think this  is a zero community contributive question/answer.


Why are my ubuntu partitions mounted somewhere else?

Question: If you refer to my other posts, I am trying to use g++ and in order to compile a .cpp file I'll have to refer to it with the drive name:
g++ /media/drivename/filename.cpp

The problem is with the file path, as you see the drives are named so ridiculously with some random number group. I can't just type in
g++ /media/123414 14124 14 1/filename.cpp

I tried relabelling the partitions and turns out you don't refer to them with their labels but with their names and these names are based on where the drives are MOUNTED. As you can see in the below picture, these are mounted at this ridiculous location /whateverucallit. This is frustrating. I just switched to Ubuntu, and I'm having a really hard time here.

The partitions were created after the ubuntu was installed and they were created with GParted. I have looked at other threads telling you to edit your etc/fstab there is no fstab folder there except a fstab.d folder and that too: an empty one.
Okay, my bad. It was talking about the fstab file. There is one here are the contents of the file:
# /etc/fstab: static file system information.
#
# Use 'blkid' to print the universally unique identifier for a
# device; this may be used with UUID= as a more robust way to name devices
# that works even if disks are added and removed. See fstab(5).
#
# <file system> <mount point>   <type>  <options>       <dump>  <pass>
# / was on /dev/sda1 during installation
UUID=956d7e6e-6935-4de9-80ec-4e4f80a510db /               ext4    errors=remount-ro 0       1
# swap was on /dev/sda5 during installation
UUID=b6dea36c-6e78-46c4-a566-9a850ddd2c9c none            swap    sw              0       0

Turns out fstab doesn't even mention the two newly created partitions. What now?.
UPDATE:
I added the following lines in fstab but since they did nothing, I've commented them out.
#device        mountpoint             fstype    options  dump   fsck

#/dev/sda3    /home/robbino/driv1    ext3    defaults    0    1
#/dev/sda4    /home/robbino/driv2    ext3    defaults    0    1

Here's the sudo fdisk-l output
$ sudo fdisk -l

Disk /dev/sda: 320.1 GB, 320072933376 bytes
255 heads, 63 sectors/track, 38913 cylinders, total 625142448 sectors
Units = sectors of 1 * 512 = 512 bytes
Sector size (logical/physical): 512 bytes / 512 bytes
I/O size (minimum/optimal): 512 bytes / 512 bytes
Disk identifier: 0x0001ec87

   Device Boot      Start         End      Blocks   Id  System
/dev/sda1   *        2048   206092287   103045120   83  Linux
/dev/sda2       617037822   625141759     4051969    5  Extended
/dev/sda3       206092288   415674367   104791040   83  Linux
/dev/sda4       415674368   617035775   100680704   83  Linux
/dev/sda5       617037824   625141759     4051968   82  Linux swap / Solaris

Partition table entries are not in disk order

Comment: It's because it _isn't_ mounted in fstab that Ubuntu is mounting it in /media.
Comment: possible duplicate of [How to mount a new drive on startup](http://askubuntu.com/questions/154180/how-to-mount-a-new-drive-on-startup)
Comment: Not really, it's not about mounting it up on startup as mine are always mounted on startup. Just the mount location that needs to be modified. I could just change in fstab if it was mentioned in it
Comment: Will the following lines do?

#device        mountpoint             fstype    options  dump   fsck

/dev/sda3    /home/robbino/drivex    ext3    defaults    0    1
/dev/sda4    /home/robbino/drivey    ext3    defaults    0    1
Answer: Open a terminal and type:
sudo blkid

Find and copy needed uuid to reproduce it in fstab then run:
sudo -H gedit /etc/fstab

add to the end lines like this (e.g.):
#My-Partition
UUID=xxxxxxxxxxxxxxx /media/Robbino1              ext3
defaults 0 1

Where xxxxxxxxxx is /dev/sda uuid that you copied, then reboot.
You can also manually change permissions (e.g.):
rw,auto,user,nls=utf8,umask=003,gid=1000,uid=1000 0 0

More detailed on mounting options here.
Comment: Tried exactly what you told and on restart it said
"Serious errors detected while looking for /media/robbino1" press i to skip mounting"

Now, the devices aren't mounted at all. I'll go comment out those lines
Comment: The following lines are the ones I'm commenting out at this instant.

UUID=ae5bdc4c-586f-42de-b43c-94f7deedcb02 /media/Robbino1 ext3 defaults 0 1

UUID=ae5bdc4c-586f-42de-b43c-94f7deedcb02 /media/Robbino2 ext3 defaults 0 1
Comment: It worked. But now on restart it says
"error mounting /etc/fstab/."
Comment: It worked! Thank you!! There was this 'w' character in the beginning of file that must've been a typo. I deleted it and restarted. Worked like a charm. THANK YOU,DUDE! THANKS A LOT! *brotherly hugs keeping crotch 42 km away*
Comment: You're welcome! Glad it worked for you.


What is the imitater useful for?

Question: I have just bought the imitater from twididinkies but I don't know what to use it  for. It says it lets you use 2 of the same plants in a single level but I don't know why I will want to use 2 of the same plants in a single level because that will just waste a seed slot. What is the imitater useful for?
Answer: There are a few reasons depending on the level you are playing.
The main reason I personally used them was for pumpkin armor increasing the survivability of your defenses.
But other good options would be:

Sunflowers/Sun Shrooms at the start of the level to boost production.
Potato mines for cheap early game defenses
Marigolds for extra money farming
Or extra emergency buttons (Jalapeno, Cherry Bomb, Hypno Shroom or
squash)

Usually you won't be needing them but they can be useful for getting certain achievements easier. But besides the achievements they are mainly used in endless levels where in each round you focus on a certain type of defensive wall.
Answer: Imitater shroom has a fixed sun amount. It is useful because it's cooldown is not in sync with the copy plant's cooldown.
It can be used as an extra plant. If the plant you copy is used constantly, the IMitater can be used as an extra when its needed, but its on cooldown.
Comment: I know you want to answer my questions but we have different versions of plants vs zombies so I cannot completely rely on your answers. However, I would like to thank you for helping so I hope you keep answering my questions. Thanks!
Comment: Welcome. Also, A meta post from one of your comments got popular, may wanna see that...
Comment: Where is it in meta? Who posted it?
Comment: Its https://gaming.meta.stackexchange.com/questions/15420/how-should-we-respond-to-users-reprimanding-other-users-in-comments?cb=1

What is the imitater useful for?


Ubuntu 22.04 LTS kernel panic (/sbin/init not found)

Question: I'm currently running a deep learning server with Ubuntu 22.04 LTS.
After a reboot, it keeps running into kernel panic with the error messages '/sbin/init not found' and '/etc/init permission denied'. Recovery mode does not help at all.
Based on a quick search, I found that this problem usually occurs after a partial update corrupting the initrd image. Following the typical approach to regenerate the initrd image, I booted into the Ubuntu 22.04 LTS live 'Try Ubuntu' using a USB stick. I checked the partitions using 'sudo parted -l', which showed that the root partition '/' was at '/dev/nvme0n1p3' and that the boot partition '/boot' was at '/dev/nvme0n1p2'.
On the live environment, I mounted these two partitions at '/mnt' and '/mnt/boot', and 'mount --bind'ed some directories (/dev, /dev/pts, /proc, and /sys). Then I 'chroot'ed into the '/mnt' directory. The networking was working in both the live environment and inside chroot, after supplying the proper static IP configurations via the GUI network manager. I tried various commands to regenerate the initrd image, but none of them worked.
To explain it in detail, 'update-initramfs -u' initially failed at 'fuse' step. So, I reinstalled fuse via apt-get install --reinstall kmod, which fixed it. However, then, I started to see that 'udev' failed (returned 1). There was no other error messages that yielded some clue. This was not fixed by apt-get install --reinstall.
I tried other commands as below, but every single one resulted in the same udev error:

apt-get install --reinstall init
apt-get install --reinstall kmod
apt-get install --reinstall initramfs-tools
Copying the contents of /boot into a temp folder and running update-initramfs in the temp folder

Here are some other things that I have tried, but none of which worked:

Checking the permission of /etc/init, which was 755
Creating a symbolic link from /sbin/init into /lib/systemd/systemd with proper permissions (755)
The weird thing was that even after creating /sbin/init as a symbolic link, the kernel panic message still insisted /sbin/init did not exist

Any help would be appreciated. Thanks.
Answer: I had this issue, too, after update from snap-store.
What I did is boot Ubunut live CD, mount the corrupted drive and then
#cp -r -n /usr/ :  /mounted_drive/
It helped restore the missing files, not sure why it happened in the first place.


How to get the Dash and HUD to appear. (and stop Unity spewing error messages.)

Question: I just installed Ubuntu 12.04 on my wifes Dell Inspiron 1501, which uses an R300 ATI graphics chip. Neither the Dash or HUD appear when pushing the appropriate key. When I try unity --reset & in the terminal, I see that over and over it's spitting out:
r300: CS space validation failed. (not enough memory?) Skipping rendering.

This is just after starting Ubuntu with no apps open, so I find it hard to believe that just rendering the Dash / HUD is completely blowing out the VRAM. Any suggestions on getting this working?

/usr/lib/nux/unity_support_test -p

shows

OpenGL vendor string: X.Org R300
Project OpenGL renderer string: Gallium 0.4 on ATI RS480
OpenGL version string: 2.1 Mesa 8.0.2
Not software rendered: yes
Not blacklisted: yes
GLX fbconfig: yes
GLX texture from pixmap: yes
GL npot or rect textures: yes
GL vertex program: yes
GL fragment program: yes
GL vertex buffer object: yes
GL framebuffer object: yes
GL version is 1.4+: yes

Unity 3D supported: yes

All sections say "YES"
Comment: I would suggest filing a bug report on launchpad/bugzilla (include if possible xorg.log, dmesg, glxinfo, lscpi and .xsession-errors)
Comment: Seems to be the same error as:
http://askubuntu.com/questions/95675/unity-on-ubuntu-11-10-the-dash-home-button-brings-up-the-panel-but-is-empty
and:
http://askubuntu.com/questions/79874/dash-home-button-brings-up-blank-window
Comment: /usr/lib/nux/unity_support_test -p
OpenGL vendor string:   X.Org R300 Project
OpenGL renderer string: Gallium 0.4 on ATI RS480
OpenGL version string:  2.1 Mesa 8.0.2

All sections say "YES"
Answer: The Unity 2d desktop might fix this issue,
You can Access Unity 2D at the LighDM log in screen (only if you have automatic login disabled).
Answer: I had the same problem, tried countless things, and using Unity 2D it indeed fixed the problem.
This was on a Dell Dimension e510.  Clicking on the Dash icon did not display the Dash window, but if I typed (invisibly) 'terminal' and pressed Enter, a terminal opened.
unity --reset is suggested elsewhere, and this produces endless r300 errors as the initial post described.  With Unity 2D, it works fine.


Div as height as possible (100% stretch)

Question: I have this layout:
banner
menu
-----
main    ||
content ||

I need the banner+menu always visible, the site is for mobile devices, so only vertical scrolling on "main content". But I have no idea how to achieve this. I set 100% to body/html, still no fun. No matter how long the "main content" I want to scroll only this.
Comment: `div#banner, div#menu {position: fixed;}`
Answer: Set the banner/menu as position: fixed in your CSS. Learn more here: http://alistapart.com/article/css-positioning-101
Comment: Check out the article - I think you need to read up on the basics of CSS positioning.
Comment: but then the two div hide themselves
Comment: but it cant be that hard - its like I set a fixed height to the "main content". If I do, everything is perfect - but I cant know the height...
Comment: You don't need to set the height on body/html at all. You just need to figure out the sizing of the banner and menu, set them to fixed, attach them to the top and you're good.
Answer: ok, its OK for doing that:

fixed

abs

but that 100px height is changing, not fixed....
Comment: or even better:     a1111111111111111111111111111111111111111111111111
fixed


Can you remove a mom and dad from the living quarters once the mom is pregnant?

Question: Does it interfere with the mom's pregnancy? e.g. delayed birth
Answer: Yes, you can, with absolutely no effect on the pregnancy. She can even be put back to work, however, she will not fight or put out fires, but will instead flee back to the living quarters during the incident.
Answer: Pregnant women work, and can be used in any room. Once they're pregnant just put the parents back to work, it's fine.
The only real difference is that they stop responding to incidents, and instead run and hide. So I'd advise you de-equip any weapons from them, which can then be handed to non-pregnant dwellers.
Comment: This does not add anything that was not already written..


Evaluate the determinant with Identity matrix

Question: Hello all I learning about determinants and this problem currently has me completely stumped.  I can not figure how the answer in the book was achieved.
Problem:
$\det(\lambda I_2 - A)$  where
$$ A = \begin{bmatrix} 4 & 2 \\ -1 & 1\\
\end{bmatrix} $$
The book answer is:
 $ \lambda^2 - 5 \lambda + 6$
I could only figure out how the 6 was found.  I would like to note we haven't gone over eigenvalues either.
Thanks.
Answer: There's nothing about eigenvalues here. It's a simple calculation:
$$\lambda I_2 - A = \left[\array{\lambda - 4 & -2 \\ 1 & \lambda - 1}\right],$$
so its determinant is $(\lambda - 4)(\lambda - 1) + 2 = \lambda^2 - 5\lambda + 6$ by the standard determinant formula for $2\times 2$ matrices.
Comment: Matrix should be $$\begin{bmatrix}\lambda-4&-2\\1&\lambda+1\end{bmatrix}$$
Comment: @user1238097 I am sure. Indeed, $$\lambda I-A=\begin{bmatrix}\lambda&0\\0&\lambda\end{bmatrix}-\begin{bmatrix}4&2\\-1&-1\end{bmatrix}$$ Notice the minus sign in front of $A$.
Comment: How did you know how use lambda on the diagnol, my book doesn't mention this notation I believe.
Comment: @Dave are you sure I user3482749 is correct.
Comment: @Dave you are definitely right.  I am at a loss on the book answer still. I realized I added a negative a22 of the matrix on accident.
Comment: @Dave Oops, failed at reading. Yours wasn't right either, though.
Comment: @user1238097 $\lambda I_2 = \left[\array{\lambda & 0 \\ 0 & \lambda}\right]$.