Q:

jQuery validation for client-side dynamic controls

I have controls that are dynamically added via javascript. I cannot set the class on these controls to “required” because I need the flexibility to place the error messages where I will.
When I add these controls, I loop through all that I need required, and call
$("#dynamicControlID").rules("add", {required:true});

The problem comes when I try to validate the form. When I call
$("#form1").validate()

any non-dynamic controls that have the class “required” specified will validate with a nice message that says “this field is required.” The controls that have been added dynamically do not show any message, and the validate function returns true even if they’re empty.
The real confusion comes when I validate the dynamic controls individually. If I call
$("#dynamicControlID").valid()

it will return false, and display the error message by the input. I do call
$("#form1").valid()

before I do anything with the dynamic controls.
Am I missing something here? What I would like is to call
$("#form1").valid()

and have the error messages show for all my dynamically added controls.

A:

You're on the right track, but when you want to add rules to the new element, you have to have already called $('#form1').validate();.
So a common setup is something like this:
$('#form1').validate({
   //your options
});

$('#dynamicControlID').rules('add',{required:true});


Q:

Merge connection & configuration related tags

configure & configuration should be merged (although I think they both should be removed).
Some of the following should be merged:

connect
connection
connectivity
disconnects
disconnection
disconnected
reconnect

connection:
All connections, wired, wireless, internet, intranet, and cable fall
  under this category. Use this tag if your issue involves establishing,
  maintaining, adding, or removing connections.

slow-connection
wireless-connection
network-connections

A:

connect
connectivity
disconnects
disconnection
disconnected
reconnect
All merged into connection
slow-connection
Also merged into connection
wireless-connection
Merged into wireless-networking
network-connections
Merged into networking

configure and configuration are status-deferred for now.


Q:

How to make a component readonly on a specific button click in JSF?

<h:panelGroup rendered="#{spkrCatEvt.createPanel}">
    Event Name
    <h:selectOneMenu style="width: 250px" class="form-control" value="#{spkrCatEvt.selected.evtId}" id="speaker_eve">
        <f:selectItems value="#{spkrCatEvt.eventlist}" var="sl" itemLabel="#{sl.value}" itemValue="#{sl.id}"/>
    </h:selectOneMenu>
    Speaker Name
    <h:selectOneMenu style="width: 250px" class="form-control" value="#{spkrCatEvt.selected.spkrId}" id="speaker">
        <f:selectItems value="#{spkrCatEvt.speakerlist}" var="sl" itemLabel="#{sl.value}" itemValue="#{sl.id}"/>
    </h:selectOneMenu>
</h:panelGroup>

Above is the part of code written in my JSF form, which displays when I click the 'ADD' button. In the same form I have also written code for table to display data like below :

            Speaker Name
            Event Name

        <ui:repeat id="dataTbl" value="#{spkrCatEvt.items}" var="item">

                <h:outputText value="#{item.spkrName}"/>
                <h:outputText value="#{item.evtName}"/>

                    <h:commandLink action="#{spkrCatEvt.prepareView()}" id="view" title="View"></h:commandLink>
                    <h:outputText value="  "/>
                    <h:commandLink  action="#{spkrCatEvt.prepareEdit()}" id="edit" title="Edit"></h:commandLink>
                    <h:outputText value=" "/>
                    <h:commandLink  action="#{spkrCatEvt.activeEdit()}" id="activate" title="Activate" rendered="#{!item.active}"></h:commandLink>
                    <h:commandLink  action="#{spkrCatEvt.activeEdit()}" id="deactivate" title="DeActivate" rendered="#{item.active}"></h:commandLink>

        </ui:repeat>

I want to make <h:selectOneNenu> readonly which displays 'event name', when I click the update button from the table.
I tried the same by giving rendered attribute to the element but it didn't work.
Being a beginner in JSF, I am not getting the solution.
I would be obliged for help.

A:

Use disabled instead of rendered on the h:selectOneMenu; rendered is for omitting it all together. Bind it to a boolean on the bean, which you set to true when clicking the button. So something like
<h:selectOneMenu ... disabled="#{spkrCatEvt.oneMenuDisabled}"/>

Remember getters/setters on the bean.
If you don't like the new grey look you can style with for example
select:disabled{
    color: black;
}

Had it been a primefaces selectOneMenu that would have been
.ui-selectonemenu.ui-state-disabled{
     opacity: 1; // Between 0.0 and 1, 0.35 being default
}


Q:

What are optimal scrypt work factors?

I'm using a Java scrypt library for password storage. It calls for an N, r and p value when I encrypt things, which its documentation refers to as "CPU cost", "memory cost" and "parallelization cost" parameters. Only problem is, I don't actually know what they specifically mean, or what good values would be for them; perhaps they correspond somehow to the -t, -m and -M switches on Colin Percival's original app?
Does anyone have any suggestions for this? The library itself lists N = 16384, r = 8 and p = 1, but I don't know if this is strong or weak or what.

A:

As a start:
cpercival mentioned in his slides from 2009 something around

(N = 2^14, r = 8, p = 1) for < 100ms (interactive use), and
(N = 2^20, r = 8, p = 1) for < 5s (sensitive storage).

These values happen to be good enough for general use (password-db for some WebApp) even today (2012-09). Of course, specifics depend on the application.
Also, those values (mostly) mean:

N: General work factor, iteration count.
r: blocksize in use for underlying hash; fine-tunes the relative memory-cost.
p: parallelization factor; fine-tunes the relative cpu-cost.

r and p are meant to accommodate for the potential issue that CPU speed and memory size and bandwidth do not increase as anticipated.  Should CPU performance increase faster, you increase p, should instead a breakthrough in memory technology provide an order of magnitude improvement, you increase r.  And N is there to keep up with the general doubling of performance per some timespan.
Important: All values change the result. (Updated:) This is the reason why all scrypt parameters are stored in the result string.

A:

Short answer
So that it takes 250 ms to verify a password
Long answer
The memory required for scrypt to operate is calculated as:

128 bytes × N_cost×r_blockSizeFactor

for the parameters you quote (N=16384, r=8, p=1)

128×16384×8 = 16,777,216 bytes = 16 MB

You have to take this into account when choosing parameters.
Bcrypt is "weaker" than Scrypt (although still three orders of magnitude stronger than PBKDF2) because it only requires 4 KB of memory. You want to make it difficult to parallelize cracking in hardware. For example, if a video card has 1.5 GB of on-board memory and you tuned scrypt to consume 1 GB of memory:

128×16384×512 = 1,073,741,824 bytes = 1 GB

then an attacker could not parallelize it on their video card. But then your application/phone/server would need to use 1 GB of RAM every time they calculated a password.
It helps me to think about the scrypt parameters as a rectangle. Where:

the width is the amount of memory required (128Nr)
the height is the number of iterations performed
and the resulting area is the overall hardness

the cost (N) increases both memory usage and iterations.
the blockSizeFactor (r) increases memory usage.

The remaining parameter parallelization (p) means that you have to do the entire thing 2, 3, or more times:

If you had more memory than CPU, you could calculate the three separate paths in parallel - requiring triple the memory:

But in all real-world implementations, it is calculated in series, tripling the calculations needed:

In reality, nobody has ever chosen a p factor other than p=1.
What are the ideal factors?

As much RAM as you can spare
for as much time as you can spare!

Bonus Chart
Graphical version of above; you're targeting ~250ms:

Notes:

the vertical axis is log scale
Cost factor (horizontal) itself is log (iterations = 2CostFactor)
Highlighted in the r=8 curve

And zoomed in version of above to the reasonable area, again looking at the ~250ms magnitude:

Bonus Chatter

scrypt is weaker than bcrypt for password storage if scrypt is configured to use less than 4 MB 1
Argon2 (i/d/id) is weaker than bcrypt when it comes to password hashing for authentication (i.e. <1,000 ms verification time) 2

A:

I don't want to step on the excellent answers provided above, but no one really talks about why "r" has the value it has. The low-level answer provided by the Colin Percival's Scrypt paper is that it relates to the "memory latency-bandwidth product". But what does that actually mean?
If you're doing Scrypt right, you should have a large memory block which is mostly sitting in main memory. Main memory takes time to pull from. When an iteration of the block-jumping loop first selects an element from the large block to mix into the working buffer, it has to wait on the order of 100 ns for the first chunk of data to arrive. Then it has to request another, and wait for it to arrive.
For r = 1, you'd be doing 4nr Salsa20/8 iterations and 2n latency-imbued reads from main memory.
This isn't good, because it means that an attacker could get an advantage over you by building a system with reduced latency to main memory.
But if you increase r and proportionally decrease N, you are able to achieve the same memory requirements and do the same number of computations as before--except that you've traded some random accesses for sequential accesses. Extending sequential access allows either the CPU or the library to prefetch the next required blocks of data efficiently. While the initial latency is still there, the reduced or eliminated latency for the later blocks averages the initial latency out to a minimal level. Thus, an attacker would gain little from improving their memory technology over yours.
However, there is a point of diminishing returns with increasing r, and that is related to the "memory latency-bandwidth product" referred to before. What this product indicates is how many bytes of data can be in transit from main memory to the processor at any given time. It's the same idea as a highway--if it takes 10 minutes to travel from point A to point B (latency), and the road delivers 10 cars/minute to point B from point A (bandwidth), the roadway between points A and B contains 100 cars. So, the optimal r relates to how many 64-byte chunks of data you can request at once, in order to cover up the latency of that initial request.
This improves the speed of the algorithm, allowing you to either increase N for more memory and computations or to increase p for more computations, as desired.
There are some other issues with increasing "r" too much, which I haven't seen discussed much:

Increasing r while decreasing N reduces the number of pseudorandom jumps around memory. Sequential accesses are easier to optimize, and could give an attacker a window. As Colin Percival noted to me on Twitter, larger r could allow an attacker to use a lower cost, slower storage technology, reducing their costs considerably (https://twitter.com/cperciva/status/661373931870228480).
The size of the working buffer is 1024r bits, so the number of possible end products, which will eventually be fed into PBKDF2 to produce the Scrypt output key, is 2^1024r. The number of permutations (possible sequences) of jumps around the large memory block is 2^NlogN. Which means that there are 2^NlogN possible products of the memory-jumping loop. If 1024r > NlogN, that would seem to indicate that the working buffer is being under-mixed. While I don't know this for sure, and would love to see a proof or disproof, it may be possible for correlations to be found between the working buffer's result and the sequence of jumps, which could allow an attacker an opportunity to reduce their memory requirements without as-greatly increased computational cost. Again, this is an observation based on the numbers--it may be that everything is so well-mixed in every round that this isn't a problem. r = 8 is well below this potential threshold for the standard N = 2^14 -- for N = 2^14, this threshold would be r = 224.

To sum up all the recommendations:

Choose r to be just large enough to average out the effects of
memory latency on your device and no more. Keep in mind that the
value Colin Percival recommended, r = 8, appears to remain fairly
optimal broadly for memory technology, and this apparently hasn't
changed much in 8 years; 16 may be ever so slightly better.
Decide on how big a chunk of memory you want to use per thread,
keeping in mind this affects computation time as well, and set N
accordingly.
Increase p arbitrarily high to what your usage can tolerate (note:
on my system and using my own implementation, p = 250 (4
threads) with N = 16384 and r = 8 takes ~5 seconds), and enable
threading if you can deal with the added memory cost.
When tuning, prefer large N and memory block size to increased p and
computation time. Scrypt's primary benefit comes from its large
memory block size.

A benchmark of my own implementation of Scrypt on a Surface Pro 3 with an i5-4300 (2 cores, 4 threads), using a constant 128Nr = 16 MB and p = 230; left-axis is seconds, bottom axis is r value, error bars are +/- 1 standard deviation:


Q:

How to fetch the datatype with column and create a dictionary

Mysql table have student have 2 tables students and teach
Code is below
def tbl_col_names(table):
    db = {}
    for i in table:
        cursor.execute("select COLUMN_NAME from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME= '%s'" % (i))
        tabledescription = cursor.fetchall()
        print ('tableDesc1', tabledescription)
        tableDescription1 = [i[0] for i in tabledescription]
        print (tableDescription1)
        db[i] = tableDescription1
        with open('data.json','w') as f:
            db1 = json.dumps(db)
            test = (f"data ='[{db1}]'")
            f.write(test)
    return db
cursor.execute("SELECT table_name FROM information_schema.tables WHERE table_type = 'BASE TABLE' AND table_schema='databasename'")
ecords = cursor.fetchall()
print (records)
member = [i[0] for i in records]
print ('member',member)
allcolumnvalues = tbl_col_names(member)
print ('all',allcolumnvalues )

data.json output is below
data = '[{"students": ["student_no"], "teach": ["last_name", "course_no"]}]'

How to fetch the data type along with column name
Below is the mysql query to get column name along with data type
select COLUMN_NAME,DATA_TYPE from INFORMATION_SCHEMA.COLUMNS where table_name='student';

cursor.execute("select COLUMN_NAME,DATA_TYPE  from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME= '%s'" % (i))

My expected out data.json is below
data = '[{"students": {"student_no":"int"}, "teach": {"last_name":"varchar", "course_no":"int"}}]'

A:

cursor.execute('show columns from databasename.students')
records = cursor.fetchall()
d = {record[0]: record[1] for record in records}
# or d = {record['Field']: record['Type'] for record in records} if the cursor.execute returns a dictionary

This will return a detailed description of each field type including precision, such as int(11) or varchar(32). If you do not want the precision included then:
d = {record[0]: record[1].split('(')[0] for record in records}

For each database/table you are interested in you would append the dictionary computed as in the above example as follows to a list to get your desired results:
def get_table_attributes(cursor, database, table):
    cursor.execute(f'show columns from {database}.{table}')
    records = cursor.fetchall()
    return {record[0]: record[1] for record in records}
    # return {record[0]: record[1].split('(')[0] for record in records}

data = []
data.append({'students': get_table_attributes(cursor, 'databasename', 'students')})
data.append({'teach': get_table_attributes(cursor, 'databasename', 'teach')})


Q:

What is the purpose of jQuery clean and cleanData methods?

jQuery has clean and cleanData methods. What is the purpose of jQuery clean and cleanData methods?

A:

Both are internal, undocumented methods, so you should not use them or rely on their current behavior, because they might change or disappear in the future.
That said, clean() sanitizes the markup in the document fragments that are created from the HTML strings passed to some functions (most notably to $() itself).
cleanData() frees the data associated with elements when they disappear from the DOM, e.g. through remove(), empty(), or html().


Q:

How to prove $\prod_{i=1}^{\infty} (1-a_n) = 0$ iff $\sum_{i=1}^{\infty} a_n = \infty$?

Given ${a_n}$ is infinite sequence, and $0 < a_n < 1$, how to prove
$$\prod_{i=1}^{\infty} (1-a_n) = 0 \text{ if and only if } \sum_{i=1}^{\infty} a_n = \infty$$
Thanks for your help.

A:

Use $1-a_n \leq e^{-a_n}$ for $ \sum_{i=1}^{\infty} a_n = \infty \implies \prod_{i=1}^{\infty} (1-a_n) = 0$
For the other direction, define independent uniform random variables $(U_n)_{n\geq 1}$ and $A_n =\{U_n < a_n\}$, then we have $\prod_{n=1}^{+\infty}P(A_n^c) = 0$
Use Borel-Cantelli lemma like here enables to conclude.
For a non-pobabilistic proof, see proof and the first comment here


Q:

Laravel Eloquent/DB getting relation by foreign table and order results

In Laravel 5.5 I have a database setup like the ERD image below. I prefer using Eloquent over Query Builder but I'm not sure it can be done by Eloquent.

Relationships

Object A -> Object B [one - one to many]
Object B -> Object C [one - one]

How would I do the following: Start the query with  Object A. Through Object A I want to obtain Object(s) B and though Object B I want to obtain the corresponding Object C. The last thing that is required is that the results will be sorted Ascending by the position column in Object B.
What I've tried myself: With Eloquent get Object A and all Objects of B (this is sorted Ascending on position). Foreach Object of B seek corresponding Object C. But I know this is not the best solution for the problem.
Any advise?

A:

With help of you guys I came to the best solution I could think off:
ObjectA::with(['ObjectB' => function($query){
    $query->orderBy('position', 'asc');
},'ObjectB.ObjectC'])->get();

ObjectA Model
public function ObjectB()
{
    return $this->hasMany('App\ObjectB');
}

ObjectB Model
public function ObjectC()
{
    return $this->hasOne('App\ObjectC');
}


Q:

DNA conditional frequency in R

I'm trying to find if there is any conditional dependence within 2 different DNA sequences in R
This is my code, however i'm getting an error;
Error in `[.data.frame`(data, i) : undefined columns selected

I'm not sure where the issue is, if I parentheses the data[i-1]==bases[b2], i just get multiple unexpected}, which is the only thing I can think else to do.
for (b1 in 1:length(bases))
{
   for (b2 in 1:length(bases))
   {
       count = 1
       for (i in 2:length(mydata1))
       {
           if ((mydata1[i]==bases[b1]) & mydata1[i-1]==bases[b2])
           {
               count = count+1
           }
       }
       b3 = c(bases[b1], bases[b2], count)
       print(b3)
   }
}

_I'm expecting essentially a list of certain DNA bases, for example I see it as if the DNA sequence IS conditional upon the previous base then;.
[1] "A" "C" "002"
[1] "A" "C" "005"
[1] "A" "C" "009"

and so on, that can show me any indication as to whether a certain base has any sort of affect upon the identity of the following base, by clearly showing a condition for A to be previous to C.
Ok so essentially the mydata1 (there is also mydata2) are DNA sequences, that is to say a list of "A", "G", "C" and "T", each of which is 10,000 bases long.
As shown here;
  V1
1  T
2  C
3  G
4  G
5  T
6  G
7  G
8  G
9  C
10 A

I'm tasked with trying to determine if the sequence has bases that are dependent on one another, so if [1] T affects the presence of [2] C, etc. One of the sequences is dependent, the other is not.

A:

If I understand correctly, you want to count the occurrences of each pair of nucleotides i, i+1 in a sequence of DNA. You can achieve this with R function table; an example is provided below.
# input sequence
seq <- "ACGTACTGCACAAACTAC"

# length of input sequence
length_seq <- nchar(seq, type="chars")

# first substring: from 1 to second-last
seq1 <- substr(seq, 1, (length_seq - 1))

# second substring: from 2 to last
seq2 <- substring(seq, 2, length_seq)

# split strings
seq1_split <- strsplit(seq1, "")[[1]]
seq2_split <- strsplit(seq2, "")[[1]]

# initialize vectors
first_nt <- vector(mode="character", length = (length_seq - 1))
second_nt <- vector(mode="character", length = (length_seq -1))

# fill vectors
count = 0
for (b in seq1_split)
{
    count = count + 1
    first_nt[count] <- b
}

count = 0
for (b in seq2_split)
{
    count = count + 1
    second_nt[count] <- b
}

# create matrix with character i and i+1 in each row
mat <- matrix(c(first_nt, second_nt), nrow=(length_seq - 1))

# collapse matrix
to_table <- apply(mat, 1, paste, collapse="")

# table
my_table <- table(to_table)

print(my_table)


Q:

Extract version from XML with Windows Batch

I have a XML file generated by Visual Studio that contains the version of the product, hence the tag will always be there just the value changes.
I need to extract the version with windows command line somehow. This is the tag in the file and I need only the version number "1.0.0.0":
 <?define BuildVersion = 1.0.0.0 ?>

Is there a built in tool (maybe with findstr) that can accomplish this?

A:

Use for /F loop to parse the output of findstr and extract the text you need (using space as delimiter, get the 4th token):
for /F "tokens=4 delims= " %%E in ('
    findstr "BuildVersion" "file.xml"
') do @echo %%E

Use a single % instead of two when running from the command line though.
For a more comprehensive information please check this post.


Q:

I am having trouble with a nested If Statement in Excel

I am attempting to formulate a nested If Statement in Excel with three qualifications:
if sales are <100--> "Low"
if sales are between 100 and 1000-->"Mid"
if sales are greater than 1000-->"High"

Here's what I have so far:
        =IF(C3<100,"Low"), if(AND(C3>100,C3=1000)), "Mid"), if(C3>1000),"High"))
but the formula doesn't work. Can anyone help me out?
Best,
Bryan McCormack

A:

IF Trouble
Compare

Here is your formula that doesn't work, and below it is the formula
in your 'style' that would have worked, to see where you went wrong.
=IF(C3<100,"Low"),IF(AND(C3>100,C3=1000)),"Mid"),IF(C3>1000),"High"))
=IF(C3<100,"Low",IF(AND(C3>100,C3<=1000),"Mid",IF(C3>1000,"High","")))

Improve

You can shorten the formula to the following:
=IF(C3<100,"Low",IF(C3<=1000,"Mid","High"))
You can add a check if there is a number in the cell:
=IF(ISNUMBER(C3),IF(C3<100,"Low",IF(C3<=1000,"Mid","High")),"")

Issues (Whole Numbers Only)
Most of the following is incorrect for decimal numbers.

What is this formula doing?
=IF(C3<100,"Low",IF(C3<=1000,"Mid","High"))
1st Case: Value is less than 100 i.e. ..., 97, 98, 99. .
2nd Case: Value is between 99 and 1001 i.e. 100, 101, 102,..., 998, 999, 1000. .
You could say Value is from 100 to 1000.
3rd Case: Value is greater than 1000 i.e. 1001, 1002, 1003,... .
Usually the same operators are used in such cases i.e. either:
=IF(C3<=100,"Low",IF(C3<=1000,"Mid","High"))
1st Case: Value is less than 101 i.e. ..., 98, 99, 100..
2nd Case: Value is between 100 and 1001 i.e. 101, 102, 103,..., 998, 999, 1000. .
You could say Value is from 101 to 1000.
3rd Case: Value is greater than 1000 i.e. 1001, 1002, 1003,... .
or:
=IF(C3<100,"Low",IF(C3<1000,"Mid","High"))
1st Case: Value is less than 100 i.e. ..., 97, 98, 99. .
2nd Case: Value is between 99 and 1000 i.e. 100, 101, 102,..., 997, 998, 999. .
You could say Value is from 100 to 999.
3rd Case: Value is greater than 999 i.e. 1000, 1001, 1002,... .

Notice the small differences in the formulas.


Q:

Is there a way to open and read zip files programmatically uploaded by PXUploadDialog?

I have a user that wants to upload a zip file that contains multiple images and a single CSV file with data related to the images. They want to be able to upload the zip file and have the program dissect it by finding and processing the data within the CSV file and then storing the images within the zip to their appropriate locations.
I'm trying to figure out how to open the zip so I can cycle through each file in there to find what I need. Is there any way to do this?

A:

You can use ZipArchive from Acumatica Framework:
// Uploaded file needs to be attached to a DAC record
Guid[] files = PXNoteAttribute.GetFileNotes(DACCache, DACRecord);
UploadFileMaintenance upload = PXGraph.CreateInstance<UploadFileMaintenance>();

foreach (Guid fileID in files)
{
    FileInfo fileInfo = upload.GetFile(fileID);

    if (fileInfo != null)
    {
        using (MemoryStream stream = new MemoryStream(fileInfo.BinData))
        {
            ZipArchive zip = ZipArchive.OpenReadonly(stream);

            string tempDirectory = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
            Directory.CreateDirectory(tempDirectory);
            ZipFolder.Decompress(zip, tempDirectory, true);

            foreach (string filePath in Directory.GetFiles(tempDirectory))
            {
                // Enumerating decompressed files
            }
        }
    }
}


Q:

Assigning viewModel on Controller Init?

I am using MVVM and want to assign my viewModel to the viewController on the Controllers init. I thought I would achieve this like so:
class LoginViewController: UIViewController, UITextFieldDelegate {

    init(loginViewModel: LoginViewModel) {
        self.loginViewModel = loginViewModel
    }

    required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
        fatalError("init(coder:) has not been implemented")
    }

However I get the error:

Super.init isn't called on all paths before returning from initializer

Is this not the correct route to take? also how would I init the viewModel correctly when it requires an object to do so, but it has to perform a network request first? Init with a blank object instance?
Thanks
edit: this is what im trying now
initWithViewAndViewModel:(loginView: LoginView, loginViewModel: LoginViewModel) {
        super.init()
        self.loginView = loginView
        self.loginViewModel = loginViewModel
    }

A:

As a best practice,
Step 1:
required init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }

Step 2:
init(loginViewModel : LoginViewModel) {
        super.init(nibName: nil, bundle: nil)
        initWithModel:(loginViewModel: LoginViewModel)
    }

Step 3: implement initWithModel function


Q:

Conversion failed when converting the nvarchar value 'FALL' to data type int

I have a query below that I have been struggled with. I know that my evt_code column is integer but includes nvarchar value also (for example FALL2015,JP19200202 and many others including letters).
I need to include those nvarchar codes in my result set. Can you help? I believe I need to add a condition into my join in order to include those codes with nvarchar datatype but don't know how.
I apologize for such a long script. You may ignore it. The question is up here but wanted to include the query also. I am using SQL Server 2014.
select distinct

prc_code AS REGCLASS,
etp_code AS TYPE,
evt_title AS TITLE,
evt_code AS MEETING,
ea.adr_city AS CITY,
ea.adr_state AS STATE,
ea.adr_country AS COUNTRY,
evt_start_date AS DATE,

case
    when net_ivd_amount_cp=0
    then 'Comp'
    else 'Paid'
end as 'Paid/Comp',

net_ivd_amount_cp as 'Revenue',
ev_registrant.reg_cst_key AS [COUNT],
net_ivd_amount_cp,
chp_name as 'District / National Council',
c03_region_name as 'DC Region',
cst_sort_name_dn as 'Name',
ind_first_name as 'First',
ind_last_name as 'Last',
cst_ixo_title_dn as 'Registrant Title',
cst_org_name_dn as 'Organization',
ca.adr_line1 as 'Address 1',
ca.adr_line2 as 'Address 2',
ca.adr_city as 'Registrant City',
ca.adr_state as 'Registrant State',
ca.adr_post_code as 'Registrant Zip',
ca.adr_country as 'Registrant Country',
cst_phn_number_complete_dn as 'Phone',
cst_eml_address_dn as 'Email',

case
    when mem_member_type IS null
    then 'Prospect'
    else mem_member_type
    end as 'Member/Prospect',
mem_join_date as 'Join Date',

reg_attendance_flag as 'Attended',

case
    when ind_int_code='Student'
    then 'Student'
    else org_ogt_code
end as 'Industry',

cr.rgn_code as 'Region'

FROM ev_registrant
    join co_customer on reg_cst_key=cst_key
    INNER JOIN ev_event on reg_evt_key=evt_key
    INNER JOIN ev_event_type ON ev_event.evt_etp_key = ev_event_type.etp_key
    left outer join dbo.ac_invoice with (nolock) ON     dbo.ev_registrant.reg_inv_code=dbo.ac_invoice.inv_code
    LEFT OUTER JOIN dbo.vw_ac_invoice_detail WITH (nolock) ON dbo.ac_invoice.inv_key = net_inv_key
    LEFT OUTER JOIN dbo.ac_payment_detail WITH (nolock) ON dbo.ac_payment_detail.pyd_ivd_key = net_ivd_key
    LEFT OUTER JOIN dbo.oe_product with (nolock) on dbo.oe_product.prd_key=net_ivd_prc_prd_key
    LEFT OUTER JOIN dbo.oe_product_type WITIH (nolock) on prd_ptp_key = ptp_key
    LEFT OUTER JOIN dbo.oe_price WITH (nolock) on net_ivd_prc_key = prc_key
    left outer join ev_event_location on evl_evt_key=evt_key and evl_primary=1
    left outer join ev_location on evl_loc_key=loc_key
    left outer join co_customer_x_address ecxa on loc_cxa_key=ecxa.cxa_key
    left outer join co_address ea on ecxa.cxa_adr_key=ea.adr_key
    left outer join client_uli_dc_region on LEFT(evt_code, 4)=c03_chp_chapter_number
    left outer join co_chapter on LEFT(evt_code, 4)=chp_chapter_number
    left outer join co_customer_x_address ccxa on cst_cxa_key=ccxa.cxa_key
    left outer join co_address ca on ccxa.cxa_adr_key=ca.adr_key
    LEFT OUTER JOIN co_country cc on ca.adr_country=cc.cty_code
    LEFT OUTER JOIN co_region cr on cr.rgn_key=cc.cty_rgn_key
    left outer join vw_client_uli_member_type on cst_key=mem_cst_key
    left outer join co_individual_x_organization on ixo_key=cst_ixo_key
    left outer join co_organization on ixo_org_cst_key=org_cst_key
    left outer join co_individual on cst_key=ind_cst_key
where
    ((net_ivd_void_flag)=0
        Or net_ivd_void_flag Is Null)
    AND (reg_delete_flag=0 Or reg_delete_flag Is Null)
    AND ((ev_registrant.reg_cancel_date) Is Null
    and evt_start_date>='2017-07-01')
    and ptp_code='event'

A:

Ok, so now we know that the evt_code is of data type NVARCHAR.
You have two joins which are joining on that field, listed below.
left outer join client_uli_dc_region on LEFT(evt_code, 4)=c03_chp_chapter_number
left outer join co_chapter on LEFT(evt_code, 4)=chp_chapter_number

If either of those columns are of any numerical data type, you'll get the error which you have mentioned. The solution would be to CAST the fields which you join to them, to NVARCHAR


Q:

How can one prove (¬ ∀ x, p x) → (∃ x, ¬ p x) from first principles in LEAN?

The proof of this basic implication from first principles, an exercise in "Theorem proving in Lean" 4.4, beats all my attempts so far:
open classical
variables (α : Type) (p q : α → Prop)
variable a : α

local attribute [instance] classical.prop_decidable
theorem T08R : (¬ ∀ x, p x) → (∃ x, ¬ p x) :=
begin
    intro nAxpx,
    --by_contradiction nExnpx,
    --apply nAxpx,
end

After the intro I don't know how to use nAxpx to go further. I thought of by_contradiction, but that only introduces the negated existence nExnpx, which can't be used with cases, so I can't produce an x : α. Excluded middle doesn't seem to help either. I can get a proof with mathlib tactics,
theorem T08R : (¬ ∀ x, p x) → (∃ x, ¬ p x) :=
begin
    push_neg,
    tauto
end

but don't have enough knowledge to translate that back into tactics mode, so this doesn't help my understanding.

A:

I think you have to do by_contradiction twice. After apply naXpx try intro a and then by_contradiction. Then you'll have an a a proof of ¬p a, but also a proof that ¬∃ (x : α), ¬p x which is a contradiction.
A full proof is
theorem T08R : (¬ ∀ x, p x) → (∃ x, ¬ p x) :=
begin
    intro nAxpx,
    by_contradiction nExnpx,
    apply nAxpx,
    assume a,
    by_contradiction hnpa,
    apply nExnpx,
    existsi a,
    exact hnpa,
end


Q:

WPF: Image click event

I can find only MouseDown Event and MouseUp Event on a image in WPF.
This causes some problem if I do MouseDown on some Image, Move the mouse and MouseUp event happens on some other image.
Is there any other event that I can use to solve this problem. like MouseClick Event for Button element.

A:

If you really must use an image then there's a couple of things you can do to check for a "click".

Check the time between the two events. If it's less than your threshold, then treat the mouse up as a click. You'll need to store the time of the mouse down event.
Check that the sender of both events is the same. Again you'll need to store the sender of the mouse down event.

You might also want to check that it's the left button that's been pressed and released.
Combining the two:
    private DateTime downTime;
    private object downSender;

    private void Image_MouseDown(object sender, MouseButtonEventArgs e)
    {
        if (e.LeftButton == MouseButtonState.Pressed)
        {
            this.downSender = sender;
            this.downTime = DateTime.Now;
        }
    }

    private void Image_MouseUp(object sender, MouseButtonEventArgs e)
    {
        if (e.LeftButton == MouseButtonState.Released &&
            sender == this.downSender)
        {
            TimeSpan timeSinceDown = DateTime.Now - this.downTime;
            if (timeSinceDown.TotalMilliseconds < 500)
            {
                // Do click
            }
        }
    }

There's actually a third thing you can do: Check the mouse position.
    private Point downPosition;

save the position:
    this.downPosition = e.GetPosition(sender as Image);

then check it in the MouseUp event, again with a tolerance value.

A:

Are you sure that you want just an image or do you actually want a button with an image as content? A button with an image will have the click event.


Q:

In Isaiah 28:16 what does it mean that the cornerstone is "tested"?

[Isa 28:16 NIV] (16) So this is what the Sovereign LORD says: "See, I lay a stone in Zion, a tested stone, a precious cornerstone for a sure foundation; the one who relies on it will never be stricken with panic.

A:

In Isaiah 28:16 what does it mean that the cornerstone is “tested”?

[Isa 28:16 NIV] (16) So this is what the Sovereign LORD says: "See, I
  lay a stone in Zion, a tested stone, a precious cornerstone for a sure
  foundation; the one who relies on it will never be stricken with
  panic.

The Apostle Peter, by quoting Isaiah's words, showed that the prophecy applied to Jesus,  " a precious corner stone" Peter wrote:
1 Peter 2:4-7 (NET Bible)
A Living Stone, a Chosen People

4 "So as you come to him, a living stone rejected by men but[b] chosen
  and precious[c] in God’s sight, 5 you yourselves, as living stones,
  are built up as a spiritual house to be a holy priesthood and to offer
  spiritual sacrifices that are acceptable to God through Jesus Christ.
  6 For it says in scripture, “Look, I lay in Zion a stone, a chosen and
  precious cornerstone, and whoever believes in him will never be put to
  shame.” 7 So you who believe see  his value, but for those who do not
  believe, the stone that the builders rejected has become the
  cornerstone."

How was Jesus tried and tested cornerstone?
I lay a stone in Zion, a tested cornerstone, Jesus was that precious cornerstone chosen by God to be the foundation of his city, for three and a half years he was tested to the utmost, in all matter of trials ,temptations, persecutions, and even nailed to  death. In all his trials He remained  obedient and faithful to the end, never going contrary to his Father's will, He loved  his  Father to the end. Being tested  in the flesh the quality of his faith was hardened  and proven something  altogether different to being faithful in heaven.
The scriptures record his trials:
Hebrews 2:18  (NASB)

18 "For since He Himself was tempted in that which He has suffered, He
  is able to come to the aid of those who are tempted."

Hebrews 4:15  (NASB)

15 "For we do not have a high priest who cannot sympathize with our
  weaknesses, but One who has been tempted in all things as we are, yet
  without sin."

Hebrews 5:7-8  (NASB)

7 "In the days of His flesh, [b]He offered up both prayers and
  supplications with loud crying and tears to the One able to save Him
  from death, and He was heard because of His piety. 8 Although He was a
  Son, He learned obedience from the things which He suffered."

Revelation 3:14  (NASB)

14 “To the angel of the church in Laodicea write: The Amen, the
  faithful and true Witness, the Beginning of the creation of God, says
  this:

1 Timothy 6:13  (NASB)

13 "I charge you in the presence of God, who gives life to all things,
  and of Christ Jesus, who testified the good confession before Pontius
  Pilate."

Jesus Christ resisted every attempt to break down his integrity, he endured all trials and continued faithfully on regardless of the opposition of sinners against him.The apostle John also uttered prophecy covering Zion many years after the literal Zion was destroyed. John  wrote ,Rev. 14:1(NASB)
The Lamb and the 144,000 on Mount Zion

14 "Then I looked, and behold, the Lamb was standing on Mount Zion,
  and with Him one hundred and forty-four thousand, having His name and
  the name of His Father."


Q:

Why doesn't ulimit -t kill a process sleeping beyond the limit with time.sleep?

I am trying to limit the CPU usage of one python script using ulimit -t.  The script contains one time.sleep() statement and it is not killed after the specified time limit. Here is the simplified python script named test.py:
import time

while True:
    time.sleep(0.1)

and I run the command as following:
ulimit -v 400000; ulimit -t 30; python test.py

The script keeps running forever. Are there any explanations for this? Thanks.
The answer of mata is correct. I updated my real code which contains a hidden thing that ulimit -t does not count the running time of spawned subprocesses.
#!/usr/bin/env python
# Run: python smt.py filename.smt2 timeout
# timeout is in seconds

import os
import subprocess
import sys
import stat
import time

current_path = os.path.dirname(os.path.realpath(__file__))

def remove_tmp (filename, version):
  try:
    os.remove(filename + '.' + version + '.tmp')
  except OSError:
    pass

  try:
    os.remove(os.path.splitext(filename)[0] + '.' + version +  '.out')
  except OSError:
    pass

  try:
    os.remove(os.path.splitext(filename)[0] + '.' + version +  '.in')
  except OSError:
    pass

def run_raSAT (filename, bounds, sbox, timeout):
  startTime = time.time()

  raSATResult = "unknown"

  # remove tmps files:
  remove_tmp(filename, "0.2")
  remove_tmp(filename, "0.3")

  proc2 = subprocess.Popen([os.path.join(current_path, "./raSAT-0.2"), filename, bounds, 'sbox=' + str(sbox), 'tout=' + str(timeout-(time.time() - startTime))])
  proc3 = subprocess.Popen([os.path.join(current_path, "./raSAT-0.3"), filename, bounds])
  while True:
    if proc2.poll():
      # try read output of 0.2
      try:
        with open(filename + '.0.2.tmp', 'r') as outfile:
          raSATResult = outfile.read().rstrip()
          outfile.close()
          if raSATResult == "unknown":
            sbox /= 10
            remove_tmp(filename, "0.2")
            proc2 = subprocess.Popen([os.path.join(current_path, "./raSAT-0.2"), filename, bounds, 'sbox=' + str(sbox), 'tout=' + str(timeout-(time.time() - startTime))])
      except IOError:
        pass

    if proc3.poll():
      # try read output of 0.3
      try:
        with open(filename + '.0.3.tmp', 'r') as outfile:
          raSATResult = outfile.read().rstrip()
          outfile.close()
      except IOError:
        pass

    if raSATResult == "sat" or raSATResult == "unsat":
      if not proc3.poll():
        proc3.kill()
      if not proc2.poll():
        proc2.kill()
      break

    time.sleep(0.01)

  return raSATResult, sbox

def run(filename, initLowerBound, initUpperBound, sbox, timeout):
  lowerBound = initLowerBound
  upperBound = initUpperBound
  raSATResult = "unknown"
  startTime = time.time()
  while (raSATResult == 'unknown'):
    (raSATResult, sbox) = run_raSAT(filename, 'lb=' + str(lowerBound) + ' ' + str(upperBound), sbox, timeout - (time.time() - startTime))
    if raSATResult == 'unsat':
      (raSATResult, sbox) = run_raSAT(filename, 'lb=-inf inf', sbox, timeout - (time.time() - startTime))
  print (raSATResult)

  # remove tmps files:
  remove_tmp(filename, "0.2")
  remove_tmp(filename, "0.3")

# get timeout from environment
timeout = float(os.environ.get('STAREXEC_CPU_LIMIT'))

run(sys.argv[1], -10, 10,  0.1, timeout)

A:

ulimit -t sets the CPU time limit. While your program is sleeping it doesn't use any CPU time, so that time doesn't count. It will only occupy a few CPU cycles to go to sleep again, that's why it's not killed.
You can't specify a real time limit using ulimit.


Q:

Find all changed objects for a given user

I have a model Car which has_paper_trail. How can I find all cars which where changed or created by current_user? I could loop through all of them but that is a performance nightmare. Some where search is what I'm searching for but can't find.

A:

There should be a whoddunnit column in the versions table which you can query in conjunction with item_type, but it's only useful if it is recorded properly.
A simple query to get IDs of the modified records:
PaperTrail::Version.where(whodunnit: current_user.id, item_type: 'Car').select('distinct item_id')

See also https://github.com/airblade/paper_trail#finding-out-who-was-responsible-for-a-change


Q:

SOAP set proper xmlns headers

I have a two fold problem with setting SOAP headers.  Primarily, I've never done it before and two, I can't seem to find a good solution on here for doing so.  I apologize if there are exact duplicates, and please point me in the right direction if there are.
I need to set the following xmlns:xsi and xmlns:xsd data sets on the soap:Envelope.  I also need to set an xmlns attribute on the first tag in the XML (rough example).
The first part needs to be added, the second part is already in there when I do a __getLastRequest().  And the third part needs to be added (just the SendPurchases xmlns attribute).
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xsd="http://www.w3.org/2001/XMLSchema">

<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/
xmlns:ns1="urn:[taken out for security purposes]">

<soap:Body>
    <SendPurchases xmlns="urn:...">
    </SendPurchases>
</soap:Body>

Would I need to use the header() for this?
I am using PHP's SOAP client.  Any help at all is greatly appreciated!
EDIT:
I went with another route, thank you for all your answers though!

A:

I had a simular problem with the envelope, I made a fix for that. I will post the fix with the data you provided, You will have to check if everything is oke:
The custom class to edit the request:
class CustomSoapClient extends SoapClient {

                            function __doRequest($request, $location, $action, $version) {

                                $request = str_replace('<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:xsd="http://www.w3.org/2001/XMLSchema">', '', $request);
                                // parent call
                                return parent::__doRequest($request, $location, $action, $version);
                            }

                        }

Setup the soap client:
$client = new CustomSoapClient($wsdl, array(
                                'features' => SOAP_SINGLE_ELEMENT_ARRAYS,
                                'exceptions' => true,
                                'trace' => 1,
                                'soap_version' => SOAP_1_2,
                                ));

The request:
//notice that the envelope is in the request! also you need to change the urn
$request = '
<SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/xmlns:ns1="urn:[taken out for security purposes]">

<soap:Body>
   <SendPurchases xmlns="urn:...">
   </SendPurchases>
</soap:Body>
</SOAP-ENV:Envelope>';

$xmlvar = new SoapVar($request, XSD_ANYXML);

$result = $client->Controleer($xmlvar);

print_r($result); // finally check the result

I hope this will help you :)


Q:

cisco network meanings and traceroute

I have a small network here. The connection from router 1 to router 3 is relevant. I have two questions in one. On the one hand I would be interested, why at Cisco between the routers always this red connection arises. Does this have something to do with WANs? My other question relates to traceroute. The command gives the next router of the connection. How about this example? I am somewhat confused, since I can not exactly assign which IP now belongs to which router (I think this red connection irritates me easy). What the command does is clear to me. Only I can not find straight in the network naming.
My approach would be:
Traceroute 192.17.5.0
The output should then be:
192.17.2.0 with XY secs
192.17.7.1 with XY secs
Is this right?
Is the router IP the respective input IP?
Sorry for my confusion. I hope you could help me. Thank you very much!

PS: I have often seen this serials S1 and S0, but what are the differences between this serials, why are there two serials? If I imagine how to connect two routers I would use only one serial. so why are there two?

A:

Traceroute is used to determine the path between hosts, not between networks.  From the PC on the left, you would traceroute to the PC on the right, 192.17.5.x.  the result would show you the path used to get from one PC to the other (subject to all the usual disclaimers).
Routers can (and often do) have multiple interfaces. In your diagram, for example, multiple interfaces allow the packet to take an alternate path if one becomes unavailable.  That's what routing is all about.  It's true, if you only have two routers, you only need one serial interface.  But that's not the real world.
I'm afraid I don't understand your question about colors.


Q:

Error when running unit tests in visual studio: Test-case objects missing

I'm getting the following error when running unit tests from visual studio using resharper:
Test-case objects missing for the following elements: ...  Rebuild the project and try again
In the tooltip next to the unit test method it says: Inconclusive: Test not run and I think it said Unit test skipped at one point.  Resharper shows a grey eye icon.
There's also a wierd issue with visual studio's Test Explorer.  It won't show all my unit tests.  In fact, it's missing over 200 of my unit tests.  They just don't appear in the Test Explorer window.  I do have a handful of tests that appear and will run just fine.
Things I've tried already: rebooting my machine, clean, rebuild, changing all dependent projects to use the same .net framework 4.7.
I'm using VS 2017 .net Framework 4.7, Resharper, and MSTest.  All with the latest updates and versions.

A:

I experienced this error after removing all nuget packages as I had changed my .net version and did not need any of them to compile.
After re-installing the MSTest.TestAdapter nuget package ReSharper started running my unit tests again as expected.
Install-Package MSTest.TestAdapter

A:

I know this won't answer the OP's question, since he/she has tried it, but maybe it will help someone else.
For me a simple restart of Visual Studio solved the Test-case objects missing for the following elements: ...  Rebuild the project and try again problem.

A:

After banging my head for a day I got Test Explorer working.  It was the target Platform.
In the unit test project properties, under Build, I had the Platform target as x64.  I switched it to AnyCPU and Test Explorer immediately picked up my missing unit tests.  However, resharper is still giving me the same error.  I'll update if I find solution for it.  In the mean time, I can at least run and debug my unit tests now.


Q:

How to do grid typesetting with amsmath?

Following the advice in the answer to this question, I did set a huge negative \lineskiplimit.  However, it turned out that align got quite upset about this.  So my question is: what would you recommend to achieve (at least partially) grid typesetting with amsmath?  By "partially" I mean that I accept not adhering to grid when there are, say, lots of theorem-like environments etc. on a page, but on pages with only text/sections/inline math I'd prefer to have it.  I am rather afraid of using any packages for grid typesetting, since in the class I am using I redefined a lot of LaTeX internals (for example, I coded theorems, sections, enumerations from scratch, not even 100% compatibly with pure LaTeX).  (I know this is risky, but "though this be madness, yet there's method in't";).)
So now I have a few options.

Redefine align & friends to temporarily set \lineskiplimit to 0pt.  Not something I'd like to do, obviously.
Set \lineskiplimit back to 0pt, and \smash (or display) manually all "too big" formulae.

Currently I am leaning towards 2., but are there any other ideas?

A:

The basic answer is that you have to make all your display objects fit into multiples of your grid, e.g., headings, display equations, etc. need to be preprocessed and boxed so that they fit the grid and similarly floats and footnotes have to be adjusted to honor the space requirements. There are a bunch of packages out there who are making an attempt at this, e.g., grid.sty from River Valley or ltxgrid from RevTeX and even if you do not want to use those, it might be worthwhile to look at what they do and how.
One option for something like display environments is to typeset them into a \vbox of column width and then measure the the amount of vertical space they occupy. Then add on top and below whatever is needed to get to the multiple of the grid. The tricky part then is to set \prevdepth properly so that the next line of text still aligns on the grid. Another problem is that you may want to split such material across the page. Using \unvbox might be an option but only ensure that you do not end up with stretchable glue that may break your grid.
Playing around with \lineskiplimit is possible and to some extend useful, but if set to a negative value for paragraphs it means that lines can overprint (and TeX will not detect this for you).


Q:

Learn Python the Hard Way Exercise 43

I do not understand how the script gets the next room, and generally how the "Engine" and "Map" classes work. Here's an excerpt:
Class Map(object):

    scenes = {
        'central_corridor': CentralCorridor(),
        'laser_weapon_armory': LaserWeaponArmory(),
        'the_bridge': TheBridge(),
        'escape_pod': EscapePod(),
        'death': Death()
    }

    def __init__(self, start_scene):
        self.start_scene = start_scene

    def next_scene(self, scene_name):
        return Map.scenes.get(scene_name)

    def opening_scene(self):
        return self.next_scene(self.start_scene)

class Engine(object):

    def __init__(self, scene_map):
        self.scene_map = scene_map

    def play(self):
        current_scene = self.scene_map.opening_scene()

        while True:
            print "\n--------"
            next_scene_name = current_scene.enter()
            current_scene = self.scene_map.next_scene(next_scene_name)

I simply don't understand how these portions work. I know how classes and object instances and attributes and all that other OOP stuff works, but for some reason this portion of the code I don't get. Mainly the Map class. If someone could explain it it would be awesome.
Also (this may require reading the exercise), why is it required to have these two classes anyway? Couldn't you just do it with class methods instead (i.e. methods without self as a param.)? Then you could just call, for example, CentralCorridor.enter(). In fact, that is how I solved it before reading the answer, and it worked out fine.
Sorry, my main question is how the Engine and Map classes work. The other thing is secondary.
Thanks in advance!

A:

The Map object is a Class which maps your scenes. It has some scenes saved in an array.
scenes = {
    'central_corridor': CentralCorridor(),
    'laser_weapon_armory': LaserWeaponArmory(),
    'the_bridge': TheBridge(),
    'escape_pod': EscapePod(),
    'death': Death()
}

When an object of Map is made you also give it an opening scene as seen in the constructor
def __init__(self, start_scene):
    self.start_scene = start_scene

This creates a variable in Map called start_scene containing your opening scene.
Furthermore Map has 2 methods
# This one returns a scene based on its name or key in the scenes array
def next_scene(self, scene_name):
    return Map.scenes.get(scene_name)

# And this one  returns the opening scene which is set when you create the map.
def opening_scene(self):
    return self.next_scene(self.start_scene)

The Engine seems to be controlling the scenes when to play and what to play.
# When creating an Engine object you give the map containing scenes to its constructor
def __init__(self, scene_map):
        self.scene_map = scene_map

# The method which starts playing the scenes
def play(self):

    # the opening scene from the map is selected as the current scene
    current_scene = self.scene_map.opening_scene()

     # You loop all the scenes probably, conditions of this loop are unknown because you haven't posted it entirely.
     while True:
         print "\n--------"
         # It seems the next scene name is known in the current scene
         next_scene_name = current_scene.enter()

         # It replaces current scene with the next scene from the map
         current_scene = self.scene_map.next_scene(next_scene_name)

why is it required to have these two classes anyway?

It isn't, unless it's required according to your assignment
Like you said it's possible to do it without, BUT there are good reasons to do so.
This way you make 2 separate classes with their own responsibilities.
This way code is more readable when the application gets bigger and bigger. And it's easy to navigate through the application.  You can easily change parts of your app etc etc.   My advice is to keep practicing and reading about OOP, you will notice why you do the things you see.

A:

The Map class has a dictionary of scene names that are keys, and instances of different classes as the values.  To retrieve one of the instances, you call a method passing in a string that is the scene name.  The Map class then returns an instance of the corresponding class.

Couldn't you just do it with class methods instead (i.e. methods
  without self as a param.)? Then you could just call, for example,
  CentralCorridor.enter().

Yes, you could.  The downside is that now you have hard coded the names of your scene classes in your code.  If you later decide to rewrite your program to remove some scenes or add other scenes, you have to change all the places in your code where you hard coded the names.  If you employ the Map class, then changes only have to be made to the dictionary.  Although, you would still have to eliminate method calls that try to retrieve class instances that you've removed.  Or, you could have the next_scene() method deal with attempts to retrieve scenes you've removed from the dictionary.
Another consideration with class methods is: will you need to store 'state'? Like, how many players are currently in the scene.  And, will you need to create more than one scene of that type?


Q:

Python- How do I update an index of a for loop that iterates over lines in a file?

Using a for loop, I'm iterating over the lines in a file. Given this line:
line= [ ‘641', '"Tornadus', ' (Incarnate Form)"', '"Flying"', '""', '5', '"TRUE"']

I need to reformat index [6] from '"TRUE"' to the boolean True.
Full expected output: d={'Tornadus, (Incarnate Form)': (641, 'Flying', None, 5, True}
I used:
if "T" in line[6]:  # format legendary if TRUE
    line[6] = True

But I get this error:

Traceback (most recent call last):
  File "tester5p.py", line 305, in test_read_info_file_05
  self.assertEqual(read_info_file(DATAFILE),info_db5())File "/Users/kgreenwo/Desktop/student.py", line 52, in read_info_file
      line[5] = False
TypeError: 'str' object does not support item assignment

How can I assign it WITHIN the for loop?
To see my full code:
def read_info_file(filename):
    f = open(filename, 'r')  # open file in read mode
    d = {}  # intitialze as empty
    count = 0  # helps to skip first line
    key = ""
    for line in f:  # get each line from file
        if count != 0:  # skip first line
        # 1___________________________________________open file,read, skip 1st line
            id_num = int(line[0])  # make id an integer
        # 2________________________________________________
            if ',' in line[1]:  # two parts to fullname, changes indexes
                part1 = line[1].strip('"')  # get format first part of name
                part2 = line[2].strip()  # get format second part of name
            # 3______________
                fullname = part1 + part2
                key = fullname
            # 4______________
                type1 = line[3].strip('"')
            # 5--------------
                if line[4] == "":  # check if there is not a second type
                    type2 = None  # correct format
                else:  # is a second type
                    type2 = line[4].strip('"')  # format second type
            # 6______________

                generation = line[5]  # format generation
            # 7_____________
                if "T" in line[6]:  # format legendary if TRUE
                    line[6] = True
                    legendary = line[6]
                else:  # format legendary if FALSE
                    line[6] = False
                    legendary = line[6]

            # 8______________________________________________one part to name
            else:  # one part to name
                fullname = line[1].strip('"')
            # 9______________
                type1 = line[2].strip('"')
            # 10_____________
                if line[3] == "":  # if no second type
                    type2 = None
                else:
                    type2 = line[3].strip('"')  # there is a second type
            # 11_____________
                generation = line[4]  # format generation
            # 12_____________
                if "T" in line[5]:  # format legendary if TRUE
                    line[5] = True
                    legendary = line[5]
                else:  # formmat Legendary if False
                    line[5] = False
                    legendary = line[5]

            value = (id_num, type1, type2, generation, legendary)
            d.update([(key, value)])
        count += 1
    return d

Reproducible example:
  input: (don't forget to skip first line!)

info_file1 = '''"ID","Name","Type 1","Type 2","Generation","Legendary"
1,"Bulbasaur","Grass","Poison",1,"FALSE"

Output:
          d={'Bulbasaur':(1,'Grass','Poison',1,False)}

A:

Instead of reassigning it, I just did this and it worked:
if "T" in line[6]:  # format legendary if TRUE
    legendary = True
else:  # format legendary if FALSE
    legendary = False


Q:

Don't create section for bibliography

I am writing a document which uses chapters (\chapter{...}) instead of sections and would like to create one chapter for my references. But when I am using these commands:
\bibliographystyle{plain}
\bibliography{ref.bib}

to generate my references, it automatically creates a section "Bibliography" which is not consistent with the document. So I would like to just generate the references without any section and than use the \chapter{...} command for sectioning.
Does anyone know how to stop the \bibliography* commands from creating this section?
My document uses a custom class which was provided by my university:
\NeedsTeXFormat{LaTeX2e}
\ProvidesClass{uva-bachelor-thesis}[2005/06/10 Version]

\RequirePackage{graphicx}
\RequirePackage[svgnames]{xcolor}
\RequirePackage[absolute]{textpos}
\RequirePackage{rotating}

\def\supervisors#1{\gdef\@supervisors{#1}}
\def\signedby#1{\gdef\@signedby{#1}}

\DeclareOption*{\PassOptionsToClass{\CurrentOption}{report}}
\ProcessOptions\relax
\LoadClass[10pt,oneside]{report}

\renewcommand{\maketitle}{%
        \thispagestyle{empty}
    % A fake element on the page (else texpos absolute option doesn't work)
    \hspace*{1em}

    \begin{textblock*}{10cm}(6cm,3cm)
        \noindent\large\scshape Bachelor \\[2ex]
        \includegraphics[height=1cm]{logo}
        %\Large University
    \end{textblock*}

    \begin{textblock*}{10cm}(6cm,12cm)
        \noindent
        \sffamily\Huge \@title
    \end{textblock*}

    \begin{textblock*}{10cm}(6cm,18cm)
        \noindent
        \sffamily\Large \@author\\[3pc]
        \@date
    \end{textblock*}

    \begin{textblock*}{10cm}(6cm,26cm)
    \noindent\sffamily
    \begin{description}
        \item[\sffamily Supervisor:] \@supervisors
        \item[\sffamily Signed:] \@signedby
        \end{description}
    \end{textblock*}

    \textblockcolor{LightGray}
    \begin{textblock*}{2cm}(3cm,2cm)
        \vspace*{26cm}\hspace*{1em}
    \end{textblock*}

    \begin{textblock*}{2cm}(3.7cm,25cm)
        \begin{rotate}{90}
            \noindent\scshape\Huge\textcolor{DarkGray}{University}
        \end{rotate}
    \end{textblock*}

%   \cleardoublepage
}

Here is my main file to reproduce the problem:
\documentclass[oneside, openright]{uva-inf-bachelor-thesis}
\usepackage{graphicx}
\usepackage{url}
\usepackage{lipsum}
\usepackage{etoolbox}
\patchcmd{\thebibliography}{\chapter{\refname}}{}{}{}

\title{}
\author{}
\supervisors{}
\signedby{}

\begin{document}

\chapter{Introduction}

\bibliographystyle{plain}
\bibliography{ref.bib} % The file containing the bibliography

\chapter{Appendix}

\end{document}

A:

Is this, what is wanted? A numbered chapter heading for bibliography? Then use \usepackage[numbib]{tocbibind}.
\documentclass[oneside, openright]{uva-inf-bachelor-thesis}
\usepackage{graphicx}
\usepackage{url}
\usepackage{lipsum}
\usepackage[numbib]{tocbibind}
\usepackage{etoolbox}
%\patchcmd{\thebibliography}{\chapter{\refname}}{}{\typeout{Foo}}{\typeout{Stuff}}

\title{}
\author{}
\supervisors{}
\signedby{}

\begin{document}
\tableofcontents

\chapter{Introduction}

\cite{Lam94}

\bibliographystyle{plain}
\bibliography{biblio} % The file containing the bibliography

\chapter{Appendix}

\end{document}


Q:

Connecting SDI and SDO to a single DATA pin

On the MMA7455 accelerometer, there is only one DATA pin which is used for both input and output. On the manual, it tells me to connect this pin to SDI and SDO. Now that's all fine, but on my chip, these are two separate pins.
If I connect SDI and SDO pins to the DATA pin, won't the data that flows out of SDO go into the SDI pin as well? Wouldn't this cause any problems?
Is there are any buffering that would potentially store the data the comes in through SDI? (So maybe after sending something out of SDO, I can clear the buffer at SDI to avoid reading what I just sent).

A:

Based on the picture, it seems you have a breakout board/module for the MMA7455, by Parallex? The chip itself allows for both 4 wire and 3 wire spi, but that module only has the 3 wire mode enabled.
But that's not really a problem. The thing about 3 wire mode is that it is half duplex, only transmits one way at a time. And this device is a slave device, it does not send arbitrary data at all times. By hooking up sdi and sdo to the same pin, you just have release the sdo pin (tristate/input mode) when you expect to read data. You Control the Clock so you control when and how fast the accelerometer sends data. You assert the cs pin, you send the register address with the read bit, then before you start clocking in the data, you release the SDO pin. You clear your buffer, then you clock the data in. If you're not ready, don't tick the spi clock.
What you want/need to do is also take a look at the chip's datasheet, not just the module's datasheet.


Q:

Function error: "Binary operator '+' cannot be applied to operands of type 'Double' and 'Int'"

I am currently working on a school assignment for my coding class. In this assignment, we are creating a function that takes a number grade (a Double) and divides it by the numberOfHours to get a GPA variable. I have run into an error though in my code:

Binary operator '+' cannot be applied to operands of type 'Double' and 'Int'

I do not understand this error and I am trying to fix the code by changing what's an Int and what's a Double, but it doesn't seem to be working.
The code where the error is coming from is:
// create your function here
func gpaUpdater(moreHours hours: Double, moreGPA grade: Double) -> Int {
    let addedHours: Int = hours + attemptedHours
    let calculatedGPA: Double = hours / grade
    //gpa = gpa + grade
    print(calculatedGPA)
    return calculatedGPA
}

Full code below:
//  My Functions Playground.swift
//
//
//: Playground - noun: a place where people can play

import UIKit

/*
 We're going to track your GPA from one semester to the next. Assume at the end of your sophomore years, you have attempted 60 hours and have earned 222.5 grade points. Assign attempted hours and grade points to variables. Write a function that updates your current GPA and assigns it to the GPA var (you'll update it along the way). Label your function arguments. Print your new GPA from within the function.

 At the end of the current semester, add 16 hours and 60 grade points to your record. Call the gpa function to update your overall gpa.

 Test your gpa at the end of the year to see if any administrative action needs to be taken. If the gpa is less than 1.8, the student will need to be placed on suspension. If less than 2.0, we need to put the student on probation. If over 3.5, we'll put the student on the dean's list, and if over 3.9, we'll put the student on the president's list. Create a switch that prints the recommended adminstrative action. If no action is required, print, "Carry on. Nothing to see here." Create internal and external labels for your arguments.

 */

var gpa: Double
var attemptedHours: Int
var earnedGradePoints: Int

// create your function here
func gpaUpdater(moreHours hours: Double, moreGPA grade: Double) -> Int {
    let addedHours: Int = hours + attemptedHours
    let calculatedGPA: Double = hours / grade
    //gpa = gpa + grade
    print(calculatedGPA)
    return calculatedGPA
}

// call the function
gpaUpdater(moreHours: 16, moreGPA: 60)

// add the new hours and grade points here and call the function again
func switchFunction() {
    switch gpa {
    case gpa..<1.8:
        print("You will be placed on suspension")
    case 1.8...2.0:
        print("You will be placed on probation")
    case 3.5...3.8:
        print("You will be put on the dean's list.")
    case 3.9..<gpa:
        print("You will be put on the president's list.")
    default:
        print("Carry on. Nothing to see here.")
    }
}
switchFunction()

A:

Change this line
let addedHours: Int = hours + attemptedHours

to
let addedHours =  Int(hours) + attemptedHours


Q:

How can I print name of corrent page using php?

How can I print name of corrent page using php ?
echo $corrent_page_name;

Result should be :
index.php

A:

$corrent_page_name = basename($_SERVER['SCRIPT_FILENAME']);

See the PHP manual for $_SERVER and basename for more information.
You could also use __FILE__ such as:
$corrent_page_name = basename(__FILE__);


Q:

Input Form On Left And Right Side Of Page

What im trying to do is to make the page has two sections, on the left and right side. But, i only managed to get it working on the left side.
I tried to search on internet but found nothing and im new to css. For example radio button positioned on the right side while the input form is on the left size. So in that way, i can utilize the webpage area.

 .myForm {
    font-family: "Lucida Sans Unicode", "Lucida Grande", sans-serif;
    font-size: 0.8em;
    width: 100em;
    padding: 1em;
    border: none;
    }

 #left{
     width: 60%;
        box-sizing: border-box;
   display: inline-block;
        float: left;
        padding: 0;
        margin: 0 auto;
    }

    #right{
     width: 40%;
        box-sizing: border-box;
   display: inline-block;
        float: right;
        padding: 0 0 0 10px;
        margin: 0 auto;
    }

    .myForm * {
    box-sizing: border-box;
    }

    .myForm fieldset {
    border: none;
 width: 100%;
    padding: 0;
    }

    .myForm legend,
    .myForm label {
    padding: 0;
    font-weight: bold;
    }

    .myForm label.choice {
    font-size: 0.9em;
    font-weight: normal;
    }

    .myForm label {
    text-align: left;
    display: block;
    }

 .myForm label_child {
    text-align: right;
    display: block;
    }

    .myForm input[type="text"],
    .myForm input[type="tel"],
    .myForm input[type="datetime-local"],
    .myForm select,
    .myForm textarea {
    float: right;
    width: 60%;
    border: 1px solid #ccc;
    font-family: "Lucida Sans Unicode", "Lucida Grande", sans-serif;
    font-size: 0.9em;
    padding: 0.3em;
    }

    .myForm input[type="radio"],
    .myForm input[type="checkbox"] {
    margin-left: 40%;
    }

    .myForm button {
    padding: 1em;
    border-radius: 0.5em;
    background: #eee;
    border: none;
    font-weight: bold;
    margin-left: 90%;
    margin-top: 1.8em;
    }

    .myForm button:hover {
    background: #ccc;
    cursor: pointer;
    }

 .body{
 width:100%;
 }
<!DOCTYPE html>

<form class="myForm">

    Project Name
    <input type="text" name="customer_name" required>

    Project ID
    <input type="tel" name="phone_number">

    Project Delivery
    <select name="workflow" >
        <option value="dummy data">Development</option>
        <option value="c_p">Time-Phase Open Budget</option>
      </select>

    Project Status
    <select name="workflow" >
        <option value="dummy data">Open</option>
        <option value="c_p">close</option>
      </select>

    Country
    <select name="workflow" >
        <option value="dummy data">Malaysia</option>
        <option value="c_p">Time-Phase Open Budget</option>
      </select>

    Region
    <select name="workflow" >
        <option value="dummy data">Pen.Malaysia</option>
        <option value="c_p">Time-Phase Open Budget</option>
      </select>

    Block
    <select name="workflow" >
        <option value="dummy data">Tangga Barat Cluster Gas Field</option>
        <option value="c_p">Time-Phase Open Budget</option>
      </select>

    Field
    <select name="workflow" >
        <option value="dummy data">Tangga</option>
        <option value="c_p">Time-Phase Open Budget</option>
      </select>

    PCSB Equity
    <input type="text" name="customer_name" value="100 %"required>

    Currency
    <select name="workflow" >
        <option value="dummy data">MYR</option>
      </select>

    Contract Category
    <select name="workflow" >
        <option value="dummy data">N/A</option>
      </select>

    Project Start Date
    <input type="datetime-local" name="pickup_time" required>

    Project End Date
    <input type="datetime-local" name="pickup_time" required>

    <fieldset id="right">

 <input type="checkbox" name="extras" value="baby"> Only Applicable To JV Module

 <input type="checkbox" name="extras" value="wheelchair"> Use Project Assurance Plan

 <input type="checkbox" name="extras" value="tip" checked> Display In EPMS Dashboards And Reports

 <input type="checkbox" name="extras" value="tip"> Display In Performance Daashboard

    </fieldset>

 <fieldset id="right">

  PPP
    <select name="workflow" >
        <option value="dummy data">Open</option>
  <option value="dummy data">Close</option>
      </select>

 </fieldset id="right">

    Date:
    <input type="datetime-local" name="pickup_time" required>

  <fieldset id="right">

  Milestone
    <select name="workflow" >
        <option value="dummy data">Open</option>
  <option value="dummy data">Close</option>
      </select>

 </fieldset id="right">

    Date:
    <input type="datetime-local" name="pickup_time" required>

  <fieldset id="right">

  Production
    <select name="workflow" >
        <option value="dummy data">Open</option>
  <option value="dummy data">Close</option>
      </select>

 </fieldset id="right">

    Date:
    <input type="datetime-local" name="pickup_time" required>

  <fieldset id="right">

  Cost
    <select name="workflow" >
        <option value="dummy data">Open</option>
  <option value="dummy data">Close</option>
      </select>

 </fieldset id="right">

    Date:
    <input type="datetime-local" name="pickup_time" required>

 <fieldset id="right">

  Manpower:
    <select name="workflow" >
        <option value="dummy data">Open</option>
  <option value="dummy data">Close</option>
      </select>

 </fieldset id="right">

    Date:
    <input type="datetime-local" name="pickup_time" required>

<button>Submit Project</button>

<button>Cancel</button>

    </form>

Im trying to do like in this picture

A:

Layout
I added a CSS class .width-6. By placing this class on the container of each 'half' of the elements you want to split should allow you to achieve the desired result.
Note, I named it width-6 because the conventions in most modern CSS frameworks is to use a 12 column grid.

Unique id attributes
I also took the liberty of removing unnecessary and invalid ids ("right", "left") in your code. These ids must be unique per HTML document and be the same logic you should almost never use them for layout styling. The layout you intended is most commonly implemented with a standardized & reusable grid system based on classes.
id Global Attribute

* {
  box-sizing: border-box;
}

.row {
  display: block;
}

.width-6 {
  display: inline-block;
  position: relative;
  width: 50%;
  float: left;
}

.container-padding {
  padding: 3em 15%;
}

.myForm {
  font-family: "Lucida Sans Unicode", "Lucida Grande", sans-serif;
  font-size: 0.8em;
  width: 100em;
  padding: 1em;
  border: none;
}

.myForm fieldset {
  border: none;
  width: 100%;
  padding: 0;
}

.myForm legend,
.myForm label {
  padding: 0;
  font-weight: bold;
}

.myForm label.choice {
  font-size: 0.9em;
  font-weight: normal;
}

.myForm label {
  text-align: left;
  display: block;
}

.myForm label_child {
  text-align: right;
  display: block;
}

.myForm input[type="text"],
.myForm input[type="tel"],
.myForm input[type="datetime-local"],
.myForm select,
.myForm textarea {
  float: right;
  width: 60%;
  border: 1px solid #ccc;
  font-family: "Lucida Sans Unicode", "Lucida Grande", sans-serif;
  font-size: 0.9em;
  padding: 0.3em;
}

.myForm input[type="radio"],
.myForm input[type="checkbox"] {
  margin-left: 40%;
}

.myForm button {
  padding: 1em;
  border-radius: 0.5em;
  background: #eee;
  border: none;
  font-weight: bold;
  margin-left: 90%;
  margin-top: 1.8em;
}

.myForm button:hover {
  background: #ccc;
  cursor: pointer;
}

.body {
  width: 100%;
}
    <!DOCTYPE html>

  <form class="myForm">

          Project Name
            <input type="text" name="customer_name" required>

          Project ID
            <input type="tel" name="phone_number">

          Project Delivery
            <select name="workflow">
              <option value="dummy data">Development</option>
              <option value="c_p">Time-Phase Open Budget</option>
            </select>

          Project Status
            <select name="workflow">
              <option value="dummy data">Open</option>
              <option value="c_p">close</option>
            </select>

          Country
            <select name="workflow">
              <option value="dummy data">Malaysia</option>
              <option value="c_p">Time-Phase Open Budget</option>
            </select>

          Region
            <select name="workflow">
              <option value="dummy data">Pen.Malaysia</option>
              <option value="c_p">Time-Phase Open Budget</option>
            </select>

          Block
            <select name="workflow">
              <option value="dummy data">Tangga Barat Cluster Gas Field</option>
              <option value="c_p">Time-Phase Open Budget</option>
            </select>

          Field
            <select name="workflow">
              <option value="dummy data">Tangga</option>
              <option value="c_p">Time-Phase Open Budget</option>
            </select>

          PCSB Equity
            <input type="text" name="customer_name" value="100 %" required>

          Currency
            <select name="workflow">
              <option value="dummy data">MYR</option>
            </select>

          Contract Category
            <select name="workflow">
              <option value="dummy data">N/A</option>
            </select>

          Project Start Date
            <input type="datetime-local" name="pickup_time" required>

          Project End Date
            <input type="datetime-local" name="pickup_time" required>

        <fieldset>

 <input type="checkbox" name="extras" value="baby"> Only Applicable To JV
              Module

 <input type="checkbox" name="extras" value="wheelchair"> Use Project Assurance
              Plan

 <input type="checkbox" name="extras" value="tip" checked> Display In EPMS
              Dashboards And Reports

 <input type="checkbox" name="extras" value="tip"> Display In Performance
              Daashboard

        </fieldset>

        <fieldset>

            PPP
              <select name="workflow">
                <option value="dummy data">Open</option>
                <option value="dummy data">Close</option>
              </select>

        </fieldset>

          Date:
            <input type="datetime-local" name="pickup_time" required>

        <fieldset>

            Milestone
              <select name="workflow">
                <option value="dummy data">Open</option>
                <option value="dummy data">Close</option>
              </select>

        </fieldset>

          Date:
            <input type="datetime-local" name="pickup_time" required>

        <fieldset>

            Production
              <select name="workflow">
                <option value="dummy data">Open</option>
                <option value="dummy data">Close</option>
              </select>

        </fieldset>

          Date:
            <input type="datetime-local" name="pickup_time" required>

        <fieldset>

            Cost
              <select name="workflow">
                <option value="dummy data">Open</option>
                <option value="dummy data">Close</option>
              </select>

        </fieldset>

          Date:
            <input type="datetime-local" name="pickup_time" required>

        <fieldset>

            Manpower:
              <select name="workflow">
                <option value="dummy data">Open</option>
                <option value="dummy data">Close</option>
              </select>

        </fieldset>
        <fieldset>

            Date:
              <input type="datetime-local" name="pickup_time" required>

        </fieldset>

<button>Submit Project</button>

<button>Cancel</button>

  </form>

Foundation: The Grid
Bootstrap: Grid system
Once you have the basics of CSS down I'd highly recommend looking into one of these front-end frameworks to help eliminate much of the repetitive style & layout formatting, while helping normalize issues between different browsers and device types.


Q:

Why does knowing the impulse response allow you to determine the output for any LTI system?

Going over some notes on LTI systems and I’m quite confused about how knowing the impulse response of a system allows us to recover the systems’ response to any signal. In the textbook screenshot below, it looks like they just replaced the Dirac deltas with $f$ when defining $y(n)$.

A:

(Adapted from this answer on dsp.SE)
The reason that the impulse response (also called the unit pulse response for discrete-time systems) determines the output for arbitrary input $x$ to an LTI system is that

The output of a linear time-invariant system in response to input $x$ is
  the sum of scaled and time-delayed versions of the
  impulse response.

This is because of the linear property of the system: if the response to input signal $x_i$ is $y_i$, then the response to input $x_1+x_2+ x_3 + \cdots$ is $y_1+y_2 + y_3 + \cdots$.  So, let's decompose the input signal $x$ into a sum of scaled
unit pulse signals. The system response to the unit pulse signal
$\cdots, ~0, ~0, ~1, ~0, ~0, \cdots$ is
the impulse response or pulse response
$$h[0], ~h[1], \cdots, ~h[n], \cdots$$
and so by the scaling property the single input value $x[0]$,
or, if you prefer
$$x[0](\cdots, ~0, ~0, ~1, ~0,~ 0, \cdots)
=  \cdots ~0, ~0, ~x[0], ~0, ~0, \cdots$$
creates a response
$$x[0]h[0], ~~x[0]h[1], \cdots, ~~x[0]h[n], \cdots$$
Similarly, the single input value $x[1]$ or creates
$$x[1](\cdots, ~0, ~0, ~0, ~1,~ 0, \cdots)
=  \cdots ~0, ~0, ~0, ~x[1], ~0, \cdots$$
creates a response
$$0, x[1]h[0], ~~x[1]h[1], \cdots, ~~x[1]h[n-1], x[1]h[n] \cdots$$
Notice the delay in the response to $x[1]$.  We can continue further
in this vein, but it is best to switch to a more tabular form
and show the various outputs aligned properly in time. We have
$$\begin{array}{l|l|l|l|l|l|l|l}
\text{time} \to & 0 &1 &2 & \cdots & n & n+1 & \cdots \\
\hline
x[0] & x[0]h[0] &x[0]h[1] &x[0]h[2] & \cdots &x[0]h[n] & x[0]h[n+1] & \cdots\\
\hline
x[1] & 0 & x[1]h[0] &x[1]h[1] & \cdots &x[1]h[n-1] & x[1]h[n] & \cdots\\
\hline
x[2] & 0 & 0 &x[2]h[0] & \cdots &x[2]h[n-2] & x[2]h[n-1] & \cdots\\
\hline
\vdots & \vdots & \vdots & \vdots & \ddots & \\
\hline
x[m] & 0 &0 & 0 & \cdots & x[m]h[n-m] & x[m]h[n-m+1] & \cdots \\
\hline
\vdots & \vdots & \vdots & \vdots & \ddots
\end{array}$$
The rows in the above array are precisely the scaled and
delayed versions of the impulse response that add up to
the response $y$ to input signal $x$.
So, we see that if we know the impulse response of an LTI system, we can figure out the response of the LTI system to any arbitrary signal $x$. We don't need any additional information about the LTI system beyond the impulse response.


Q:

How to shuffle a dataframe while maintaining the order of a specific column

I have a pandas dataframe which I want to shuffle, but keep the order of 1 column.
So imagine I have the following df:
| i | val | val2| ID |
| 0 | 2   | 2 |a  |
| 1 | 3   | 3 |b  |
| 2 | 4   | 4 |a  |
| 3 | 6   | 5 |b  |
| 4 | 5   | 6 |b  |

I want to shuffle the rows but keep the order of the ID column of the first df. My wanted result would be something like this:
| i | val | val2| ID |
| 2 | 4   | 4 |a  |
| 4 | 5   | 6 |b  |
| 0 | 2   | 2 |a  |
| 3 | 6   | 5 |b  |
| 1 | 3   | 3 |b  |

How do I do this?

A:

Here's a solution:
df = pd.DataFrame({"val": [1, 2, 3, 4, 5, 6, 7], "ID": ["a", "b", "a", "b", "a", "a", "b"]})
df["val"] = df.groupby("ID").transform(lambda x: x.sample(frac=1))
print(df)

The output is:
   val ID
0    5  a
1    7  b
2    1  a
3    2  b
4    3  a
5    6  a
6    4  b

If you have a dataframe with multiple columns, and you'd like to shuffle while maintaining the order of one of the columns, the solution is very similar:
df = pd.DataFrame({"val": [1, 2, 3, 4, 5, 6, 7],
                   "val2": range(10, 17),
                   "ID": ["a", "b", "a", "b", "a", "a", "b"],
                  })

df[["val", "val2"]] = df.groupby("ID").transform(lambda x: x.sample(frac=1))
print(df)

==>

   val  val2 ID
0    3    12  a
1    7    16  b
2    5    14  a
3    2    11  b
4    6    15  a
5    1    10  a
6    4    13  b


Q:

I am trying to understand the line with string declaration

string Possible::str(int width) const {
    string s(width, ' '); // <-- this line
    int k = 0;
    for (int i = 1; i <= 9; i++) {
        if (is_on(i)) s[k++] = '0' + i;
    }
    return s;
}

What does that mean? string s(width, ' ');

A:

It means that the (space) character will be repeated (width) times.
So for example if width is 5, the output of this line will be 5 spaces.
Check this example about using std::string constructors.

A:

Its one of the std::string constructors, for building a string of repeat characters.