text:
Q: How to update a PowerPoint slide while presenting I need to find a way to update a powerpoint slide mid-presentation with images based on audience feedback (ie. audience votes for an image and then that image gets put on a slide later).
I'm concerned about the risk of editing in presentation mode and the editor inadvertently exiting the slideshow in the middle of the presentation.
Are there any add-ons etc. that can be used in PowerPoint to edit/modify a slide during mid presentation while preventing the risk of messing up the live presentation if possible?
Ideas thus far:

*

*Using the LiveWeb plugin and an FTP site/Dropbox to point to an image and overwrite the image on the LiveWeb slide based on audience feedback (too complicated for the editors that will be doing this live)

*Update presentation remotely while on a shared network (not sure if PPT will update this live.).

*Update: As long as the presentation is using "Presenter View" and an extended monitor, you can navigate through the entire computer and edit any slide on the PowerPoint. Edited slides will show the updated content/images in the live presentation. Doing this, however, pauses the live presentation. So if the person presenting needs to go to the next slide or activate an animation while you are editing, it won't happen until the presentation is resumed. This seems like it will work as long as the presenter doesn't try to move to the next slide before the editor is done editing. Any add-ins that allow for simultaneos editing AND navigation of the presentation?

Has anyone ever done something like this before? What did you do to make it work in a live presentation?

A: In PowerPoint 2013, it is really very simple:

*

*In Presenter View, click on Show Taskbar (upper left corner)

*When taskbar opens at bottom of screen, click on PowerPoint tab,

*In three views that are shown (Editor, Presenter and SlideShow), click on the Editor view.

*If you want audience to see your changes as you make them, have same slide showing in all 3 views.

*If you don't want audience to see changes until you are done, click the Black screen icon in Presenter View (Monitor with diagonal line across), before you start your change, OR change to a different slide in Presenter view.

*Slideshow will show your changed slide on the big screen, when you go to it.
Happy PowerPointing!

A: This is really quite simple, especially since you say you want to change a slide that's not currently in view (which can get tricky due to bugs in some PPT versions).
Add this to a VBA module in your presentation.
You'll have to save the presentation as PPTM or PPSM rather than PPTX/PPTX.
Follow the instrux included as comments:
Option Explicit

' We'll modify slide #4 ... change as needed
' Make sure that the slide has no empty content or picture placeholders on it
Const lSlideNum As Long = 4

Sub AddAnImage()
    ' add a shape to any slide you like
    ' assign the shape an Action Setting of Run Macro: AddAnImage

    Dim oSl As Slide
    Dim oSh As Shape

    Set oSl = ActivePresentation.Slides(lSlideNum)

    ' bring in the image; setting width/height to -1 ensures that you
    ' don't distort it
    Set oSh = oSl.Shapes.AddPicture("c:\temp\photo.jpg", msoFalse, msoTrue, 0, 0, -1, -1)

    With oSh
        .LockAspectRatio = msoTrue ' to make sure it stays undistorted
        ' change its position/size as you wish
        ' for example, let's make it the full width of the slide:
        .Width = ActivePresentation.PageSetup.SlideWidth
    End With

End Sub

A: MDT is closer than he might think; I used to brief a stack of presentations some of which were being edited during the show.  The key is to create the master presentation as a smooth interface to a collection of presentations.  I used to get this done in Office 97; I'm sure it can be done now.
If that suits your needs, static link to a volatile presentation (but with a stable filename) might be the thing.

A: Option Explicit

' We'll modify slide #4 ... change as needed ' Make sure that the slide has no empty content or picture placeholders on it Const lSlideNum As Long = 4

Sub AddAnImage()
    ' add a shape to any slide you like
    ' assign the shape an Action Setting of Run Macro: AddAnImage

    Dim oSl As Slide
    Dim oSh As Shape

    Set oSl = ActivePresentation.Slides(lSlideNum)

    ' NEW:  Delete any existing image we may have added previously
    On Error Resume Next
    Set oSh = oSl.Shapes("MagicImage")
    If Err.Number = 0 Then
       oSh.Delete
    End If

    ' bring in the image; setting width/height to -1 ensures that you
    ' don't distort it
    Set oSh = oSl.Shapes.AddPicture("c:\temp\photo.jpg", msoFalse, msoTrue, 0, 0, -1, -1)

    With oSh
        ' NEW:  Name it so we can locate it easily later:
        .Name = "MagicImage"
        .LockAspectRatio = msoTrue ' to make sure it stays undistorted
        ' change its position/size as you wish
        ' for example, let's make it the full width of the slide:
        .Width = ActivePresentation.PageSetup.SlideWidth
    End With

End Sub

A: Have you ever thought about custom shows?  Create a single PPT file with all the different combinations possible.  As you click through the slides and select a picture hyperlink to a custom show that includes the correct picture.  With a little thought and a tree to track all possible combinations, you can do what you want.

A: This is very old, but as someone who needed to be able to update future slides without interrupting the current show, I found that Powershow worked exactly how I needed it to work. The changes in 2013 are great, however, it does not allow the user to edit the show without affecting what the audience sees.
The dance school I work for uses slides and sometimes movies during our recital. There were a few times where I clicked a different slide and cut off the sound for the video displaying because it cut off the show. I did some research and found Powershow. It took a little getting used to, but is exactly what I needed.
I can do whatever I want, including update and rearrange, as well as delete upcoming slides, while the show displays in a different session in powerpoint.


text:
Q: Is there a way I can search Wordpress usermeta key using wildcards? Is there a way to search the wp_usermeta table in Wordpress using wildcards on keys?  For example, I have actionItems which have the following structure:
actionItem(idNum)
  actionItemDescription
  actionItemAssignedTo
  actionItemStatus
  actionItemCompletedDate

I can store them just fine like this:
    $actionItemId="actnItemId".uniquid();
    $actionItemDescription="test";
    $actionItemAssignedTo="test";
    $actionItemStatus="test";
    $actionItemCompletedDate="test";

    $actionItemArray = array (
        'action_item_description' => $actionItemDescription,
        'action_item_assigned_to' => $actionItemAssignedTo,
        'action_item_status' => $actionItemStatus,
        'action_item_completed_date' => $actionItemCompletedDate,
    );
    update_user_meta($userId,$actionItemId,$actionItemArray);

I'm not sure how I can use WP_User_Query to retrieve the data unless I can do a wildcard search of a key. I would be grateful for any assistance.

A: I had to go a different route.  Here is my solution:
global $wpdb;

$results = $wpdb->get_results("select meta_value from pfpwp_usermeta where user_id=".$contactId." and meta_key like 'actionItem%'");

$retVal=[];
foreach( $results as $result ) {
    $rows = unserialize($result->meta_value);
    foreach($rows as $row ) {
        array_push($retVal,$row);
    }
}
$retVal=json_encode($retVal);

return $retVal;

redpajama_set_name: RedPajamaStackExchange


text:
Q: Pass a list of files to sed to delete a line in them all I am trying to do a one liner command that would delete the first line from a bunch of files. The list of files will be generated by grep command.
grep -l 'hsv,vcv,tro,ztk' ${OUTPUT_DIR}/*.csv | tr -s "\n" " " | xargs /usr/bin/sed -i '1d'

The problem is that sed can't see the list of files to act on.I'm not able to work out what is wrong with the command. Please can someone point me to my mistake.

A: Line numbers in sed are counted across all input files. So the address 1 only matches once per sed invocation.
In your example, only the first file in the list will get edited.
You can complete your task with loop such as this:
grep -l 'hsv,vcv,tro,ztk' "${OUTPUT_DIR}/"*.csv |
while IFS= read -r file; do
    sed -i '1d' "$file"
done

A: This might work for you (GNU sed and grep):
grep -l 'hsv,vcv,tro,ztk' ${OUTPUT_DIR}/*.csv  | xargs sed -i '1d'

The -l ouputs the file names which are received as arguments for xargs.
The -i edits in place the file and removes the first line of each file.
N.B. The -i option in sed works at a per file level, to use line numbers for each file within a stream use the -s option.

A: The only solution that worked for me is this  apart from the one posted by Dan above -
for k in $(grep -l 'hsv,vcv,tro,ztk' ${OUTPUT_DIR}/*.csv | tr -s "\n" " ")
do
    /usr/bin/sed -i '1d' "${k}"
done


text:
Q: Make tkinter button that calls function below it I am working on a script that will text you when a product is in stock and I want it to run when you press the start button how ever the function that is supposed to run is below the start button
here is my code.
import tkinter as tk
from tkinter import filedialog, Text
import os
import requests
import twilio
from bs4 import BeautifulSoup
import time
from lxml import html
import os
from twilio.rest import  Client

root = tk.Tk()

canvas = tk.Canvas(root, height=700, width=700, bg='#263D42')
canvas.pack()

productlink = tk.Entry (root)
canvas.create_window(200, 140, window=productlink)

phonenmbr = tk.Entry(root)
canvas.create_window(500, 140, window=phonenmbr)

productUrl = tk.Label(root, text='Enter Product Url')

productUrl.config(font=('bebas-neue', 14))
canvas.create_window(200, 110, window=productUrl)

phonenumbertext = tk.Label(root, text='Enter Phone Number')

phonenumbertext.config(font=('bebas-neue', 14))
canvas.create_window(500, 110, window=phonenumbertext)

start = tk.Button(root, text='Start Bot', padx=10, pady=5, fg='White', bg='#1E1513', command=stockCheck())
canvas.create_window(350, 150, window=start)

root.mainloop()

account_sid = 'sid'
auth_token =  'auth_token'
client = Client(account_sid, auth_token)

headers = {"User-Agent": 'Mozilla/5.0 (X11; Linux x86_64)', 'Cache-Control': 'no-cache', "Pragma": "no-cache"}
page = requests.get(productlink, headers=headers)
soup = BeautifulSoup(page.content, 'html.parser')

def stockCheck():
    while True:
        if soup.find(id='outOfStock'):
                time.sleep(1)
        else:
            publish()
            break

def publish():
    message = client.messages \
                    .create(
                        body="The Product: " + productlink + " Is in Stock BUY IT NOW",
                        from_='+14804057767',
                        to= phonenmbr
                    )

the stockCheck function is below the start button and it is hard to move them around because of everything else. Any help?


text:
Q: Enclosing the value of a variable in single quotes in BASH I'm trying to adapt some Perl scripts to Bash to run them in Nagios XI.
The problem is that Nagios expects the values of the variables to arrive between single quotes, but I can't manage to escape the variables correctly.
For example, in the top area where I declare variables and/or constants, I have this:
status='OK'

And when I replace it in the value to return to Nagios, I put it like this and it works correctly:
output="[$status]"
output_msg="Voting disks status check succeeded"

Which when printed, returns that [OK] Voting disks status check succeeded.
However, I have other variables that I build from executed commands, like this:
command=`/oracle/app/grid/19300/bin/crsctl query css votedisk | grep asm`
output1=`echo $command | cut -d " " -f4`
output2=`echo $command | cut -d " " -f5`

If I run this script locally, the result is as expected:
[OK] Voting disks status check succeeded - (/dev/mapper/asm_ocr1) [OCR].

But when I launch it from the Nagios server, the $output1 and $output2 variables always arrive empty:
[OK] Voting disks status check succeeded -

I know it's because of the single quotes because when I try to declare a third variable with a literal text, it comes out correctly:
output3='Test'
output="[$status] $output_msg - $output3

This paints on the Nagios server:
[OK] Voting disks status check succeeded - Test

Any idea how to put the text contained in $output1 and $output2 in single quotes so Nagios will interpret it?
EDIT
To corroborate that the content of the variable must be in single quotes, I have made the following test:
#Add the path that $output1 should return
test='/dev/mapper/asm_ocr1'
#Paint in the output the variable $test
output="[$status] $output_msg - $test $output1 $output2"

########

#On the Nagios server, the $test variable send correctly:
[OK] Voting disks status check succeeded - /dev/mapper/asm_ocr1 ''

EDIT 2
I found out that the error does not come from the quotation marks, but from the Nagios communication with the node where the DB is running.
The complete script, so far, is this one:
. /home/oracle/.profile_RAC
ORACLE_HOME=/oracle/app/grid/19300
ORACLE_BASE=/oracle/app/base
nagios_exit_codes=('UNKNOWN', 3, 'OK', 0, 'WARNING', 1, 'CRITICAL', 2)
status='OK'
ok=1
action=$1

case $action in
        "votedisk")
                #command=`/oracle/app/grid/19300/bin/crsctl query css votedisk | grep asm`
                #command=$(/oracle/app/grid/19300/bin/crsctl query css votedisk)
                command=`/oracle/app/grid/19300/bin/crsctl query css votedisk`

                case $comando in
                        *"failed"*|*"OFFLINE"*|*"PROC"*)
                                status='CRITICAL'
                                output_msg="Voting disk status check failed!"
                        ;;

                        * )
                                output_msg="Voting disks status check succeeded"
                        ;;
                esac

                output="[$status] $output_msg - $command"

        ;;

        "clusterstatus")
                comando=`/oracle/app/grid/19300/bin/crsctl query crs releaseversion`
                output_msg="All clusterware services are up (clusterware version: $comando)"
                output="$output_msg"

        ;;
esac

echo -e $output
exit 0

Running this script locally, the result is this:
[root@bbddmachine plugins]# sh ./script_prueba.sh votedisk
[OK] Voting disks status check succeeded - ## STATE File Universal Id File Name Disk group -- ----- ----------------- --------- --------- 1. ONLINE 8dfc2a9528244f95bf87bb394e793995 (/dev/mapper/asm_ocr1) [OCR] Located 1 voting disk(s).

But on the Nagios machine, the result is wrong:
[nagios@ng1esp libexec]$ ./check_nrpe -2 -H 172.47.62.12 -t 60 -c check_crs_votedisk
[OK] Voting disks status check succeeded - Unable to communicate with the Cluster Synchronization Services daemon.

However, if I launch the other option in the script called ```clusterstatus`` everything works fine:
[nagios@ng1esp libexec]$ ./check_nrpe -2 -H 172.47.62.12 -t 60 -c check_crs_clusterstatus
All clusterware services are up (clusterware version: Oracle High Availability Services release version on the local node is [19.0.0.0.0])


text:
Q: Is it possible to walk stack frames from an Exception? I want to log the first stack frame which is visible from within my own code. Is it possible to walk a stack trace from a Throwable - something similar to StackWalker.walk(...)

A: You can stream the StacktraceElements:
Arrays.stream(throwable.getStackTrace().forEach(element ->{
    if(element.getClassName().startsWith("your.package"){
        logger.info(element.toString());
    }
});

A: The best solution is to stream the results of Throwable.getStackTrace()

I know you can stream the array, but this will cause performance overhead.

In fact, it won't.  The overheads of capturing the stack frames and turning them into an array of StackFrameElement is incurred when fillInStackTrace() is called.  This happens during the instantiation of the Throwable (exception) object; i.e. before you throw it.
Basically, you have already taken the performance overhead of creating the array ... before you decide if you want to stream the stack frames or not.
On the flipside, it is possible to instantiate a Throwable (via a subclass) with the writableStackTrace argument set to false.  That inhibits the call to fillInStackTrace.  The net result is that no stackframes will be captured ... and there would be nothing to stream.
(And you can't change the mind.  If the stackframes don't get captured when the Throwable is instantiated, they will be discarded as the stack is unwound during propagation of the exception.)

A: The most correct way is to pay the penalty and stream the Throwable.getStackTrace()...
This will though come with performance issues as the jvm must create all elements in the stack trace (not just the ones you want)...
If paying this performance overhead is not an option, you should "walk the stack" using the StackWalker from the java 9 stack walking api... This stack will deviate from the exception stack trace, and this needs to be considered when walking the stack...


text:
Q: How to prove that the Hochschild cohomology algebra is isomorphic to the algebra given by Hom's in the derived category. Let $A$ be a finite-dimensional algebra over an algebraically closed field (I think this can be generalized to Artinian algebras over commutative rings, but lets work with this hypothesis for now).
Then the cup product on $\mathrm{HH}^*(A) = \bigoplus_{n \geq 0} \mathrm{HH}^n(A)$, gives an algebra structure.
The vector space $B = \bigoplus_{n \geq 0} \operatorname{Hom}_{D^b(A^e)}(A,A[n])$ with product given by composition and the shift of $D^b(A)$ gives also an algebra.
I have found a lot of references where they claim that $\mathrm{HH}^*(A) \cong B$ as algebras, but I have never seen a proof for this.
Can anyone help me out with this proof? or a reference for it?


text:
Q: What happens to a (moving) magnetic-dipole in an external electric-field? An electric-charge (positive) feels a force in direction of electric-field (external) . A magnetic-monopole, if existed, would experience force in direction of external magnetic-field, which, is proved by behavior magnetic-dipoles.
Something interesting happens when a moving electric-charge enters external magnetic-field, i.e., force is in direction given by vector-product (vector cross product) of velocity and field. But, does it means that a moving magnetic-dipole or -monopole will experience some type of force in external electric-field??

A: You are essentially asking about what is known as the Aharonov-Casher effect (https://journals.aps.org/prl/abstract/10.1103/PhysRevLett.53.319), which is the electromagnetic dual of the Aharonov-Bohm effect. The simplest realization of the Aharonov-Casher effect arises, when an uncharged particle with a magnetic moment (spin) is encircling a tube of constant line charge density which generates a radial electric field. The circular motion leads to the accumulation of a quantum phase, the so-called Aharonov-Casher phase. The effect can be understood by considering the relativistic transformation of the electric field into the moving reference frame of the neutral particle. The magnetic moment experiences a magnetic field
$$ {\mathbf B} = \frac{1}{c^2}{\mathbf v}\times\mathbf{E} $$
brought about by this transformation, and changes its orientation under the influence of this field. The Aharonov-Casher phase is then given by
$$ \Delta\varphi_\mathrm{AC} = \frac{1}{\hbar c^2}\oint {\mathbf \mu}\times\mathbf{E}d\mathbf{s}, $$
where the integration is along the circular path of the magnetic moment ${\mathbf\mu}$.
There are experiments with neutrons that measure this phase by interference (https://journals.aps.org/prl/abstract/10.1103/PhysRevLett.63.380).


text:
Q: Pandas read_csv - How to handle a comma inside double quotes that are themselves inside double quotes This is not the same question as double quoted elements in csv cant read with pandas.
The difference is that in that question: "ABC,DEF" was breaking the code.
Here, "ABC "DE" ,F" is breaking the code.
The whole string should be parsed in as 'ABC "DE", F'. Instead the inside double quotes are leading to the below-mentioned issue.
I am working with a csv file that contains the following type of entries:

header1, header2, header3,header4
2001-01-01,123456,"abc def",V4
2001-01-02,789012,"ghi "jklm" n,op",V4

The second row of data is breaking the code, with the following error:
ParserError: Error tokenizing data. C error: Expected 4 fields in line 1234, saw 5

I have tried playing with various sep, delimiter & quoting etc. arguments but nothing seems to work.
Can someone please help with this? Thank you!

A: Based on the two rows you have provided here is an option where the text file is read into a Series object and then regex extract is used via Series.str.extract() get the information you want in a DataFrame:
with open('so.txt') as f:
    contents = f.readlines()

s = pd.Series(contents)

s now looks like the following:

0       header1, header2, header3,header4\n
1                                        \n
2          2001-01-01,123456,"abc def",V4\n
3                                        \n
4    2001-01-02,789012,"ghi "jklm" n,op",V4

Now you can use regex extract to get what you want into a DataFrame:
df = s.str.extract('^([0-9]{4}-[0-9]{2}-[0-9]{2}),([0-9]+),(.+),(\w{2})$')

# remove empty rows
df = df.dropna(how='all')

df looks like the following:

            0       1                  2   3
2  2001-01-01  123456          "abc def"  V4
4  2001-01-02  789012  "ghi "jklm" n,op"  V4

and you can set your columns names with df.columns = ['header1', 'header2', 'header3', 'header4']


text:
Q: DHCP-defined local DNS address isn't responding I set up a bind DNS server on 10.0.0.2 on my network. named.conf looks like this:
options {
        directory "/var/named";
        pid-file "/run/named/named.pid";
        auth-nxdomain yes;
        datasize default;
        listen-on-v6 { any; };

        allow-recursion { any; };
        allow-transfer { none; };
        allow-update { none; };
    version none;
    hostname none;
    server-id none;
    forwarders {
       8.8.8.8;
       8.8.4.4;
    };
    // samba DLZ key
    tkey-gssapi-keytab "/var/lib/samba/private/dns.keytab";
};
//SAMBA: allows automatic update of active directory names
dlz "AD DNS Zone" {
    database "dlopen /usr/lib/samba/bind9/dlz_bind9_9.so";
};

zone "localhost" IN {
        type master;
        file "localhost.zone";
        allow-transfer { any; };
};

zone "0.0.127.in-addr.arpa" IN {
        type master;
        file "127.0.0.zone";
        allow-transfer { any; };
};
// Lets me do reverse lookups on LAN IPs
zone "0.10.in-addr.arpa" IN {
        type master;
        file "10.0.zone";
        allow-transfer { any; };
};
// Definitions for root name servers
zone "." IN {
        type hint;
        file "root.hint";
};

When I do something like nslookup google.com 10.0.0.2 on another machine, the DNS server returns a response like it should.
However, when I define 10.0.0.2 as a DNS server on my modem/router, (I think this is part of DHCP, but I'm not an expert so I'm probably wrong - some insight here would be appreciated too) nslookup google.com returns something like:
DNS request timed out.
    timeout was 2 seconds.
*** Can't find server name for address 10.0.0.1: Timed out
*** Default servers are not available
Server:  UnKnown
Address:  10.0.0.1

10.0.0.1 is the address of my router.
For reference, where I am putting this address for the DNS server into my router has this description:
DNS Server Configuration

If 'Enable Automatic Assigned DNS' checkbox is selected, this router will accept the first received DNS assignment from one of the PPPoA, PPPoE or MER/DHCP enabled PVC(s) during the connection establishment. If the checkbox is not selected, enter the primary and optional secondary DNS server IP addresses. Click 'Save' button to save the new configuration. You must reboot the router to make the new configuration effective.

What am I doing wrong?

A: Your router (as usually) announces itself as DNS resolver for all your pcs in the network. Now you configured it to lookup using 10.0.0.2, which seems not possible to do so - it can only do lookups on the wan interface ("outside", "the intarwebs").
Unfortunately, it seems you cannot edit the DHCP settings, you'd have to add 10.0.0.2 as the DNS server by hand on any of your machines.
(Edit: You could - if possible - disable DHCP on your router/modem and add DHCP to that server on 10.0.0.2, that way you can push even more settings)


text:
Q: Add a node in the middle of a line java fx I have a line and I want a square with text inside of the square to be placed in the middle of this line.
I have created the square with text using a stack pane. This line is draggable so I want the square to stay in the middle of this line when it is being dragged.
I tried:
weightSquare.layoutXProperty().bind((line.startXProperty().add(line.endXProperty())).divide(2).add(line.translateXProperty()));
weightSquare.layoutYProperty().bind((line.startYProperty().add(line.endYProperty())).divide(2).add(line.translateXProperty()));

where weightSquare is a StackPane containing a rectangle and text.
Currently, the weightSquare is near the middle of the line but not perfectly in the middle. When the line moves around the weightSquare stays relatively near the middle of the line but sometimes goes off the line slightly.
I want something like this:
Example of what I want
Thank you.

A: Assuming no transformations have been applied to the line or the StackPane, you can calculate the position of the StackPane based on the line properties like this
stackPane.layoutX = (line.startX + line.endX - stackPane.width) / 2;

(Procede accordingly for y coordinates.)
transformX and transformY could simply be added, but general transforms would require you to

*

*Listen to changes of the transforms

*Use localToParent on the start/end coordinates of the line to get the location in the parent.

I recommend using Bindings.createDoubleBindings for complicate double bindings btw, since this makes the formula for calculating the values much easier to read.
Example
I use a Label, since this provides background/border functionality too.
@Override
public void start(Stage primaryStage) throws IOException {
    Label label = new Label();
    label.setStyle("-fx-background-color: white; -fx-border-color: black;");
    label.setPadding(new Insets(2, 4, 2, 4));

    Line line = new Line(300, 300, 300, 100);

    label.layoutXProperty().bind(Bindings.createDoubleBinding(
            () -> (line.getStartX() + line.getEndX() - label.getWidth()) / 2,
            line.startXProperty(), line.endXProperty(), label.widthProperty()));
    label.layoutYProperty().bind(Bindings.createDoubleBinding(
            () -> (line.getStartY() + line.getEndY() - label.getHeight()) / 2,
            line.startYProperty(), line.endYProperty(), label.heightProperty()));

    DoubleProperty angle = new SimpleDoubleProperty();
    line.endXProperty().bind(Bindings.createDoubleBinding(() -> 300 + 200 * Math.sin(angle.get()), angle));
    line.endYProperty().bind(Bindings.createDoubleBinding(() -> 300 + 200 * Math.cos(angle.get()), angle));

    Timeline timeline = new Timeline(
            new KeyFrame(Duration.ZERO, new KeyValue(angle, 0d, Interpolator.LINEAR)),
            new KeyFrame(Duration.seconds(10), new KeyValue(angle, Math.PI * 2, Interpolator.LINEAR)));
    timeline.setCycleCount(Animation.INDEFINITE);
    label.textProperty().bind(timeline.currentTimeProperty().asString());
    timeline.play();

    Scene scene = new Scene(new Pane(line, label), 600, 600);

    primaryStage.setScene(scene);
    primaryStage.show();
}


text:
Q: Textbox data saved to database but dropdown box data didn't I custom form designed HTML and its working fine with Yii2 but only the data within textboxes is going into database and data within dropdown boxes doesn't go into database.
Sample code:
<form id="form-signup" action="/frontend/web/index.php?r=site%2Fsignup" method="post" role="form">
<input type="text" class="form-control" id="inputFirstName" name="SignupForm[firstName]" placeholder="Type First Name">

    <select onchange="getCountList(this.value)" id="inpCountry" name="SignupForm[region]" class="gwt-ListBox stdTextWidth">
                            <option value="">Select Region</option>
                            <option value="1">Australia and the Pacific</option>
                            <option value="2">Africa</option>
                            <option value="51">Asia</option>
                            <option value="3">Europe</option>
                            <option value="4">North America</option>
                            <option value="5">South America</option>
                          </select>
    </form>

When I submit the form the first name goes into database but the region id doesn't go into database.
My Model:
public function signup()
    {
        if ($this->validate()) {
            $user = new User();
            $user->FirstName = $this->firstName;
            $user->UserRegionID = $this->region;
            if ($user->save()) {
                return $user;
            }
        }

        return null;
    }

In debugger I can see data is being submitted by the form but its not saving in database.
[
    'firstName' => 'Pen'
    'region' => '1'
]

My table name is User and my fields are FirstName and UserRegionID

A: If you don't want to validate some model attributes, in order to massively assign them, you need at least explicitly mark them as safe:
public function rules()
{
    ['UserRegionID', 'safe'],
}

Please read these official documentation sections to better understand validation:

*

*Massive assignment

*Safe attributes

*Validating input


text:
Q: Lisp, While function undefined error with CLISP? I am working on a program in LISP, using CLISP to run the program.
My function has a while statement in it, but CLISP is returning
*** - EVAL: undefined function WHILE

Function is nothing fancy,
(defun heap-insert (heap item key)
  "Put an item into a heap. [Page 150 CL&R]."
  ;; Note that ITEM is the value to be inserted, and KEY is a function
  ;; that extracts the numeric value from the item.
  (vector-push-extend nil heap)
  (let ((i (- (length heap) 1))
    (val (funcall key item)))
    (while (and (> i 0) (>= (heap-val heap (heap-parent i) key) val))
      do (setf (aref heap i) (aref heap (heap-parent i))
               i (heap-parent i)))
        (setf (aref heap i) item)))

A: There's no function or macro (or "statement") with the name while in Common Lisp, so CLISP is right to give you that error message.
Maybe you meant to use the loop macro, which accepts while as part of its syntax.

A: You missed loop before your while
try:
(defun heap-insert (heap item key)
  "Put an item into a heap. [Page 150 CL&R]."
  ;; Note that ITEM is the value to be inserted, and KEY is a function
  ;; that extracts the numeric value from the item.
  (vector-push-extend nil heap)
  (let ((i (- (length heap) 1))
    (val (funcall key item)))
    (loop while (and (> i 0) (>= (heap-val heap (heap-parent i) key) val))
      do (setf (aref heap i) (aref heap (heap-parent i))
               i (heap-parent i)))
        (setf (aref heap i) item)))

A: There is no standard while looping construct in Common Lisp, there is one in Emacs Lisp. However, if you want one, it is relatively simple to make that happen.
(defmacro while (condition &body body)
  `(loop while ,condition
      do (progn ,@body)))


text:
Q: Playing a sound in an AJAX chat I am using the Audio class to play a sound in an AJAX chat when there's a new message. My code:
if ( ! $.browser.msie || ( $.browser.msie && parseFloat(jQuery.browser.version) >= 9 ) )
{
   //var notif = new Audio('http://cycle1500.com/sounds/infbego.wav');
   var notif = new Audio('/media/sounds/drip.wav');
   notif.play();
}

*

*I am checking the version of IE because only 9 seems to support
HTML5 audio. Is there a better way to do it?

*var notif = new
Audio('http://cycle1500.com/sounds/infbego.wav'); works
var notif = new Audio('/media/sounds/drip.wav'); doesn't work
Why not?

*Where can I find documentation on how to construct the Audio class?

A: You can use HTML5 <audio> tag in you application, this will be supported in recent browser version and to support older version you can create fallback.
Clear and beautiful documentation is here.Have a look .
http://html5doctor.com/native-audio-in-the-browser/


text:
Q: It seems like ''break'' here is not functioning Here is the code:
for i in range(12):
  for j in range(8):
    if i == j:
        break

print i
print j

My thought is: at first i is equal to 0 and j is equal to 0. This matches with the

i == j

condition and so

break

would be triggered. It would then exit the innermost for loop. So the value of j would be 0. Since the outer for loop doesn't get exited, i would continue to loop through all the elements in range(12) and at the end i would be assigned 11. So when I printed the values of i and j, they would be 11 an
d 0 respectively.
However the result was:

i = 11 and j == 7

I would like to know which part in my argument above goes wrong.

A: with your code, the output is as below. So it the result is completely as expected and break is functioning well.
When ever i == j is true, the inner loop exists but the outer loop is still running and again loops the inner loop till either i==j is met or inner loop is completely iterated. Thus final output is i = 11 ; j = 7, the final result.
print 'i','j'
for i in range(12):
    for j in range(8):
        print i, j
        if i == j:
            #print " yes "
            break
    print "---------"

print i
print j

output is :
i j
0 0
---------
1 0
1 1
---------
2 0
2 1
2 2
---------
3 0
3 1
3 2
3 3
---------
4 0
4 1
4 2
4 3
4 4
---------
5 0
5 1
5 2
5 3
5 4
5 5
---------
6 0
6 1
6 2
6 3
6 4
6 5
6 6
---------
7 0
7 1
7 2
7 3
7 4
7 5
7 6
7 7
---------
8 0
8 1
8 2
8 3
8 4
8 5
8 6
8 7
---------
9 0
9 1
9 2
9 3
9 4
9 5
9 6
9 7
---------
10 0
10 1
10 2
10 3
10 4
10 5
10 6
10 7
---------
11 0
11 1
11 2
11 3
11 4
11 5
11 6
11 7
---------
11
7


text:
Q: Unique representation of a degenerate simplex I recently learned about simplicial sets, and now I'm studying some basic properties. I've learned that every degenerate simplex is a degeneracy of a unique non-degenerate (nice) simplex. However, I suspect that the entire representation must also be unique.
(This question started as a request for help when I was stuck, but while I was writing the post I figured it out myself, so I end up asking if you could check my proof.)
This means, given a nice simplex $x$  and
$$\large
z = s_{j_n}\cdots s_{j_1}x = s_{i_n}\cdots s_{i_1}x,
\qquad 0\le j_1 <\cdots <j_n, \;\; 0\le i_1 <\cdots< i_n
$$
does this imply that $j_k=i_k$ for all $k$? If $s_j x = s_i x,\ i<j$, for a simplex $x$, then
$$\large
x = d_i s_i x = d_i s_j x = s_{j-1} d_i x
$$
So if $x$ is nice, then $s_j x \ne s_k x$. This can be seen as the induction start.
Assume that the claim is true for $n$.
Let's first consider the case $j_{n+1} > i_{n+1}+1$. If we apply $d_{j_{n+1}}$ to both sides, we get
$$\large
d_{j_{n+1}} z = s_{j_n} \cdots s_{j_1} x =
s_{i_{n+1}} \cdots s_{i_n}d_{j_{n+1}-n-1} x
$$
which means that $d_{j_{n+1}} z$ is degeneracy of $x$ and of $d_{j_{n+1}} x$, but then $d_{j_{n+1}}x$ has to be a degeneracy of $x$. We can conclude that  $j_{n+1}\in\{i_{n+1},i_{n+1}+1\}$.
Clearly, $j_{n+1} = i_{n+1}$ implies by induction that $j_k = i_k$ for all $k$. But what if $j_{n+1}=i_{n+1}+1$?
We can write
$$\large\begin{align}
s_{i_n}\cdots s_{i_1} x
& = d_{i_{n+1}} s_{i_{n+1}} \cdots s_{i_1} x \\
& = d_{i_{n+1}} s_{i_{n+1}+1} \cdots s_{j_1} x \\
& = s_{i_{n+1}} d_{i_{n+1}} s_{j_n} \cdots s_{j_1} x
\end{align}$$
If $i_{n+1} > j_n +1$, the last line would transform into an $(n+1)$-fold degeneracy of $d_{i_{n+1}-n} x$. So $d_{i_{n+1}}s_{j_n}$ must vanish, and we can use the induction hypothesis to conclude  that $i_n = i_{n+1}$, which is a contradiction.
Is this proof correct? And can it be simplified?
Thanks.


text:
Q: Unable to find topsearch template file in magento 1.9.2.4 I am making a custom theme from scratch in magento using bootstrap, i have already raised a question for that purpose i have received really helpful answers.
Now i am on my way to make theme, but currently i am stuck with finding the template .phtml file for top search bar in default theme. I have already searched base theme and google but did not reached anywhere.

A: You can find any template file from
->Go to admin->system->configuration.
-> Switch to the store view on the top left to your current website or store view.
-> Go to Developer on the bottom left under ADVANCED
->Under the Debug tab of the same Developer config page you will see a new option appear that will allow you to turn on/off template path hints.
Search Form File:
app/design/frontend/Your-Package/Your-Theme/template/catalogsearch/form.mini.phtml
In default RWD theme
app/design/frontend/rwd/default/template/catalogsearch/form.mini.phtml

A: Just find form.mini.phtml on this location:

app\design\frontend\base\default\template\catalogsearch

For modify it copy it on your theme like:

app\design\frontend\theme_package\your_theme\template\catalogsearch

Hope it will help you.


text:
Q: why data-inputmask is not working : npmjs I am trying to apply phone number masking. I followed this Documentation and did everything but still, phone masking is not working.

Below is the code.

var template = '\

\
                    Home phone\
                    <input class="form-control" type="text" data-inputmask="\'mask\': \'999-99-9999\'" /> \

\

\
';

self.dialog = puDialogV2.showDialog($('.body-content'), 'Add Contact', template, self, self.addContact, self.cancelSaveContact);

A: Looks like you are following the "via data-inputmask attribute" option in documentation. Most probably you are missing the second part of it. Try adding below code to your javascript part.
$(document).ready(function(){
  // $(":input").inputmask();
  // or
  Inputmask().mask(document.querySelectorAll("input"));
});


text:
Q: Как запретить удаление определенных записей? В таблицу добавил boolean поле deleting. Записи, у которых deleting равно false, удалять нельзя.
Для реализации этого я добавил этот код в модель:
class Item < ApplicationRecord
    before_destroy :can_i_delete_this?

    def can_i_delete_this?
        unless deleting
            errors[:base] << 'This item can not be deleted.'
            return false
        end
    end
end

Но при удалении элемента:
def destroy
    item = Item.find(params[:id])
    item.destroy
    redirect_to action: :index
end

Он без проблем удаляется. Где я свернул не там?
P.S. У удаляемой записи поле deleting имеет значение false.

A: Судя по ApplicationRecord, это Rails 5. А там обрыв цепочки коллбэков путём возврата false больше не работает.
Вместо return false теперь нужен throw(:abort).


text:
Q: Changing the getROW index in apachee POI throw NullPointerException I am trying to write to Excel using apachee POI. It works when the getrow index is 0 like[getrow(o)]. But changing it other than zero throw nullpointer exception.
package fairfoxchecking;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

public class writingInExcel {
    public static void main(String []args) throws IOException {

    File src = new File("D:/Etl_Bug_reporting_Template.xlsx");
    FileInputStream fis = new FileInputStream(src);
    XSSFWorkbook wb = new XSSFWorkbook(fis);
    XSSFSheet sheet1 =wb.getSheetAt(0);

    sheet1.getRow(0).createCell(5).setCellValue("cheasdfasdfasck1");
    sheet1.getRow(1).createCell(5).setCellValue("cheasdfasdfasck1");

    FileOutputStream fout = new FileOutputStream(src);
    wb.write(fout);
    wb.close();
}

A: Before you do create a cell, you have to ensure the row is created.
Try something like,
if(sheet1.getRow(rowIndex) == null)
      sheeet1.createRow(rowIndex)
sheet1.getRow(rowIndex).createCell(colIndex).setCellValue(stringVal);

A: As per this , getRow might return null if it is not defined. So you might have to create one before writing.
sheet1.createRow(index)

Check this lib - seems to be nice.


text:
Q: Strange Nginx Redirects to Foreign Servers I'm seeing some strange redirects in a Rails app, instead of a redirect to /login, there are one-off requests with redirects like:

*

*Redirected to https://www.group-ib.ru/login

*Redirected to https://buybestbiz.net/login

*Redirected to https://swipe.bz/login

*Redirected to https://blackpass.cc/login
I'm not sure how these foreign servers are landing there. I don't see how it can be a hack in my app code, because these are single random instances out of thousands happening in an hour.
I suspect it has something to do with the Nginx config.
try_files $uri/index.html $uri @puma;
location @puma {
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header Host $http_host;
    proxy_redirect off;
    proxy_set_header X-Forwarded-Proto https;
    proxy_pass http://puma;
}

```
What am I missing here?


text:
Q: How to restore Ubuntu broken partition after Windows 7 install I previously had a Windows 7 partition and a Ubuntu partition. When I formatted and reinstalled Windows 7, somehow the Ubuntu partition got corrupted. I can't open it and recover my files even with the Ubuntu Live CD. I can't fix grub because it doesn't find the Ubuntu partition either. I'm 100% sure I didn't delete the Ubuntu partition when I installed Windows 7, I know it's there but it's corrupted. Is there any way I can recover it, or at least recover the files?
This is sudo fdisk -l:
ubuntu@ubuntu:~$ sudo fdisk -l

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

   Device Boot      Start         End      Blocks   Id  System
/dev/sda1   *        2048      206847      102400    7  HPFS/NTFS/exFAT
/dev/sda2          206848   419637247   209715200    7  HPFS/NTFS/exFAT
/dev/sda3       419639294   625141759   102751233    5  Extended
/dev/sda5       616697856   625141759     4221952   82  Linux swap / Solaris

Thanks in advance!

A: There is a gap between the start of the extended partition (at sector 419639294) and the one and only partition it contains (at sector 616697856). That suggests that the Windows installer erased references to the first logical partition. If so, it may be possible to find it again with TestDisk or something similar, but I can make no promises that it will work.

A: According to this fdisk output, there is no GNU/Linux partition on your harddrive that could contain usable data.
/sda1 is the MS Windows 7 boot partition
/sda2 is the MS Windows 7 system partition
/sda3 is the container for logical partitions
/sda5 is a GNU/Linux swap partition on a logical partition, e. g. it is only used to page out system RAM content. It is not permanent storage.
I'm afraid you lost your data, unless you have made a backup.


text:
Q: Datatable Server Side não faz paginação, ordenação nem pesquisa beleza? Então, estou passando o processamento da minha datatable para serverside, devido a lentidão extrema com alto volume de dados. Os dados estão sendo retornados via json encode perfeitamente, porém, a paginação, ordenação e a pesquisa da datatable não estão funcionando. Alguém poderia me ajudar? Segue códigos abaixo.
Código Html + Jquery

      Id Empresa
      Cidade
      Estado

Código PHP da página table_server_processing.php
<?php
/**
 * Script:    DataTables server-side script for PHP 5.2+ and MySQL 4.1+
* Notes:     Based on a script by Allan Jardine that used the old PHP mysql_* functions.
*            Rewritten to use the newer object oriented mysqli extension.
* Copyright: 2010 - Allan Jardine (original script)
*            2012 - Kari Söderholm, aka Haprog (updates)
* License:   GPL v2 or BSD (3-point)
*/

mb_internal_encoding('UTF-8');

/**
 * Array of database columns which should be read and sent back to DataTables. Use a space where
 * you want to insert a non-database field (for example a counter or static image)
 */

$aColumns = array( 'id_empresa', 'cidade', 'estado' );

// Indexed column (used for fast and accurate table cardinality)

$sIndexColumn = "id_empresa";

/* DB table to use */
$sTable = "cadastro_fornec";

/* Database connection information */
$gaSql ['user'] = "connect@cubo";
$gaSql ['password'] = "4c3sso4lm0xcub0c0nn3ct";
$gaSql ['db'] = "voucher";
$gaSql ['server'] = "192.168.20.16";

// Input method (use $_GET, $_POST or $_REQUEST)

$input =& $_GET;

/** * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
 * If you just want to use the basic configuration for DataTables with PHP server-side, there is
 * no need to edit below this line
 */

/**
 * Character set to use for the MySQL connection.
 * MySQL will return all strings in this charset to PHP (if the data is stored correctly in the database).
 */
$gaSql['charset']  = 'utf8';

/**
 * MySQL connection
 */

$db = new mysqli($gaSql['server'], $gaSql['user'], $gaSql['password'], $gaSql['db']);
if (mysqli_connect_error()) {
    die( 'Error connecting to MySQL server (' . mysqli_connect_errno() .') '. mysqli_connect_error() );
}

if (!$db->set_charset($gaSql['charset'])) {
    die( 'Error loading character set "'.$gaSql['charset'].'": '.$db->error );
}

/**
 * Paging
 */
$sLimit = "";
if ( isset( $input['iDisplayStart'] ) && $input['iDisplayLength'] != '-1' ) {
    $sLimit = " LIMIT ".intval( $input['iDisplayStart'] ).", ".intval( $input['iDisplayLength'] );
}

/**
 * Ordering
 */
$aOrderingRules = array();
if ( isset( $input['iSortCol_0'] ) ) {
    $iSortingCols = intval( $input['iSortingCols'] );
    for ( $i=0 ; $i<$iSortingCols ; $i++ ) {
        if ( $input[ 'bSortable_'.intval($input['iSortCol_'.$i]) ] == 'true' ) {
            $aOrderingRules[] =
            "`".$aColumns[ intval( $input['iSortCol_'.$i] ) ]."` "
                    .($input['sSortDir_'.$i]==='asc' ? 'asc' : 'desc');
        }
    }
}

if (!empty($aOrderingRules)) {
    $sOrder = " ORDER BY ".implode(", ", $aOrderingRules);
} else {
    $sOrder = "";
}

/**
 * Filtering
 * NOTE this does not match the built-in DataTables filtering which does it
 * word by word on any field. It's possible to do here, but concerned about efficiency
 * on very large tables, and MySQL's regex functionality is very limited
 */
$iColumnCount = count($aColumns);

if ( isset($input['sSearch']) && $input['sSearch'] != "" ) {
    $aFilteringRules = array();
    for ( $i=0 ; $i<$iColumnCount ; $i++ ) {
        if ( isset($input['bSearchable_'.$i]) && $input['bSearchable_'.$i] == 'true' ) {
            $aFilteringRules[] = "`".$aColumns[$i]."` LIKE '%".$db->real_escape_string( $input['sSearch'] )."%'";
        }
    }
    if (!empty($aFilteringRules)) {
        $aFilteringRules = array('('.implode(" OR ", $aFilteringRules).')');
    }
}

// Individual column filtering

for ( $i=0 ; $i<$iColumnCount ; $i++ ) {
    if ( isset($input['bSearchable_'.$i]) && $input['bSearchable_'.$i] == 'true' && $input['sSearch_'.$i] != '' ) {
        $aFilteringRules[] = "`".$aColumns[$i]."` LIKE '%".$db->real_escape_string($input['sSearch_'.$i])."%'";
    }
}

if (!empty($aFilteringRules)) {
    $sWhere = " WHERE ".implode(" AND ", $aFilteringRules);
} else {
    $sWhere = "";
}

/**
 * SQL queries
 * Get data to display
 */
$aQueryColumns = array();
foreach ($aColumns as $col) {
    if ($col != ' ') {
        $aQueryColumns[] = $col;
    }
}

$sQuery = "
    SELECT SQL_CALC_FOUND_ROWS " . str_replace ( " , ", " ", implode ( ", ", $aColumns ) ) . "
    FROM `".$sTable;

$rResult = $db->query( $sQuery ) or die($db->error);

// Data set length after filtering

$sQuery = "SELECT FOUND_ROWS()";
$rResultFilterTotal = $db->query( $sQuery ) or die($db->error);
list($iFilteredTotal) = $rResultFilterTotal->fetch_row();

// Total data set length

$sQuery = "SELECT COUNT(`".$sIndexColumn."`) FROM `".$sTable."`";
$rResultTotal = $db->query( $sQuery ) or die($db->error);
list($iTotal) = $rResultTotal->fetch_row();

/**
 * Output
 */
$output = array(
        "sEcho"                => intval($input['sEcho']),
        "iTotalRecords"        => $iTotal,
        "iTotalDisplayRecords" => $iFilteredTotal,
        "aaData"               => array(),
);

while ( $aRow = $rResult->fetch_assoc() ) {
    $row = array();
    for ( $i=0 ; $i<$iColumnCount ; $i++ ) {
        if ( $aColumns[$i] == 'version' ) {
            // Special output formatting for 'version' column
            $row[] = ($aRow[ $aColumns[$i] ]=='0') ? '-' : $aRow[ $aColumns[$i] ];
        } elseif ( $aColumns[$i] != ' ' ) {
            // General output
            $row[] = $aRow[ $aColumns[$i] ];
        }
    }
    $output['aaData'][] = $row;
}

echo json_encode($output);

A: Você precisa utilizar na sua query principal as partes do SQL que o script monta e que vão efetivamente fazer suas devidas funções, algo como:
$sQuery = "
    SELECT SQL_CALC_FOUND_ROWS " . str_replace ( " , ", " ", implode ( ", ", $aColumns ) ) . "
    FROM `".$sTable . $sWhere . $sOrder . $sLimit;


text:
Q: How to check multiple columns of a dataframe for a value and get the column names and the value as lists in new columns? I am trying to get see if the pandas dataframe columns as values from a list.
    df = pd.DataFrame({'id':[np.nan,2,3,4,5,6],
                      'column1':[np.nan,10,15,20,25,25],
                      'column2':[np.nan,4,6,8,10,np.nan],
                       'column3':[np.nan,6,9,12,np.nan,15],
                      'column4':[np.nan,np.nan,np.nan,np.nan,np.nan,np.nan]})

    lst = ['4','6','10','25']
    cols = ['column1','column2','column3','column4']

I am trying to check the value of lst in the multiple columns in df and get the column names of the df if value exist in the df.
The result I am looking for is:

The result I am getting is in True and False.
I was able to get result but not result1:
I got result by
m1  = df[cols].isin(lst)
m2 = pd.DataFrame((~m1.any(1)).to_numpy()[:, None] &  df[cols].eq(2).to_numpy(),
                       index=m1.index, columns=m1.columns)

m = (m1 | m2)

df['result'] = m.where(m).stack().reset_index().groupby('level_0')['level_1'].agg(list)

A: Here is one way to do it:
import numpy as np
import pandas as pd

df = pd.DataFrame(
    {
        "id": [np.nan, 2, 3, 4, 5, 6],
        "column1": [np.nan, 10, 15, 20, 25, 25],
        "column2": [np.nan, 4, 6, 8, 10, np.nan],
        "column3": [np.nan, 6, 9, 12, np.nan, 15],
        "column4": [np.nan, np.nan, np.nan, np.nan, np.nan, np.nan],
    }
)

# Setup
lst = ["4", "6", "10", "15", "25"]
cols = ["column1", "column2", "column3", "column4"]
result = [[] for _ in range(df.shape[0])]
result1 = [[] for _ in range(df.shape[0])]

# Iterate and record results
for col in cols:
    for i, x in enumerate(df[col]):
        if x in df[col].tolist():
            result[i].append(x)
            result1[i].append(col)

# Add results rto dataframe
df = df.assign(result=result, result1=result1)

print(df)
# Output
    id  column1  column2  ...  column4             result                      result1
0  NaN      NaN      NaN  ...      NaN                 []                           []
1  2.0     10.0      4.0  ...      NaN   [10.0, 4.0, 6.0]  [column1, column2, column3]
2  3.0     15.0      6.0  ...      NaN   [15.0, 6.0, 9.0]  [column1, column2, column3]
3  4.0     20.0      8.0  ...      NaN  [20.0, 8.0, 12.0]  [column1, column2, column3]
4  5.0     25.0     10.0  ...      NaN       [25.0, 10.0]           [column1, column2]
5  6.0     25.0      NaN  ...      NaN       [25.0, 15.0]           [column1, column3]


text:
Q: checking diagonals in 2d list (Python) The initial problem: for a given 3x3 tic tac toe board check if one of the players has won.
The simplest solution I have come up so far is rotating the matrix and summing up each row:
board
[[0, 1, 2], [3, 4, 5], [6, 7, 8]]

pr(board)
0 1 2
3 4 5
6 7 8

pr(zip(*board))
0 3 6
1 4 7
2 5 8

0..9 numbers above are just for showing positions on the board, normally they would be filled with 1 for player 1 and -1 for player 2 and 0 for unfilled position. Go row by row and if it sums up to 3 or -3 this is the winning block.
However, diagonals are not checked. Is there some way to extract diagonals from such matrix in elegant + highly performant way? I don't mean using trivial indexes "manually" (0, 1, 2), but rather get diagonal of n x n matrix.
P.S. pr is just a helper function for printing 2d list:
def pr(x):
    for row in x:
        print ' '.join(map(str, row))

A: Number your game field with a magic square
2|9|4
7|5|3
6|1|8

Now sum up after three moves and check if the sum is 15 --> Winner. You have to check this for every player. Surely you have to recheck after 4th move and 5th move (only the player that started the game)
This is how I solved this problem in my first Java class.

A: Probably what you need is in numpy, see Get all the diagonals in a matrix/list of lists in Python. Maybe you can use this, and flip it like you did to get the other solution.
if sum(board[i][i] for i in (0, 1, 2)) in (-3, 3):
    true

A: The diagonals on a square board lie either where the indices are equal, so for a 3x3 board they are
board[0][0], board[1][1], and board[2][2] or where the two sum to the board size-1 (3 places in this case): such as board[0][2], board[1][1], and board[2][0] -- notice that board[1][1] is included in both sets, as it should be. These facts makes it fairly easy to write Python code to compute them:
board = [[0, 1, 2], [3, 4, 5], [6, 7, 8]]
BOARD_SIZE = len(board)

diags1 = [board[i][i] for i in xrange(BOARD_SIZE)]
diags2 = [board[i][BOARD_SIZE-1-i] for i in xrange(BOARD_SIZE)]

print diags1
print diags2

Output:
[0, 4, 8]
[2, 4, 6]

A: You can get one diagonal with:
[r[i] for i, r in enumerate(board)]
# [0, 4, 8]

And the opposite diagonal with:
[r[-i-1] for i, r in enumerate(board)]
# [2, 4, 6]

A: This will give you a list containing the diagonal elements of one direction (top left to bottom right):
[board[i][i] for i in range(len(board))]

This will do the same for the opposite direction:
[board[i][len(board)-i-1] for i in range(len(board))]

A: tmp_diagonals = [set(), set()]
    num = 0
    for idx in range(len(board) - 1, -1, -1):
        tmp_diagonals[0].add(board[num][num])
        tmp_diagonals[1].add(board[num][idx])
        num += 1


text:
Q: How to stop a random ramp in FCGI Processes Killing the server So got the below earlier to day...
Around that time the logs show a ramp in processes(600) and associated memory (1.2g), cpu usage load average (80) untill the server gave out.
Server had to be hard reset by host as there was no ssh or plesk panel access.
Fast CGI is configured as below and is setup for one high use site. As I understand it  FcgidMaxProcesses 20 should protect against what happen but has not.
I've read many forums with differing answers and references to many different fcgi directives, but have found nothing conclusive.  Any one got some definitive answers on how to stop this sort of server process ramping and subsequent server failure?
If you need more info let me know.
Cheers Andy
 /var/log/apache2/error_log
[Thu May 17 07:40:47 2012] [warn] mod_fcgid: process 17651 graceful kill fail, sending SIGKILL
[Thu May 17 07:40:47 2012] [warn] mod_fcgid: process 17650 graceful kill fail, sending SIGKILL
[Thu May 17 07:40:47 2012] [warn] mod_fcgid: process 17649 graceful kill fail, sending SIGKILL
[Thu May 17 07:40:47 2012] [warn] mod_fcgid: process 17644 graceful kill fail, sending SIGKILL
[Thu May 17 07:40:47 2012] [warn] mod_fcgid: process 17643 graceful kill fail, sending SIGKILL
[Thu May 17 07:40:47 2012] [warn] mod_fcgid: process 17638 graceful kill fail, sending SIGKILL
[Thu May 17 07:40:47 2012] [warn] mod_fcgid: process 17633 graceful kill fail, sending SIGKILL
[Thu May 17 07:40:47 2012] [warn] mod_fcgid: process 17627 graceful kill fail, sending SIGKILL
[Thu May 17 07:40:47 2012] [warn] mod_fcgid: process 17622 graceful kill fail, sending SIGKILL
[Thu May 17 07:40:51 2012] [warn] mod_fcgid: process 17674 graceful kill fail, sending SIGKILL
[Thu May 17 07:40:51 2012] [warn] mod_fcgid: process 17673 graceful kill fail, sending SIGKILL
[Thu May 17 07:40:51 2012] [warn] mod_fcgid: process 17672 graceful kill fail, sending SIGKILL
[Thu May 17 07:40:51 2012] [warn] mod_fcgid: process 17667 graceful kill fail, sending SIGKILL
[Thu May 17 07:40:51 2012] [warn] mod_fcgid: process 17666 graceful kill fail, sending SIGKILL
[Thu May 17 07:40:51 2012] [warn] mod_fcgid: process 17665 graceful kill fail, sending SIGKILL
[Thu May 17 07:40:51 2012] [warn] mod_fcgid: process 17664 graceful kill fail, sending SIGKILL
[Thu May 17 07:40:51 2012] [warn] mod_fcgid: process 17659 graceful kill fail, sending SIGKILL
[Thu May 17 07:40:51 2012] [warn] mod_fcgid: process 17658 graceful kill fail, sending SIGKILL
[Thu May 17 07:40:51 2012] [warn] mod_fcgid: process 17657 graceful kill fail, sending SIGKILL
[Thu May 17 07:40:51 2012] [warn] mod_fcgid: process 17656 graceful kill fail, sending SIGKILL
[Thu May 17 07:40:51 2012] [warn] mod_fcgid: process 17651 graceful kill fail, sending SIGKILL

https://docs.google.com/a/thesugarrefinery.com/open?id=0B_XbpWChge0VRmFLWEZfR2VBb2M
https://docs.google.com/a/thesugarrefinery.com/open?id=0B_XbpWChge0VWTcwZEhoV2Fqejg
https://docs.google.com/a/thesugarrefinery.com/open?id=0B_XbpWChge0VUUtVWWFINHZjZ0U
https://docs.google.com/a/thesugarrefinery.com/open?id=0B_XbpWChge0VZEVMclh6ZUdaOUE
<IfModule mod_fcgid.c>

<IfModule !mod_fastcgi.c>
    AddHandler fcgid-script fcg fcgi fpl
</IfModule>
  FcgidIPCDir /var/lib/apache2/fcgid/sock
  FcgidProcessTableFile /var/lib/apache2/fcgid/shm

  FcgidIdleTimeout 40
  FcgidProcessLifeTime 30
  FcgidMaxProcesses 20
  FcgidMaxProcessesPerClass 20
  FcgidMinProcessesPerClass 0
  FcgidConnectTimeout 30
  FcgidIOTimeout 120
  FcgidInitialEnv RAILS_ENV production
  FcgidIdleScanInterval 10
  FcgidMaxRequestLen 1073741824
</IfModule>

A: There was a bug in Debian (at least) that rendered the limit useless with virtual hosts. It is fixed now.
http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=615814

A: This is often caused by a setuid CGI script that hangs; it exceeds the IOtimeout, and apache tries to kill it, but is unable because of the change in uid, resulting in the error.
You may want to increase the FcgidIOTimeout or FcgidProcessLifetime to allow the thread more time to complete.
Another workaround is to make the Apache server run under the same UID that the setuid script is chaning to.  This allows it to kill the process, though it may not be advisable for security reasons.  Similarly, running apache as root is also a workaround but not very secure.  If you do this, note that your fcgi sock directory (under /var/lib/apache2/fcgid/sock or similar) and process table file need to be writeable by the apache process owner.
The root cause, though, is the CGI script itself taking too long.  The cause for that depends on the CGI code which I have no visibiilty of.


text:
Q: SVM results in Rapidminer much worse than in knime I'm comparing various classification algorithms for a project using knime. I was very happy with the results I got for Support Vector Machines (LibSVM).
I then wanted to try hierarchical classification and installed the Rapidminer plugin for knime. To get things to work I first tested the SVM implementation without hierarchies.
Comparing the results of the knime LibSVM implementation and the rapidminer LibSVM implementation I noticed that the rapidminer implementation yielded worse results.
The knime implementation in fact produced an error rate of approximately 2.4% while the rapidminer one produced an error rate of approx. 61%.
Why is that? Am I doing something wrong?

I use C-SVC SVMs with linear kernel, 1.0 Cost, 0.001 epsilon and 80mb cache for both implementations.

The documents are wikipedia article texts, preprocessed, transformed to a binary document vector and labeled with some kind of type.
I hope you can help me.

A: You do not need to include the Row IDs in this case (Row ID tab, make to button show Do not use by clicking on it in case it is Use and the text field is not disabled), and you should not perform Nominal to... transformations on them. After that, you should get similar results in both cases.


text: Q: How to get data attribute from HTML option value, and parse into integer, using javascript? I am trying to build a nutrition calculator, and this is just a very very basic start to my code. I am trying to figure out how to have more than one value for each dropdown select option. I am using data-attributes to do this. For example, in my code below, the "original" option is "value = 5 data-fat = 13" meaning there are 5 calories and 13 grams of fat. I am trying to parse these integers out using javascript. My code below functions, but it only prints the calories, and it doesn't print it as an integer. Please send any advice you can! I am new to coding in javascript :P


text:
Q: PHP simpleXML: Read XML, add node and save I'm having some problems with adding a xml node to its parent.
I receive variables $cat, $title and $isbn.
I want to parse $title and $isbn to an XML node and add it to the right categorie ($cat).
die(var_dump($parent)); --> returns NULL, so the biggest problem (I think) is that I can't figure out how to add my node to the right parent because I cant get it identified.
Any suggestions?
The XML file:
<?xml version="1.0"?>
<books version="1.0">
  <categorie name="catone" id="100">
    <book title="1_WS2012" isbn="isbnone" />
    <book title="1W2012DHCP" isbn="ibsntwo" />
  </categorie>
  <categorie title="cattwo" id="101">
    <book title="2W2008R2DC" isbn="isbnthree" />
  </categorie>
  <categorie title="catthree" id="103">
    <book title="3SBS" isbn="isbnfout=" />
  </categorie>
</books>

The Code:
//Get variables
$cat = "catone";
$title = "testtitle";
$isbn = "testisbn";

$xmlDoc = simplexml_load_file("books.xml");
$parent = null;

//Construct node
$childstring = "<book></book>";
$child = new SimpleXMLElement($childstring);
$child->addAttribute('title', $title);
$child->addAttribute('isbn', $isbn);
//This works (results in <book title="testtile" isbn="testisbn" />)

//Add node to correct parent
for ($i=0; $i <= sizeof($xmlDoc->categorie) -1; $i++) {

  //The condition does also work
  if (strtoupper($xmlDoc->categorie[$i]->attributes()->name) == strtoupper($cat))
  {
    //I'm stuck here
    $parent = $xmlDoc->categorie[$i]->attributes()->xpath('/object/data[@type="me"]');;
    $xmlDoc->$parent->addChild($child);
  }
}

//Write file
file_put_contents("books.xml", $xmlDoc->asXML());

Desired result:
<books version="1.0">
  <categorie name="catone" id="100">
    <book title="1_WS2012" isbn="isbnone" />
    <book title="1W2012DHCP" isbn="ibsntwo" />
    <book title="testtitle" isbn"testisbn" />
  </categorie>
  <categorie title="cattwo" id="101">
    <book title="2W2008R2DC" isbn="isbnthree" />
  </categorie>
  <categorie title="catthree" id="103">
    <book title="3SBS" isbn="isbnfout=" />
  </categorie>
</books>

A: First, use xpath to select the parent. xpath is like SQL for XML:
$xml = simplexml_load_string($x); // assume XML in $x
$parent = $xml->xpath("/books/categorie[@name = 'catone']")[0];

Note: The above code requires PHP >= 5.4 for the [0] at the end of line 2. (1)
Now, add the new <book> and its attributes:
$new = $parent->addChild("book","");
$new->addAttribute("title", "testtitle");
$new->addAttribute("isbn", "testisbn");

see it working: https://eval.in/131009
(1) if you are on PHP < 5.4, either update or do:
$parent = $xml->xpath("/books/categorie[@name = 'catone']");
$parent = $parent[0];


text:
Q: JS disable beforeunload event handler for a specific case I have an event handler for the beforeunload window event.
window.addEventListener("beforeunload", myScript);

I also have an A tag which his href is a download file link. So when I click on the link the browser file download popup opens and it causes the beforeunload to get fire. How can I prevent this from this specific link?
 Download

A: open a new tab
Download


text:
Q: How to clear fields in a form after hitting submit? I tried
c.clear(),

accts.clear() and
contacts.clear()

on the controller after Insert c but it didn't work.
Visualforce page
<apex:page controller="SubmitCaseController">

Submit New Case

    <apex:form >
        <apex:pageMessages />

                Your Name:
                <apex:inputText value="{!Name}"/>

                Your Email:
                <apex:inputText value="{!Email}"/>

                Your Account Number:
                <apex:inputText required="true" value="{!acctNum}"/>

                Title:
                <apex:inputText required="true" value="{!Subject}"/>

                Your Problem:
                <apex:inputTextArea required="true" rows="5" value="{!Description}"/>

                <apex:commandButton value="Submit Case" action="{!submitCase}"/>

    </apex:form>

</apex:page>

Controller
public with sharing class SubmitCaseController {

    public Case c { get; set; }

    public String acctNum { get; set; }
    public String Name{ get; set; }
    public String email { get; set; }
    public String Subject { get; set; }
    public String Description { get; set; }

    public SubmitCaseController() {
        c = new Case();
    }

    public PageReference submitCase() {
     List<Account> accts = [SELECT Id, Name FROM Account WHERE AccountNumber = :acctNum];
        Contact contacts = [SELECT Id, Email FROM Contact WHERE Email= :email];

            if (accts.size() != 1) {
            ApexPages.Message msg = new ApexPages.Message(ApexPages.Severity.FATAL, 'Invalid account number');
            ApexPages.addMessage(msg);
            return null;
        } else {
            try {
                c.AccountId = accts.get(0).Id;
                c.SuppliedEmail = email;
                c.ContactId = contacts.Id;
                c.Subject = Subject;

  Database.DMLOptions dmlOpts = new Database.DMLOptions();
                dmlOpts.assignmentRuleHeader.useDefaultRule = true;
                c.setOptions(dmlOpts);

 INSERT c;

            ApexPages.Message msg = new ApexPages.Message(ApexPages.Severity.CONFIRM, 'Success! Your case has been registered.');
            ApexPages.addMessage(msg);

                return null;
 } catch (Exception e) {
                ApexPages.addMessages(e);
                return null;
            }
        }
    }
}

A: Added a few lines:

try {
                c.AccountId = accts.get(0).Id;
                c.SuppliedEmail = email;
                c.ContactId = contacts.Id;
                c.Subject = Subject;

  Database.DMLOptions dmlOpts = new Database.DMLOptions();
                dmlOpts.assignmentRuleHeader.useDefaultRule = true;
                c.setOptions(dmlOpts);

 INSERT c;

            ApexPages.Message msg = new ApexPages.Message(ApexPages.Severity.CONFIRM, 'Success! Your case has been registered.');
            ApexPages.addMessage(msg);
//----ADD------
c = new Case();
acctNum = null;
Name = null;
email = null;
Subject = null;
Description = null;
//----------
                return null;
 } catch (Exception e) {
                ApexPages.addMessages(e);
                return null;
            }

Just need to clear the info in those fields.


text:
Q: Javascript - encodeURI() returing different results in different browsers I use encodeURI() to encode a php request url, it works perfectly fine in Firefox and Chrome but it doesn't in IE/Edge.
The actual url is:
http://localhost/get.php?id=e_e2&title=e2&desc=just a note&stime=6/12/2015, 1:00:00 AM&etime=15/12/2015, 1:00:00 PM
What Firefox returns is (works):
http://localhost/get.php?id=e_HO%20Event%201&title=HO%20Event%201&desc=This%20is%20just%20a%20test%20event%20of%20this%20handover%20only&stime=6/12/2015,%201:00:00%20AM&etime=10/12/2015,%201:00:00%20PM
What IE returns (Break the php code):
http://localhost/get.php?id=e_HO%20Event%201&title=HO%20Event%201&desc=This%20is%20just%20a%20test%20event%20of%20this%20handover%20only&stime=%E2%80%8E6%E2%80%8E/%E2%80%8E12%E2%80%8E/%E2%80%8E2015%E2%80%8E%20%E2%80%8E1%E2%80%8E:%E2%80%8E00%E2%80%8E:%E2%80%8E00%E2%80%8E%20%E2%80%8EAM&etime=%E2%80%8E10%E2%80%8E/%E2%80%8E12%E2%80%8E/%E2%80%8E2015%E2%80%8E%20%E2%80%8E1%E2%80%8E:%E2%80%8E00%E2%80%8E:%E2%80%8E00%E2%80%8E%20%E2%80%8EPM
I have tried to decode what IE returns but it caused me a lots of problems!, so is there an alternatives to encodeURI() ?, FF seems to work even if I dont encode the url, where IE works if I copy the FF encoded url to it!

update:
example code link
I think it has something to do with toLocaleString()

Final update:
As few answered, it was some weard marks in the link "appears only in IE!" I had to filter and changes what my php script date format to remove the comma
function FixLocaleDateString(localeDate) {
    var newStr = "";
    for (var i = 0; i < localeDate.length; i++) {
        var code = localeDate.charCodeAt(i);
            if (code != 44 && code != 8206 ) {
                newStr += localeDate.charAt(i);
            }
    }
        return newStr;
}

I found this function in another answer and modify it: ToLocaleDateString() changes in IE11

A: The problem is not encodeURI (though as others have pointed out, you should never use encodeURI, but rather encode individual components with encodeURIComponent and then join them together).
The problem is that the dates for some reason contains lots of U+200E "LEFT-TO-RIGHT MARK" characters (which are invisible, but still present), which once encoded become %E2%80%8E.
Show us where/how you get the times, or filter the time strings to remove those characters before encoding.

A: Define a simple params object to represent desired URL parameters and glue its items. If there some incorrect characters in the properties, you need to filter them out before encodeURIComponent() call.
var params = {
  'id': 'e_'.concat(event.title.toString()),
  'title': event.title.toString(),
  'desc': event.description.toString(),
  'stime': stime.toString(),
  'etime': etime.toString()
};

var chunks = [];
for (var property in params) {
  if (params.hasOwnProperty(property)) {
    chunks.push(property.concat('=', encodeURIComponent(params[property])));
  }
}
var href = 'http://localhost/get.php?'.concat(chunks.join('&'));

console.log(href);

A: Use encodeURIComponent when you want to encode a URL parameter.
Here is some useful links
When are you supposed to use escape instead of encodeURI / encodeURIComponent?
https://coderwall.com/p/y347ug/encodeuri-vs-encodeuricomponent


text:
Q: Angular 4 basic routing I'm trying to show different htmls for different urls. When user types basic url he should see maincomponent.html, when application recognizes there is additional /admin subpath it should show admin.html. Both are modules. As far as I know, Routes makes it possible. How can I achieve that?
app.module.ts:
    import { AppComponent } from './app.component';
    import { NgModule } from '@angular/core';

    import { BrowserModule } from '@angular/platform-browser';
    import {Routes, RouterModule} from "@angular/router";

    import { AdminModule } from './Admin/admin.module';
    import { MainpageModule } from './Mainpage/mainpage.module';

    const appRoutes: Routes = [
      {path: 'admin', component: AdminModule},
      {path: '', component: MainpageModule}
    ];

    @NgModule({
      declarations: [
        AppComponent
      ],
      imports: [
        MainpageModule,
        AdminModule,
        BrowserModule,
        RouterModule.forRoot(
          appRoutes, {enableTracing: true}
        )
      ],
      providers: [],
      bootstrap: [AppComponent]
    })
    export class AppModule { }

mainpage.module.ts
    import { NgModule } from '@angular/core';
    import { CommonModule } from '@angular/common';
    import {MainpageComponent} from './mainpage.component'

    import { HeaderComponent } from './Header/header.component';
    import { FooterComponent } from './Footer/footer.component';
    import { SidebarComponent } from './Sidebar/sidebar.component';
    import { BottompanelComponent } from './Bottompanel/bottompanel.component'
    import { CarouselComponent } from './Carousel/carousel.component'

    @NgModule({
      declarations: [
        MainpageComponent,
        HeaderComponent,
        FooterComponent,
        SidebarComponent,
        BottompanelComponent,
        CarouselComponent
      ],
      imports: [CommonModule],
      entryComponents: [MainpageComponent],
      exports: [MainpageComponent],
      providers: [],
      bootstrap: []
    })

    export class MainpageModule {}

admin.module.ts:
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';

import {AdminComponent} from './admin.component'

@NgModule({
  declarations: [
    AdminComponent,
  ],
  imports: [CommonModule],
  exports: [AdminComponent],
  providers: [],
  bootstrap: []
})

export class AdminModule {}

However it doesn't works, I can't see anything, just blank site. This is my log output:
Router Event: NavigationStart
platform-browser.js:367 NavigationStart(id: 1, url: '/')
platform-browser.js:367 NavigationStart {id: 1, url: "/"}
core.js:3687 Angular is running in the development mode. Call enableProdMode() to enable the production mode.
platform-browser.js:380 Router Event: RoutesRecognized
platform-browser.js:367 RoutesRecognized(id: 1, url: '/', urlAfterRedirects: '/', state: Route(url:'', path:'') { Route(url:'', path:'') } )
platform-browser.js:367 RoutesRecognized {id: 1, url: "/", urlAfterRedirects: "/", state: RouterStateSnapshot}
platform-browser.js:380 Router Event: GuardsCheckStart
platform-browser.js:367 GuardsCheckStart(id: 1, url: '/', urlAfterRedirects: '/', state: Route(url:'', path:'') { Route(url:'', path:'') } )
platform-browser.js:367 GuardsCheckStart {id: 1, url: "/", urlAfterRedirects: UrlTree, state: RouterStateSnapshot}
platform-browser.js:380 Router Event: ChildActivationStart
platform-browser.js:367 ChildActivationStart(path: '')
platform-browser.js:367 ChildActivationStart {snapshot: ActivatedRouteSnapshot}
platform-browser.js:380 Router Event: ActivationStart
platform-browser.js:367 ActivationStart(path: '')
platform-browser.js:367 ActivationStart {snapshot: ActivatedRouteSnapshot}
platform-browser.js:380 Router Event: GuardsCheckEnd
platform-browser.js:367 GuardsCheckEnd(id: 1, url: '/', urlAfterRedirects: '/', state: Route(url:'', path:'') { Route(url:'', path:'') } , shouldActivate: true)
platform-browser.js:367 GuardsCheckEnd {id: 1, url: "/", urlAfterRedirects: UrlTree, state: RouterStateSnapshot, shouldActivate: true}
platform-browser.js:380 Router Event: ResolveStart
platform-browser.js:367 ResolveStart(id: 1, url: '/', urlAfterRedirects: '/', state: Route(url:'', path:'') { Route(url:'', path:'') } )
platform-browser.js:367 ResolveStart {id: 1, url: "/", urlAfterRedirects: UrlTree, state: RouterStateSnapshot}
platform-browser.js:380 Router Event: ResolveEnd
platform-browser.js:367 ResolveEnd(id: 1, url: '/', urlAfterRedirects: '/', state: Route(url:'', path:'') { Route(url:'', path:'') } )
platform-browser.js:367 ResolveEnd {id: 1, url: "/", urlAfterRedirects: UrlTree, state: RouterStateSnapshot}
platform-browser.js:380 Router Event: ActivationEnd
platform-browser.js:367 ActivationEnd(path: '')
platform-browser.js:367 ActivationEnd {snapshot: ActivatedRouteSnapshot}
platform-browser.js:380 Router Event: ChildActivationEnd
platform-browser.js:367 ChildActivationEnd(path: '')
platform-browser.js:367 ChildActivationEnd {snapshot: ActivatedRouteSnapshot}
platform-browser.js:380 Router Event: NavigationEnd
platform-browser.js:367 NavigationEnd(id: 1, url: '/', urlAfterRedirects: '/')
platform-browser.js:367 NavigationEnd {id: 1, url: "/", urlAfterRedirects: "/"}

EDIT: according to answers I edited app.module.ts and added <router-outlet></router-outlet> to app.component.html.
app.module.ts:
import { AppComponent } from './app.component';
import { NgModule } from '@angular/core';

import { BrowserModule } from '@angular/platform-browser';
import {Routes, RouterModule} from "@angular/router";

import { AdminComponent } from './Admin/admin.component';
import { MainpageComponent } from './Mainpage/mainpage.component';

const appRoutes: Routes = [
  {path: 'admin', component: AdminComponent},
  {path: '', component: MainpageComponent}
];

@NgModule({
  declarations: [
    MainpageComponent,
    AdminComponent,
    AppComponent
  ],
  imports: [
    BrowserModule,
    RouterModule.forRoot(
      appRoutes, {enableTracing: true}
    )
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

Now i see these errors:
compiler.js:485 Uncaught Error: Template parse errors:
'app-header' is not a known element:
1. If 'app-header' is an Angular component, then verify that it is part of this module.
2. If 'app-header' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message. ("[ERROR ->]<app-header></app-header>

"): ng:///AppModule/MainpageComponent.html@0:0
'app-sidebar' is not a known element:
1. If 'app-sidebar' is an Angular component, then verify that it is part of this module.
2. If 'app-sidebar' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message. ("

          [ERROR ->]<app-sidebar></app-sidebar>

"): ng:///AppModule/MainpageComponent.html@4:10
'app-carousel' is not a known element:
1. If 'app-carousel' is an Angular component, then verify that it is part of this module.
2. If 'app-carousel' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message. ("

        [ERROR ->]<app-carousel></app-carousel>
        <app-bottompanel></app-bottompanel>

"): ng:///AppModule/MainpageComponent.html@7:8
'app-bottompanel' is not a known element:
1. If 'app-bottompanel' is an Angular component, then verify that it is part of this module.
2. If 'app-bottompanel' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message. ("

        <app-carousel></app-carousel>
        [ERROR ->]<app-bottompanel></app-bottompanel>

"): ng:///AppModule/MainpageComponent.html@8:8
'app-footer' is not a known element:
1. If 'app-footer' is an Angular component, then verify that it is part of this module.
2. If 'app-footer' is a Web Component then add 'CUSTOM_ELEMENTS_SCHEMA' to the '@NgModule.schemas' of this component to suppress this message. ("

[ERROR ->]<app-footer></app-footer>
"): ng:///AppModule/MainpageComponent.html@12:0
    at syntaxError (compiler.js:485)
    at TemplateParser.parse (compiler.js:24668)
    at JitCompiler._parseTemplate (compiler.js:34621)
    at JitCompiler._compileTemplate (compiler.js:34596)
    at eval (compiler.js:34497)
    at Set.forEach (<anonymous>)
    at JitCompiler._compileComponents (compiler.js:34497)
    at eval (compiler.js:34367)
    at Object.then (compiler.js:474)
    at JitCompiler._compileModuleAndComponents (compiler.js:34366)

This is how my structure looks like:

A: Unless you are doing lazy loading, your routes definition must point to components, not modules.
const appRoutes: Routes = [
  {path: 'admin', component: AdminComponent},
  {path: '', component: MainpageComponent }
];

Also make sure that you have <router-outlet></router-outlet> in you app.component.html

A: read about routing in google guide it has beautiful, full things you need to know first:
https://angular.io/guide/router

A: Ok I found a solution. The problem was I did not declared components in app.module.ts, also in submodules we can remove that declarations. Finally it should look that:
app.module.ts:
import { AppComponent } from './app.component';
import { NgModule } from '@angular/core';

import { BrowserModule } from '@angular/platform-browser';
import { Routes, RouterModule } from "@angular/router";

import { AdminComponent } from './Admin/admin.component';
import { MainpageComponent } from './Mainpage/mainpage.component';

import { HeaderComponent } from './mainpage/header/header.component'
import { FooterComponent } from './mainpage/footer/footer.component';
import { SidebarComponent } from './mainpage/sidebar/sidebar.component';
import { BottompanelComponent } from './mainpage/bottompanel/bottompanel.component'
import { CarouselComponent } from './mainpage/carousel/carousel.component'

const appRoutes: Routes = [
  { path: 'admin', component: AdminComponent },
  { path: 'home', component: MainpageComponent },
  { path: '', redirectTo: '/home', pathMatch: 'full' }
];

@NgModule({
  declarations: [
    MainpageComponent,
    HeaderComponent,
    FooterComponent,
    SidebarComponent,
    BottompanelComponent,
    CarouselComponent,
    AdminComponent,
    AppComponent
  ],
  imports: [
    BrowserModule,
    RouterModule.forRoot(
      appRoutes, { enableTracing: true }
    )
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

mainpage.module.ts:
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';

import {MainpageComponent} from './mainpage.component'

 @NgModule({
  declarations: [
    MainpageComponent
  ],
  imports: [BrowserModule],
  exports: [MainpageComponent],
  providers: [],
  bootstrap: []
})

export class MainpageModule {}

admin.module.ts:
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';

import {AdminComponent} from './admin.component'

@NgModule({
  declarations: [
    AdminComponent,
  ],
  imports: [CommonModule],
  exports: [AdminComponent],
  providers: [],
  bootstrap: []
})

export class AdminModule {}

Thanks for your help guys :)


text:
Q: Test telephone numbers for Twilio Does Twilio have any "test" telephone numbers that I can use to emulate outbound calls? For example, I'd like to be able to test my app to the fullest, getting back asynchronous responses (like I would normally expect to) for calls that are busy, answering machines, out-of-order, invalid numbers etc.
There are a few numbers you can use for SMS messages - but these all return simple, immediate responses, and not the kind of asynchronous ones you'd expect through voice calls that are being handled through TwilXML.
How am I supposed to test all this functionality without making calls to tons of "live" numbers?

A: Twilio evangelist here.
Have you looked at using Test Credentials?  These are a special set of credentials and magic phone numbers that you can use to tell Twilio via the REST API to emulate things like making an outbound phone call.  Using the magic phone numbers you can get Twilio to return specific responses (like trying to dial an international phone number without the right permissions).
For testing webhook endpoints (the URL's in your webhook that Twilio is going to make its HTTP requests to), you can use the same testing techniques you would to test a normal web app.

A: I was looking for the same thing, because I need to test external calls to my internal IPs, and because I don't want the phone ringing all the time! While I find it disappointing that Twilio doesn't provide this functionality, Devin's response seems reasonable.
I was wondering if someone else had created the set of HTTP interactions in a more comprehensive manner, and found this:
https://github.com/minddog/twilio-emulator
Trying it out now. Perhaps in the future Twilio could add basic callback, not necessarily a full set of Twiml cases that would have to be passed in for each interaction.