text:
Q: IF COUNTIF Unique Value + 1st duplicate I have basic question related with Excel 2016.
I have a huge table which displays names, as shown here
For Column B "Helper" has been used below formula :
=IF(COUNTIF(A:A,A2)=1,"Unique","")

The formula is flagging all unique values, but I want to flag also the 1st duplicate row as well, as shown in here .
I saw that formula on topic "How to get distinct values in Excel (unique + 1st duplicate occurrences)" :
=IFERROR(INDEX($A$2:$A$10, MATCH(0, INDEX(COUNTIF($B$1:B1, $A$2:$A$10), 0, 0), 0)), "")

But the formula is using duplicating list INDEX(COUNTIF($B$1:B1, and is not useful in my scenario due the fact I have millions rows.
In additional I need one value  for all unique + 1st duplicating row for latter calculations.
Unfortunately we are limited to Office 2016 and UNIQUE function from Office 365 cannot be used  :(
Sound quite simple, but I'm stuck from couple of hours, and any help will be much appreciated.


text:
Q: In R, how do I count unique values of a factor based on another factor? I have data which could be described as...
factor1 <- c(rep("A", 5), rep("B", 5), rep("C", 5))
factor2 <- c("title1", "title1", "title2", "title2", "title3",
             "title4", "title4", "title4", "title4", "title5",
             "title6", "title6", "title6", "title6", "title6")

df <- data.frame(factor1, factor2)

...and what I want is a count of how many unique values in factor2 occur at each level of factor1. So my expected output in this case would be:
A   3
B   2
C   1

What is the most efficient (because Shiny will later be involved) function to do this? My various attempts at table or xtabs or aggregate are being foiled by the fact that both columns are factors.

A: Using base-R's tapply you can do:
tapply(factor2, factor1, function(x) length(unique(x)))

what results in
A B C
3 2 1

Usind data.table you could do it as follows:
require(data.table)
DT <- data.table(df)
DT[,uniqueN(factor2), factor1]

result
   factor1 V1
1:       A  3
2:       B  2
3:       C  1

Thanks @ytk for the advice on using uniqueN

A: You can just use unique and table:
table(unique(df)$factor1)    # piped: df %>% unique() %>% `[`('factor1') %>% table()

## A B C
## 3 2 1

Or turn the table into a data.frame if you'd like it in long form:
as.data.frame(table(unique(df)$factor1))

##   Var1 Freq
## 1    A    3
## 2    B    2
## 3    C    1

redpajama_set_name: RedPajamaStackExchange


text:
Q: Jquery prepend click handler If you know a better way to do this then please let me know.
Right I have a page which will contain lots of buttons, charts and tables.
I have read about stopping event propogation and that's what I'll be using.
I want to enable help on cerain elements. I have a checkbox which changes the cursor on help enabled divs. What I want to do is prepend a help function before the normal click behaviour.
Basically it's like this.
<input type="button" value="Click me" onclick="alert ('hello')" />

what i want is that if the checkbox is clicked I add a css class (already done) and then I add a click handler before the normal click. When the element is clicked then the helpfunction is run and the default button click handler is not fired. When the help checkbox is unchecked I want to remove the help function.
I realise that I could hardocde this for each element and have a check in the helperfunction to see if the checkbox is checked. But I'd prefer a more generic way of doing it.
Thanks
John

A:         $(":button").each(function() {

            // your button
            var btn = $(this);

            // original click handler
            var clickhandler = btn.attr("onclick");
            btn.attr("onclick", "return false;");

            // new click handler
            btn.click(function() {

                if ($("#chkbox").attr("checked") == true) {

                    // TODO: show your help
                    // TODO: catch event

                }
                else {

                    clickhandler();

                }
            });
        });

A: I think you want to play around with bind/unbind in this case - see http://docs.jquery.com/Events/unbind#typefn
when selecting the checkbox you can bind new click events on your buttons - and unbind them later on.
You will probably also have to work with Event.preventDefault (http://docs.jquery.com/Events/jQuery.Event) in order to suppress the default click behavior if you dont want it
You would use something the likes of:
$("a").bind("click", function(event){
 if ($("#helpcheckbox").attr('checked')
 {
  event.preventDefault();
  // do something
 }
});

Without more code it's hard to be more exact.


text:
Q: Detect and query specific languages I have data in different languages inserted into my db, such as chinese, french, english, malay, japanese, korean, etc.
How can I detect those languages and query the specific one. For example if I only want to query data in chinese and display it to users.

A: If I were you, I'd have something like this to store the text that is displayed in your UI controls:
create table ui_labels (
  control_id int,
  language varchar(2),
  label varchar(500),
  primary key (control_id, language)
);

There will be one unique control_id for each control (e.g. button) in your UI. Each control can have many labels, one for each language.
Then, each UI control can have a different label for each language. (I'm assuming a two-letter ISO language code here, but you could also use a numeric ID or some other identification scheme.)
This makes it easy to add new languages just by adding rows to the ui_labels table, and easy to switch the language displayed in the UI just by switching the language value that you use in your queries.
The data for a button could look like this:
insert into ui_labels (control_id, language, label)
  values (1, 'en', 'Read the article');
insert into ui_labels (control_id, language, label)
  values (1, 'es', 'Leer el artículo');
insert into ui_labels (control_id, language, label)
  values (1, 'tl', 'Bumasa ang balita');

As an alternative to this approach, though, you may want to look into gettext, which is a standard way to do translation in PHP. It doesn't use your database. If it's a requirement to put the strings in the database (for example, if an end-user has to be able to edit them), then this isn't an option, but it may be something that you can consider. If you are interested in this, you might want to have a look at this blog post:
http://verens.com/2008/04/03/translation-in-php/


text:
Q: Error in training objects detection in CNTK I am new in using CNTK cognitive tool kit. When trying to train Faster RCNN. It stopped because of the error:
ValueError: all the input array dimensions except for the concatenation axis must match exactly
reading at the code, maybe it happens when in the input, there is only one object. Because the module have problem in dealing with a vector. How do I fixed it?
I am using version 2.2. The full code description:
C:\Users\USER\AppData\Local\Programs\Python\Python35\Lib\site-packages\CNTK-    Samples-        2-\Examples\Image\Detection\utils\annotations>python                          annotations_helper.py
Traceback (most recent call last):
File "annotations_helper.py", line 137, in
create_map_files(data_set_path, class_dict, training_set=True)
   File "annotations_helper.py", line 75, in create_map_files
   gt_annotations = _load_annotation(abs_img_path, class_dict)
   File "annotations_helper.py", line 59, in _load_annotation
   annotations = np.hstack((bboxes, label_idxs))
   File "C:\Users\USER\AppData\Local\Programs\Python\Python35\lib\site-       packages\numpy\core\shape_base.py", line 288, in hstack
   return _nx.concatenate(arrs, 1)
   ValueError: all the input array dimensions except for the

   oncatenation axis must match exactly


text:
Q: Jquery datepicker : jquery-ui.js:7639 Uncaught Missing instance data for this datepicker_getInst Our web designer used Adobe Muse to generate a responsive page. So that each screen breakpoint has its own DOM elements but those elements are same with other respective elements in another breakpoint.
One of the element is for date of birth field. The designer used textarea to represent the field. Knowing that JQuery's datepicker does not work with textarea so I changed the element type from textarea to input text with datepicker as the class. I changed all the textarea related to date of birth field in every screen breakpoint to the same input with the same class.
So that in JQuery I can do it like this:
 $( ".datepicker" ).datepicker();

But unfortunately, when I tried to pick a date from the datepicker view, it returns an error saying jquery-ui.js:7639 Uncaught Missing instance data for this datepicker_getInst
I googled and tried to find a solution. I found the following code and tried it.
$('.datepicker').live('focus', function(){
      $(this).datepicker({
          changeMonth: true,
          changeYear: true,
          yearRange: '1930:'+(new Date).getFullYear()
      });
    });

But to no avail.
Anyone knows what caused the error ? and how to solve it ?
Any help would be appreciated.
Following is the break point of 870 screen

      <form class="form-grp clearfix grpelem temp_no_id" method="post" enctype="multipart/form-data" action="{{url('spark/regstudent_step2')}}" data-orig-id="widgetu209537">

       <input type="hidden" name="first_name" value="{{!empty($first_name) ? $first_name : ''}}">
      <input type="hidden" name="last_name" value="{{!empty($last_name) ? $last_name : ''}}">
      <input type="hidden" name="mobile_number" value="{{!empty($mobile_number) ? $mobile_number : ''}}">
      <input type="hidden" name="email" value="{{!empty($email) ? $email : ''}}">

       <input class="submit-btn NoWrap grpelem temp_no_id" type="submit" value="" tabindex="28" data-orig-id="u209555-17"/>

        <select style="padding-left:30px;padding-top:13px;" class="wrapped-input" id="widgetu209550_input" name="custom_U209550" tabindex="1">
        <option value="">Select a gender</option>
        <option value="">--------------------------</option>
        <option value="male">Male</option>
        <option value="female">Female</option>
        </select>

        <input id="datepicker5" placeholder="Date of Birth" placeholder="Date of Birth" type="text" style="padding-left:30px;padding-top:13px;" class="wrapped-input temp_no_id datepicker" name="custom_U209542" tabindex="26" data-orig-id="widgetu209542_input"/>

        <textarea style="padding-left:30px;padding-top:13px;" class="wrapped-input temp_no_id" name="custom_U209546" tabindex="27" data-orig-id="widgetu209546_input"></textarea>

      </form>


text:
Q: Kprobe on Linux Scheduler and finding linux scheduler I have two question:
1 - In Fedora source code, where can I find scheduler code?
2 - Can I put Kprobe in Fedora Scheduler? (Or Can I use register_kprobe() in Fedora scheduler?)
thanks.

A: Scheduler code could be found under kernel/sched/ directory on latest source code (this is the core file: http://lxr.linux.no/linux+*/kernel/sched/core.c).
You can insert kprobe hooks almost anywhere in kernel source but not everywhere a list could be found under this list /sys/kernel/debug/kprobes/list (assuming you've a kprobe enabled kernel, and properly mounted).


text:
Q: Can I use a shell script to automate the setup of my HPC cluster node? I am using a data centre to compute a simulation for a project, but in between sessions the node I get assigned may change and will not have conda or FEniCS activated. It is also necessary for my program that I change the cache dir due to the permissions on the server. I therefore would like a shell script to execute all of my start up commands to save me having to retype 6+ commands each time I disconnect. However, whilst the commands work as expected when I type them in the command line, they do not work in the script.
My shell script:
\#!/bin/bash

echo "================================="
srun -p cpu_inter -t 120 --exclusive -N 1 -n 32 --pty bash
echo "srun"
source /opt/conda/bin/activate
echo "conda"
source activate fenicsproject
echo "fenics"
export DIJISTSO_CACHE_DIR=$HOME
echo "home dir"
mysrun
echo "use 'scancel \<jodId\>' if needed"
echo "================================="

I run the script:
username@chome:\~$ ./shellscriptname.sh
Output:
=================================
username@nodename:\~$

(so only the first line was executed, srun was successfully started)
I rerun but with the first command commented out:
username@nodename:~$ ./shellscriptname.sh
=================================
srun
conda
fenics
home dir
./shellscriptname.sh: ligne 12: mysrun : commande introuvable
use 'scancel <jodId>' if needed
=================================
username@nodename:~$

So not only is the mysrun command not working, but none of the others did, as there is no (fenicsproject) prefix in the input line. See expected result below from when each command executed individually:
username@nodename:~$ source /opt/conda/bin/activate
(base) username@nodename:~$ source activate fenicsproject
(fenicsproject) username@nodename:~$ export DIJISTSO_CACHE_DIR=$HOME
(fenicsproject) username@nodename:~$ mysrun
             22841     bash  RUNNING       4:37   2:00:00      1 nodename cpu_name
(fenicsproject) username@nodename:~$

I have also tried replacing the first line of the script with \#!/bin/sh but in this case I get the 'source: not found' error.


text:
Q: How do I convert this SQL statement to linq in C#? Please help me to convert this SQL statement to Linq in C#:
string cmd = "SELECT * FROM dbo.Personnel WHERE (dbo.Personnel.FName LIKE
    @FName + '%' AND dbo.Personnel.LName LIKE @LName +'%')";

if (objPPersonnel.PersonnelCode != 0)
{
    cmd += "AND ( dbo.Personnel.PersonnelCode =@PersonnelCode ) ";
}

if (objPPersonnel.NationalCode != "0")
{
    cmd += "AND ( dbo.Personnel.NationalCode =@NationalCode ) ";
}

if (objPPersonnel.OrganizationPostId > 0)
{
    cmd += "AND ( dbo.Personnel.OrganizationPostId =@OrganizationPostId ) ";
}

A: I'm not sure if this is what you're asking:
    var query = from c in dbContext.Personnel
                where c.Personnel.LName.Contains(parLName)
                $$ ((c.Personnel.PersonnelCode = parPersonnelCode && parPersonnelCode != 0)||parPersonnelCode == 0)
                $$ ((c.Personnel.NationalCode = parNationalCode && parNationalCode != 0)||parNationalCode == 0)
                $$ ((c.Personnel.OrganitationPostId = parOrganitationPostId && parOrganitationPostId > 0)||parOrganitationPostId == 0)
                select c;

A: persons.Where(p => p.FirstName.StartsWith("firstName") &&
                             p.LastName.StartsWith("lastName") &&
                            (p.PersonCode != 0 ? p.personCode == personCode : true) ...

A: This will do:
var result = Personnel
    .Where(p =>
    {
        p.FName.IndexOf(firstName) == 0
        && p.LName.IndexOf(lastName) == 0
        &&
        (
            (p.PersonnelCode == personnelCode && objPPersonnel.PersonnelCode != 0) ||
            (p.NationalCode == nationalCode && objPPersonnel.NationalCode != 0) ||
            (p.OrganizationPostId == organizationPostId && objPPersonnel.OrganizationPostId != 0)
        )
    });


text:
Q: Fluctuation and standard errors in election polling British politics is very interesting lately; particularly so since Corbyn was elected Labour leader in 2015, and later with Brexit happening and so on.
Since then, multiple events have had dramatic effect on opinion polls, which can be seen here.

Compare that to also quite interesting situation in Austria, where a right wing government fell because of corruption (link).

This stark contrast strikes me as odd. In Austria, the political events of the past two months not only had absolutely no effect on polling numbers and only a very small effect in March-April (which is surprising from a political point of view), but also itra-poller agreement is unbelievably high (which is surprising from a statistical point of view). For example, consider the 26 most recent polls, conducted between 8 July and 23 September, only 2 report the FPÖ outside the 20±1% range (one of them at 22%, the other is denoted "raw data").
In the UK, however, we observe several instances of polls being conducted at the very same day, yet they often differ substantially. For example, Labour is at 21% in a 17-18 Sep poll, at 27% in a 18-19 Sep poll, and again at 22% in a 19-20 Sep poll.
I understand that it is very much possible that the public mood can swing back and forth considerably within hours, but I wonder if that sufficiently explains the stark and persisting contrast in variation between Austrian and UK polling numbers.
Note also that Austrian polls, which are much more stable, are usually based on a smaller sample size.
What is going on here?

A: For change over time -- well, as you note, British politics has had a lot of big events lately. I'd expect change over time. I don't know much about Austrian politics -- but the very fact that I don't know anything is a tiny indicator that nothing too crazy has happened lately.
For inter-poller analysis:
One possibility is that the weighting methods used by British pollsters vary a lot, while those used by Austrian pollsters vary relatively little.
Good pollsters don't use the raw data they collect, because they know that it is not a random sample of any particular population (e.g. voters or adults). They weight the data to match the population they want. This is very tricky when you are trying to match the voting population because we don't know who exactly voted in the last election and we don't know if that will change in the next election.  Different pollsters have different ideas about who will vote.  Some are less accurate than others; sometimes they are all wrong.
To use one recent and fairly famous example from USA politics, Alexandria Ocasio-Cortez was predicted to be way behind in the primary in her district. She won fairly easily. Her explanation (almost certainly correct) is that the pollsters used a weighting scheme that was based on other elections and, so, figured that few young people would vote. This turned out to be incorrect.


text:
Q: Modals lost its z-index when used in carousel I am using Materializecss in my ruby on rails project. I tried to use modals in carousel. The carousel seems to work fine but as i click on a image to open the modal. It doesn't retain its z-index. The black layout covers the whole screen. Here is my code:

  <% examples.each_with_index do |example,index| %>
    <a class="carousel-item modal-trigger" href="#example-video-<%= index %>">
      <%= image_tag vimeo_api(VideoInfo.new("#{example.video}").video_id, "thumbnail_url_with_play_button"), class: 'responsive-img' %>

    <div id="example-video-<%= index %>" class="modal">

          <%= vimeo_api(VideoInfo.new("#{example.video}").video_id, "html").html_safe %>

  <% end  %>

If i use the same modal without carousel, it works fine as expected. I am attaching a screenshot for the reference.


text:
Q: Conditions on $f(\lambda):=\sum_{n=0}^\infty a_n e^{-\lambda}\frac{\lambda^n}{n!}$ to have $a_n\approx n$ Assume the real non-negative function $f(\lambda):=\sum_{n=0}^\infty a_n e^{-\lambda}\frac{\lambda^n}{n!}$. For the simple case that the function fulfills $f(\lambda)=\lambda$ for all $\lambda\geq0$, it follows that $a_n = n$.
Now assume $f$ only fulfills this condition approximately, $\lambda(1-\delta)\leq f(\lambda) \leq \lambda(1+\delta)$ for all $\lambda\geq0$ and for some $0 < \delta\ll1 $.
Given some $\varepsilon<1$, how $\delta$ needs to be chosen and which additional conditions on $f$ are necessary to have $n(1-\varepsilon) \leq a_n \leq n(1+\varepsilon)$ for all $n\geq0$ ?


text:
Q: Display only text to WordPress loop without loosing the text formatting I want to display text from content (only text) with the formating (paragraph, bold, italic.) on loop.
When I am using this code:
<?php echo mb_substr( strip_tags( get_the_excerpt() ),0,255); ?>

or
<?php the_excerpt(); ?>

The text displayed without the text formating. No p, br even the hr is disappear.
When I am using this code:
<?php echo apply_filters('the_content',substr(get_the_content(),0,550)); ?>

The text displayed with the format, but the other content also display (image, video and else)  I just want to display the text with the format.
Anybody know how to resolve the problem?
Really appreciate for any help
Thank you

A: Try this code in your theme's functions.php file-
function filtered_content($content){
    $content = preg_replace("/<img[^>]+\>/i", "", $content); // removes images
    $content = preg_replace('/<iframe.*?>/', "", $content); // removes iframes
    return $content;
}
add_filter('the_content', 'filtered_content');

This will remove img and iframe tag from your content. Then use the_content() in your template.


text:
Q: Import error flask application I got this error running the application with this command
'python manage.py runserver'
the error
C:\Users\Kamran\Envs\thermos\lib\site-packages\flask_sqlalchemy\__init__.py:800: UserWarning: SQLALCHEMY_TRACK_MODIFICATIONS adds significant overhead and will be disabled by default in the future.  Set it to True to suppress this warning.
  warnings.warn('SQLALCHEMY_TRACK_MODIFICATIONS adds significant overhead and will be disabled by default in the future.  Set it to True to suppress this warning.')
Traceback (most recent call last):
  File "manage.py", line 1, in <module>
    from thermos import app, db
  File "E:\Kamran\My Work\Website\Python Flask Tutorial\thermos\thermos\__init__.py", line 13, in <module>
    import models
  File "E:\Kamran\My Work\Website\Python Flask Tutorial\thermos\thermos\models.py", line 3, in <module>
    from thermos import db
ImportError: cannot import name db

and I have managed my files like this

manage.py
from thermos import app, db
from thermos.models import User
from flask.ext.script import Manager, prompt_bool

manager = Manager(app)

@manager.command
def initdb():
    db.create_all()
    db.session.add(User(username='Cameron', email='cameron@google.com'))
    db.session.add(User(username='Mahshid', email='mahshid@python.org'))
    db.session.commit()
    print 'Initialized the database'

@manager.command
def dropdb():
    if prompt_bool(
    'Are you sure you want to lose all your data'):
        db.drop_all()
        print 'Dropped the database'

if __name__ == '__main__':
    manager.run()

init.py
import os
from flask import Flask
from flask_sqlalchemy import SQLAlchemy

basedir = os.path.abspath(os.path.dirname(__file__))

app = Flask(__name__)
app.config['SECRET_KEY'] = 'K\xa5r\x94\xc2"\x06\x14\'\xc1\xe4\xa6\r\x9f\x16\xf9z4hIR\x14g\x1c'
app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///' + os.path.join(basedir, 'thermos.db')
app.config['DEBUG'] = True
db = SQLAlchemy(app)

import models
import views

models.py
from datetime import datetime
from sqlalchemy import desc
from thermos import db

class Bookmark(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    url = db.Column(db.Text, nullable=False)
    date = db.Column(db.DateTime, default=datetime.utcnow)
    description = db.Column(db.String(300))
    user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)

    @staticmethod
    def newest(num):
        return Bookmark.query.order_by(desc(Bookmark.date)).limit(num)

    def __repr__(self):
        return '<Bookmark "{}": "{}">'.format(self.description, self.url)

class User(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(80), unique=True)
    email = db.Column(db.String(120), unique=True)
    bookmarks = db.relationship('Bookmark', backref='user', lazy='dynamic')

    def __rep__(self):
        return '<User %r>' % self.username

views.py
from flask import render_template, redirect, url_for, flash
from thermos import app, db
from forms import BookmarkForm
from models import User, Bookmark

def logged_in_user():
    return models.User.query.filter_by(username='Cameron').first()

@app.route('/')
@app.route('/index')
def index():
    return render_template('index.html', new_bookmarks=models.Bookmark.newest(5))

@app.route('/add', methods = ['GET', 'POST'])
def add():
    form = BookmarkForm()
    if form.validate_on_submit():
        url = form.url.data
        description = form.description.data
        bm = models.Bookmark(user=logged_in_user(), url=url, description=description)
        db.session.add(bm)
        db.session.commit()
        flash('stored "{}"'.format(description))
        return redirect(url_for('index'))
    return render_template('add.html', form=form)

@app.errorhandler(404)
def page_not_found(e):
    return render_template('404.html'), 404

@app.errorhandler(500)
def page_not_found(e):
    return render_template('500.html'), 500

if __name__=='__main__':
    app.run(debug=True)

A: It is not the Cirular Import problem, Its bad addressing the modules
In the views.py
from flask import render_template, redirect, url_for, flash
from thermos import models, app, db
from forms import BookmarkForm
from models import User, Bookmark


text:
Q: How can I format strings to query with mysqldb in Python? How do I do this correctly:
I want to do a query like this:
query = """SELECT * FROM sometable
                    order by %s %s
                    limit %s, %s;"""
conn = app_globals.pool.connection()
cur = conn.cursor()
cur.execute(query, (sortname, sortorder, limit1, limit2) )
results = cur.fetchall()

All works fine but the order by %s %s is not putting the strings in correctly. It is putting the two substitutions in with quotes around them.
So it ends up like:
ORDER BY 'somecol' 'DESC'
Which is wrong should be:
ORDER BY somecol DESC
Any help greatly appreciated!

A:
paramstyle
   Parameter placeholders can only be used to insert column values. They can not be used for other parts of SQL, such as table names, statements, etc.

A: %s placeholders inside query string are reserved for parameters. %s in 'order by %s %s' are not parameters. You should make query string in 2 steps:
query = """SELECT * FROM sometable order by %s %s limit %%s, %%s;"""
query = query % ('somecol', 'DESC')
conn = app_globals.pool.connection()
cur = conn.cursor()
cur.execute(query, (limit1, limit2) )
results = cur.fetchall()

DO NOT FORGET to filter first substitution to prevent SQL-injection possibilities

A: Not all parts of an SQL query can be parametrized. The DESC keyword for example is not
a parameter. Try
query = """SELECT * FROM sometable
                    order by %s """ + sortorder + """
                    limit %s, %s"""

cur.execute(query, (sortname, limit1, limit2) )

A: You could try this alternatively...
query = """SELECT * FROM sometable
                    order by {0} {1}
                    limit {2}, {3};"""

sortname = 'somecol'
sortorder = 'DESC'
limit1 = 'limit1'
limit2 = 'limit2'

print(query.format(sortname, sortorder, limit1, limit2))


text:
Q: How to do a recursive template match in xslt I have a text with html inside it, im trying to render the html present in it. But im facing problem when there are nested tags inside.
For ex: In my XML

Hello

And in my XSLT i have like
<xsl:choose>
<xsl:when test="section/b">
<fo:inline font-weight="bold"><xsl:apply-templates select="*|text()"/>
</fo:inline>
</xsl:when>
<xsl:when test="section/u">
<fo:inline text-decoration="underline"><xsl:apply-
templats select="*|text()"/>
</fo:inline>
</xsl:when>
<xsl:when test="section/em">
<fo:inline font-style="italic"><xsl:apply-
templats select="*|text()"/>
</fo:inline>
</xsl:when>

<xsl:otherwise>
<xsl:value-of select="section"/>
</xsl:otherwise>
</xsl:choose>

But it is not getting this rendered in my PDF.
Is there a way to match tags or any ways to do recursive template matching, or any other solutions?
Any idea/ suggestions?

A: Use multiple templates, they will apply recursively:
  <xsl:template match="b">
    <fo:inline font-weight="bold">
      <xsl:apply-templates select="*|text()"/>
    </fo:inline>
  </xsl:template>

  <xsl:template match="u">
    <fo:inline text-decoration="underline">
      <xsl:apply-templates select="*|text()"/>
    </fo:inline>
  </xsl:template>

  <xsl:template match="em">
    <fo:inline font-style="italic">
      <xsl:apply-templates select="*|text()"/>
    </fo:inline>
  </xsl:template>


text:
Q: Start loading screen when function start and end loading screen when done. (Javascript) I have a javascript app. i want to show the loading screen before i start doing something and stop loading screen when something done. here my code.
btn_start.addEventListener('click',function(){
    $('#loading-screen').show();
    //do something (example i do function in object)
    the_object.startFuntion(param1);
    $('#loading-screen').hide();
});

if i use that code, the loading screen doesnt appear, so the app like pause sometime then the_object.startFunction(param1) just done without loading screen.
UPDATE :
the div lookslike this

actually i try to generating word search board (in word search game). There's many process before showing the board so, i tried to show loading screen when it generating the board.
here the css of loading screen :
#loading-screen{
  background-color: white;
  position: fixed;
  width: 100%;
  height: 100%;
  z-index : 1000;
  text-align: center;
  display: block;
  display: none;
}

#loading-screen:before {
    content: ' ';
    display: inline-block;
    vertical-align: middle;
    height: 100%;
}

#img-loading{
  vertical-align: middle;
  width: 80%;
  height: auto;
  margin:auto;
}

A: You need to use setTimeout function otherwise it will be instant effect because .hide() wouldn't normally be applied the animation objects.
btn_start.addEventListener('click',function(){
    $('#loading-screen').show('slow');
    //do something (example i do function in object)
    the_object.startFuntion(param1);
   setTimeout(function() { $('#loading-screen').hide('slow'); }, 5000);
});

Your html should be as follows and try adding slow animation to check more into it

Demo
https://jsfiddle.net/4t3mLjxz/2/


text:
Q: Is GAE's method of serving django static files efficient? In the Django docs it mentions that in production using the built in server to serve static files is "grossly inefficient". However according to Google App Engine's documentation they do not recommend anything special to serve static files.
Does GAE do something on the backend to serve static files 'more efficiently'? Is the current implementation less than optimal? Is there a better way to serve static files?
I previously published on Heroku where it was best to use Amazon S3 to serve static files.

A: The Google docs aren't saying that Django should serve the static files, it's just saying that you should make use of the staticfiles app to collect your static files in a directory that will eventually be served by GAE.
You can read the documentation on actually serving static files via GAE with python here

... there are many cases where you want to serve static files directly to the web browser. Images, CSS stylesheets, JavaScript code, movies and Flash animations are all typically stored with a web application and served directly to the browser. App Engine can serve specific files directly without you having to code your own handler.


text:
Q: how to use multiple data-frames for training and testing purpose in python? I have multiple data-frames e.g windows 1,windows 2.......windows 6. i have used sliding window technique to split dataset. each window contains 336 records. i have concatenate all windows in a data-frame with the name of 'big data'. now i want to train multiple windows one by one in a loop and append(row wise) all windows records in train and test will return testing. how to do that  by using looping condition? please help me..
n_rows = Len(windows 1)

train_idx = n_rows

test_idx = train_idx + n_rows

big data = windows 1.append([windows2,windows 3,windows4,windows5,windows6], ignore_index=True)

big data=pd.DataFrame(big data)

train = big data.iloc[:train_idx, :]

test = big data.iloc[train_idx: test_idx, :]

i have different data frames e.g windows 1.....windows 79. each window contains 336 records e.g for windows 1(index start with 0-336)records, windows 2(index start with 337-672) and so on. now i want to use all data frames one by one for train like windows 1 train and save into train variable and windows 1 train with 336 records and predict next 336 records which is save in test variable. next windows 2 train with next 336 records but in train variable we want to append windows 1+ windows 2 (row wise append) now the train variable for second time execution will be total 672 records and then train the whole 672 rows and test next 336 records which is save in test variable. actually i want to use this approach for classification method. i want to apply this method with looping wise.. hope is that clear?


text:
Q: How to Display two different data from json on same tableview I am trying to put 2 diff data from same json on same tableview but I am not able to do! In every case, I can put only one. I want to display .name and .email at the same time
Thanks
import UIKit

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {

    var userInfo = [UserData]()

    @IBOutlet weak var tableView: UITableView!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.

        JsonDownload
            {

                self.tableView.reloadData()
           }
        tableView.delegate = self
        tableView.dataSource = self

    }

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

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = UITableViewCell(style: .default, reuseIdentifier: nil)
        cell.textLabel?.text = userInfo[indexPath.row].name

        return cell
    }

    func JsonDownload(completed: @escaping () -> ()) {

        let source = URL(string: "https://jsonplaceholder.typicode.com/users")

        URLSession.shared.dataTask(with: source!) { (data, response, error) in

            if let data = data {
                do
                {
                    self.userInfo = try JSONDecoder().decode([UserData].self, from: data)

                    DispatchQueue.main.async
                    {
                        completed()
                    }
                }
                catch
                {
                    print("Json Error")
                }
            }
        }.resume()
    }
}

A: here is how you can display .name and .email at the same time.. but instead of creating new cell each time .. use deque
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

         if  let cell = tableView.dequeueReusableCell(withIdentifier: "Cell"){
            cell.textLabel?.text = userInfo[indexPath.row].name
            cell.detailTextLabel?.text = userInfo[indexPath.row].email

            return cell
          }
            return UITableViewCell()
        }

A: If you want to use the default cell provided by Apple.
You can you textLabel and detailTextLabel. Another better way is creating your custom tableviewcell.


text:
Q: Pass data on dismiss to view controller outside of navigation controller?
As shown in the picture above, I have two view controllers, one of which is within a navigation controller. When a button is pressed in controller A, controller B is presented through the navigation controller and is displayed modally. Is it possible for me to pass data from controller B back to controller A when the dismiss function is called on B?

A: You can use delegation pattern or callbacks to do this

A: If you are using storyboards and navigating using segues, then an unwind segue will do this for you. Here is a simple tutorial that should help:
https://www.andrewcbancroft.com/2015/12/18/working-with-unwind-segues-programmatically-in-swift/
This stack overflow answer has much more detailed and valuable information on this topic
Passing Data between View Controllers

A: You can pass through NSNotificationCentre .
First you need to add Notification Observer and its selector  in ViewControllerA as below :
[[NSNotificationCenter defaultCenter] addObserver:self
                                          selector:@selector(receiveTestNotification:) name:@"notificationName"
                                               object:nil];

-(void) receiveTestNotification:(NSNotification*)notification
{
  NSDictionary* userInfo = notification.userInfo;
  NSLog (@"%@",userInfo);
}

Now in ViewController B you need to post notification as below :
 NSDictionary* userInfo = your data ;
 NSNotificationCenter* nc = [NSNotificationCenter defaultCenter];
[nc postNotificationName:@"notificationName" object:self userInfo:userInfo];


text:
Q: Do-While Loop When Media Player Is Playing In my app there is a "Start" button.
The desire result is whenever the media player is playing,the text of the button should be change to "Stop", and when the music stops the button text should change back to "Start".
I tried doing "Do While Loop" as a solution, but even when media player isn't playing,the text is changed.

*

*Is this the right solution ?

*Why does it work even when mainViewModel.mediaPlayer.isPlaying is false?

This is what I tried:
private fun trackPlayButtonTransformation() {

    do {
        rootView.speakButton.text = "Stop"

    } while (mainViewModel.mediaPlayer.isPlaying)

}

mainViewModel.mediaPlayer:
var mediaPlayer = MediaPlayer()

Thanks!

A: In a do while, the first instruction is ran no matter what, therein lies your problem. Do a regular while
private fun trackPlayButtonTransformation() {
    while (mainViewModel.mediaPlayer.isPlaying) {
        rootView.speakButton.text = "Stop"
}

}
Even this is clearly missing, you want to set the text to Play if the condition is'nt met.
You should probably use an actionListener on the button itself, and do a switch
const button = findById...... You should be able to find that easily.

button.addEventListener('click', buttonIsClicked())

private buttonIsClicked () {
   if ( mainViewModel.mediaPlayer.isPlaying ) {
      // stop that song
      // change the text
   }
   else {
      // play that song
      // change the text
   }
}

this is a rought draft, but this kind of is how I would do a play button.


text:
Q: How to set up the angular child routing correctly I'm trying to set up child paths, but when navigating, the path turns out to be the wrong one
I have a cabinet module and these are its routers
const routes: Routes = [
  {
    path: '',
    component: CabinetComponent,
    children: [
      {
        path: RouteCabinetPath.DASHBOARD,
        loadChildren: () => import('./pages/dashboard/dashboard.module').then(m => m.DashboardModule)
      },
    ]
  }
];

export enum RouteCabinetPath {
  CABINET = 'cabinet',
  DASHBOARD = 'dashboard',
}

I want to make sure that I have paths to the cabinet itself /cabinet and /cabinet/dashboard

A: Since this is a feature module that is (probably) lazy loaded, the /cabinet-part of your routes will be located in the AppRoutingModule:
{path: 'cabinet', loadChildren: () => ...CabinetModule }

Here in the CabinetRoutingModule you will need to define two routes:
[
  {path: '', component: CabinetComponent},
  {path: 'dashboard', loadChildren: () => ...DashboardModule}
]

or if you want to embed those two routes into your CabinetComponent you could add a child route with an empty route
{path: '', component: CabinetComponent,
 children: [
    {path: '', component: CabinetDetailsComponent},
    {path: 'dashboard', loadChildren: () => ...DashboardModule
 ]

A: You should change         path: '' to         path: 'cabinet',
 const routes: Routes = [
      {
        path: 'cabinet',
        component: CabinetComponent,
        children: [
          {
            path: RouteCabinetPath.DASHBOARD,
            loadChildren: () => import('./pages/dashboard/dashboard.module').then(m => m.DashboardModule)
          },
        ]
      }
    ];


text:
Q: How to get all star comments, rate, rate_count with fb graph api I'm using the Graph API Explorer to get the
star comments, star_rating and rating_count, the url like
https://www.facebook.com/weddingdaytaiwan?fields=overall_star_rating,rating_count

and get the response
{
  "overall_star_rating": 4.9,
  "rating_count": 95,
  "id": "168354659975964"
}

I already get the star_rating and rating_count but what about star comments?


text:
Q: Probability Theory: Random variables. The question reads:
" A standard deck of 52 cards is shuffled and dealt.$X_{1}$ be the number of cards appearing before the first ace and $X_{2}$ be the number of cards between first and second ace (not counting either ace). Find the probability of $P(X_{2} = 10 | X_{1} = 15)$".
My attempt is to use conditional probability formula: $P(X_{2} = 10 | X_{1} = 15) = \frac{P(X_{2}= 10, X_{1} = 15)}{P(X_{1} = 15)}$
I was about to find the denominator of this by:
$P(X_{1} = 15) = \{ \text{ drawing 15 cards and the 16th will be the first ace} \} = \frac{48}{52} \times ...\times \frac{33}{37} \times \frac{4}{36}$.
How can I find the numerator where there are 15 cards before the first ace and 10 cards between first and second ace?

A: You've already got a start on the numerator! Think about what it means:
$P(X_2 = 10, X_1 = 15)$ = the probability that $X_2$ is 10 and $X_1$ is 15. In other words, the probability that you draw 15 cards before the first ace, THEN 10 cards before the second.
$P(X_2 = 10, X_1 = 15) = \frac{48}{52} \times ...\times \frac{33}{37} \times \frac{4}{36} \times \frac{32}{35} \times ...$


text:
Q: What is the reason for the electrons in a given subshell to orient in certain preferred regions?

My text book says: "Magnetic quantum number describes the behavior of electron in a magnetic field. We know that the movement of electrical charge is always associated with magnetic field. Since the revolving electron possesses angular momentum, it will give rise to a very small magnetic field which interact with the external magnetic field of the earth. Under the influence of external magnetic field, the electrons in a given subshell orient themselves in certain preferred regions of space around the nucleus. These are called orbitals".

I got a question here. If external magnetic field of the earth is the reason for the electrons in a given subshell orient themselves in certain preferred regions of space, then

*

*would there be no particular orientations of electrons when there is no earths magnetic field? If this is the case, won't geometry of the compounds change (because of varied angle between the orbitals) without earth's magnetic field?

*And won't it also cause crashing of orbitals in the absence of particular orientation? But this never happens, I hope. Then what could be the possible explanation that can be given for the above cases.
Even I am not convinced with my text book explanation regarding orientation of electron in the subshell. How could the $p$ orbitals be oriented exactly perpendicular to each other, only because of the earth's magnetic field? We can even consider other orbitals too. Is there any other factor which is responsible for the orientations?
I don't know whether I have misunderstood anywhere, if so please explain and pardon me.

A: I think you are correct in being confused. The earth's magnetic field, or any external to the atom magnetic field , can distort orbitals but is not the creators of them.
Orbitals are the locus in space where the probability of finding an electron is large enough to be measurable.  In the quantum mechanical framework orbitals play the role orbits have in classical central potentials, for example gravity.

The five d orbitals in ψ(x, y, z)2 form, with a combination diagram showing how they fit together to fill space around an atomic nucleus.

The wave functions, i.e. the quantum mechanical solutions of the Schrodinger equation for the atom, have complicated functions of space. Their square describes the probability of finding an electron which is symmetric but does not fill all space. The solution giving the figure  depends on the n,l,m quantum numbers . The n quantum number defines the main energy level, the angular momentum l (=2 in the figure)  gives the shapes we see in the figure and the  m is degenerate and can split in magnetic fields, each triplet defining a specific orbital. If there are no external magnetic fields the m states are degenerate as far as energy goes. An external  magnetic field would split the degeneracy  and create a difference in the pattern above in space, but it is not the creator of the orbitals.

A: To start answering this question let us talk about a diatomic molecule.  In that case we can define the internuclear axis as the z axis in the molecular frame, and talk about the orientation of the various atomic orbitals with respect to that.  There is a natural choice of orientation along the bond.
For an isolated atom there is no preferred z axis to refer the orbital orientation to but what we can do is to choose the z axis so that if the atom were in a magnetic field, the z axis would be along the direction of the field.  The projection of the orbital angular momentum along the z (magnetic) axis is then m hbar.
The book is badly confused/confusing


text:
Q: C# In Memory Assembly to DLL File I am trying to save an Assembly to a file using System.Reflection.Emit.AssemblyBuilder but it's not working.
I've got a variable to hold an assembly that is running perfect when I load and run it.
System.Reflection.Assembly dll = GetAssembly(resource);

Is there anyone who can help me to save this "dll" into a file like "name.dll"?

A: In the comments, you've said that the private GetAssembly method fetches data from a resource file and builds an assembly from it. Assuming the "bytes" it's getting from the resource file really are just the bytes of the assembly, the simplest way of getting a file is to get those same bytes from the resource file, and call File.WriteAllBytes. You don't need to go via an Assembly object, and doing so makes the job harder.

A: Your AssemblyBuilderAccess flags must be RunAndSave or Save for it to work.


text:
Q: jquery serialize don't work well with angular material tabs I'm using angular material tabs inside form tag and this is my code exemple :
So the problem is when I try to serialize the form using jquery in my submit function like this:
submit(f: HTMLElement){
   let serializedForm = $(f).serialize()
   this.serialisedData = serializedForm
}

Only the the fields in the active tab are being serialized and ignore the fields in the other tabs, alghout the normal behaviour of this function is to serialize all the inputs inside the form.
Why it's not working as expected?

A: try this on ts:
submit(){

   this.serialisedData =  this.form.value
}

on html:
 {{serialisedData | json}}


text:
Q: regular expressions missing out certain letters Is there a simple way to ignore/miss out certain letters. The problem is find a word that is 5 letters long but does not contain the letters b,j,m or n.
Can I simply only specify the letters I do want such as [a][c-i][k-l][o-2]? This doesn't appear very clean and I still need to specify the word needs to be 5 letters long. So I guess I need a /w and a {5} but am not sure how to combine it all.
Thanks.

A: This selects all characters except bjmn:
[^bjmn]{5}

If you want only lower case letters except those you listed:
[c-ik-lo-za]{5}

If you don't want 5-letter-words that are part of longer words, add word boundary checking:
\b[c-ik-lo-za]{5}\b

A: Instead of [a][c-i][k-l][o-2], try [ac-ik-lo-z]{5}, which should detect strings of five allowed letters.
EDIT: Oops, you specifically wanted words. Just test for word boundaries on either side, then: \b[ac-ik-lo-z]{5}\b - checking for spaces will make you miss a match if it's the last on a line and has a period after it, a comma after it, is in brackets, etc.

A: Use [^bjmn] or [^BbJjMmNn] if you also do not want the uppercase ones.

A: Try \W[ac-ik-lo-z]{5}\W (this matches white space on either side of a group of five characters that don't contain the ones you were looking for.
You can combine multiple ranges into one list, as above.

A: This requires a word to have 5 letters but not include any of the bjmn. This could be simplified by using letter spans like [ac-i] but those tend to get a bit confusing when trying to read.
\b([acdefghiklopqrstuvwxyz]{5})\b


text:
Q: Is it possible to apply rotation/scale/position on THREE.Object3D Using blender Im used to apply any transformations to object with CTRL+A; so object becomes zero transformations (rotation/scale/position). Then I can transform object from scratch not worring about previous transformations.
Is there any way to do the same in THREE.JS? Something like THREE.Object3D.commitTransforms()?
blender

A: You should be able to achieve the intended effect by using BufferGeometry.applyMatrix() and passing the Object3D.matrixWorld into it. This will bake the world transformation into the geometry.
However, you have to manually reset Object3D.position, Object3D.scale and Object3D.rotation.
three.js R109.


text:
Q: Refresh button using image in JavaScript I am trying to make a refresh button, using an image (.jpg), in JavaScript for a website that every time it refreshes two images changes (uploaded from a database)  but it wont work for some reason. This is my code so far:

A: Since it does not get clear to me what you actually want to achieve I can only guess what could help you.
The first thing is that your "Next"-input is missing some quotation marks around the type:
document.write('<form><input type="button" value="Next" onClick="history.go()"></form>');

I would advise you to put the form directly into the div-container instead of using the document.write.
Are you trying to add the image in the script to the button you defined below?
Then you have to refer to it, e.g. with an id:

    <input type="button" id="nextBtn" value="Next" onClick="location.reload(true)">

I also removed the form, since it sends the image coordinates to the reloaded page, and used location.reload instead of history.go().
This code adds the image to the button, which refreshes the page when clicked.


text:
Q: Websocket autocompletion shows weird behaviour I have a text input with an eventlistener that will send the current value to a server via websocket. The server then answers with a json array of matches. The matches will be appended to a div below the input and event listeners will be added to them, so that they change the input's value when clicked.
However what I am getting is: typing a single letter completes the text without clicking any a element in the div. Additionally I become unable to change the text (e.g. remove characters).
Following is my code:
var webSocket = new WebSocket('ws://' + location.hostname + ':' + location.port + '/autoComplete');
var searchbox = document.getElementById('searchbox');
var suggestions = document.getElementById('suggestions');

webSocket.onmessage = function (event) {
    var results = JSON.parse(event.data);

    var html = '';
    for(var result of results) {
        html += '' + result + ' ';
    }

    suggestions.innerHTML = html;
    updateCompleterActions();
};

webSocket.onopen = function(event) {
    searchbox.addEventListener('input', function() {
        webSocket.send(searchbox.value);
    });
};

webSocket.onclose = function(event) {
    clearInterval(window.refresher);
};

var updateCompleterActions = function() {
    var elems = document.getElementsByClassName('completer');

    for(var elem of elems) {
        elem.addEventListener('click', setSearchboxText(elem.innerHTML));
    }
}

var setSearchboxText = function(value) {
    searchbox.value = value;
    for(var elem of elems) {
        elem.removeEventListener('click');
    }
}

Following is the serverside code:
@OnWebSocketMessage
public void message(Session s, String message) throws IOException {
    // TODO: implement DB access here
    List<String> words = Arrays.asList("Auto", "Baumhaus", "Peter", "fahren");
    List<String> matches = new ArrayList<>();

    for(String word : words) {
        if(word.contains(message)) {
            matches.add(word);
        }
    }

    s.getRemote().sendString(gson.toJson(matches));
}

How can I achieve that only a click will change the text of the input and fix the inability to change text afterwards (without using jQuery)?

A: You are calling the setSearchboxText function, not setting it as a callback.
change your
elem.addEventListener('click', setSearchboxText(elem.innerHTML));

to
elem.addEventListener('click', function(e) {
    setSearchboxText(this.innerHTML);
});


text:
Q: Windows Phone 7 Linenumbers in StackTraces? I am developing a WP7 app.
The app has a pretty large XML Parsing method and a try/catch block around it. When an exception occurs I just get the causing method's name from the exception's stacktrace, but no line numbers.
So it is pretty annoying to debug in a 400+ LoC method.
My guess is that the pdb files are not deployed to the phone at all.
A workaround would be to split large methods into smaller ones and to use more and smaller try/catch blocks.
But is there any way to enable line numbers in Windows Phone 7 Exceptions?

A: First of all, a 400+ LoC method is a bad practice, I would definitely recommend to split it.
Little trick: if you're using the debugger, just configure it to break on any exception (in Visual Studio, press Control + Alt + e, and check the 'thrown' checkbox in front of "Common Language Runtime Exceptions". Then, when the exception is thrown, the debugger will automatically stop at the exception location.
Now to answer your question, if you don't have line numbers when compiling in debug mode, then there's probably no practical way to get them. You can try injecting the pdb in the xap file, but I don't think it's worth the trouble.


text:
Q: Hi all, How can use a variable from one route file to another route file? personalinfo.js
var express = require("express"),
router = express.Router(),
personalinfo = require("../models/personalinfo");
// To show PersonalInfo
router.get("/new", function(req, res) {
res.render("personalinfo/new");
});
// To create personalInfo date
router.post("/new", function(req, res) {
const personalInfo = req.body.personalinfo;
console.log(personalInfo);
personalinfo.create(req.body.personalinfo, function(err, ninfo) {
    if (err) {
        res.send(err);
    } else {
        res.redirect("/objective/new");
    }
});
});
module.exports = router;

obj.js
var express = require("express"),
router = express.Router(),
objective = require("../models/objective");

router.get("/new", function(req, res) {
res.render("objective/new");
});

router.post("/new", function(req, res) {
objective.create(req.body.objective, function(err, nobj) {
    if (err) {
        res.send(err);
    } else {
        res.send(nobj);
    }
});
});

module.exports = router;

From the personalinfo.js route file I want to use the personalInfo variable in obj.js route file. How can I do that. Thanks for helping me. :)

A: You can use a module in node.
npm install connect-flash

var express = require('express');
var flash = require('connect-flash');
var app = express();
app.use(flash());

app.get('/login', function(req, res){
  req.flash('profileInfo', 'SomeText')
});

app.get('/profile', function(req, res){

  let message = req.flash('profileInfo')
  res.render('index', { message: message });
});

More info about NPM package


text:
Q: Import mathjs as a JavaScript module fails I try to import mathjs as a module in a browser (client side). I copied this file on the server, and then try to import the JS module, but it always fails. Here are some trial I already made:
import { mathjs } from "./math.min.js"

SyntaxError: The requested module './../modules/math.min.js' does not
  provide an export named 'mathjs'

import { math } from "./math.min.js"

SyntaxError: The requested module './../modules/math.min.js' does not
  provide an export named 'math'

import { create, all } from "./math.min.js"

SyntaxError: The requested module './math.min.js' does not provide an export named 'all'
I also try:
import("/math.min.js");

Uncaught (in promise) TypeError: Cannot set property 'math' of undefined

Note that the path is OK, I checked. I'm probably missing something, but I can't find what I am doing wrong. Any help is welcome.
Here is a repl.it with the code: https://repl.it/@FifiLulu/NewJollyRoutes

A: You'll need to add:
<script type="module">

to your html file.


text:
Q: Cleaning up a program on exit and dealing with the GC I'm writing a program that involves a ton of images, over 100 per screen density.  Fortunately, they aren't very big in terms of space.  I use roughly 11 at any given time.  I also use the function Bitmap.createScaledBitmap on every image which seems to take up a lot of memory.
So far in debugging this app, I seem to be able to use it indefinitely without running into a memory problem, which I'm hoping means I'm not leaking memory.
However, the one thing I've noticed is that if I "exit" my app through the back button (I'm not running anything in the background), and then restart the app shortly after, I sometimes get a out of memory error at a call to Bitmap.createScaledBitmap
01-07 19:01:24.935: ERROR/AndroidRuntime(27419): java.lang.OutOfMemoryError: bitmap size exceeds VM budget

So basically my question is, what am I doing wrong here?  Do I need to be cleaning up my own garbage, like in onDestroy when the user presses the back button?  I would have thought the GC would automatically take care of this when the back button was pressed and the activity was destroyed.  This leads me to believe I am doing something else wrong, like a memory leak.  But then I come back to the fact my app can take heavy memory use for 20 minutes but then kill itself in 5 seconds after a restart, which is what is baffling me.
Thanks all.
Edit:  I implemented a couple quick and dirty fixes.
First I tried this, and it was harder to get the application to force close.
@Override
public void onBackPressed() {
    finish();
}

Next I tried this combined with the onBackPressed and I could no longer duplicate my problem.  Note that the method call is just a loop that basically does allImages = null;
protected void onStop () {
    super.onStop();
    mComponent.releaseImages();
}

At this point it appears that after calling finish(), there are still objects in memory from the activity.  Rather strange.

A: Maybe you got something about the android lifetime of your application wrong. Pressing the back button does not kill your java program. SO sarting your app again does start a new app.
See http://developer.android.com/guide/topics/fundamentals.html#actlife
If you for example create the images in onStart() but do not remove them in onStop() you still have the references to your images. Each time will add more memory.

A: 1: When your application is resumed by onResume() your previous Bitmap objects are loaded once again. You need to make sure you don't allocate all Bitmap objects one more time.
2: It's very often it's memory leaks that causing these errors. The Bitmap objects still have references to their initializon state when your application is resumed. You can use a specific pattern to prevent reallocating same Bitmap objects. This pattern is called Memory Pools and it prevents fragmentation of your memory.
Think of fragmentation like this: You're trying to park a car. A stupid human parked a little too much to right and another stupid human parked a little too much to left. That slot is fragmented. Originally you should have enough of space to park your car right in that spot but the parking area itself is now fragmented. There's no empty slot for your car - the parking area is running out of memory.
To prevent that scenario, you can use the Memory Pools pattern.
By using this pattern you can:

*

*Set a total maximum of Bitmap
objects you will use during the
application's lifetime.

*Ask for an empty slot when your application is resumed and then reinitialize your
Bitmap objects instead of reallocate them.

By using this pattern you need to make sure:

*

*That you have enough space for your Bitmap objects in the specific pool.

However, the solution of part two isn't necessary at all (hey, it's a good tool).
The short solution: You can't create same amount of Bitmap objects when the application is resumed when you still have old Bitmap references in memory. Check if you already have your Bitmap objects loaded when your application is resumed and if you don't, create them.

A: This problem has been attributed to a bug with android.  Refer to the following links for information about the problem and some workarounds.
OutofMemoryError: bitmap size exceeds VM budget (Android)
http://code.google.com/p/android/issues/detail?id=8488
http://mobi-solutions.blogspot.com/2010/08/how-to-if-you-want-to-create-and.html


text:
Q: ASPNET Core returning file fails using IE11? Content_Length Mismatch I have a controller method that returns a file, and in all browsers this works apart from IE11.  In IE11 i get a 500 server exception.  In my dotnet run console command, i get this message.

fail: Microsoft.AspNetCore.Server.Kestrel[13]
        Connection id "0HLAA8HNC511P", Request id "0HLAA8HNC511P:00000007": An unhandled exception was thrown by the
  application. System.InvalidOperationException: Response Content-Length
  mismatch: too few bytes written (0 of 9283).

I cannot seem to catch the exception either, even by adding the app.UseDeveloperExceptionPage(); call in my Startup.cs file.
My controller method is very simple and looks like this
public async Task<IActionResult> GetAsync([FromRoute] long id, [FromRoute] long fileId, [FromQuery] FilePreviewModel previewOptions)
{
    var entity = await _fileService.GetAsync(Module, id, fileId);

    var fileName = "MEARS 2000 LOGO";
    var contentType = "image/gif";

    // this is a byte array
    var data = entity.Data.Content;

    // return file content
    return File(data, contentType, fileName);
}

In IE11, the request and response headers look like this.

In chrome, my headers look like so.

I have updated my dotnet SDK to version 2.1.3.
Anyone know what could possibly be going on??

A: I had this problem too, instead, it won't throw the error always.
Managed to solve it by removing the headers inside the action like this:
[HttpGet("{container}/{id}")]
public async Task<IActionResult> Get(string container, string id)
{
    /* remove both of these headers... put a warning here to apply the fix after dotnet team distributes the fix. */
    HttpContext.Request.Headers.Remove("If-Modified-Since");
    HttpContext.Request.Headers.Remove("If-None-Match");

    var _fileInfo = provider.GetFileInfo($"{container}/{id}");
    if (!_fileInfo.Exists || string.IsNullOrEmpty(id))
        /* return a default file here */

    var last = _fileInfo.LastModified;
    /* ... some code removed for brevity */

    return base.File(_fileInfo.CreateReadStream(), MimeTypeMap.GetMimeType(id.Substring(id.LastIndexOf("."))), id, lastModified: _lastModified, entityTag: _etag);
}

dotnet --info shows version : 2.0.4


text:
Q: Collecting all skins and customizations I found several class and vehicle skin upgrades/customizations/unlocks, e.g.:

Do they carry between games? Do some always drop in the same locations? Do they always appear in the same places or after the same quests? If so, what and where are all of them? What do I need to know to collect the whole list?

A: You can get them from chests,containers,from breakable and destroyable objects,enemy/boss drops,slot machines and they can be found in shops as "Item of the day".You can also get some from quests and challenges.
Yes,they do carry between all characters you have on your profile.
You can also get "Borderlands Veteran" heads and skins for all classes if the game detects a save file from Borderlands 1 on your PC.

A: Since I don't seem to have any rep and can't just append this as a comment, I'm making it its own answer.  I'm pretty sure you can get them from the same places ChrisHateZ mentioned: shops, chests, and breakables.
You can, however, also get them as quest rewards.  For example, the side quest "Shielded Favors" (from Sir Hammerlock) tends to reward you with skins/heads as well.  And, of course, there are also the skins for having a Borderlands 1 save and for having bought any of the special editions.

A: Most customization rewards are for your current class, but you can pick up/activate other classes' customization items. Skin collection progress carries between characters. Activated skins show as "Already Unlocked."
This wiki is a work in progress—modify the listings if a skin isn't class-specific.
Mission rewards

*

*Shielded Favors

*

*Sting Like a Bee (Assassin skin)

*At Arms (Commando skin)

*Amarillo (Gunzerker skin)

*Mellow Yellow (Siren skin)

*Symbiosis

*

*Blast Shield (Assassin head)

*A Sense of Dread (Gunzerker head)

*One-Eye Spy (Siren head)

*Grizzled Veteran (Commando head)

*Plan B

*

*SDU Weapon Equip Slot

*No Vacancy

*

*Streamlined (Assassin skin)

*Loud and Proud (Siren skin)

*In Memorium

*

*Punk (Assassin head)

*Bowler Badass (Gunzerker head)

*Nevermore (Siren head)

*The Cold Shoulder

*

*Salvador SMASH! (Gunzerker skin)

*Statuesque

*

*3ng13 (Assassin head)

*Top Card (Gunzerker head)

Challenge rewards

*

*"Boom." Level 3 (explosive damage)

*

*Torgue Explosiveness (Assassin skin)

*"It's Not Easy Looting Green" Level 3 (get green items)

*

*Preying Mantis (Siren skin)

*"Whaddaya Buyin?" Level 3 (Eridium purchases)

*

*Green-Eyed Monster (Assassin skin)

*Greenblood (Siren skin)

*"Open Pandora's Boxes" Level 3 (open lootable objects)

*

*Blue Bot (Assassin skin)

*Aggravated Assault Level 3 (assault rifle kills)

Misc.

*

*Moxxi slot machines (get triple 7s)

*

*Vladof Sickle (skin, all classes)

*Tediore Customer Service (skin, all classes)

*Marcus weapons vending machine "Item of the Day"

*

*Dahl Elite (Assassin skin)

*Jakobs Old-Fashioned (Assassin skin)

*Torgue High Octane (Assassin skin)

*Bandit Blood and Rust (Gunzerker skin)

*Hyperion Honor (Gunzerker skin)

*Tediore Low Price (Siren skin)

*Vault Veteran Rewards (detecting a Borderlands 1 save on your console)

*

*Vault Veteran: Arachn1d (Assassin head)

*Vault Veteran: Lancer (Commando head)

*Vault Veteran: Sledgehammer (Gunzerker head)

*Vault Veteran: Dr. Crazy (Siren head)

*Pandoran Legend (all classes skin)

*Special edition

*

*Special Edition: F0rg0tten (Assassin head)

*Special Edition: Snowblind (Commando head)

*Special Edition: Private Eyes (Gunzerker head)

*Special Edition: Clean Shave (Siren head)

*Special Edition: Fired Up (all classes skin)

*Enemy drops (random?)

*

*Honey Hive (Bandit Technical skin, found in Southern Shelf Bay)

*Burst Fire (Assassin skin, found from ship boss in north Southern Shelf)

*Alabaster (Bandit Technical skin, found in Southern Shelf Bay and Tundra Express)

*Infrared (Bandit Technical skin, found in Southern Shelf Bay)

*Volcanic (Commando skin, found in The Dust)

*Blue Barber (Runner skin, found in Southern Shelf Bay and Tundra Express)

*Spilled Paint (Runner skin, found in Southern Shelf Bay)

*Splatter Burst (Runner skin, found in Southern Shelf Bay and Tundra Express)

*Lootable objects (random?)

*

*Blood Bank (Runner skin, found in a Bullymong pile right outside Liar's Berg)

*Sky Runner (Runner skin, found in a Bullymong pile within Liar's Berg)

*Splatter Burst (Runner Skin, found in a Bullymong pile in Liar's Berg graveyard)

*Don't Remember

*

*Root for the Home Team (Gunzerker skin)

*Woe in the Dark (Gunzerker skin)

A:
Do they carry between games?

Yes.
While playing Commando, I got a GunZerker customization.  I used it promptly and then was able to customize my GunZerker in a different game.

A: I completed some challenge as an Assassin (I forget which, but I believe it was for dealing damage to slagged enemied), and I received a Gunzerker Maliwan skin. Weird. Also, I've never even made a Gunzerker.
The challenge reward for killing either 300 or 500 Loaders (challenge level 3) is the Hyperion skin.


text:
Q: Convert string into nested dictionary python I am newbie to python. I know this question has been asked many times before, but I looking to find solution to my query. I have a string(result of json.dumps) that needs to be converted into nested dictionary.
'["INPUT LABELS:\\n", "0 wwwwwwwwwwwwwwwww\\n", "1 Input 2\\n", "2 Input 3\\n", "\\n","OUTPUT LABELS:\\n", "0 Output 1\\n", "1 Output 1\\n", "2 Output 3\\n", "\\n"]'

Any ideas?


text:
Q: How to compile custom kernel for Raspberry Pi I'm trying to run the Ubuntu 14 Raspberry Pi ARM image in QEMU, and for that I need the kernel that matches the version used in the image.
If I mount the image and run file vmlinuz I see:
vmlinuz: symbolic link to `boot/vmlinuz-3.18.0-20-rpi2'

so I'm interpreting that to mean that image uses kernel version 3.18.0.
Using this guide, I tried compiling this version of the kernel, which I'm doing with:
TOOLCHAIN=arm-linux-gnueabihf

sudo apt-get update && sudo apt-get install git libncurses5-dev gcc-arm-linux-gnueabihf
git clone https://github.com/raspberrypi/linux.git
cd linux
# checking out 3.18.0+ branch - change it if you want to change kernel version
# for kernel specific hash, have a looks at : https://github.com/raspberrypi/linux/commits/rpi-3.18.y
# git checkout 1bb18c8f721ef674a447f3622273f2e2de7a205c
make ARCH=arm versatile_defconfig
cat >> .config << EOF
CONFIG_CROSS_COMPILE="$TOOLCHAIN"
CONFIG_CPU_V6=y
CONFIG_ARM_ERRATA_411920=y
CONFIG_ARM_ERRATA_364296=y
CONFIG_AEABI=y
CONFIG_OABI_COMPAT=y
CONFIG_PCI=y
CONFIG_SCSI=y
CONFIG_SCSI_SYM53C8XX_2=y
CONFIG_BLK_DEV_SD=y
CONFIG_BLK_DEV_SR=y
CONFIG_DEVTMPFS=y
CONFIG_DEVTMPFS_MOUNT=y
CONFIG_TMPFS=y
CONFIG_INPUT_EVDEV=y
CONFIG_EXT3_FS=y
CONFIG_EXT4_FS=y
CONFIG_VFAT_FS=y
CONFIG_NLS_CODEPAGE_437=y
CONFIG_NLS_ISO8859_1=y
CONFIG_FONT_8x16=y
CONFIG_LOGO=y
CONFIG_VFP=y
CONFIG_CGROUPS=y
CONFIG_MMC_BCM2835=y
CONFIG_MMC_BCM2835_DMA=y
CONFIG_DMADEVICES=y
CONFIG_DMA_BCM2708=y
EOF

make savedefconfig
#make -j 4 -k ARCH=arm CROSS_COMPILE=${TOOLCHAIN}- menuconfig
make -j 4 -k ARCH=arm CROSS_COMPILE=${TOOLCHAIN}- bzImage
cd ..
cp linux/arch/arm/boot/zImage kernel-qemu-3.18

However, when I go to run this kernel with qemu-system-arm, I get the error:
Error: unrecognized/unsupported processor variant (0x410fb767).

Also, I'm noticing the make command removes my changes to the .config file.
How do I fix this error?
Can I use the vmlinuz file from the image instead of compiling my own from scratch?


text:
Q: Can't get the web content with UTF-8 I'm trying to get the string by webclient and it has japanese characters but it shows these kind of characters ,�^�p�Ǘ�.
var url= "http://www.itmedia.co.jp/im/articles/0609/14/news117.html";

using (var w = new WebClient())
{
   w.Encoding = Encoding.UTF8;
   var htmlData= w.DownloadString(url);
}

The value of json_data doesn't show Japanese Characters.
Can you enlighten me why it doesn't convert to Japanese characters even if I encode it to UTF-8?

A: According to 3rd line of view-source, it's encoded in shift-jis:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html lang="ja" id="masterChannel-enterprise"><head>
<meta http-equiv="content-type" content="text/html;charset=shift_jis">

A: If you open the page with Postman, you can see the headers of the response.

As you can see in the picture, the response is compressed with gzip. That is probably causing the scrambled response you see.
WebClientnowadays supports decompressing gzip automatically, but it wasn't that way always. (If I run your code on .NET 4.6.2 on Windows 10, I do get the right results) It might be you are targeting an older version of the .NET Framework that doesn't support gzip decompression out of the box. The linked post should solve that.

A: I changed the code from UTF-8 to shift_jis.
w.Encoding = Encoding.GetEncoding("shift_jis");


text:
Q: D flip flop with asynchronous reset circuit design
I've been looking at the circuit for the D flip flop with asynchronous reset and I do understand how the overall circuit works, but I can't understand what  the point of connecting the wire in the red rectangle to the reset is.
The output will get reset if reset is set to 0 regardless of this connection.
Please correct me If I'm wrong.

A: The wire in red is to make sure that the D input is overridden with a logic 0. This makes sure both sides of the master FF are reset at the same time. This also overrides the state of the clock input.
Now S and R will clear the slave latch so it is in the proper state. S is forced to '1' and R is forced to '0' at the same instant, thus Q is forced to '0' and Q\ is forced to '1' at the same instant. Q and Q\ can NEVER have the same state at the same time.
Since the rising edge of clock is used to load in the value at the D input which briefly causes both master R-S latches to toggle states (They are cross-wired so the value of D is sampled and locked into the latches in nanoseconds, or even picoseconds), both master R-S latches must be cleared at the same instant or a glitch could appear at R and S that briefly makes the slave latch put out glitches.
The operation of the reset pin should be clean and glitch free at the Q and Q\ outputs. If Q is set to 1 then a reset should clear it to 0 and Q\ becomes 1 with almost no skewing.
That is another reason for the extra reset connection. Data is supposed to be loaded in with almost no skewing in time between Q and Q\ changing states, so RESET has to work the same way, or downstream logic could be confused. These  flip-flops are often used to sync data from a asynchronous source by using 2 in series with a common clock, so internally created glitches would never be tolerated. This could cause havoc and miss-counts in ripple-carry counters where many FF's are daisy-chained in a row.


text:
Q: PayPal 3-day guarantee on Auth/Capture if buyer uses CC PayPal says that that guarantee funds for 3 days if seller is using Authorization/Capture.  Does this guarantee stand if the buyer chooses to use a Credit Card instead of funds in a PayPal account?

A: When someone makes an Express Checkout or credit card authorization (though PayPal Payments Pro), that authorization is good for up to 29 days, provided you don't extend it.
https://developer.paypal.com/webapps/developer/docs/classic/admin/auth-capture/


text:
Q: Setting the path of properties file along with Java command I have created a shell script to run my project in Ubuntu.  There I had to give the properties file path along with the Java command.
I'm using this command to do so but its not working the file is not loading and it is giving NullPointerException as I'm trying to use it.

/usr/lib/jvm/java-7-openjdk-i386/bin/java" -cp $CLASSPATH
  -Doligosoft.POSconfig.file=/home/mlpc04/Paritosh/POS_3.0/resources/posconfig.properties
  com.floreantpos.main.Main

In the Classpath I had given properly the location where this file is located but don't know what is going wrong please suggest me the command I'm using is correct or the problem is something else.
EDIT
private static void loadPosConfig() {
     String filename = System.getProperty( "oligosoft.POSConfig.file" );
     posConfig = new Properties(); System.out.println(filename);
     File file = new File(filename);
     System.out.println( file.getAbsolutePath());
     FileInputStream inputStream = null;
     try {
        inputStream = new FileInputStream( file ); posConfig.load(inputStream);
     } catch ( Exception e) { logger.error( "Not able to load configuration" , e ); }

I am using the file in this method of my application,but i m trying to provide this file through my script.

A: you have a typo in your shell invocation you are using -Doligosoft.POSconfig.file=... instead of -Doligosoft.POSConfig.file=...


text:
Q: Meaning of "Protect the valley something, something, something, something alive!" This sentence is from the theme song of an animated series called Kung Fu Panda: Legends of Awesomeness. You can find it on YouTube.
I found this question here: "A little something something"? but I don't think that the meanings listed there fit in the song. This Wiktionary entry and this Urban Dictionary entry didn't help either.
However, this Urban Dictionary entry might fit in the lyrics:

"Something something" means that whatever the person is talking about
  isn't worth clarifying.

I also found a TV special of Family Guy called "Something, Something, Something, Dark Side" which is a parody of Star Wars. But I don't think that the songwriter wanted listeners to think that the series is made up of repeated ideas and things not worth mentioning. I can't think of another meaning, though.
Any ideas?

A: In addition to the uses you found we also use the word "something" to describe a thing that we can't remember or don't know.
For example, "I can't exactly remember what Alice said. She said something about 'the furious five' and 'alive.'"
This is a very typical use, but not exactly like the one in the song.  In the song, "something" doesn't describe the forgotten word, it stands in for the forgotten word:
"Protect the valley, something (some word I can't remember), something (some word I can't remember), something (some word I can't remember), something (some word I can't remember) alive"
This is a common* way of singing a song, or quoting a speech, that you only partially remember. It's not formal, so don't use it in an essay for school, or a published article.
*The joke here is that we might expect that a viewer of a cartoon show would sing the theme song like this, because they could only remember some of the words. We would not expect the person singing the theme song on the show itself to have forgotten the words.


text:
Q: Issue resolving conflicts in git When I do a pull in git and have to do manual conflict resolution, I then do a rebase and I end up having to resolve the same conflicts again. I want to figure out a process where I only have to resolve the conflicts once. Here's a more detailed description of the process that currently occurs for me.
1) Do a git pull which indicates that there are conflicts with my local changes.
2) Run 'git mergetool' and manually resolve all conflicts
3) Do 'git add' and 'git commit' of the merge resolution changes.
4) Do a 'git rebase origin/master' to have my local commits placed on top.
5) Here's the issue - I get prompted to resolve the same conflicts from step 2 a second time.
6) Do a 'git rebase --continue'
I'd like to eliminate either step 2) or step 5) from this process.

A: You should try git rerere
git config --global rerere.enabled true

After you have enabled rerere, Git will remember the conflict resolutions you have done, and apply them automatically the next time.

A: You could do the pull using rebase instead of merge
git pull --rebase

This will first fetch the changes to your remote branch, then it will immediately try to rebase your local commits on top of the tip of the remote branch.
That way you should only have to do one conflict resolution step.
You can configure rebase to be the default pull behavior for a branch (in this case "master"):
git config branch.master.rebase true

You can also set rebase to be the default pull behavior for all new branches in all repositories:
git config --global branch.autosetuprebase always


text:
Q: how to replicate variables on multiple locales in Chapel I'm wondering that is there an easy way to make a copy of a global variable on each locale so that later each locale will directly access its local copy instead of accessing the original variable stored in locale0 ?
thanks

A: You can use the ReplicatedDist distribution to get a copy of a variable per locale.  There is a module UtilReplicatedVar to simplify its use.
use UtilReplicatedVar;

var regularInt = 42;

// rcDomain is declared in UtilReplicatedVar.  It maps
// one int value to each locale
var repInt: [rcDomain] int;

// Other types can be replicated as well.  Here a
// heterogeneous tuple containing an integer,
// real, and complex is replicated
var repTuple: [rcDomain] (int, real, complex);

// Assign 42 to the replicated int on all locales
rcReplicate(repVar, regularInt);

// Access the local copy of the replicated var.
// The first form must use 1 as the index.
repVar[1] = 0;
writeln(rcLocal(repVar));

// Access the local complex component of the tuple
writeln(repTuple[1](3));

// Access a remote copy.
rcRemote(repVar, remoteLocale);


text:
Q: python list of tuple iteration for BWT decoding input list:
list = [(a, 6), (e, 3), (e, 4), (g, 0), (m, 1), (s, 2), (s, 5)]

and I need to receive sorted list of tuples by 2nd value in tuple
but the second value in result should be index of tuple from previous list:
list1 = [[(g, 3), (m, 4), (s, 5), (e, 1), (e, 2), (s, 6), (a, 0)]]

and then somehow iterate starting from 1 element of list1 append the char to result and come to the next tuple(index of next is a number in tuple) and receive 'message' string

A: Not the prettiest, but you'd do this with enumerate + sorted.
>>> [(x[1][0], x[0]) for x in sorted(enumerate(lst), key=lambda x: x[1][-1])]
[('g', 3), ('m', 4), ('s', 5), ('e', 1), ('e', 2), ('s', 6), ('a', 0)]


text:
Q: DNN: Using multiple web user controls in one module and showing different controls in different pages I'm a DotNetNuke newbie. Please be gentle. I'm using the "DotNetNuke 6 Compiled Module" template to build my module. I already have View.ascx control in the project and have added another control called test.ascx.
My question is: how do I show different different views in different pages I add the module to. (if that is possible at all)
e.g
Show View.ascx on say the default.aspx page and then on the default2.aspx page show the test.ascx user control?
If this is not possible does it mean I need different visual studio projects for each ascx control. Surely not.

A: Astro,
Option 1:
You need to go to Host > Extensions > Edit your extesion > Expand Module definition and click on add control.
Here you have to select your ascx control and provide key as any string. Let's say you provided key test, you selected user control and selected control type as view and saved it.
Now from view you can use following code to navigate to the newly added control:
DotNetNuke.Common.Globals.NavigateUrl(TabId,"test","mid="+ModuleID);
This will redirect the page and load your page with test.ascx.
You can use this kind of option when you want to show view.ascx by default and want to switch view when on some action and show test.ascx. Disadvantage here is, when you switch to test.ascx, all other modules added to page will not be visible.
Option 2:
You have to create a new definition in module. For that go to Host > Extensions > Edit Your module > Expand Module Definitoins > Click on add and add new definition. Once definition is added, you can add your test.ascx and view control to the definition without any key.
Once above is done, if you delete and add your module to page again, it will show two modules added in the page. These are two definitions. Look at the blog module definition for example of how multiple definitions works.
This option is used when you want to show multiple view control at the same time from the same module.
I hope this helps. Let me know if you have any more questions.

A: A little late to the party here, but if I understand you correctly, you want to have a module with different views. To add to Prashant's methods, here are 2 options I often use;
1.) Multiview
<asp:MultiView ID="myMView" runat="server" ActiveViewIndex="0">
    <asp:View ID="ViewOne" runat="server">

      ...Content 1 here...

    </asp:View>
    <asp:View ID="ViewTwo" runat="server">

      ...Content 2 here...

    </asp:View>
</asp:MultiView>

In code behind you can set the active view based on some condition
if(someCondition)
  myMView.ActiveViewIndex = 0;
else
  myMView.ActiveViewIndex = 1;

2.)Placeholder. This is my favorite as it allows me to separate each view and its code in its own control. You only need to register one control (the Master control) with DNN. You can have 10s, 100s, 1000s of child controls and they don't need to be registered with DNN as they will be contained inside MasterControl.ascx placeholder.
In the MasterControl.ascx, add
<asp:PlaceHolder ID="myPholder"  runat="server"></asp:PlaceHolder>

Follow Prashant's instruction in method 1 and register the MasterControl with DNN. In the code behind, add the following,
string childControl;
switch (condition)
{
    case "condition1":
        childControl = ControlPath + Child1.ascx";
        break;
    case "condition2":
        childControl = ControlPath + Child2.ascx";
        break;
    ...more conditions...
}
PortalModuleBase objModule = (PortalModuleBase)this.LoadControl(childControl);
if ((objModule != null))
{
    myPholder.Controls.Clear();
    objModule.ModuleConfiguration = this.ModuleConfiguration;
    myPholder.Controls.Add(objModule);
}

Just a different way of doing things. Good luck.


text:
Q: How to run all gtest files at once using cmake? I have several .cpp files that contain tests for different classes and look like this:
#include <gtest/gtest.h>

namespace {
//lots of tests
}

int main(int argc, char** argv)
{
    ::testing::InitGoogleTest(&argc, argv);
    return RUN_ALL_TESTS();
}

and a CMakeLists.txt file that looks like this:
add_subdirectory(/usr/src/gtest gtest)
include_directories(${GTEST_INCLUDE_DIR})

add_executable(TestA TestA.cpp)
target_link_libraries(TestA
     gtest
)

add_executable(TestB TestB.cpp)
target_link_libraries(TestB
    gtest
)

add_executable(TestC TestC.cpp)
target_link_libraries(TestC
    gtest
)

I like this setup because it's handy to run just the tests for the component I am currently working on. Executing one Test file is obviously much faster than executing all of them. However, every now and then I want to run all tests. How can I achieve this easily within my setup?

A: You can use CTest (it's usually installed along with CMake) to achieve this.
First, you need to include the CTest module in your CMakeLists.txt, then you just need to use the add_test command for each of your test executables:
include(CTest)
add_subdirectory(/usr/src/gtest gtest)
include_directories(${GTEST_INCLUDE_DIR})

add_executable(TestA TestA.cpp)
target_link_libraries(TestA gtest)
add_test(NAME AllTestsInA COMMAND TestA)

add_executable(TestB TestB.cpp)
target_link_libraries(TestB gtest)
add_test(NAME AllTestsInB COMMAND TestB)

add_executable(TestC TestC.cpp)
target_link_libraries(TestC gtest)
add_test(NAME AllTestsInC COMMAND TestC)

Now, once your test exes are built, from your build folder you can execute CTest to run all the tests.  E.g. to run the Debug tests:
ctest -C Debug

or to get more verbose output:
ctest -C Debug -V


text:
Q: Using implicit differentiation for finding the equation of the normal at a parabola I wanted to ask a question about using implicit differentiation to find coordinates where a normal to a hyperbola intersects at 2 different locations.
I'm studying fundamental advanced mathematics so I apologise if the error in my reasoning seems obvious!
I was presented with the following question:

The points $P(4, 12)$ and $Q(-8, -6)$ lie on the rectangular hyperbola $H$ with equation $xy = 48$.
 The equation of the line $PQ$ is given to be $3x - 2y + 12 = 0$.
 The point $A$ lies on $H$. The normal to $H$ at $A$ is parallel to the chord $PQ$.
Find the exact coordinates of the two possible positions of $A$

Given from the equation of the line, the gradient of the line $PQ$ is $\frac{3}{2}$ so the gradient of the tangent at $H$ is $-\frac{2}{3}$.
I then attempted implicit differentation of $xy = 48$:
$$x \frac{\mathrm{d}y}{\mathrm{d}x} + y = 0$$
and from here
$$-\frac{2}{3}x + y = 0$$
However, I am stuck here and not able to progress further.
In the solutions, the derivative of $y = \frac{48}{x}$ was taken and evaulated:
$$\frac{\mathrm{d}y}{\mathrm{d}x} = -\frac{48}{x^2} = -\frac{2}{3}$$
to yield
$$72 = x^2$$ and from there lead to the final solution.
The struggle that I'm facing is trying to understand why implicit differentiation isn't working to guide me to a final solution, unlike explicit differentiation.
I might have made an error or not realised the limitations of implicit differentiation in this context, but I'd like to know if there is a mistake that I have made or whether I've not considered the limitations of implicit differentation.

A: We have
$$\dfrac{d}{dx}(xy)=\dfrac{d}{dx}(48)\Rightarrow y+x\frac{dy}{dx}=0\Rightarrow\frac{dy}{dx}=-\frac{y}{x}.$$
Thus, at the point $A(x_0,y_0)$ the slope of the tangent line is $-\dfrac{y_0}{x_0}$, therefore, the slope of the normal line will be given by
$$\frac{x_0}{y_0}.$$
However, such line is parallel to the line $3x - 2y + 12 = 0\Leftrightarrow y=\dfrac{3}{2}x+6$, then
$$\frac{x_0}{y_0}=\frac{3}{2}\Longrightarrow\left\{\begin{matrix}x_0&=3k\\y_0&=2k\end{matrix}\right., k\in\mathbb{R}.$$
But $A$ lies on the hyperbole $xy=48$, thus
$$x_0y_0=48\Rightarrow 6k^2=48\Rightarrow k^2=8\Rightarrow k=\pm2\sqrt{2}.$$
Therefore, the possibles values for $A$ are $(6\sqrt{2},4\sqrt{2})$ and $(-6\sqrt{2},-4\sqrt{2})$.


text:
Q: p4 sync to an alternate location I am writing a build script that gets all the source code for a particular changelist and builds it. I would like to be able to run the script at any time, without having to shelve local changes or move files to a temporary location. The script will be used by others who have their own workspaces defined.
I thought it would be easiest just to get all the source code from Perforce at a temporary location and build from there. Unfortunately p4 sync does not seem to support this, it will only put files into the client view as specified by the workspace, meaning it would overwrite local changes before I could copy the files to the temporary location.
Is there any way to use p4 to copy files from Perforce into an arbitrary location?

A: You could create a dedicated workspace for the build script and then have the build script sync to it by using
p4 -c [workspace name] sync [depot path]

This is what a continuous build system would typically do.  Be sure to blank out the Host: section of the workspace spec in this case so that it can be used on multiple systems.
An alternative might be to use p4 print with the -o option to dump the files to an arbitrary location without syncing them.

A: P4 sync can be done only to a client spec. Possibly, you need to create another client spec and sync to that client spec.


text:
Q: Launch Failed. Binary not found. CDT on Eclipse Helios I'm using Eclipse Helios on Ubuntu 10.04, and I'm trying to install CDT plugin on it. I download it from here here.
And then I go to Install New Software and select the zip file (I don't extract it, just select the zip file). And its ok, it installs, everything works fine, it shows optional features, blah blah blah.
And then I create a new HelloWorld project. And when I try to run it, it shows an error and says:
Launch failed. Binary not found.
Can anyone explain me how to fix it?
Thanks.

A: You must "build" before "run", otherwise "Binary not found". You can set up "Auto build", so that it will build and run. Check this post to set up "Auto build" http://situee.blogspot.com/2012/08/how-to-set-eclipse-cdt-auto-build.html

A: I had this problem for a long while and I couldn't figure out the answer. I had added all the paths, built everything and pretty much followed what everyone on here had suggested, but no luck.
Finally I read the comments and saw that there were some compilation errors that were aborting the procedure before the binaries and exe file was generated.
Bottom line: Do a code review and make sure that there are no errors in your code because sometimes eclipse will not always catch everything.
If you can run a basic hello world but not your code then obviously something is wrong with your code. I learned the hard way.

A: If you still have an error even after building the project then try to do this:

*

*click on Binaries in Project Explorer with the left button

*click on green "Play" button (Run  Debug)

A: First you need to make sure that the project has been built. You can build a project with the hammer icon in the toolbar. You can choose to build either a Debug or Release version. If you cannot build the project then the problem is that you either don't have a compiler installed or that the IDE does not find the compiler.
To see if you have a compiler installed in a Mac you can run the following command from the command line:
g++ --version

If you have it already installed (it gets installed when you install the XCode tools) you can see its location running:
which g++

If you were able to build the project but you still get the "binary not found" message then the issue might be that a default launch configuration is not being created for the project. In that case do this:
Right click project > Run As > Run Configurations... >

Then create a new configuration under the "C/C++ Application" section > Enter the full path to the executable file (the file that was created in the build step and that will exist in either the Debug or Release folder). Your launch configuration should look like this:

A: I was having this same problem and found the solution in the anwser to another question:
https://stackoverflow.com/a/1951132/425749
Basically, installing CDT does not install a compiler, and Eclipse's error messages are not explicit about this.

A: I faced the same problem. I have Eclipse Indigo and Eclipse Luna on Ubuntu. I tried many solutions, but none worked. Here's how you can try :)
Try it in order :)

*

*Either do Build All and then compile :)

*Install G++ Compiler

*Windows->Preferences->NEW CDT PRoject-> Makefile-> Binary Parsers-> Choose Cywin or Window PE depending on your Os :)

*Change your toolchain to cywin gcc

*Project->Properties->Environment-> Release Active

After 1,2, 3, and 4, I tried changing paths, and other stuff, but nothing worked. In the end, I noticed that it mentioned Debug Active was not configured. So when I changed it to Release Active, it worked. Do note that change in environment and path is not required.

A: Go to the Run->Run Configuration-> now
Under C/C++ Application you will see the name of your executable + Debug (if not, click over C/C++ Application a couple of times). Select the name (in this case  projectTitle+Debug).
Under this in main Tab ->  C/C++ application -> Search your project -> in binaries select your binary titled by your project....

A: You must build an executable file before you can run it. So if you don't "BUILD" your file, then it will not be able to link and load that object file, and hence it does not have the required binary numbers to execute.
So basically right click on the Project -> Build Project -> Run As Local C/C++ Application should do the trick

A: I faced the same problem while installing Eclipse for c/c++ applications .I downloaded Mingw GCC ,put its bin folder in your path ,used it in toolchains while making new C++ project in Eclipse and build which solved my problem.
Referred to this video

A: Seems like having "Build Automatically" under the Project menu ought to take care of all of this. It does for Java.

A: make sure you have GDB installed on your system...
If your using Linux based OS simply in  a terminal type:
sudo apt-get install gdt

when finished downloading extract the file and install.
close your IDE (in this case eclipse and open it again and run your project.

A: Adding the compiler to the PATH fixed the problem for me...
export PATH="$HOME/opt/cross/bin:$PATH"

A: My problem was the same as one commenter above. I had to change the binary parser to the correct one (PE for windows, ELF for Linux, mach for mac)