text:
Q: How to change Domain database connection of Informatica server after instalation The informatica server is configured on linux based system .
Now the domain database connection got changed. I mean the port number was changed due to some issue.
Now the infa services fails to start up . Please let me know how to change the configuration now.

A: You can use the infasetup.sh command to update connectivity information for domain configuration database.
Switch to the directory <InformaticaInstallationDir>/isp/bin. Then run the below command with database details
infasetup.sh UpdateGatewayNode -da  database_hostname:database_port -du database_user_name -dp database_password -dt oracle -ds database_service_name -dn domain_name
OR
infasetup.sh UpdateGatewayNode -ds "jdbc:informatica:oracle://host_name:port;SID=sid" -du database_user_name -dp database_password -dt oracle -dn domain_name


text:
Q: JSF multi messages support not working I've been using this approach (Persist and pass FacesMessages over multiple page redirects) in my application and it has been working fine.
Recently, the application was heavily changed and now the messages are no longer showing up. I tried to compare the source code, but there are just too many differences.
Looking at the log, it seems that the messages are only being added after MultiPageMessagesSupport finishes processing, and are lost with the redirect:
[#|2017-01-23T09:23:18.321+0000|SEVERE|glassfish 4.1||_TimeMillis=1485163398321;|
  SAVING MESSAGES RESTORE_VIEW 1|#]

[#|2017-01-23T09:23:18.331+0000|SEVERE|glassfish 4.1||_TimeMillis=1485163398331;|
  SAVING MESSAGES RESTORE_VIEW 1|#]

[#|2017-01-23T09:23:18.333+0000|SEVERE|glassfish 4.1||_TimeMillis=1485163398333;|
  SAVING MESSAGES RENDER_RESPONSE 6|#]

[#|2017-01-23T09:23:18.333+0000|SEVERE|glassfish 4.1||_TimeMillis=1485163398333;|
  RESTORING MESSAGES RENDER_RESPONSE 6|#]

[#|2017-01-23T09:23:23.571+0000|INFO|glassfish 4.1||_TimeMillis=1485163403571;|
  [ERROR] ecc_src - Failed to access the WSDL at: http://epms:10130/endpoint?wsdl. It failed with:
                Connection refused: connect.|#]

[#|2017-01-23T09:23:23.571+0000|SEVERE|glassfish 4.1||_TimeMillis=1485163403571;|
  MESSAGES ADDED AT PHASE RENDER_RESPONSE 6|#]

I've tried comparing the usual suspects (faces-config.xml, web.xml, filters), but can't find anything that justifies this change of behavior.
Can someone give me some hints on what should I be looking for?
EDIT #1
Following @Kukeltje suggestion, I've double checked all external components and noticed that Omnifaces' version was different (currently 2.5.1, previously 2.0). Switching back to version 2.0 was enough to make the issue go away.
I'll investigate further and check in which version of Omnifaces this behavior has changed (I'll try versions 2.1, 2.2, 2.3 and 2.4).
EDIT #2
It works fine with Omnifaces' versions 2.1 and 2.2 and stops working from versions 2.3 and on.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to return results from a loop in plpgsql? I want to see the result displaying dates like this
 "2001-01-01 00:00:00+05:30"
 "2001-01-02 00:00:00+05:30"
 "2001-01-03 00:00:00+05:30"
 "2001-01-04 00:00:00+05:30"
 "2001-01-05 00:00:00+05:30"
 "2001-01-06 00:00:00+05:30"
 "2001-01-07 00:00:00+05:30"

so on...
but iam getting error
ERROR:  query has no destination for result data
HINT:  If you want to discard the results of a SELECT, use PERFORM      instead.
CONTEXT:  PL/pgSQL function insert_date_dimension(date) line 12 at SQL statement

can  you tell me what is the issue
function i created
create or replace function insert_date_dimension("Date" date)
returns text as
$$
Declare dat date;
start_date date;
end_date date;
Begin
start_date:='2016/01/01';
end_date:='2016/12/31';
while start_date<=end_date
loop
select start_date;
start_date:=start_date+ interval  '1 day';
End loop;
return start_date;
end;
$$
LANGUAGE 'plpgsql';

can you tell me what is the issue with this function i was not able to execute it.I want to take all the column in select statment..please tell me                                                                                create or replace function insert_date_dimension("date" date)
returns setof date as $$
    declare
        dat date;
        start_date date;
        end_date date;
    begin
        start_date := '2016/01/01';
        end_date := '2016/12/31';
        while start_date <= end_date loop
            --return next  start_date;
            select start_date,date_part('week',start_date),date_part('quarter',start_date),to_char(start_date, 'day'),to_char(start_date, 'month'),
            extract(year from current_date),extract(month from current_date);
            start_date:= start_date + interval  '1 day';
        end loop;
    end;
$$ language plpgsql;
  ERROR:  query has no destination for result data
  HINT:  If you want to discard the results of a SELECT, use PERFORM    instead.
  CONTEXT:  PL/pgSQL function insert_date_dimension(date) line 11 at SQL    statement
  ********** Error **********

A: No need for a user defined function. Just use generate_series:
select generate_series('2016/01/01'::date, '2016/12/31', '1 day');

But if you are just fiddling with plpgsql then return next a setof date
create or replace function insert_date_dimension("date" date)
returns setof date as $$
    declare
        dat date;
        start_date date;
        end_date date;
    begin
        start_date := '2016/01/01';
        end_date := '2016/12/31';
        while start_date <= end_date loop
            return next start_date;
            start_date := start_date + interval  '1 day';
        end loop;
    end;
$$ language plpgsql;

plpgsql is an identifier. Do not quote it.


text:
Q: Couldn't set values in Custom Cell in UITableView from NSMutableArray Help me to get rid of with this dilemma that occurred yet when I tried to dequeued the cell (Custom Cell).Below are some steps and Indents that I did with my Project.
The very first is I drag and drop a UITableView in my ViewController and add the  ViewController.h doing after this
@interface ViewController : UIViewController <UITableViewDataSource,UITableViewDelegate>

Then I made a Custom Cell with 3 UILabels and change the height of the Cell to 65.
After that I made a property in ViewController.m
@property (nonatomic,strong) NSMutableArray *myTodoTitles;

Then in method(ViewDidLoad) I did.
myTodoTitles = [NSMutableArray arrayWithCapacity:10];
[myTodoTitles addObject:@"Go for ride"];
[myTodoTitles addObject:@"Do University Assignments"];
[myTodoTitles addObject:@"Watch Show"];
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:[self.myTodoTitles count]-1 inSection:1];

[self tableView:self.myTodoTable cellForRowAtIndexPath:indexPath];

After that I just did these things in my ViewController.m
#pragma mark - Table view data source

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    NSString *myIdentifier = @"TodoCell";
    TodoCell *todoCell = (TodoCell*)[tableView dequeueReusableCellWithIdentifier:myIdentifier];

    todoCell.todoTitleLabel.text = [self.myTodoTitles objectAtIndex:indexPath.row];

    return todoCell;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return [myTodoTitles count];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

But when I run the project it dequeued nothing.
Please help

A: Most likely that you have not connected your viewController to be the dataSource of your tableView. This could be done from Interface Builder or from the code. You can easily check it by adding self.myTodoTable.dataSource = self; at the very first of viewDidLoad method.
And also: what did you mean by `
[self tableView:self.myTodoTable cellForRowAtIndexPath:indexPath];`

in viewDidLoad ? Seems like you wanted to do
[self.myTodoTable reloadData];

A: There are to UITableView methods with similar name:
- (id)dequeueReusableCellWithIdentifier:(NSString *)identifier

and
- (id)dequeueReusableCellWithIdentifier:(NSString *)identifier
                           forIndexPath:(NSIndexPath *)indexPath

The first one will try to dequeue a reusable cell. If it returns nil you are responsible to create appropriate cell.
The latter one will always return a valid cell: you will have to register a certain class or NIB with that tableview beforehand though. Docs.
EDIT:
As ReDetection pointed out: first method will also return a valid cell as long as you had registered a proper class (or nib) with that tableview.
In your case that means that you should register TodoCell in viewDidLoad with your tableView.
If TodoCell is made without .xib:
[self.tableView registerClass:[ToDoCell class]
       forCellReuseIdentifier:@"TodoCell"];

Or if it is made with .xib.
[self.tableView registerNib:[UINib nibWithNibName:@"TodoCell"
                                           bundle:nil]
     forCellReuseIdentifier:@"TodoCell"];

EDIT2:
Your code also seems to be missing the dataSource setting. Something like:
self.tableView.dataSource = self;

This will trigger initial reload.
You'd probably want to set a delegate (since your controller claims to adopt that protocol) in the same manner.


text:
Q: Data Modeling : Item With Dimensions (One-to-Many) I need suggestions on how to properly model an item record along with all of its corresponding dimensions.
Consider the following:
|  ITEM_ID | ITEM_DESCRIPTION | ITEM_PRICE  | SIZE | LENGTH | COLOR
|   SH01   |   POLO SHIRT     |   22.95     | LARGE|        |
|   PA02   |  KHAKI PANTS     |    9.95     |  38  |   32   |
|   BR22   |   BRACELET       |   10.95     |      |        | GREEN

All of the items have different dimensions that may/may not be used by other items.  Shirts and pants have sizes and lengths.  The bracelet, however, has only a color.
Also, new dimensions may be necessary as new items are added (weight, pattern, etc.).
I've looked at EAV (entity-attribute-value), but from what I understand, reporting would be a nightmare with such a model.
How can I manage the dimensions for each item?  Any and all suggestions would be greatly appreciated.

A: By using the word 'Dimension' you imply you are building a star schema. The physical representation of these 'optional' attributes is mostly dependent on your query tool and desired performance.
IMHO, in dimensional modelling, you should not be afraid of very wide dimensions, particularly if they make querying easier.
If a user runs a query on all product sizes including watches and pants, does it make sense to bucket watches etc. into a N/A size?
EAV is in many ways the opposite of dimensional modelling. dimensional modelling is about making querying as fast and as simple as possible by rearranging data in the ETL process.
Design is often easier if you find a pre proven design approach and stick with it.


text:
Q: SOA sensors are not working in Oracle 12c I created an application containing 4 variables with 4 sensors at variable level and one at activity level.
I deployed and executed the application instance via soa-infra, but I am not able to see any of the sensors for the same.
also there are no errors in logs for both deployment and execution.
I had done similar application in 11g and it was working perfectly.
Any clues?


text:
Q: Determine continuous function from piecewise derivative I'm having trouble solving this issue.

Determine a continuous function $f$ on the interval $[-2,2]$ whose derived function on $[-2,2] \setminus \{0\}$ is known to be the function:
$$
f(x)=
\left\lbrace
\begin{array}{lll}
\dfrac{x^2+4x+7}{2x^3-x^2+18x-9} & \text{ if} -2 \leq x < 0 \\
& \\
x^2 \sin^2 (x) & \text{ if } 0 < x \leq 2
\end{array}
\right.
$$

I tried to calculate the integral of the function in each definition interval, add a constant and impose conditions to determine the constant. I have the problem in the first interval. I can't integrate the function. How do I solve this problem? Thanks!

A: You can use partial fractions. First, factorize the denominator as $$2x^3-x^2+18x-9 = (2x-1)(x^2+9) = (2x-1)(x+3i)(x-3i) $$ Now, set $$\frac{x^2+4x+7}{(2x-1)(x-3i)(x+3i)} = \frac{P}{2x-1} + \frac{Q}{x+3i} +\frac{R}{x-3i} \\ \implies  x^2+4x+7 = P(x^2+9) +Q(2x-1)(x-3i) +R(2x-1)(x+3i)$$
Letting $x=\frac 12, 3i, -3i$ will give you $P=1, Q=\frac i3, R= -\frac i3 $. Hence, the integral is $$\int \frac{dx}{2x-1} +\frac i3 \int \frac{dx}{x+3i} -\frac i3 \int \frac{dx}{x-3i} \\ =\ln|2x-1| +\frac i3 \ln(x+3i) -\frac i3 \ln(x-3i) + C \\ =\ln(1-2x) +\frac i3  \left[ \ln \sqrt{x^2+9} +i(\pi +\tan^{-1} \frac 3x) \right] -\frac i3 \left[ \ln\sqrt{x^2+9} +i(-\pi -\tan^{-1}\frac 3x ) \right] + C \hspace{0.1 cm} (*) \\ = \ln(1-2x)-\frac 23 (\pi+\tan^{-1} \frac 3x ) + C \\ = \ln(1-2x)-\frac 23 \tan^{-1} \frac 3x +C'$$
$ \begin{align} (*) \ln(z) = \ln |z| +i\arg z \end{align}$

A: Thank you very much for your responses.
So in summary, the $f$ function has the form:
$$
f(x)=
\left\lbrace
\begin{array}{ll}
\dfrac{1}{2} \ln | 2x-1 |
+ \dfrac{2}{3} \arctan (x/3) + C & \text{ if } -2 \leq x < 0  \\
& \\
\dfrac{x^3}{6}  - \dfrac{x^2}{4} \sin (2x)
- \dfrac{x}{4} \cos (2x) + \dfrac{1}{8} \sin (2x) + D
 & \text{ if } 0< x \leq 2  \\
\end{array}
\right.
$$
To impose that $f$ be continuous at $x=0$, we impose that the
lateral limits are equal:
$$
f(0^+) = f(0^-) \Rightarrow C=D
$$
So any constants $ C = D $ are solution to the problem ?? That's right ??
Thank you!


text:
Q: XSLT/X-PATH EXPRESSION The Below is my input xml
<ServiceIncident xmlns="http://b2b.ibm.com/schema/IS_B2B_CDM/R2_2">
<RequesterID/>
<ProviderID>INC0011731</ProviderID>
<ProviderPriority>4</ProviderPriority>
<WorkflowStatus>NEW</WorkflowStatus>
<Transaction>
    <Acknowledge>1</Acknowledge>
    <StatusCode>0</StatusCode>
    <Comment>String</Comment>
    <TransactionName>Problem_Submittal</TransactionName>
    <TransactionType>2</TransactionType>
    <TransactionDateTime>2012-10-19T16:05:56Z</TransactionDateTime>
    <TransactionNumber>2012-10-19T16:05:56Z:1ae9b6a79901fc40fa75c64e1cdcc3b4</TransactionNumber>
    <TransactionRouting>MX::ITELLASNINCBRDG</TransactionRouting>
    <DataSource>ServiceNow</DataSource>
    <DataTarget>NASPGR72</DataTarget>
</Transaction>

My problem is only one or two fields i need to map in xslt other than that whatever is in the input i need in output.
Below is the code iam using in the xslt to copy input.
<xsl:template match="node()|@*">
    <xsl:copy>
        <xsl:apply-templates select="node()|@*"/>
    </xsl:copy>
</xsl:template>

After that iam mapping one element which is not same in input and output by using   the following x-path expression but iam not getting output.
<TransactionRouting>
    <xsl:text>Maximo</xsl:text>
</TransactionRouting>

By using the above copy code iam able to copy whole input as output but if iam trying to do map one element in xsl by using x-path expression as shown above which is not same in input and output iam not able to do so please help me on this.

A: Your XML has a default namespace xmlns="http://b2b.ibm.com/schema/IS_B2B_CDM/R2_2"
This means all nodes are under that namespace. You need to include this in your stylesheet in this case xmlns:ibm="http://b2b.ibm.com/schema/IS_B2B_CDM/R2_2". After that you can refer to a node using a prefix ibm:. exclude-result-prefixes="ibm" eliminates the prefix at the output.
The following stylesheet is probably what you need
<xsl:stylesheet version="1.0"
    xmlns:ibm="http://b2b.ibm.com/schema/IS_B2B_CDM/R2_2"
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
    exclude-result-prefixes="ibm">
    <xsl:output method="xml" indent="yes" />

    <xsl:template match="node()|@*">
        <xsl:copy>
            <xsl:apply-templates select="node()|@*"/>
        </xsl:copy>
    </xsl:template>

    <!-- match element TransactionRouting  -->
    <xsl:template match="ibm:TransactionRouting">
        <xsl:copy>
            <xsl:text>Maximo</xsl:text>
        </xsl:copy>
    </xsl:template>

</xsl:stylesheet>

A: Your question is not very clear, but based on my understanding i have tried this
<xsl:stylesheet  version="2.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
   <xsl:output method='xml' indent='yes'/>

   <xsl:template match='/'>
      <xsl:apply-templates/>
      <xsl:element name='TransactionRouting'>Maximo</xsl:element>
   </xsl:template>

   <xsl:template match="node()|@*">
      <xsl:copy>
         <xsl:apply-templates select="node()|@*"/>
      </xsl:copy>
   </xsl:template>

</xsl:stylesheet>

Hope! this would meet ur requirement :)


text:
Q: App isn't installed error when using In-App Promo SDK on Android 13 I followed this tutorial to implement in-app promo SDK, everything works fine but when you update the targetSdkVersion to 33 (Android 13), if you try any shortcut you'll get a Toast message displaying "App isn't installed" and it doesn't open the app.

A: The solution was to add an VIEW action to your Activity in the AndroidManifest.xml and it will open the app without any errors.
<intent-filter>
       <action android:name="android.intent.action.VIEW" />
       <action android:name="android.intent.action.MAIN" />
       <category android:name="android.intent.category.LAUNCHER" />
</intent-filter>


text:
Q: Unable to get access to iframe elements on same domain in Microsoft Edge I tried all solutions available online but unable to achieve the result!
I want to access element inside iframe of my index.html page
index.html
//jquery-3.6.0 cdn
<script src="https://code.jquery.com/jquery-3.6.0.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>

//iframe
<iframe id="myIFrame" src='test/button.html' width="80%" height="600"></iframe>

<script>
    $(document).ready(function () {
        //change button color inside iframe to red when clicked
        $("#iviFrame1").on("load", function () {
            $("#iviFrame1").contents().find("button").on("click", function () {
                $("#iviFrame1").contents().find("button").css("background-color", "red");
            });
        });
    });
</script>

I also tried:
$('#quizIFrame').contents().find('body')

Also tried by replacing load with ready and ready with load.. but not working!!


text:
Q: use jQuery .on() parsing multiple events will cause performance issues? On the case of form validation through jQuery, I've been reading and found out that using a .keyup() handler won't allways work as expected. For instance, this event alone doesn't work on my Android (gingerbread) and doesnt cover the possible paste or autocomplete the user may perform on the input. Instead, using .on('input keyup change', '#selector', function(){}) seems to be the best choice. Will jQuery perforperform the event only once in case more than one of the binded events gets executed?

A: Here is a demo : http://jsfiddle.net/eyxb7973/1/
It will cause performance issues yes, if you try to type something in the field, you will see that input and keyup are fired.


text:
Q: Change SI font in equation Right now I have SI defined so:
\usepackage{siunitx}
\sisetup{
  group-digits=integer,
  group-minimum-digits = 4,
  detect-display-math = true,
  detect-weight,
  detect-mode = true,
  group-separator = {,}
}

My numbers are serif whereas I use Arial, which is a san serif font. Is it possible to make SI generate serif only when in equation mode?
sample equation:
\begin{subequations}
\label{eqn:decanterholdup}
  \begin{align}
    T & = 0.1\frac{\mu}{S_H - S_L} \\
     & = 0.1 \frac{0.856551}{0.999492 - 0.88435} \nonumber\\
     & = \SI{0.7439}{\hour}
  \end{align}
\end{subequations}

text font:
\usepackage{helvet}

MWE:
\documentclass{article}
\usepackage[utf8]{inputenc}
\usepackage{helvet}
\renewcommand{\familydefault}{\sfdefault}

\usepackage{siunitx}
\sisetup{
  group-digits=integer,
  group-minimum-digits = 4,
  detect-display-math = true,
  detect-weight,
  detect-mode = true,
  group-separator = {,}
}
\usepackage{amsmath}

\begin{document}

This is san serif. In the equation it is serif.

\begin{subequations}
\label{eqn:decanterholdup}
  \begin{align}
    T & = 0.1\frac{\mu}{S_H - S_L} \\
     & = 0.1 \frac{0.856551}{0.999492 - 0.88435} \nonumber\\
     & = \SI{0.7439}{\hour}
  \end{align}
\end{subequations}

This text is san serif. \SI{5}{\cm}
\end{document}

The numbers in the math environment are serif fonts but the last line with SI is san serif. How can I make that last line in the math environment serif?


text:
Q: Python: Change condition value of while loop from called module inside loop I want the variable for the condition of my while loop (while repeat is True) to be changed (to repeat = False, thus not meeting the condition of the while loop) via the if statement in the action() module that is being called within the while loop itself.
Comments should explain my intentions throughout.
Note This is a simplified version of the larger code I am actually working. Hopefully I made it simple and clear enough to get my point across without additional confusing code as I have come across in other posts.
# Defining the variables

repeat = True
class monster:
    hp = 5
class fighter:
    damage = 1

# Defining my action module

def action():
   monster.hp -= fighter.damage # Monster's hp decreases by fighter's damage
   print "Monster HP is %s" % monster.hp # Print this result
   if monster.hp < 1: # Check to see if monster is dead, hp less than 1
       repeat = False # If monster is dead, stop repeating
   else:
      repeat = True # If monster is not dead, repeat attack

# Here is the while loop

while repeat is True: # Defining the condition for the while loop
   print "repeat is %r" % repeat # Here it should print repeat is True
  action() # Then call the action module

print "repeat is %r" % repeat # Here it should print repeat is False

A: You have to declare repeat as a global variable to change it from inside action(). Include this line after the def action():
def action():
    global repeat


text:
Q: How to create relative increase drawn in excel? I saw in an excel sheet this formatting:

How to create this?
I appreciate your replies!

A: select your data then Home > Conditional Formatting > Data Bars, possibly > More Rules..., adjust to suit


text:
Q: how to return method which has task return type public override Task<IdentityResult> ValidateAsync(AppUser item)
        {
            if(item.Email != "a@a.com")
            {
                IEnumerable<string> errors = new List<string>() { "error1" };

            }
        }

The IdentityResultjust needs a simple array or ienumerable of strings in its constructor.
Whats the correct syntax?

A: If you absolutely need to have ValidateAsync() instead of just Validate(), use a TaskCompletionSource to simulate.
public override Task<IdentityResult> ValidateAsync(AppUser item)
{
    var result = new IdentityResult();
    var tcs = new TaskCompletionSource<IdentityResult>();

    if(item.Email != "a@a.com")
    {
        IEnumerable<string> errors = new List<string>() { "error1" };
        result.Add(errors)
    }
    tcs.SetResult(result);
    return tcs.Task;
}

Using Task.Run creates unnecessary overhead.
EDIT: I'm not exactly sure if TaskCompletionSource is any better than Task.Run. I'd love to hear the answer.

A: You could use Task.Run() to start and get a reference to a new Task:
public IdentityResult Validate( AppUser item )
{
     IdentityResult result;

     // do stuff

     return result;
}

public override Task<IdentityResult> ValidateAsync( AppUser item )
{
    return Task.Run( () => Validate(item) );
}


text:
Q: Why does web2py display disabled input html when I use the checkbox widget? I am learning web2py but am having some trouble. I have a one-to-many relationship as defined here:
db.define_table('dog',
    Field('name', requires=IS_NOT_EMPTY()))
db.define_table('person',
    Field('name', requires=IS_NOT_EMPTY()),
    Field('dogs', 'list:reference dog'))

db.person.dogs.widget=SQLFORM.widgets.checkboxes.widget

Where a dog has one owner, but an owner can have multiple dogs.
In my controller, I create a form which has a textfield for the person's name, and a list of dogs represented as checkboxes.
The controller code for the form creation is simply:
form = SQLFORM(db.person)   # rendered with {{=form}} in views

This works, but at the end of the list of checkboxes there is an odd text input which is marked as disabled:

<input class="hidden" disabled="disabled" name="dogs" type="text" />

This isn't actually hidden, just greyed out.
I looked at the web2py source, and the checkbox widget is located in web2py.gluon.sqlhtml, but I'm having a hard time interpreting why it's appending this disabled input to the checkbox list.
Can anyone clarify why this disabled input is there or how to properly create this form without this problem?

A: Anthony's comment was correct: I had forgotten to load the css file.


text:
Q: Bootstrap Basics When using random sampling (bootstrap), I get 3500 estimates of R squared. Curious as to what causes the variation between these individual estimates as they've all been pulled from the same dataset. Just trying to expand my understanding, thanks!

A: Welcome to Cross Validated!
While you're drawing from the same dataset, each bootstrap sample is different. Consequently, calculations based on individual bootstrap samples should not be expected to be the same.
Consider an easy dataset of $D=(1, 2, 3)$. Let's bootstrap and calculate the mean, $\bar x$.
$$
D_{boot1}=(1,3,1)\implies \bar x_{boot1}=5/3\\
D_{boot2}=(1,1,2)\implies\bar x_{boot2}=4/3
$$
Et cetera…
EDIT
Let's do an example for $R^2$. Consider a dataset $D$.
$$
D = ((1,2), (2,2), (3, 5), (4, 3))\\
D_{boot1} = ((1,2), (1,2), (3,5), (2, 2)) \implies R^2_{boot1} = 0.758\\
D_{boot2} = ((1,2), (3,5), (3,5), (4,3)) \implies R^2_{boot1} = 0.236
$$
However, in the original $D$, $R^2=0.3$.


text:
Q: Simple inverting op-amp problem I don't know what op-amps have against me, but they don't like me.
Yesterday, I wanted to amplify an AC signal coming from a photodiode using a non-inversing configuration mode. I had a lot of noize, so I wanted to inverse it twice.
My problem is the following: When I measure the voltage across D1, it gives me 230mV. The output of my op-amp is a non-inverted signal with an amplitude of 15mV.
NB: It is not high frequency
,the board, the op-amp, the voltage source, the oscilloscope, the resistors, the wires, everything has been changed; it is not failure related.
Thank you!

simulate this circuit – Schematic created using CircuitLab
Shouldn't the op-amp try to compensate to bring the fake ground to a 0V, so output a negative signal? (at the very least)... I expected a 2V over inverted PWM signal...

A: You can't drive the output outside the power supply rails. If the negative supply is 0V then -2V on the output isn't going to happen. You could disconnect the negative supply from ground, and instead tie the noninverting input to a divider that halves the supply, but then you won't see +-2V swing anyway due to the input common mode range for the LM358 which can't come closer than about 1.5V to the positive supply. Your supply is insufficient for the desired output signal swing.
THanks to @replete for the answer.

A: Do you have the diode the correct way round in the schematic?
The way you have it shown it should produce a negative voltage from the diode and that should be amplified by the opamp.  I have used that particular arrangement successfully.
Is the output of the diode negative or positive?  If it is positive reverse the connections to the diode.
The circuit will not be very sensitive as it will require 100uA of photocurrent to produce 1V at the output.
Also for that particular arrangement R1 is not necessary. The opamp will act as a Transimpedance Amplifier producing 1v per 100uA of photocurrent.  The voltage across the diode will be about zero.  It will actually be the offset voltage of the opamp which is +/-3mV or so depending upon which particular version.
The sensitivity can be improved by increasing R2.  With an LM358 the bias current will cause an error if you use more than about 1megohm.
A better amplifier with lower bias current such as a CMOS version can be more sensitive you need one with a rail-to-rail input capability. (the common mode range of the input includes ground).


text:
Q: Populate ComboBox With Sheet Names Dynamically I am having trouble with populating a combo box on a excel ribbon dynamically.
I wish for the combo box to be populated using the names of the sheets of the workbook dynamically.
I am able to select the sheet names already presentin the combo box that is placed on the ribbon however I do not seam to be able to code the VBA to populate the combo box with the sheet names if I add them or modify the name.
I have written below code but its not working :
Sub SelectionFeuille_GetItemLabel(control As IRibbonControl, index As Integer, ByRef returnedVal)

 Dim dTime As Date

dTime = Now + TimeValue("00:00:01") 'hh:mm:ss
Application.OnTime dTime, "Refresh_all"

returnedVal = ActiveWorkbook.Worksheets(index + 1).Name

End Sub

Please help me....

A: The simplest way I've found to do this is to capture the Calculate event, and I do that by having a hidden worksheet with formulae to each sheet in its cells. It's far from perfect and, if truth be told, is a pretty ugly workaround, but at least it's food for thought for you. I guess a timer would also work but that seems just as ugly.
All of this code goes in the code behind your workbook:
Option Explicit
Private Const NAMES_SHEET As String = "Hidden|Sheet|Names"
Private mNamesSheet As Worksheet
Private Sub Workbook_Open()
    Dim b As Boolean

    b = Application.ScreenUpdating
    On Error Resume Next
    Set mNamesSheet = ThisWorkbook.Worksheets(NAMES_SHEET)
    On Error GoTo 0
    If mNamesSheet Is Nothing Then
        Application.ScreenUpdating = False
        Set mNamesSheet = ThisWorkbook.Worksheets.Add
        mNamesSheet.Name = NAMES_SHEET
        mNamesSheet.Visible = xlSheetVeryHidden
    End If
    WriteNamesOfSheets
    Application.ScreenUpdating = b

End Sub
Private Sub WriteNamesOfSheets()
    Dim v() As Variant
    Dim ws As Worksheet
    Dim i As Integer
    Dim b As Boolean

    b = Application.EnableEvents
    Application.EnableEvents = False
    ReDim v(1 To ThisWorkbook.Worksheets.Count, 1 To 1)
    mNamesSheet.Cells.Clear
    i = 0
    For Each ws In ThisWorkbook.Worksheets
        If ws.Visible = xlSheetVisible Then
            i = i + 1
            v(i, 1) = "=" & ws.Name & "!A1"
        End If
    Next

    mNamesSheet.Range("A1").Resize(UBound(v, 1)).Formula = v
    Application.EnableEvents = b
End Sub
Private Sub Workbook_SheetCalculate(ByVal Sh As Object)
    Dim ws As Worksheet
    Dim b As Boolean

    On Error GoTo EH
    b = Application.EnableEvents
    Application.EnableEvents = False
    WriteNamesOfSheets
    For Each ws In ThisWorkbook.Worksheets
        If ws.Visible = xlSheetVisible Then
            '
            'Populate your combobox here with ws.Name
            '
        End If
    Next

    Application.EnableEvents = b

    Exit Sub

EH:
    Err.Clear
End Sub


text:
Q: Difference between BorderStyle = NotSet and BorderStyle = None There is a common property for every web controls, BorderStyle. It can be set to many values and two of them are NotSeet and None. What is the basic difference in between them?

A: The BorderStyle property is actually rendered out as an entry in the style attribute in the mark-up of the control.
None means no border, and the control will render a specific value to say that. NotSet leaves it up to the control to decide what it should be - which should end up with the control not rendering anything at all, which means it will be up to to any css present on the page to set the border style.
This bit of code:
void WebForm1_PreRender(object sender, EventArgs e)
{
    b = new Button();
    b.ID = "button1";
    b.Width = 100;
    b.Height = 50;
    b.BorderStyle = BorderStyle.NotSet;

    c = new Button();
    c.ID = "button2";
    c.Width = 100;
    c.Height = 50;
    c.BorderStyle = BorderStyle.None;

    div1.Controls.Add(b);
    div1.Controls.Add(c);
}

renders out as this HTML:
<div id="div1">
    <input type="submit" name="button1" value="" id="button1" style="height:50px;width:100px;" />
    <input type="submit" name="button2" value="" id="button2" style="border-style:None;height:50px;width:100px;" />
</div>

Note how Button2 has its BorderStyle explicitly turned off.


text:
Q: autoDocumentation of SQL queries We use SQL queries to do most of analytical work at our company (PostgreSQL). Currently there are 250+ queries stored in fixed directory structure (there is also a lot of DDL/DML files).
Is there any autodoc tool to create documentation of all those queries and produce some output (e.g. html)?
I know there are some tools that can be used for functions/tables/procedures documentation, but none (as far as I understand it) is suitable for queries, e.g.:

*

*HyperSQL

*Doxygen

*NaturalDocs
In documentation, I would like to track the following:

*

*file name

*sql description

*author(s)

*project(s)

*tags

Limitation of fixed directory structure is obvious - there are many times where the query belongs logically to more folders, but you have too choose one. We have tried to use trac wiki, but it is to complicated (you have to copy/paste every version of your query to wiki). On the other hand you can use tags, it is easily searchable and you have versioning. I've also tried using some query tools with advanced built-in search (e.g. toad plugin for eclipse), but you have to write pretty complex regexs to get files your are interested in.
This is why I believe that autodoc approach is the only possible way for this task.

A: I don't think such a tool is readily possible for a general use case so your best option is to settle on convention is to write your own.  The big thing is that many documentation generators for SQL will try to track dependencies etc.  You can do this with tables relatively easily (dynamically discovering foreign keys for example) and in some cases you can do this with functions, but beyond this it becomes really difficult.  Note I use postgresql_autodoc for db objects.  Being able to track to tables is problematic (what if the query is run with a different search_path?  There are many things you can't know...).
If it were me, I would look at modifying doxygen to track the information you want.  It's further possible to do this only if you have one sql statement per file.  For example, it is one thing to document files but very different to document queries.
I would however suggest adopting a discoverable stored procedure interface and putting the comments in SQL COMMENT ON statements.  This is what we do and it makes autodocumentation much easier.  Then you can use postgresql_autodoc if you want or other tools.

A: the only 1 I know of is a MS SQL based one: http://www.apexsql.com/sql_tools_doc.aspx


text:
Q: How do I stop my loop from running after getting correct result from my code? my code gives me the correct result, but will not stop looping. Newbie question. Any help is greatly appreciated
#Gets user integer input
while True:

value = int(input(" Please print a positive integer:"))
num = value + 1

# re-prompts user for valid entry
if value <= 0:
continue

#calculates all numbers divisible by user enter
if value > 0:
print('The factors of', value, 'are:')

for i in range(1, num):
factors = value % i
if factors == 0:
print(i)

A: If you only want to loop until the user gives a positive number then you only need to put that part of the code in a loop and exit the loop when a positive number is entered.
value = -1
while value < 1 :
    value = int(input(" Please print a positive integer:"))

num = value + 1

#calculates all numbers divisible by user enter
if value > 0:
    print('The factors of', value, 'are:')

for i in range(1, num):
    factors = value % i
    if factors == 0:
        print(i, end = ' ')


text:
Q: Where should I save an API key of my user when installing my plugin? I'm creating a plugin that will require the user to set an API key in order to communicate with my API. My question is: where should I save it?
Logically, I would think that it should be saved in the database, and that's what I started doing it. I came up with the following code that creates a table and where I can store the api_key:
<?php

/**
 * Fired during plugin activation.
 */
class Plugin_Activator {
    public static function activate() {
        global $wpdb;

        $table_name = $wpdb->prefix . 'my-plugin-name'
        $charset_collate = $wpdb->get_charset_collate();

        $sql = "CREATE TABLE $table_name (
                        id int(11) NOT NULL auto_increment,
                        api_key varchar(23) NOT NULL
                ) $charset_collate;";

        require_once( ABSPATH . 'wp-admin/includes/upgrade.php' );
        dbDelta( $sql );
        add_option( 'test_db_version', $test_db_version );
    }
}

BUT it feels wrong to have a table to only store this so I'm wondering if there is another way of doing it that I don't know.

A: Using the Settings API to display the field and the Options API to store the value would be a good way to go.
Your hunch is correct -- creating a custom table to store an API key is not the way to go.
Edit
Here's a complete example (copied from this oldie but goodie https://wpengineer.com/2139/adding-settings-to-an-existing-page-using-the-settings-api/) that adds a custom setting to the Options - General page:
// Register and define the settings
add_action('admin_init', 'ozhwpe_admin_init');
function ozhwpe_admin_init(){
    register_setting(
        'general',                 // settings page
        'ozhwpe_options',          // option name
        'ozhwpe_validate_options'  // validation callback
    );

    add_settings_field(
        'ozhwpe_notify_boss',      // id
        'Boss Email',              // setting title
        'ozhwpe_setting_input',    // display callback
        'general',                 // settings page
        'default'                  // settings section
    );

}

// Display and fill the form field
function ozhwpe_setting_input() {
    // get option 'boss_email' value from the database
    $options = get_option( 'ozhwpe_options' );
    $value = $options['boss_email'];

    // echo the field
    ?>
<input id='boss_email' name='ozhwpe_options[boss_email]'
 type='text' value='<?php echo esc_attr( $value ); ?>' /> Boss wants to get a mail when a post is published
    <?php
}

// Validate user input
function ozhwpe_validate_options( $input ) {
    $valid = array();
    $valid['boss_email'] = sanitize_email( $input['boss_email'] );

    // Something dirty entered? Warn user.
    if( $valid['boss_email'] != $input['boss_email'] ) {
        add_settings_error(
            'ozhwpe_boss_email',           // setting title
            'ozhwpe_texterror',            // error ID
            'Invalid email, please fix',   // error message
            'error'                        // type of message
        );
    }

    return $valid;
}

I changed the code so that the option appears on the General Options page. It won't be too difficult to modify this code to use your API key field.


text:
Q: How do I change the bitrate field of an mp3 file? I have some music files which have somehow the wrong bitrate settings (32 instead of 320). Yes they are really 320bps, the file size and show exactly that. So this means no Apple Music availability. I tried changing the values in the iTunes XML file, but that did nothing, as kind-of expected. Other programs also show the wrong bitrate or none at all. Searching for 32 in a Hex-Editor of that file was useless as well.

A: Sorry but if the file has been encoded at the wrong bitrate, then they'll need to be re-encoded i.e. you'll need to rip them from a CD again. The bitrate refers to the amount of data that is used to store a second of audio. There is no way to increase this, in any meaningful way, once it's been created.
However if the file are encoded with Variable Bit Rate (VBR) encoding there does seem to be a common problem where the bitrate is misreported. If I'm reading things correctly it's because software like iTunes just looks at the bitrate of the first chunk of the file (which might just be silence or something simply resulting in a low bitrate encoding) and report that as the bitrate even though subsequent chunks might have completely different (higher) rates. There does appear to be a tool to fix this called vbrfix. However there doesn't seem to be an easy to get this tool for Macs.
If you are relatively confident with using the Terminal you could try the following:

*

*Download http://http.debian.net/debian/pool/main/v/vbrfix/vbrfix_0.24+dfsg.orig.tar.xz

*Decompress the file with something like The Unarchiver (macOS native Årchive Utility won't know what to make of it)

*Open a Terminal window and cd to the path of the unarchived files

*Run ./configure and then make to compile the vbrfixc binary

*Assuming the binary compiles successfully cd into the "vbrfixc" folder and you should find the vbrfixc binary.

*Run it with ./vbrfixc -log input.mp3 output.mp3.

If the file is a VBR MP3 file this will attempt to fix it by placing a blank chunk at the beginning of the file with a bitrate that is more representative of the entire file.


text:
Q: Trying to create a list that counts the number primes for each remainder class Considier the remainder of the first $2500$ prime numbers by the numbers from $3$ to $30$, included.

*

*Calculate how many primes are in each remainder class. That is, create a list that for each number between $3$ and $30$, gives for each remainder class the number of primes in it.
Example. the first $5$ primes are: $2,3,5,7,11$. If we consider the remainders by $3$, we have: $2,0,2,1,2$.
That is: $1$ with remainder $0$; $1$ with remainder $1$ and $3$ with remainder $2$.

I am having trouble condensing my program because I need to create a list for each number between 3 to 30. How could I add the remainders $3$ to $30$ to my program before it counts how many primes are in each remainder class.
I shortened just to see what is happening (ie. I shortened $2500$ to $5$)
list = Sort[Flatten[Table[n, {n, 1, 5}]]];
PrimeQ[list];
primelist =
Length[Select[list, PrimeQ]] ;
divide = Mod[Total /@ list, 3];
remainder2 = Count[divide, 2]
remainder1 = Count[divide, 1]
remainder0 = Count[divide, 0]

results were:
    {2, 3, 5, 7, 11}
    {True, True, True, True, True}
    3
    1
    1

A: n = 2500;
m = 21;
primes = Prime[Range @ 2500];

Counts[Mod[primes, #]] & /@ Range[3, m] // Column

If you wish you can reorganize the information above into a Dataset:
KeyMap[ToString] /@ KeySort /@ KeyUnion[Counts[Mod[primes, #]] & /@ Range[3, m]] //
  MapIndexed[Join[Association["m" -> ToString[#2[[1]] + 2]],
     Association["remainderClass" -> #]] &] // Dataset


text:
Q: change registered users 1=123 //connect to the server
mysql_connect("mysql", "root", "") or die ("cannot connect to mysql");
mysql_select_db ("db") or die ("Can not Connet to the database ");
$sql = mysql_query("SELECT * FROM users")or die(mysql_error());
$nrows = mysql_num_rows($sql);
echo $nrows;

the php code shows registered users.
now i have 2 registered users and it show 2 i need to change like this 1 registered user =123 for example if i have 2 registered users it must show 246 on website how can i do like this

A: Just multiply your result.
echo $nrows * 123;


text:
Q: Javascript forEach() skips items I am new to javascript. Simply i want to remove all objects with completed: true.
But my function doesn't do that. What am i missing ?
const todo = [{
    title: 'do this',
    completed: true
},{
    title: 'do this',
    completed: true
},{
    title: 'do this',
    completed: true
},{
    title: 'do this',
    completed: true
}]

const remove = function(todo){
    todo.forEach(function(item,index){

        if(item.completed){
            todo.splice(index,1)
        }
    })

}

remove(todo)
console.log(todo)

A: You could use Array.prototype.filter instead:
const undone = todo.filter((item) => !item.completed)
const completed = todo.filter((item) => item.completed)


text:
Q: Is it possible to encapsulate P5 into a global variable like JQuery does with $ I was wondering if it's possible to remove the entire P5(or whatever other frame work/lib) from the global variable
and put it inside one single global variable without actually edit the P5.JS project it's self.
Just like JQuery does with the $ symbol. So you can actually declare variables named point, or mouseX that are P5 variable and will conflict with your variable.
So for example
window.P5 = (some way to get the all instance form the P5);
let point = {myPont:..., props....};
let canvasPoint = P5.point(...);

A: Sure. Use instance mode.
var s = function( sketch ) {

  var x = 100;
  var y = 100;

  sketch.setup = function() {
    sketch.createCanvas(200, 200);
  };

  sketch.draw = function() {
    sketch.background(0);
    sketch.fill(255);
    sketch.rect(x,y,50,50);
  };
};

var myp5 = new p5(s);


text:
Q: Solution design for ASP.NET MVC and Entity Framework database first I've inherited an ASP.NET (4.6.1) MVC solution that uses Entity Framework (database first) as its data access. All of the dbcontext calls and all of the business logic is in the controller methods. There are no domain models.... only view models and the generated entity models from EF.
So the solution structure is basically:

*

*Web (MVC web proj) → DAL (EF6...class lib proj)

*DAL contains

*

*An .edmx

*dbContext - auto generated

*Entity models  - auto generated

*Partial classes for the entity models

*Partial dbcontext (contains some custom logic)

*MVC

*

*Controller

*Private dbcontext at class level

*Some simple to complex CRUD dbcontext calls in each method

*Models

*Only view models (some with dbcontext calls...oy)

*Views

*

*Some views use VMs as their model while others use EF entity models

At the very least, I want to isolate my DAL from my presentation layer and clean up my controllers. I'm not trying to create the perfect app... but I want to make incremental improvements. So my goal this round is to create a logical structure.
So I'm adding another project in between Web and DAL (called Service or whatever) and I'm moving all of the dbcontext calls/logic into that layer. I'm adding another project (called Core) to hold some DTOs, custom exceptions, and other goodies.
So this is my current solution:

*

*Web (MVC web proj with Autofac)

*

*Some service manager classes (injected into controllers)

*This is where I get my DTOs and convert them into view models or convert view models into DTOs to send to the Service layer

*Core (not to be confused with .NET Core)

*

*Referenced by all

*Entity models (moved from DAL)

*Partial classes for the entity models (moved from DAL)

*DTOs, exceptions, etc...

*Service

*

*Referenced by Web

*Some service classes (injected into Web service managers) that will hold all of the complex CRUD dbcontext calls previously in controller methods (ex: var result = dbcontext.SomeTable where some id = n...blah blah)

*I'll also inject the DAL dbcontext into these classes (which then requires a reference to Entity Framework)

*DAL

*

*Referenced by Service

*An .edmx

*Dbcontext

*Partial dbcontext (contains some custom logic)

So I'm keeping the auto generated dbcontext in the DAL, moving the generated entity objects to Core so Service can see them.
My questions:

*

*Does it make sense to move all of the dbcontext calls/logic out of the controllers and into the Service? Some of the logic is simple but there are several controller methods that have complex business logic in them as well. I'm just not sure where to put this logic/calls to dbcontext.

*Does the overall solution design seem OK or am I making it to complex? It's a medium size app but it has potential to grow and I want to set myself up for future development.
Thanks for reading...any input is appreciated!


text:
Q: Can I manipulate a function (with a parameter) to show it converges to another function? Please bear with me. So, for example the limit for $a$ in this hyperbola:
$$\lim_{a \to 0^+} (y^2 -x^2 = a) \, ,\,\,\, \, y \ge 0 \tag{A}$$
This appears to make the equation go to:
$$y^2 = x^2 \, ,\,\,\, \, y \ge 0 \tag{B}$$
$$y = |x| \tag{C}$$
So, is $(A)$ a valid mathematical definition of the absolute value? And furthermore, is $(A)$ differentiable? Because if it was, that immediately means that it's differentiable as $a$ is aribitrarily close to $0$ which is the same thing as $(C)$, but we know $(C)$ is not differentiable at $0$.
In short, I'm wondering if (and maybe the above is a bad example) we can show, via a parameter, that one function converges to another in this type of limiting process and, if so, why would it lose it's differentiability (if that even makes sense)?
 Here's a Desmos link link to the action I'm talking about.

A: What you've stumbled upon is a property of something called uniform convergence. Uniform convergence is a way to talk about how a sequence of functions approaches a limiting function.
A sequence of functions $f_n(x) \xrightarrow[unif]{} f(x) $ if for each $\epsilon > 0$ and $x \in I$ there exists N such that $n > N$ implies $| f_n(x) - f(x) | < \epsilon$
What this means intuitively is that our sequence of functions converges to the limiting function at a worst case rate. So for all points in the interval, the error, $| f_n(x) - f(x) |$ can be made as small as we want.
Lets prove that your sequence converges uniformly: Let $f_n(x) = \sqrt{x^2 + \frac{1}{n}}$ and let $f(x) = |x|$. If we let $n \to \infty$, then this is identical to your question, except we only take the upper branch of the hyperbola.
Let $\epsilon > 0$ be given. Let $x \in I$, where $I$ is some bounded interval.
Now, choose $N = \frac{1}{\epsilon^2}$ Then $n>N$ implies
$$\left|\sqrt{x^2+\frac{1}{n}}-|x|\right|=\sqrt{x^2+\frac{1}{n}}-|x|$$
Since $x^2$ and $\frac{1}{n}$ are both positive$$\sqrt{x^2+\frac{1}{n}}-|x|\leq \sqrt{x^2}+\sqrt{\frac{1}{n}}-|x|$$
But $\sqrt{x^2}=|x|$ so we have $$\sqrt{\frac{1}{n}} \leq \sqrt{\frac{1}{N}}=\epsilon$$
So the sequence converges uniformly for ANY bounded interval.
What does all this mean? It means that you are exactly right. The upper branch of that hyperbola does approach $|x|$. Uniform convergence, then, must not conserve differentiability. It does however conserve continuity and integrability.


text:
Q: Show array data in Table rows in ReactJS How can I output that productName inside that return? The items are from the selected cart items. The const order (function) does show in the console, but I can't get it to show inside the return of render.
const mapState = ({ user }) => ({
  currentUser: user.currentUser,
});

const mapCartItems = createStructuredSelector({
  items: selectCartItems,
});

const CheckingOut = (product) => {
  const { total, cartCount, items } = useSelector(mapCartItems);
    const order = {
    orderItems: items.map((item) => {
      const { productName, qty} = item;
      return {
        productName,
      };
      console.log(item.productName); // this one is showing in the console
    }),
  };

  return (

      <Container fixed>

              Name : 	 // like show the items here

                <PaymentIcon
                  style={{ marginRight: "1rem", color: " #e31837" }}
                />
                Total Price:

              ₱{total}.00

        //just other codes for submit
      </Container>

  );
};

export default CheckingOut;

A: const order = (product) => {
  const order = {
    orderItems: items.map((item) => {
      const { productName, qty} = item;
      return {
        productName,
      };
    }),
  };

  order.orderItems.forEach((item) => console.log(item.productName)) // will log all productName
return order.orderItems
}

Function order will return order.orderItems which has array of objects. For example:
order :{
  orderItems: [
    {
      productName: 'car',
    },
    {
      productName: 'bike',
    }
  ]
}

To access each of product name you have to iterate throught Array nested in order.orderItems
order(product).forEach((item) => {
  console.log(item.productName) // car, bike
});

A: Assuming items is an array similar to:
[
  { ID: 1, productName: 'p1', qty: 10 },
  { ID: 2, productName: 'p2', qty: 15 },
]

You can show productName and qty of each item in this array in
 and  of a table as:
{items.map((item) => (

        Name: {item.productName}
        {item.qty}

))}

This will work even when items is empty array i.e. []. In case, it is null or undefined, you may do optional chaining.
It will show something like this in the table at UI:

Name: p1
10

Name: p2
15

PS: Above solution doesn't really require a separate function order as shown in your question.

A: You can map over arrays and return each element of the array inside a jsx element. If you had an array:
const arr = [1,2,3,4,5]

You could map over them and return them as:
arr?.map(num => (
 {num}
))

Likewise, you can do:
return(
  order?.orderItems?.map(item => (

{item.productName}

  ))
)

A: EDITED
// WHITHOUT STATE
const order = (product) => {
  const order = {
    orderItems: items.map((item) => {
      const { productName, qty} = item;
      return {
        productName,
      };
    })
  };
  return order; // Add this line to return your order object
};

// WITH STATE
const [myOrders, setMyOrders] = useState({});
const order = (product) => {
  setMyOrders({
    orderItems: items.map((item) => {
      const { productName, qty} = item;
      return {
        productName,
      };
    })
  });
  return //some layout;
};

Then in the return you can access like this:
// WITHOUT STATE
return order().orderItems.map(item =>
  whatever you want to do with item.productName...
);

// WITH STATE
return myOrders.orderItems.map(item =>
  whatever code you want to add...
);


text:
Q: Trigonometry proof Question:
$$2\cos x -\cos 3x - \cos 5x = 16\cos^3 x\sin^2 x$$
What I have tried:
Using the identities, I have converted all the cos and sin so that the angle inside is only $x$. However, I couldn't proceed by simplifying and the equation got too complicated. I must be missing something, which would make the question surprisingly easy...
Please point me in the right direction!

A: Using the trigonometric sum and difference angle identities we have (the last expression involves factorising out the common factor $2\cos x$)
$$2\cos x -\cos 3x - \cos 5x = 2\cos x - (\cos 3x + \cos 5x )\\=2\cos x - 2\cos x\cos 4x=2\cos x(1-\cos 4x)$$
This is because (have a look at the "angle sum and difference identities" in here) we have
$$\cos 5x = \cos (4x+x)=\color{green}{\cos 4x\cos x} - \sin 4x \sin x$$
$$\cos 3x = \cos (4x-x)=\color{green}{\cos 4x\cos x} + \sin 4x \sin x$$
Adding the above two equations leads to the cancellation of the sine terms, resulting in
$$\cos 5x + \cos 3x=\color{green}{2\cos 4x\cos x}$$
Applying the double angle formula for $\cos 4x$ then $\sin 2x$ as below, results in
$$2\cos x(1-\color{blue}{\cos 4x})=2\cos x(1-\color{blue}{(1-2\sin^22x)})=4\cos x\color{red}{\sin^22x}\\=4\cos x\color{red}{(2\sin x\cos x)^2}=16\cos^3x\sin^2x$$

A: Since $\cos 3x = 4\cos^3x - 3\cos x$ and $\cos 5x = 5\cos x - 20\cos^3 x + 16\cos^5 x$, substituting those on the left-hand side and simplifying gives
$$16\cos^3 x - 16\cos^5 x = 16\cos^3x(1-\cos^2 x) = 16\cos^3x\sin^2 x.$$

A: Use Euler's formula to get
$e^{ix}+e^{-ix} - {1 \over 2} (e^{i3x}+e^{-i3x} ) - {1 \over 2} (e^{i5x}+e^{-i5x} ) $ on the left hand side.
On the right hand side we have (using $\sin^2 x = 1-\cos^2 x$ to simplify):
$  (e^{ix}+e^{-ix})^3 (2-{1 \over 2}(e^{ix}+e^{-ix})^2) =
(e^{i3x}+ 3e^{ix} + 3 e^{-ix} + e^{-i3x} ) (1  -{1\over 2} e^{i2x} -{1\over 2} e^{-2x}) $.
Carrying out the tedious multiplication shows that they are the same.

A: For Details check all the trignometric identities here
$2\cos  x-\left(\cos  3x+\cos  5x\right)$
$\implies 2\cos  x-\left(2\cos  x.\cos  4x\right)$
$\implies 2\cos  x\left(1-\cos  4x\right)$
$\implies 2\cos  x(1-\left(1-2\sin ^2 2x\right)$
$\implies 4\cos  x\left(\sin ^2 2x\right)$
$\implies 4\cos  x\left(\left(2\sin  x\cos  x\right)^2\right)$
$\implies 16\cos ^3 x\sin ^2 x$

A: $$I=2\cos x-\cos3x-\cos5x=(\cos x-\cos3x)+(\cos x-\cos5x)$$
Using Prosthaphaeresis Formula, $\displaystyle\cos C-\cos D$,
$$I=2\sin x\sin2x+2\sin2x\sin3x=2\sin2x(\sin x+\sin3x)$$
and using $\displaystyle\sin C+\sin D$ formula, $$\sin x+\sin3x=2\sin2x\cos x$$
Finally use $\displaystyle\sin2x=2\sin x\cos x$


text:
Q: Refresh selection model of p:datatable on row deselection I have a problem with the selection model of a Primefaces 5.0 datatable. This selection model does not process deselection properly:
Selection of rows adds these roles as expected to the list of selected rows. But a deselection has no influence on this list; deselected rows remains in it. Only deselecting all rows produces an empty list.
The following gives the definition of the datatable (reduced to relevant tags) - the data model is of type org.primefaces.model.LazyDataModel:
<p:dataTable id="cases"
    widgetVar="cases"
    var="cases"
    value="#{casesController.dataModel}"
    selection="#{casesController.selectedCases}"
    selectionMode="multiple"
    />

There is a Javascript function used in that project which processes clicks on rows to select and deselect the rows.
onRowClick : function(event, rowElement, silent) {
    // Check if rowclick triggered this event not a clickable
    // element in row content
    if ($(event.target).is('td,span:not(.ui-c)')) {
        var row = $(rowElement),
            selected = row.hasClass('ui-state-highlight'),
            metaKey = event.metaKey || event.ctrlKey,
            shiftKey = event.shiftKey;
            mouseBtn = event.which;

        // unselect if already selected on leftClick/touch to enable
        // contextMenu to be shown on rightclick
        if (selected && mouseBtn == 1) {
            this.originRowIndex = row.index();
            this.cursorIndex = null;
            this.unselectRow(row, silent);
        } else {
            // unselect previous selection if this is single
            // selection or multiple one with no keys
            if (this.isSingleSelection()
                    || (this.isMultipleSelection() && event
                            && !metaKey && !shiftKey && this.cfg.rowSelectMode === 'new')) {
                this.unselectAllRows();
            }

            // range selection with shift key
            if (this.isMultipleSelection() && event && event.shiftKey) {
                this.selectRowsInRange(row);
            }
            // select current row
            else {
                this.originRowIndex = row.index();
                this.cursorIndex = null;
                this.selectRow(row, silent);
            }
        }
        PrimeFaces.clearSelection();
    }
}

Debugging this script shows that the branches are passed as expected. But it seems to me, that unSelectRow() is not the opposite of selectRow().
Adding a comment around the javascript function to use the original Primefaces function has no effect on my problem.

A: I finally found the solution. They had extended PrimeFaces implemenation and incompletely implemented some methods. The following thread helped me in solving the problem: p:dataTable selections are lost after paginating a LazyDataModel


text:
Q: In C++ can I create a Binary Search Tree using objects/structs as the node? In other related c++ work I managed to create a sort of binary search tree template. The implication here is that using this template, I can create a BST for all sorts of data types... Int, string, so on. I've been asked to use a BST as a data structure. Let's imagine it's weather data. A measuring device records the temperature several times daily so I have a date and a time as well as the temperature. Each record I want to use a struct as a container, so I want something like this:
struct Record
{
string DateTime;
float temperature;
};

DateTime is a string here because it has a format like dd/mm/yyyy xx:xx. I could convert that into an int perhaps.
With thousands of records, I want to insert them all into my BST. This isn't going to work, my BST template has no idea how to compare 2 Records to say which one will go into the left link and right link. Can I just write a bool operator > function that will take 2 Records, compare the datetimes of both, then say whether a Record made later is 'greater than' a Record made earlier, thus it goes into the tree here and so on? Will this work in general?
Should I do something like create a map with an int called DateTime paired with a record, then insert all the integer values representing the DateTimes into my BST. Then when I need to get back my data, first I search the BST to check whether there is an entry, then use that result against my map, which is then supposed to give me the object I want.
The reason why I need to do all this is because I would like to perform calculations such as, 'give me the average temperature for each month in the year of 2018'. Then I would search my BST to give me back all my DateTimes for each month of 2018, then access my Records through the map to tally up the temperatures and average them.
Please feel free to point me in the right directions. I found that googling how to create BSTs of objects and structs gave me implementations of BST using integer nodes, which is not enough...?

A:
DateTime is a string here because it has a format like dd/mm/yyyy xx:xx. I could convert that into an int perhaps.

You could.

Can I just write a bool operator > function that will take 2 Records, compare the datetimes of both, then say whether a Record made later is 'greater than' a Record made earlier, thus it goes into the tree here and so on? Will this work in general?

Yes it will.

Should I do something like create a map with an int called DateTime paired with a record

That is one possibility, although it should not be a separate data structure. One node in your BST would be keyed by the int and have as payload the associated Record (so a struct with an int and a Record). Alternatively, you could pair the int with just the temperature (again as a struct) if space efficiency is a concern. Then define a function that can convert an int back to a date string.
Another alternative is that you change the DateTime string format to ISO 8601 format: yyyy-mm-ddThh:mm:ss, and do this at the source of your data, so no back-and-forth conversion is needed.
This has two advantages:

*

*It is a good standard, supported by many services/libraries/APIs

*The lexical order is the order you would expect for date/time. This means you no longer need the conversion to int, but can use the records as nodes in your BST and just compare dates with string comparison.

A: As trincot pointed out, there are quite a number of ways to use a binary search tree with structures. I kept in mind that I should NOT use a separate structure to store my records, as they rightly pointed out that using my BST template it should generally be declared as BST< Record > rather than BST< int >.
In my earlier example I used a struct to store Record data. I decided to use a class instead. In my new Record class I added operator functions so that my BST template knew what to do when comparing 2 objects.
Imagine that my new Record class looks something like this:
class Record
{
    public:
        /*
        member variables
        */
        void printValues();
        bool operator>(const Record& otherRecord) const;
        bool operator==(const Record& otherRecord) const;
};

ostream & operator<<(ostream &out, const Record &REC);
//implementation below
bool Record::operator>(const Record& otherRecord) const
{
    return (date > otherRecord.date);
}

bool Record::operator==(const Record& otherRecord) const
{
    return (date == otherRecord.date);
}

As you can see I overloaded the > and == operators. For example in my template, functions that use these operators look like this (this is just 1 of the functions for illustration):
template<class T>
void BSTTemplate<T>::insert(const T& insertItem)
{
    Node<T>* current;
    Node<T>* trailCurrent;
    Node<T>* newNode;

    newNode = new Node<T>;
    newNode->info = insertItem;
    newNode->leftLink = nullptr;
    newNode->rightLink = nullptr;

    if (root == nullptr)
        root = newNode;
    else
    {
        current = root;
        while (current != nullptr)
        {
            trailCurrent = current;
            if(current->info == insertItem)
            {
                cout << "Item is already in tree. Duplicates not allowed." << endl;
                return;
            }
            else if(current->info > insertItem)
                current = current->leftLink;
            else
                current = current->rightLink;

        }
        if (trailCurrent->info > insertItem)
            trailCurrent->leftLink = newNode;
        else
            trailCurrent->rightLink = newNode;
    }
}// end insert()

Without the overloaded operators, statements like
if(current->info == insertItem)

and
else if(current->info > insertItem)

would not work for the objects that I wish to create and use.
I was advised by other users that I should type out an answer that helped me solve my problem, so there you go! Hope that helps someone else...


text:
Q: java system.out.println when printing a byte I have a question about this code:
    String st = "AaHello";
    byte[] bt = st.getBytes("UTF-8");
    for (int i = 0; i < bt.length; i++){
        System.out.println(bt[i]);
    }

I don't quite understand why I got the following output:
65
97
72
101
108
108
111
I think 65 is the ASCII CODE for A, 97 is the ASCII CODE for a, 72 is the ASCII CODE for H... so it seems that it is printing out ASCII code.
But shouldn't it print the byte in the UTF-8 encoding format? (hexa decimal or binary)
for example shouldn't
A be printed out as 41? and then a be printed out as 61? ....
Why is it that it is not printout out the UTF-8 bytes code?
On the other hand, from the example on the JAVA oracle tutorial site, the corresponding UTF-8 actually got printed out https://docs.oracle.com/javase/tutorial/i18n/text/string.html for example here in the example:
utf8Bytes[0] = 0x41
I am just wondering is my code and the code in the example doing the same thing? (I used getBytes() method too just like in the example there, why is it that I am not printing out the byte code it seems, but the example in the java oracle site is printing out the byte code correctly)?

A: 65 decimal == 41 hexadecimal
As comments indicate, your output when printing a byte value is a number in base 10, decimal. That means 65 for the byte value for A, as the US-ASCII number assigned to that letter is sixty-five. (The Unicode code point is also 65, with Unicode being a superset of US-ASCII.)
The 0x41 seen in the Oracle Tutorial was text generated by the UnicodeFormatter class, using hexadecimal digits (base 16) rather than decimal (base 10). Look for the call UnicodeFormatter.byteToHex(array[k]) in that example code on tutorial page. That class was written for the tutorial, and is not bundled with a JDK. See source code.
If you want your code to print 0x41 for a byte with a decimal value of 65, either use that tutorial's class source code if you can abide its license terms or write your own such class from scratch. Or find a solution on the Stack Overflow page, Java code To convert byte to Hexadecimal such as calling Integer.toHexString.


text:
Q: How do I change color of app title bar in recents apps menu? Please, look at the provided screenshot. How do I change the color of this bar? I don't know how to name it. Let's call it "color of app title bar".

A: If you want to change this color for whole application, you need to change ThemeData as follow:
MaterialApp(
  theme: ThemeData(
    // changing theme color
    colorScheme: ColorScheme.fromSwatch(
      primarySwatch: Colors.blue,
    ).copyWith(
      secondary: Colors.green,
    ),
    // for changing text color and style
    textTheme: TextTheme(
      bodyText1: TextStyle(),
      bodyText2: TextStyle(),
    ).apply(
      bodyColor: Colors.orange,
      displayColor: Colors.blue,
    ),
  ),
)

but if you need to only change the appBar color on one single page, use this:
appBar: AppBar(
   backgroundColor: Colors.red //or whatever you want

A: Just add backgroundColor in AppBar :
AppBar(
    backgroundColor: add color,
),

A: I found the solution! It's the "color" property of MaterialApp widget. Thank you all for your participation! :) Also, the name of this thing is "app bar in apps switcher" (or apps recents).
Here the result:
MaterialApp(
  title: 'Аквамарин',
  theme: theme,
  color: Colors.white // this one
)


text:
Q: Does a exception with just a raise have any use? For example, here is some code from django.templates.loader.app_directories.py.[1]
try:
    yield safe_join(template_dir, template_name)
except UnicodeDecodeError:
    # The template dir name was a bytestring that wasn't valid UTF-8.
    raise

If you catch an exception just to re raise it, what purpose does it serve?
[1] http://code.djangoproject.com/browser/django/trunk/django/template/loaders/app_directories.py

A: None at all, that I can think of, except if you're debugging that source code and set a breakpoint on the raise statement.

A: Strictly speaking, it's unneeded.
Some possibilities:

*

*For documentation purposes - just to make it explicit which exceptions are expected

*As a placeholder for a future (or past) more serious handling before re-raising

A: In the code you linked to is another additional exception handler:
try:
    yield safe_join(template_dir, template_name)
except UnicodeDecodeError:
    # The template dir name was a bytestring that wasn't valid UTF-8.
    raise
except ValueError:
    # The joined path was located outside of template_dir.
    pass

Since UnicodeDecodeError is a subclass of ValueError, the second exception handler would cause any UnicodeDecodeError to be ignored. It looks like this would not be the intended effect and to avoid it the UnicodeDecodeError is processed explicitly by the first handler. So with both handlers together a ValueError is only ignored if it's not a UnicodeDecodeError.

A: The most common use is to propagate some one particular exception and handle all the rest. You can find a lot of examples for propagating KeyboardInterrupt and SystemExit (e.g. look at asyncore source): it's convenient for servers to log and continue in case of error in request handler, but you shouldn't catch KeyboardInterrupt to exit on SIGINT.


text:
Q: ffmpeg for android avformat_open_input = qsub_0_in_QPR_VFP2 FFMpeg version 2.1.4 on android 4.4 gives me following error

10-21 18:13:33.191: E/FFMPEGCLIENT(2561): avformat_open_input
  ret=qsub_0_in_QPR_VFP2

Error code was -1094995529
and i converted into message as AVERROR(errCode);
Does any one know what this error means?
This is not defined in libavutil/error.h and i can't find it in the code.
Code Snippet
int errCode = avformat_open_input(&thumb_ctx, thumb_path, 0, 0);

A: Error codes from ffmpeg (error.h from avutil) :
http://ffmpeg.org/doxygen/trunk/error_8h_source.html
It turns out the value you specified is :
#define AVERROR_INVALIDDATA        FFERRTAG( 'I','N','D','A')

The -1094995529 becomes -0x41444E49 and when you look at those letters, in ACSII, 0x41 = 'A', 0x44 = 'D', 0x4E = 'N, and 0x49 = 'I'.   Due to the macro/etc things are reversed, so ADNI becomes INDA, which you can see from the #define snippet, is the AVERROR_INVALIDDATA defined FFERRTAG( 'I','N','D','A').
The rest of the error codes are in that file and I've pasted them below here :
#define AVERROR_BSF_NOT_FOUND      FFERRTAG(0xF8,'B','S','F') ///< Bitstream filter not found
#define AVERROR_BUG                FFERRTAG( 'B','U','G','!') ///< Internal bug, also see AVERROR_BUG2
#define AVERROR_BUFFER_TOO_SMALL   FFERRTAG( 'B','U','F','S') ///< Buffer too small
#define AVERROR_DECODER_NOT_FOUND  FFERRTAG(0xF8,'D','E','C') ///< Decoder not found
#define AVERROR_DEMUXER_NOT_FOUND  FFERRTAG(0xF8,'D','E','M') ///< Demuxer not found
#define AVERROR_ENCODER_NOT_FOUND  FFERRTAG(0xF8,'E','N','C') ///< Encoder not found
#define AVERROR_EOF                FFERRTAG( 'E','O','F',' ') ///< End of file
#define AVERROR_EXIT               FFERRTAG( 'E','X','I','T') ///< Immediate exit was requested; the called function should not be restarted
#define AVERROR_EXTERNAL           FFERRTAG( 'E','X','T',' ') ///< Generic error in an external library
#define AVERROR_FILTER_NOT_FOUND   FFERRTAG(0xF8,'F','I','L') ///< Filter not found
#define AVERROR_INVALIDDATA        FFERRTAG( 'I','N','D','A') ///< Invalid data found when processing input
#define AVERROR_MUXER_NOT_FOUND    FFERRTAG(0xF8,'M','U','X') ///< Muxer not found
#define AVERROR_OPTION_NOT_FOUND   FFERRTAG(0xF8,'O','P','T') ///< Option not found
#define AVERROR_PATCHWELCOME       FFERRTAG( 'P','A','W','E') ///< Not yet implemented in FFmpeg, patches welcome
#define AVERROR_PROTOCOL_NOT_FOUND FFERRTAG(0xF8,'P','R','O') ///< Protocol not found
#define AVERROR_STREAM_NOT_FOUND   FFERRTAG(0xF8,'S','T','R') ///< Stream not found
#define AVERROR_BUG2               FFERRTAG( 'B','U','G',' ')
#define AVERROR_UNKNOWN            FFERRTAG( 'U','N','K','N') ///< Unknown error, typically from an external library
#define AVERROR_EXPERIMENTAL       (-0x2bb2afa8) ///< Requested feature is flagged experimental. Set strict_std_compliance if you really want to use it.
#define AVERROR_INPUT_CHANGED      (-0x636e6701) ///< Input changed between calls. Reconfiguration is required. (can be OR-ed with AVERROR_OUTPUT_CHANGED)
#define AVERROR_OUTPUT_CHANGED     (-0x636e6702) ///< Output changed between calls. Reconfiguration is required. (can be OR-ed with AVERROR_INPUT_CHANGED)
#define AVERROR_HTTP_BAD_REQUEST   FFERRTAG(0xF8,'4','0','0')
#define AVERROR_HTTP_UNAUTHORIZED  FFERRTAG(0xF8,'4','0','1')
#define AVERROR_HTTP_FORBIDDEN     FFERRTAG(0xF8,'4','0','3')
#define AVERROR_HTTP_NOT_FOUND     FFERRTAG(0xF8,'4','0','4')
#define AVERROR_HTTP_OTHER_4XX     FFERRTAG(0xF8,'4','X','X')
#define AVERROR_HTTP_SERVER_ERROR  FFERRTAG(0xF8,'5','X','X')


text:
Q: Applying .animate() to a row added using .after() So I currently use the following:
$.ajax({
    type: "GET",
    url: "file.php",
    success: function(html) {
        $("#tableRow").after(html);
    }
});

which neatly adds a new row (or rows) to an existing table.
file.php returns:

stuff

I can add a single row at a time.
I'm trying to animate just the newly added row like:
$("#tableRow").after(html).animate({ backgroundColor: "#bce4b4" }, "fast")

but that highlights the row I'm adding the new row after.  I can't get it to apply to just that new row.  How can I do that?
UPDATE:
Based on the answers given I put this together:
http://jsfiddle.net/jreljac/5ctpc/3/ where I do the following:
$("
2 1	2 2
").insertAfter("#tableRow").animate({
    backgroundColor: "#bce4b4"
}, "slow");

(I replaced what file.php will give with text") and that does not seem to work.  It creates the row but does not animate.  Am I missing something simple?

A: User insertAfter instead.  It will then animate the correct row.
$(html).insertAfter("#tableRow").animate(...

A: Try using insertAfter() instead
$(html).insertAfter('#tableRow').animate({ backgroundColor: "#bce4b4" }, "fast");

A: This will do what you want:
$(html).insertAfter('#tableRow').animate({ backgroundColor: "#bce4b4" }, "fast")

Although 'html' is just a string, you can still wrap it in $() to turn it into a jQuery object.


text:
Q: How can I populate the rows of an R data frame, in which each row represents a day, with a single common value for each day of a year? R: how can I populate the rows of a data frame, in which each row represents a day, with a single common value for each year?
I have a data frame consisting of a date column, a price column and then various other columns derived from those two columns. One of the columns calculates, for each day in a given year, the percentage change in the price from the beginning of that year (this is related to an earlier question).
I want to add a column that holds, for each day of a given year, the percentage change in the price for the whole of that year. So, if the price rose 10% from the first to the last day of 2009, the column for all the days of 2009 should hold the value 10% (or 0.1). If the price fell by 2% between the first and last days of 2010, the column for each day in 2010 should hold the value -0.02 and so on.
The code I have so far is:
require(lubridate)
require(plyr)
# generate data
set.seed(12345)
df <- data.frame(date=seq(as.Date("2009/1/1"), by="day", length.out=1115),price=runif(1115, min=100, max=200))
# remove weekend days
df <- df[!(weekdays(as.Date(df$date)) %in% c('Saturday','Sunday')),]
# add some columns for later
df$year <- as.numeric(format(as.Date(df$date), format="%Y"))
df$month <- as.numeric(format(as.Date(df$date), format="%m"))
df$day <- as.numeric(format(as.Date(df$date), format="%d"))
df$daythisyear <- as.numeric(format(as.Date(df$date), format="%j"))
df <- transform(df, doy = as.Date(paste(2000, month, day, sep="/")))
df <- ddply(df, .(year), transform, pctchg = ((price/price[1])-1))

I realise that I can get the annual (year-on-year) change by using another data frame, something like this:
df.yr <- ddply(df, .(year), function(x) (x[nrow(x),2]/x[1,2])-1)

...but I can't work out how to add the figures for the years to a column in an existing data frame, particularly given that (if you are working with 4 years of data) there are only 4 rows, one for each year, compared to about 800 in the data frame of daily data used to derive those 4 rows - you get a mismatch.
It is straightforward to use a for loop starting at the last row of the data frame and moving back up the daythisyear column to achieve this (if daythisyear on current row is larger than daythisyear on the row below, you have a change in year, so take new value from that row to use in the column being added etc). Nevertheless, I feel sure there must be a more R-colloquial approach using an apply function or ddply, which I have so far studiously avoided tackling. So my question is:
Q. How do I calculate the annual change in the value of a column and then insert that value, as a new column, into every row for that year?

A: I've not yet converted to being a ddply user, preferring instead to use ave when it is the obvious solution. I suspect that this code would translate across:
 df$pctYrChng <- ave(df$price, df$year, FUN=function(x) tail(x,1)/head(x,1) - 1)
 unique(df$pctYrChng)
#[1] -0.03259032 -0.05781901  0.35932519  0.04246669


text:
Q: Looking for a book from the 70s probably about space war and robots Looking for a book from my childhood. It would be from the 70s, probably '77 or later, and my recollection is it was a dystopian book about a war between humans and androids or cyborgs.
It was an oversized paperback book with black and white illustrations.  I think it also had some kind of "code wheel" built into the cover to solve codes in the book.
I do not remember a title or an author.
The book was actually a puzzle book and wove the story and the puzzles together.  I don't know if you had to complete the puzzles to follow the story.  I remember one puzzle involved plotting points in 3D, and I could never figure out how they derived their answer.
It was probably a YA book, and since I was only 8 or 9 it was probably over my head which is why it didn't click with me at the time.
But now I've been googling furiously trying to find it but coming up empty.

A: I found it.  The name of the book is Star Games by Jim Razzi, Rick Brightfield and Jack Looney.
Interestingly, Jim Razzi's name kept popping up in all my googling because he has a large back catalog of puzzle books with tie ins to movies like Star Wars and Star Trek.  His Star Trek Puzzle Compendium would frequently appear at the top of the list.
However Star Games is not tied to any property.  It's a story that stands alone.  The idea seems to be a series of games to train you for fighting in some galactic war.
To finally find the book I had to go to the Internet Speculative Fiction Database and go through the book list for '77 and '78 and click on anything that might sound right.  I finally had that ``Eureka!'' moment.
You can actually see the book at BoardGameGeek of all places.  Someone was more obsessed with it than me and tracked the book down and took photos of I think all the pages.


text:
Q: Weibull Distribution parameter estimation error I used the following function to estimate the three-parameter Weibull distribution.
library(bbmle)
library(FAdist)
set.seed(16)
xl=rweibull3(50, shape = 1,scale=1, thres = 0)
dweib3l <- function(shape, scale, thres) {
  -sum(dweibull3(xl , shape, scale, thres, log=TRUE))
}
ml <- mle2(dweib3l, start= list(shape = 1, scale = 1, thres=0), data=list(xl))

However, when I run the above function I am getting the following error.
Error in optim(par = c(shape = 1, scale = 1, thres = 0), fn = function (p)  :
  non-finite finite-difference value [3]
In addition: There were 16 warnings (use warnings() to see them)

Is there any way to overcome this issue?
Thank you!

A: The problem is that the threshold parameter is special: it defines a sharp boundary to the distribution, so any value of thres above the minimum value of the data will give zero likelihoods (-Inf negative log-likelihoods): if a given value of xl is less than the specified threshold, then it's impossible according to the statistical model you have defined.  Furthermore, we know already that the maximum likelihood value of the threshold is equal to the minimum value in the data set (analogous results hold for MLE estimation of the bounds of a uniform distribution ...)
I don't know why the other questions on SO that address this question don't encounter this particular problem - it may be because they use a starting value of the threshold that's far enough below the minimum value in the data set ...
Below, I use a fixed value of min(xl)-1e-5 for the threshold (shifting the value downward avoids numerical problems when the value is exactly on the boundary). I also use the formula interface so we can call the dweibull3() function directly, and put lower bounds on the shape and scale parameters (as a result I need to use method="L-BFGS-B", which allows for constraints).
ml <- mle2(xl ~ dweibull3(shape=shape, scale = scale,
                        thres=min(xl)-1e-5),
           start=list(shape=1, scale=1),
           lower=c(0,0),
           method="L-BFGS-B",
           data=data.frame(xl))

(The formula interface is convenient for simple examples: if you want to do something very much more complicated you may want to go back to defining your own log-likelihood function explicitly.)

If you insist on fitting the threshold parameter, you can do it by setting an upper bound that is (nearly) equal to the minimum  value that occurs in the data [any larger value will give NA values and thus break the optimization].  However, you will find that the estimate of the threshold parameter always converges to this upper bound ... so this approach is really getting to the previous answer the hard way (you'll also get warnings about parameters being on the boundary, and about not being able to invert the Hessian).
eps <- 1e-8
ml3 <- mle2(xl ~ dweibull3(shape=shape, scale = scale, thres = thres),
            start=list(shape=1, scale=1, thres=-5),
            lower=c(shape=0,scale=0,thres=-Inf),
            upper=c(shape=Inf,scale=Inf,thres=min(xl)-eps),
            method="L-BFGS-B",
            data=data.frame(xl))

For what it's worth it does seem to be possible to fit the model without fixing the threshold parameter, if you start with a small value and use Nelder-Mead optimization: however, it seems to give unreliable results.


text:
Q: Expo - Package 'com.xxx.native.xxx' from AndroidManifest.xml is not a valid Java package name as 'native' is a Java keyword I have used the pattern 'com.mycompanyname.native.appname' to name the bundle Ids for my apps since years and have created many apps using the keyword "native" in the package name. I didn't get this error when using classic expo builds until I switched to EAS builds.
Now, I have to upgrade a few of the live apps, can there be a workaround to overcome this error?

A: Yes, there is a workaround, which is a two step progress:

*

*Adjust the package name in your config to be a valid Java name

*Use a config plugin to set the applicationId in your build.gradle to your old package name

That way, your applicationId for Play Console stays the same, and the package name used in Java is valid for building.
Here is a gist with an example config plugin, and how to add it to your app.json:
https://gist.github.com/kbrandwijk/cef9e3b01cff91f8dfad8f47f02cb880


text:
Q: How to save copied font in mysql database? I'm trying escape string using db.escape but it's through error. I'm using MySQL Node.js as back-end. Is there any way to save data into database?
"INSERT INTO address SET  address = '        .'";

Formatted text in address below.

"INSERT INTO address SET  address = '        .'";
This query return MySQL error.


text:
Q: Add custom file (.bin) to Unity Android build In my Unity project i have placed a .bin file at the project root folder, through a script i i am calling a dll function that uses this file and it works for PC builds.
Now i am compiling for Android and the .dll file was replaced with .so, and i got a bit confused with where do i need to place the file in order for the Android system will find it?


text:
Q: Running MQTT broker in Kubernetes (nginx-ingress-controller) with TCP over SSL I'm currently trying to setup a MQTT broker (VerneMQ) on my kubernetes cluster (GKE).
At the moment I'm using nginx-ingress-controller with a Google provided L4 load balancer. The VerneMQ deployment and service are running in the cluster and a sub-domain is pointing to the specific IP of the load-balancer. The specific config-map for TCP over nginx-ingress-controller was created. I'm able to connect with a MQTT client via the subdomain via MQTT/TCP but now I want this also run in a more secure way with MQTTS/TLS.
Is it possible to run TCP over SSL through nginx-ingress-controller with lets-encrypt certificates issued by cert-manager in order to connect with MQTTS to my broker ?
Are there any other ingress-controllers which offer these functionality ?
Thank you in advance.

A: It seems that haproxy-ingress supports this? I haven't tested it, but from the documentation this option may work:
...
data:
  "9900": "system-prod/admin:9900:PROXY::system-prod/tcp-9900"

9900 will proxy to admin service, port 9900, on the system-prod namespace. Clients should connect using the PROXY protocol v1 or v2. Upcoming connections should be encrypted, HAProxy will ssl-offload data using crt/key provided by system-prod/tcp-9900 secret.


text:
Q: RFID scanner doesn't scan afterwards I am very new to coding and I'm working on this project that I have no idea why is it not running as expected. I am sorry if I'm not posting this correctly because this is my first time posting on stackoverflow. Pardon my English if there's any point where I didn't explain it correctly.
This is a project supposed to be a security system one, where we work with RFID Scanner, Camera, LED, Servo and PIR Sensor.
The conditions are as, when the time is 7am to 11pm, the pir sensor would be off and when time is 11pm onwards to 7am in the morning, the PIR sensor and camera will be turned on. Where during anytime, as long as the number of people in the house is = 0 (determined by the RFID), the camera and PIR Sensor would turn on too.
I haven't got a chance to even test out my code's logic, because when I tried to run the code, an error occurs at the loop part. "Scan a registered card to skip registration" would print and "checkpoint" would print, but afterward the code just stops there. It is supposed to be listening to the RFID scanner to read for scans, but when I tapped my card on the RFID scanner there was no response. And my code just dies there. As I'm very new to coding and python, I don't know where the errors could be. Would appreciate the help given!!
import RPi.GPIO as GPIO
from time import sleep
import sys
import requests
from datetime import datetime
from mfrc522 import SimpleMFRC522 #RFID
import os
import pygame, sys
import smtplib
from email.mime.text import MIMEText
from email.mime.multipart import MIMEMultipart
from email.mime.image import MIMEImage
from pygame.locals import *
import pygame.camera

width = 640
height = 480

#initialise pygame
pygame.init()
pygame.camera.init()
cam = pygame.camera.Camera("/dev/video0",(width,height))
no=0

GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)

GPIO.setup(24,GPIO.OUT) #LED
GPIO.setup(26,GPIO.OUT) #Servo
GPIO.setup(17,GPIO.IN) #PIR Sensor

current_time =datetime.now() #Current time

sleep(5)

reader = SimpleMFRC522() #RFID reader
auth = []
in_house =[]
p = open("presentlist.txt","a+")
p = open("presentlist.txt","r+")
present = 0

PIR_state =0

PWM=GPIO.PWM(26,50) #Set 50hz PWM output at GPIO26
PWM.start(12) #To edit to actual 3oclock (Locked)

fromaddr = "pythonprogramtest123@gmail.com" # change the email address accordingly
toaddr = "pythonprogramtest123@gmail.com" # Same email
#password: abcdefgpython
mail = MIMEMultipart()

mail['From'] = fromaddr
mail['To'] = toaddr
mail['Subject'] = "Attachment"
body = "Unusual movement detected"

print('Door Locked')
print("Hold card near the reader to register it in the database.")
print("Registration up to 10 cards")
print("Scan a registered card to skip registration")

for count in range (0,11):
    print("checkpoint1")
    id = reader.read_id()
    id = str(id)
    f = open("authlist.txt", "a+")
    f = open("authlist.txt", "r+")
    print("checkpoint2")
    if f.mode == "r+":
        auth=f.read()
    if id not in auth:
        f.write(id)
        f.write('\n')
        f.close()
        pos = auth.count('\n')
        print("New card with UID", id, "detected: registered as entry #",pos)
        count = count +1
    else:
        number = auth.split('\n')
        pos = number.index(id)
        print("Card with UID", id, "already registered as entry #", pos)
        count = 11
        break

while (True):
    id = reader.read_id()
    id = str(id)
    f = open("authlist.txt", "a+")
    f = open("authlist.txt", "r+")
    if current_time.hour >= 7 or current_time.hour <= 23 or present == 0: #awake or nobody in house
        #RFID is on
        if f.mode == "r+":
            auth=f.read()
        if id in auth and id not in in_house:
            p.write(id)
            p.write('\n')
            p.close()
            present = in_house.count('\n')
            print("Recognition successful \n Allowing Access")
            PWM.start(1) #Servo to actual 12 o clock position (Unlocking)
            print("Door unlocked for 30 seconds. Tap once more to change to 1 minute")
            if f.mode == "r+":
                auth=f.read()
            if id in auth:
                print("Unlocking door for 1 minute")
                sleep(60)
                PWM.start(12) #To edit to actual 3oclock (Locked)
                f.close()

            else: #no tap detected
                sleep(30)
                PWM.start(12) #To edit to actual 3oclock (Locked)
                f.close()
                break

        elif id in auth and id in in_house:
            p.remove(id)
            print("Recognition successful \n Allowing Access")
            PWM.start(1) #Servo to actual 12 o clock position (Unlocking)
            print("Door unlocked for 30 seconds. Tap once more to change to 1 minute")
            if f.mode == "r+":
                auth=f.read()
            if id in auth:
                print("Unlocking door for 1 minute")
                sleep(60)
                PWM.start(12) #To edit to actual 3oclock (Locked)
                f.close()

            else: #no tap detected
                sleep(30)
                PWM.start(12) #To edit to actual 3oclock (Locked)
                f.close()
                break
        else:
            print("Card not recognised \n Access Denied")

        break

    elif current_time.hour < 7 or current_time.hour > 23: #sleeping
        id = reader.read_id()
        id = str(id)
        f = open("authlist.txt", "a+")
        f = open("authlist.txt", "r+")
        #RFID is on
        if f.mode == "r+":
            auth=f.read()
        if id in auth:
            print("Recognition successful \n Allowing Access")
            PWM.start(1) #Servo to actual 12 o clock position (Unlocking)
            print("Door unlocked for 30 seconds. Tap once more to change to 1 minute")
            if f.mode == "r+":
                auth=f.read()
            if id in auth:
                print("Unlocking door for 1 minute")
                sleep(60)
                PWM.start(12) #To edit to actual 3oclock (Locked)

            else: #no tap detected
                sleep(30)
                PWM.start(12) #To edit to actual 3oclock (Locked)
                break
        else:
            print("Card not recognised \n Access Denied")
        break

        #Camera
        if GPIO.input(17): #read a HIGH i.e. motion is detected

            #LED Blink
            GPIO.output(24,1)
            sleep(1)
            GPIO.output(24,0)
            sleep(1)
            GPIO.output(24,1)
            sleep(1)
            GPIO.output(24,0)

            if PIR_state==0:
                print('detected HIGH i.e. motion detected')
                PIR_state=1

                #Camera
                cam.start() #start
                image = cam.get_image() #take pic
                cam.stop()
                no = no + 1
                saved_img=pygame.image.save(windowSurfaceObj,'picture' + "{:03d}".format(no) + '.jpg')

                #Thingspeak
                print("Updating Thingpseak")
                resp = requests.get("GET https://api.thingspeak.com/update?api_key=PQ44ZG5JR49ABODY&field1=0")
                #Email
                def sendMail(data):
                    mail.attach(MIMEText(body, 'plain'))
                    print (data)
                    dat='%s.jpg'%data
                    print (dat)
                    attachment = open(dat, 'rb')
                    image=MIMEImage(attachment.read())
                    attachment.close()
                    mail.attach(image)
                    server = smtplib.SMTP('smtp.gmail.com', 587)
                    server.starttls()
                    server.login(fromaddr, "abcdefgpython")
                    text = mail.as_string()
                    server.sendmail(fromaddr, toaddr, text)
                    server.quit()

        else: #read a LOW i.e. no motion is detected
            if PIR_state==1:
                print('detected LOW i.e. no motion detected')
                PIR_state=0
        sleep(1)
        print("...")
        break

    sleep(2)


text:
Q: Vue + TypeScript app is showing a blank white page I'm trying to follow along with a paid course to learn Vue + Firestore, but adpat it to use TypeScript instead of plain JavaScript.
I have gone through the basic setup, but my app is blank. The local host home page should be showing some simple header text from within the App.vue file. But it's just a white blank page.
Here is the full repo.
And here is the App.vue file:
<template>

Vue Voxer

Realtime Walkie-Talkie Voice Chat

    <router-view></router-view>

</template>

What have I done wrong?

A: There is a note on vuefire's document

Note: This version currently supports Vue 2 and Firebase 7. Support
for Vue 3 / Composition API and Firebase 8 is on the way.

You are using Vue3 so you must install the correct version of vuefire
npm install vuefire@next firebase@next


text:
Q: Simple PHP Controller, any issues with this code? I'm trying to build a really simple php controller page for a small site.  Here is what I have so far.  It seems to work well.  Are there any issues I might be missing with doing it this way?
$page = $_GET['p'];

switch ($page)
{
case "":
    ob_start();
    include "inc/home.php";
    $content = ob_get_contents();
    ob_end_clean();
    break;
case $page:
    $page = str_replace("/", "", $page);
    if (file_exists("inc/".$page.".php"))
    {
       ob_start();
       include "inc/".$page.".php";
       $content = ob_get_contents();
       ob_end_clean();
    }
    else
       include "inc/404.php";
    break;
}

include("inc/header.php");

echo $content;

include("inc/footer.php");

UPDATE:  Here is the final code based on comments that works well.
<?php

$page = (isset( $_GET['p']) && !empty($_GET['p'])) ? $_GET['p'] : 'home';

if( preg_match( '/[^a-z]/i', $page))
{
    $page = '404';
}

if( !file_exists( "inc/".$page.".php"))
{
    $page = '404';
}

ob_start();
include("inc/header.php");
include("inc/".$page.".php");
include("inc/footer.php");

?>

A: Your entire script can be rewritten as follows:
$page = ( isset( $_GET['p']) && !empty( $_GET['p'])) ? $_GET['p'] : 'home';

// Only allow alphabetic characters in a user supplied page
if( preg_match( '/[^a-z]/i', $page))
{
    $page = '404';
}

if( !file_exists( "inc/".$page.".php"))
{
    $page = '404';
}

include("inc/header.php");
include("inc/".$page.".php");
include("inc/footer.php");

However, this is also no longer susceptible to Local File Inclusion, as $page is restricted to only alphabetic characters, and the script will show the 404 page if anything else is submitted.
It's also more efficient as its not using output buffering.