text:
Q: How to use Math.floor method for solving numbers Values entered on input fields will split into 3 parts 30%, 30% 40% e.g. physics has values = 500 then values will be 150, 150, 200
How to do this part please help. I am new in JavaScript.

A: Math.floor method is used to round off the number passed as a parameter to its nearest integer in Downward direction of rounding i.e. towards the lesser value.
for ex:
input => Math.floor(22.9)
output => 22
can you be more specific?

A: You can multiple the number by 0.3 and 0.4 to get the required percentage. To get te floor or ceil you can do this:
Math.floor(num)
Math.ceil(num)

A:

const inputValue = 500
const percentages = [30, 30, 40]

const result = percentages.map(percentage => Math.floor(inputValue * percentage / 100)).join(', ')

console.log(result)


text:
Q: Inserting leading zeros into an integer I have a function in C which generates a number of hours from a rtc peripheral, which I then want to fill an array within a struct object.  The array is set up to take 5 digits, but I need to prepend leading zeros to the number when it is less than 5 digits.
Could anyone advise on an easy way of achieving this?

A: char array[5];
snprintf(array, 5, "%05d", number)

A: like @Aaron's solution, the only way to do it in C is to treat it like a character instead of a number.  Leading zeros are ignored when they occur as a value and indicate an octal constant when appearing in code.
int a = 0000015; // translates to decimal 13.

A: A couple little routines that'll do what you want without having a printf() library hanging around.  Note that there's not a way for the routines to tell you that the int you've passed in is too big for the buffer size passed in - I'll leave adding that as an exercise for the reader.  But these are safe against buffer overflow (unless I've left a bug in there).
void uint_to_str_leading( char* dst, unsigned int i, size_t size )
{
    char* pCurChar;

    if (size == 0) return;

    pCurChar = dst + size;  // we'll be working the buffer backwards

    *--pCurChar = '\0';   // take this out if you don't want an ASCIIZ output
                          //   but think hard before doing that...

    while (pCurChar != dst) {
        int digit = i % 10;
        i = i /10;

        *--pCurChar = '0' + digit;
    }

    return;
}

void int_to_str_leading( char* dst, int i, size_t size )
{
    if (size && (i < 0)) {
        *dst++ = '-';
        size -= 1;

        i *= -1;
    }

    uint_to_str_leading( dst, i, size);

    return;
}

Note that these routines pass in the buffer size and terminate with a '\0', so your resulting strings will have one less character than the size you've passed in (so don't just pass in the field size you're looking for).
If you don't want the terminating '\0' character because you're dealing with a fixed char[] array that's not terminated, it's easy enough to take out that one line of code that does the termination (but please consider terminating the char[] array - if you don't, I'll bet you'll see at least one bug related to that sometime over the next 6 months).
Edit to answer some questions:

dst is a pointer to a destination buffer.  The caller is responsible to have a place to put the string that's produced by the function, much like the standard library function strcpy().
The pointer pCurChar is a pointer to the location that the next digit character that's produced will go.  It's used a little differently than most character pointers because the algorithm starts at the end of the buffer and moves toward the start (that's because we produce the digits from the 'end' of the integer). Actually, pCurChar points just past the place in the buffer where it's going to put the next digit.  When the algorithm goes to add a digit to the buffer, it decrements the pointer before dereferencing it. The expression:
*--pCurChar = digit;

Is equivalent to:
pCurChar = pCurChar-1;  /* move to previous character in buffer */
*pCurChar = digit;

It does this because the test for when we're done is:
while (pCurChar == dst) {   /* when we get to the start of the buffer we're done */

The second function is just a simple routine that handles signed ints by turning negative numbers into positive ones and letting the 1st function do all the real work, like so:

*

*putting a '-' character at the start of the buffer,

*adjusting the buffer pointer and size, and

*negating the number to make it positive

*passing that onto the function that converts an unsigned int to do the real work

An example of using these functions:
char buffer[80];

uint_to_str_leading( buffer, 0, 5);
printf( "%s\n", buffer);

uint_to_str_leading( buffer, 123, 6);
printf( "%s\n", buffer);

uint_to_str_leading( buffer, UINT_MAX, 14);
printf( "%s\n", buffer);

int_to_str_leading( buffer, INT_MAX, 14);
printf( "%s\n", buffer);

int_to_str_leading( buffer, INT_MIN, 14);
printf( "%s\n", buffer);

Which produces:
0000
00123
0004294967295
0002147483647
-002147483648

A: Initialize every element in the array to 0 before inserting the digits into the array. That way you're guaranteed to always have 5 digits with leading zeroes.

A: If the type is int, then no.  Set the type to string?

A: try this :

    char source[5+1] = { '1','2', 0, 0, 0, 0 };
    char dest[5+1];
    int nd = strlen(source) ;
    memset ( dest, '0', 5 - nd );
    sprintf ( dest+nd+1, "%s", source );

A: Doesn't simple total bzero() or something like this and then filling with new value suit you? Could you please describe more details if not?
I'm not joking, I have seen several cases when total filling with 0 is faster then tricks to add 0s, especially if memory was cached and bzero() had some burst write support.

A: int newNumber [5]  = 0;

for ( int i=0; givenNumber != 0 && i < 5 ; i++ ) {
    newNumber[i] = givenNumber%10;
    givenNumber = givenNumer/10;
}

A: apologies for the lack of detail.  My code generates a 32-bit integer, which I am expecting to only get to 5 decimal digits in size.  I then call the function:
numArray = numArrayFill(12345, buf, sizeof(buf));

(uint32_t number, char *buffer, int size)
{
    char *curr = &buffer[size];
    *--curr = 0;
    do
    {
        *--curr = (number % 10) + '0';
        number /= 10;
    }
    while (number != 0);

    if (curr == buffer && number != 0)
    return NULL;

    return curr;
}

The problem comes when I put in a less than 5 digit number and I get random behaviour.  What I need to do is to append zeros to the front so that it is always a 5 digit number.
Thanks
Dave

redpajama_set_name: RedPajamaStackExchange


text:
Q: jQuery Cloud Zoom - Advance Images on large image click I'm using the jQuery cloud zoom for an image gallery and have disabled the zoom (long story, but it's working). Right now, I have disabled clicking the large image.
I'm looking to advance the images (i.e. go to the next image) on click of the large image, rather than having to click the thumbnails to change the image.
Here's my example page:
http://future.thefutureforward.com/~field/Travel-Kit.html
Any thoughts?

A: Ok, I took the cloud zoom example and made a jsfiddle working example
The jQuery code below works, the only minor 'bug' is when the last image is clicked, it does not go back to number one. But otherwise there is nothing more to do for you ;) lol
Please note that I have had to use the live method for binding the click event.
$(".mousetrap").live("click", function(){
    var current = $(this).prev().attr("href");
    var tmp = $("a.cloud-zoom-gallery[href='" + current + "']").next();

    if(tmp.length)
        tmp.click();
    else
    {
        alert($("a.cloud-zoom-gallery:first-child").html()); /* null?? */
        $("a.cloud-zoom-gallery:first-child").click();
    }
});


text:
Q: Есть ли скрипт для скачивание с google play? Как можно скачивать приложение с гугл плей через php скрипт? это нужно что бы отдавать готовый файл пользователям.
Есть мб готовое решение?(сайты которые скачивают не нужны, нужны скрипты)

A: Это не так просто. Максимум, что я видел - это расширение для хрома.
Сделать это с серверной стороны сложно, т.к. нужна авторизация. Почитайте это обсуждение, может натолкнёт на какие-то мысли.
Периодически появляются скрипты вроде такого и такого. Можете доработать.


text:
Q: How to reduce the background colour length of a node in Jtree? Basically am setting a background color for the selected component/node in the Jtree.
But the problem is the background color length is exceeding the length of the node text.
So can anybody tell on how to control the length of the background color? I want the background color of any node to be adjusted according to the text length of a node.


text:
Q: Increase element width by percentage using jQuery This answer by Varinder works well but I would like to get the element width which is set in pixels and increase it by 10%.
$(window).load(function() {
    $(".ml").each(function() { // this is kindof sugary way of doing for loop over array of elements - which is $(".ml")
         var $this = $(this); // the current jQueried .ml element
         var currentWidth = $this.width(); // get width of current element, width is a jQuery method: https://api.jquery.com/width/
         var newWidth = currentWidth + 5; // increment the width
         $this.width(newWidth); // pass in the new width as the parameter.
    });
});

A: I think there's several ways to do that, try ;
 var currentWidth = $this.width();

 var newWidth = currentWidth * 1.1; //increment by 10%
 //OR
 var newWidth = currentWidth + ( currentWidth * 10) / 100; //increment by 10%

Hope this helps.

A: Try to replace the currentWidth with var newWidth = currentWidth * 1.1;

A: You just have to set the new width to the old width + 10% of the old width:
var newWidth = currentWidth + (currentWidth * 0.1);


text:
Q: Unwanted double underline under subsection numbers I just updated my LaTeX distribution to MacTex 2016 and also updated all my packages with the tlmgr update --all-command.
After that I recompiled a project of mine and didn't believe my eyes.
My subsections, which were underlinded, are now double-underlined, but only under the numbers (-> screenshots).
I have coded them like this in the preamble, so that they are displayed in the same serif font as the text:
\addtokomafont{disposition}{\rmfamily}

\titleformat{\subsection}
    {\normalfont\scshape}
    {\thesubsection}
    {1.5em}
    {}

\subsectionfont{\normalfont\underline}

If I remove \underline from the last line of code, both underlines disappear.
This was the document before updating:

An this is after updating:

Do you have an idea why this happened?
How can I remove the second underline?

Edit 1 - Added an MWE:
% -------------------------------------
% -----        PREAMBLE           -----
% -------------------------------------

% Set Document Class
\documentclass[12pt,a4paper]{scrartcl}

% Layout & Language Packages & Options
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage[german]{babel}
\usepackage{lmodern}
\usepackage{titlesec}
\usepackage{sectsty}

% Code to display subsections in the serif font
\addtokomafont{disposition}{\rmfamily}

\titleformat{\subsection}
    {\normalfont\scshape}
    {\thesubsection}
    {1.5em}
    {}

\subsectionfont{\normalfont\underline}

% -------------------------------------
% -----        DOCUMENT           -----
% -------------------------------------
\begin{document}
\section{Test Section}

\subsection{Test Subsection}
Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet. Lorem ipsum dolor sit amet, consetetur sadipscing elitr, sed diam nonumy eirmod tempor invidunt ut labore et dolore magna aliquyam erat, sed diam voluptua. At vero eos et accusam et justo duo dolores et ea rebum. Stet clita kasd gubergren, no sea takimata sanctus est Lorem ipsum dolor sit amet.
\end{document}

It compiles to this:

A:
Usage of package `titlesec' together(scrartcl) with a KOMA-Script class is not recommended.

But if you insist on using titlesec, you could use the solution https://tex.stackexchange.com/a/27337/36296 and do something like:
 \documentclass{scrartcl}

\usepackage[explicit]{titlesec}
\usepackage[normalem]{ulem}

\titleformat{\subsection}
  {\normalfont\scshape}{}{0em}{\uline{\thesubsection\hspace*{1em}#1}}

\begin{document}
\section{Test Section}
\subsection{Test Subsection}
\end{document}


text:
Q: parametric circle in 3D? Suppose I have two distinct unit vectors $P_0$ and $P_1$ both $
\in R^3$, such that $P_0 . P_1 = 0$, ie they are at right angles to each other.
I want a function $f$ that takes a real number and returns a unit vector such that
$f(0) = P_0$
$f(1) = P_1$
$f(2) = -P_0$
$f(3) = -P_1$
$f(4) = P_0$
ie $f(t)$ describes a parametric circle with period 4 and radius 1.
What is the formula for $f$ in terms of $t$, $P_0$ and $P_1$?


text:
Q: Video couldn't be cued in onActivityResult() I have two activities: MainActivity has a youtubePlayerView to display video from YouTube and a button "Chose", ChoseVideoActivity has 2 buttons with text "Video1" and "Video2".
At MainActivity I clicked the "Chose" button to open ChoseVideoActivity. In ChoseVideoActivity, I could click either of the two buttons.
When the button with text "video1" is clicked, the activity sends back the YouTube ID of video 1. When the button with text "video2" is clicked, the activity sends back the YouTube ID of video 2.
In onActivityResult, I call cueVideo() with the ID that is sent back.
It should have worked but it didn't.
It worked fine when i work in the same activity.
I used the YouTube Android player API.
onActivityResult() in MainActivity
 private void addEvents() {
    btChose.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(MainActivity.this, ChoseVideoActivity.class);
            startActivityForResult(intent,REQUEST_CODE);
        }
    });
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

    if(requestCode == REQUEST_CODE && resultCode == RESULT_OK && data!=null)
    {
        String link = data.getStringExtra("LINK");
        player.cueVideo(link);
        Toast.makeText(this, link, Toast.LENGTH_SHORT).show();
    }
}

@Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer youTubePlayer, boolean b) {
    player = youTubePlayer;
}

@Override
public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult youTubeInitializationResult) {
    Toast.makeText(this, "Error!",Toast.LENGTH_LONG).show();
}

Click listener in ChoseVideoActivity
private void addEvents() {
    btVideo1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent();
            intent.putExtra("LINK",link_video1);
            setResult(RESULT_OK,intent);
            finish();

        }
    });
    btVideo2.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent();
            intent.putExtra("LINK",link_video2);
            setResult(RESULT_OK,intent);
            finish();

        }
    });
}

A: As I am new here so I can't comment on your post. Your code seems okay. As we can't see that how are you opening the next activity, so I want to make sure, Are you really using startActivityForResult function for opening second activity?
Like this:
Intent intent = new Intent(this, SecondActivity.class);
startActivityForResult(intent, 0);


text:
Q: EAR structure for Java EE Migrating an application from Glassfish 2.1.1 to Glassfish 4. Upon deploying the .ear to the server using the admin console, an error of the type (Archive of type xxxx.ear is not recognised) - while the same ear file is deployable to glassfish 2. Current structure of ear:

*

*lib

*META-INF

*

*MANIFEST.MF

*application.xml

*xxx.war

*xxx.war

*xxx.war

*xxx.war

*xxx.war

According to https://docs.oracle.com/javaee/7/tutorial/packaging001.htm#BCGDJDFB, the file structure appears to be consistent with what is expected, so I'm not sure what I'm missing to get the error that is appearing.

A: The problem was the ear needed to be deployed to the full version of glassfish, not the web version. The .ear file was accepted in the full version of glassfish.


text:
Q: Prove that P(A-B) = P(A) - P(A and B) using Probability axioms I have tried many ways
P(A-B) = P(A and B')
Then i applied DeMorgan's law and got  P(A and B')' = P(A' or B)
Since A' and B are disjoint set we get 1- P(A and B') = P(A') + P(B)
And then i got an absured result that P(A and B') = P(A) - P(B)
What is wrong here, i think i have done something wrong in applying DeMorgan's law.

A: Start with
$P(A\cap B) + P(A\cap B') = P(A)$
Then you have:
$P(A-B) = P(A\cap B') = P(A) - P(A\cap B)$

A: $A\cap B$ and $A-B$ are two disjoint sets/events and this with $$A=(A\cap B)\cup(A-B)$$
Then the additivity of $P$ allows us to conclude that:$$P(A)=P(A\cap B)+P(A-B)$$or equivalently:$$P(A-B)=P(A)-P(A\cap B)$$


text:
Q: jQuery popup Close button missing I have a script to auto open and auto close a jQuery window. However, the X doesn't show up. I see the circular button, but it is missing the big X in the middle.
Code:

$(function() {
  var popup = $('#test_popup');
  popup.popup();
  //popup.popup('open');
  setTimeout(function() {
    popup.popup('open');
  }, 2000);

  $(document).on('popupafteropen', '.ui-popup', function() {
    var popup = $(this);
    setTimeout(function() {
      //popup.popup('close');
      popup.hide();
    }, 10000);
  });
});

     Close

A: I figured out the issue, I was not calling the correct CSS, it works fine now.
link rel="stylesheet" href="jquery.mobile-1.4.5.min.css"


text:
Q: Jquery-Ui autocomplete skips expressions "+" and "-" I use Jquery-Ui version 1.12.1 for auto-complete. But it can only autocomplete alphabet-based search but not expressions like '+' and '-'.
Can I add a regular expression inside the plugin?

A: its functional with text beginning by + and - using regexp with $.ui.autocomplete.escapeRegex(request.term), this function protects the special characters using in regexp, so its possible to use +-[]() and so on in search.

var tags = ["c++", "+bonjour", "--learn", "super", "beauty", "wasp", "rubics"];
$("#autocomplete").autocomplete({
  source: function(request, response) {
    var matcher = new RegExp("^" + $.ui.autocomplete.escapeRegex(request.term), "i");
    response($.grep(tags, function(item) {
      return matcher.test(item);
    }));
  }
});
<!doctype html>
<html lang="en">

<head>
  <meta charset="utf-8">
  <title>autocomplete with + and -</title>
  <link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/smoothness/jquery-ui.css">
  <script src="//code.jquery.com/jquery-1.12.4.js"></script>
  <script src="//code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
</head>

<body>

  <label for="autocomplete">Select Something </label>
  <input id="autocomplete">

</body>

</html>


text:
Q: Highlight ListViewItem only OnMouseOver and Modifier key pressed I am trying to add a style to my ListView's ItemContainerStyle so that the row will only be highlighted in certain color when my mouse move over that row and a modifier key was pressed (say Alt). The MouseOver part is straight forward but not sure how to work on the key pressed part in the Style.
XAML for highlight OnMouseOver:
<Style x:Key="CustomListViewItemStyle" TargetType="{x:Type ListViewItem}">
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type ListViewItem}">
                <Grid>
                    <Border x:Name="ListViewItemBorder" BorderBrush="Black" BorderThickness="2" />
                    <GridViewRowPresenter Columns="{TemplateBinding GridView.ColumnCollection}" Content="{TemplateBinding Content}" />
                </Grid>
              <ControlTemplate.Triggers>
                <Trigger Property="IsMouseOver" Value="True">
                  <Setter TargetName="ListViewItemBorder" Property="BorderBrush" Value="Red"/>
                  <Setter TargetName="ListViewItemBorder" Property="BorderThickness" Value="4"/>
                </Trigger>
              </ControlTemplate.Triggers>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>

A: My workaround is using a custom EventTriggerBase<T> from System.Windows.Interactivity.
public class MyMouseMoveEvenTrigger : EventTriggerBase<ListView>
{
    public ModifierKeys Modifier
    {
        get { return (ModifierKeys) GetValue(ModifierProperty); }
        set { SetValue(ModifierProperty, value); }
    }

    public static readonly DependencyProperty ModifierProperty =
        DependencyProperty.Register("Modifier", typeof (ModifierKeys), typeof (MyMouseMoveEvenTrigger), new PropertyMetadata(ModifierKeys.None));

    public Key Key
    {
        get { return (Key) GetValue(KeyProperty); }
        set { SetValue(KeyProperty, value); }
    }

    public static readonly DependencyProperty KeyProperty =
        DependencyProperty.Register("Key", typeof (Key), typeof (MyMouseMoveEvenTrigger), new PropertyMetadata(Key.None));

    private bool _matchPredicate;

    private ListView ListView
    {
        get { return AssociatedObject as ListView; }
    }

    protected override void OnAttached()
    {
        Keyboard.AddPreviewKeyDownHandler(ListView, PreviewKeyDownHandler);
        Keyboard.AddKeyUpHandler(ListView, KeyUpHandler);

        base.OnAttached();
    }

    private void PreviewKeyDownHandler(object s, KeyEventArgs e)
    {
        var modifierOk = Equals(Modifier, DependencyProperty.UnsetValue) || Modifier == ModifierKeys.None || Keyboard.Modifiers == Modifier;
        var keyOk = Equals(Key, DependencyProperty.UnsetValue) || Key == Key.None || Keyboard.IsKeyDown(Key);

        _matchPredicate = modifierOk && keyOk;
        e.Handled = _matchPredicate;

        RefreshItems();
    }

    private void KeyUpHandler(object s, KeyEventArgs e)
    {
        _matchPredicate =
            (Equals(Modifier, DependencyProperty.UnsetValue) || Modifier == ModifierKeys.None)
            &&
            (Equals(Key, DependencyProperty.UnsetValue) || Key == Key.None);

        RefreshItems();
    }

    protected override void OnDetaching()
    {
        Keyboard.RemoveKeyDownHandler(ListView, PreviewKeyDownHandler);
        Keyboard.RemoveKeyUpHandler(ListView, KeyUpHandler);

        base.OnDetaching();
    }

    protected override void OnEvent(EventArgs eventArgs)
    {
        Keyboard.Focus(ListView);

        var modifierOk = Equals(Modifier, DependencyProperty.UnsetValue) || Modifier == ModifierKeys.None || Keyboard.Modifiers == Modifier;
        var keyOk = Equals(Key, DependencyProperty.UnsetValue) || Key == Key.None || Keyboard.IsKeyDown(Key);

        _matchPredicate = modifierOk && keyOk;

        RefreshItems();
    }

    private void RefreshItems()
    {
        foreach (ListViewItem lvi in ListView.Items)
        {
            lvi.Tag = _matchPredicate && lvi.IsMouseOver ? "Yes" : null;
        }
    }

    protected override string GetEventName()
    {
        return "MouseMove";
    }
}

Because of MyMouseMoveEvenTrigger uses the Tag property (set the string "Yes" when predicate match) we need to change the ControlTemplate.Triggers.
...
<ControlTemplate.Triggers>
    <Trigger Property="IsMouseOver" Value="False">
        <Setter Property="Tag" Value=""/>
    </Trigger>
    <Trigger Property="Tag" Value="Yes">
        <Setter TargetName="Border" Property="BorderBrush" Value="Red"/>
        <Setter TargetName="Border" Property="BorderThickness" Value="4"/>
    </Trigger>
</ControlTemplate.Triggers>
...

And finally, include the custom trigger to the ListView object. The example uses the key C and the modifier Alt.
<ListView>
    <i:Interaction.Triggers>
        <wpfCalc:MyMouseMoveEvenTrigger Modifier="Alt" Key="C"/>
    </i:Interaction.Triggers>
...
</ListView>

I hope it helps.


text:
Q: In the Substrate framework, how do you get the private key (secret key) from a Keypair? I have this code:
use schnorrkel;
use schnorrkel::{
    derive::{ChainCode, Derivation, CHAIN_CODE_LENGTH},
    signing_context, Keypair, MiniSecretKey, PublicKey, SecretKey,
};
use substrate_primitives::crypto::Pair as PairT;
use substrate_primitives::sr25519;
use substrate_primitives::sr25519::Pair;

fn main() {
    let keypair = sr25519::Pair::generate();
    let private_key = keypair.somehow_get_the_private_key_func();
}

I tried to use the SecretKey trait (imported at the beginning), but it says SecretKey is private, so the only way I am thinking of is to modify Substrate's sources to add a function that gives me the private key, but I don't want to do it by source code alteration.
What would be the way to go?

A: What do you actually need to do? You shouldn't be getting a private key in the runtime at all.
If you want to sign something in your runtime, there are helper functions that will sign a message, if you just pass in the public key, with its corresponding private key.
https://substrate.dev/rustdocs/master/sp_io/crypto/fn.sr25519_sign.html
testing: https://substrate.dev/rustdocs/master/sp_core/testing/struct.KeyStore.html


text:
Q: Client Rendering Problem after 'page.' calls I have tried, 'PreviousPage', 'PreviousPage.IsCrossPagePostBack' 'Page.previousPage', page.title
It causes the client to stop rendering the page after this line.
simple example
protected void Page_Load(object sender, EventArgs e)
{
response.write("I can see this");
string test = PreviousPage.IsCrossPagePostBack.toString(); //Any page call Causes client rendering to freeze
response.write("But i cant see this");
System.Windows.Forms.MessageBox.Show("However i can see this,proving that the server is still running the code");
}

Anybody Please, any ideas?

A: ANSWER
Well it ended up it was something stupid. code smell over.
The button i was using to fire the PostBack had a handler that fired to redirect, i just deleted the handler, keeping the PostBackUrl setting and magic.

A: Have you checked PreviousPage for null?
From msdn:

The PreviousPage property is a null
  reference (Nothing in Visual Basic)
  when the user requests that page
  directly from the server.

Also - MessageBox in a web form, not a great idea... perhaps use the inbuilt trace.axd


text:
Q: Using CS inequality to find maximum of a function I am trying to us Cauchy-Schwarz inequality to find the maximum of:
$$|(a^2)(b^2)(a-b)+(b^2)(c^2)(b-c)+(c^2)(a^2)(c-a)|$$
Where $a$, $b$, and $c$ are real numbers, and $a+b+c=0$ and $a^2+b^2+c^2=2$.
What I've tried:
$$a_1=a,\ a_2=b,\ a_3=c$$
$$b_1=b\sqrt{a-b}, \ b_2=c\sqrt{b-c}, \ b_3=a\sqrt{c-a}$$
Which gives:
$$(a^2)(b^2)(a-b)+(b^2)(c^2)(b-c)+(c^2)(a^2)(c-a)\leq(a^2+b^2+c^2)(a-b^3+b-c^3+c-a^3)$$
And I can rearrange and apply the constraints to get
$$(a^2)(b^2)(a-b)+(b^2)(c^2)(b-c)+(c^2)(a^2)(c-a)\leq2(-b^3-c^3-a^3)$$
But I'm not sure where to go from here. How can I use CS to get to an answer here?

A: Let $a=1$, $b=-1$ and $c=0$. Hence, we get a value $2$.
We'll prove that it's a maximal value.
Indeed, since the condition gives $ab+ac+bc=-1$, we obtain:
$|\sum\limits_{cyc}(a^3b^2-a^3c^2)|=|(ab+ac+bc)(a-b)(a-c)(b-c)|=|(a-b)(2a+b)(a+2b)|$.
Since the condition gives $a^2+ab+b^2=1$, it remains to prove that
$$4(a^2+ab+b^2)^3\geq(a-b)^2(2a^2+5ab+2b^2)^2$$
which is $(a+b)^2a^2b^2\geq0$. Done!


text:
Q: Automorphism in the special linear algebra $\mathfrak{sl}_2(F)$
If $L=\mathfrak{sl}(n,F), g\in GL(n,F)$, prove that the map of $L$ to itself defined by $x\rightarrow -gx^tg^{-1}$ ($x^t=$transpose of $x$) belongs to $\operatorname{Aut}L$. When $n=2,g=$identity matrix, prove that this automorphism is inner.

The first part is routine. We check that the map $\varphi$ satisfies $\varphi([x,y])=[\varphi(x),\varphi(y)]:$ $$ -g(xy-yx)^tg^{-1}=gx^ty^tg^{-1}-gy^tx^tg^{-1} $$
so that $\varphi$ is a homomorphism. Moreover, the inverse $\varphi^{-1}$ of $\varphi$ is given by $$\varphi^{-1}(x) = -g^tx(g^{-1})^t$$
so that $\varphi$ is an isomorphism.
Now take $n=2$ and $g=$identity matrix. The map $\varphi$ takes a $2\times 2$ matrix $y$ to $\varphi(y)=-y^t$. We must prove that this automorphism is inner, i.e. it is of the form $\exp\operatorname{ad}x$, with $\operatorname{ad}x$ nilpotent. We have $\exp\operatorname{ad}x=1+\operatorname{ad}x+(\operatorname{ad}x)^2/2!+\ldots$, so that $\exp\operatorname{ad}x(y) = y + [x,y] + [x[x,y]]/2! + \ldots = y + (xy-yx) + \ldots$.
How can we find the right matrix $x$?

A: Hint: every matrix $y\in\mathfrak{sl}_2(\mathbb K)$ is a unique linear combination
$$y=aX+bY+cH,$$
where $(X,Y,H)$ is the standard basis and $a,b,c\in\mathbb K$. If you write $y$ explicitly, you can show that
$$-y^t=aY+bX-cH.$$
The OP asks for a nilpotent matrix $x$ s.t.
$$\exp(\operatorname{ad}_x)(y)=a\exp(\operatorname{ad}_x)(Y)+b\exp(\operatorname{ad}_x)(X)-c\exp(\operatorname{ad}_x)(H)
\stackrel{!}{=}aY+bX-cH.$$
This answer here can be useful to finish the proof. Alternatively, what you need is to compute $\exp(\operatorname{ad}_x)(\cdot)$ on the basis of $\mathfrak{sl}_2(\mathbb K)$.


text:
Q: JSLint Expected 'new' and instead saw '.' I am facing this message from JSLint
Expected 'new' and instead saw '.'.

The line of code that is responsible:
utc = Date.UTC(year, month, date);

This function returns a string.
So JSLint is expecting new instead of the "." between Date and UTC(). JSLint expects new in front of constructors and it also assumes that functions starting with Capital letter is constructor by convention.
I do not have control over this as this is a pre-build function. It doesn't take a form to be constructed with new.
Also I tried to ignore it by following options suggested in other answers:
/*jslint ignore:start */
/*ignore:true */
/*ignore jslint start*/
// jslint ignore:line
/*jsl:ignore*/

None of these worked !
I am looking forward for a workaround "new" or ignore that particular line or section of code. How to resolve this ?

A: I filed a bug for this behavior and Crockford fixed it the same day. (He's an incredibly responsive maintainer.) Use the most recent version of JSLint to fix this behavior. It is not yet on jslint.com, but I expect it will be soon.
This is a very unusual case, since capital letters normally indicate constructors. Using an initial capital U in UTC for a non-constructor function is contrary to JSLint's recommended style, but in this case there's nothing to be done about it, as its been part of the standard for at least five years. JSLint simply needed a narrow exception to its "initial capital means constructor" rule to allow the specific standards-required UTC non-constructor function.


text:
Q: Docusign API - Secure Fields not visible for second recipient using composite templates I'm continuing to work with the scenario described in this question and thus far I do have the ability as the insured (first recipient) to edit all secure fields that were created when I initially created my server templates. What doesn't happen, however is the second recipient (producer-who is also a signer) does not have those fields that were designated as required visible. This only seems to happen when I send an API call for signature on composite templates. When working with a single template both parties have designated fields available to edit. I understand this may be a configuration issue but wanted to rule out the possibility of essential parameters in my call being omitted. I have gone into console account features and set secure fields visible to all recipients (see Molly's comment in the forum).
Here is my call XML. There may be some redundancy (e.g. type, routing order) but I'm working from various examples. Thanks in advance.
<envelopeDefinition xmlns=\"http://www.docusign.com/restapi\">
<accountId>123456</accountId>
<status>sent</status>
<emailSubject>another test</emailSubject>
<emailBlurb>This comes from Me</emailBlurb>
<compositeTemplates>
    <compositeTemplate>
        <serverTemplates>
            <serverTemplate>
                <sequence>1</sequence>
                <templateId>894ed334-4183-4b68-857e-01fe4829f79e</templateId>
            </serverTemplate>
        </serverTemplates>
    <inlineTemplates>
        <inlineTemplate>
        <sequence>2</sequence>
            <recipients>
                <signers>
                    <signer>
                        <type>Signer</type>
                        <email>insured@email.com</email>
                        <name>test insured</name>
                        <RoutingOrder>1</RoutingOrder>
                        <recipientId>1</recipientId>
                        <roleName>Insured</roleName>
                    </signer>
                    <signer>
                        <email>producer@email.com</email>
                        <type>Signer</type>
                        <roleName>Producer</roleName>
                        <name>Test Agent</name>
                        <recipientId>2</recipientId>
                        <RoutingOrder>2</RoutingOrder>
                    </signer>
                </signers>
            </recipients>
        </inlineTemplate>
    </inlineTemplates>
</compositeTemplate>
</compositeTemplates>

A: I'm unable to repro the issue you describe. I can successfully create an Envelope from a single template (using Composite Templates in my XML request), where a data field is required/editable for the first Recipient, and the same data field is editable for the second Recipient (but optional -- since the field is 'owned' by the first Recipient).  Here's my request XML:
<envelopeDefinition xmlns="http://www.docusign.com/restapi">
   <accountId>ACCOUNT_ID</accountId>
   <status>sent</status>
   <compositeTemplates>
    <compositeTemplate>
        <serverTemplates>
            <serverTemplate>
                <sequence>1</sequence>
                <templateId>TEMPLATE_ID</templateId>
            </serverTemplate>
        </serverTemplates>
        <inlineTemplates>
            <inlineTemplate>
                <sequence>2</sequence>
                <recipients>
                  <signers>
                    <signer>
                     <email>johnsemail@outlook.com</email>
                     <name>John Doe</name>
                     <recipientId>1</recipientId>
                     <roleName>signer</roleName>
                     <routingOrder>1</routingOrder>
                    </signer>
                    <signer>
                     <email>janesemail@outlook.com</email>
                     <name>Jane Doe</name>
                     <recipientId>2</recipientId>
                     <roleName>signer2</roleName>
                     <routingOrder>2</routingOrder>
                    </signer>
                  </signers>
               </recipients>
            </inlineTemplate>
        </inlineTemplates>
    </compositeTemplate>
  </compositeTemplates>
</envelopeDefinition>

Here are a few suggestions for troubleshooting...
First, make a couple of changes to your request XML:

*

*Try using routingOrder (lower-case 'r') instead of RoutingOrder (upper-case 'r') in your XML.  In my (limited) testing just now, DocuSign seems to be ignoring the RoutingOrder element if it starts with an uppercase 'r'.

*Remove the type element from the XML request -- this isn't
necessary because you're mapping each recipient to a Template
role (which defines recipient type).
Also, if you want both recipients to be able to Edit a field, double-check the field properties in the Template via the DocuSign web console to confirm that the field has "Allow All to Edit" selected.

Finally, it wouldn't hurt to double-check the Account settings (Preferences >> Features) to confirm that the Display Initial SecureField property is selected.  (Occasionally I've seen it where someone enables a setting, but forgets to Save the change (by clicking the SAVE button that's located at the very bottom of the page.))


text:
Q: How to show link in autocomplete I want to show link for my autocomplete
my code is
   $("#search-header").autocomplete({
                source: function (request, response) {
                    $.ajax({
                        url: "Search",
                        dataType: "json",
                        data: {
                            name: request.term,
                            maxRows: 12
                        },
                        success: function (data) {
                            response($.map(data.atomList, function (item) {
                                console.log(item);
                                return {
                                    label: "" + item.name + "",
                                    value: item.id
                                }
                            }));
                        },
                        error: function (data) {
                            alert(data);
                            console.log(typeof data);
                            console.log(data);
                            alert('error');
                        }
                    });
          },.....

It is showing output like
Text
not the link how to resolve this

A: You can use renderItem

jQuery(function($) {

  $("#search-header").autocomplete({
    source: function(request, response) {
      //to simulate a async ajax request
      setTimeout(function() {
        var data = {
          atomList: [{
            id: '1',
            name: 'v-1'
          }]
        }
        response($.map(data.atomList, function(item) {
          return {
            label: item.name,
            value: item.id
          }
        }));
      })
    }
  }).data('uiAutocomplete')._renderItem = function(ul, item) {
    return $("
")
      .append("" + item.value + "")
      .appendTo(ul);
  };
});

<link rel="stylesheet" type="text/css" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/redmond/jquery-ui.css" />

<input id="search-header" />

A: You want to use autocompletes' _renderItem which allows you to define how your autocomplete list is displayed.  Unlike Arun's answer my _renderItem is inside the autocomplete declaration which makes it a little more readable.
$("#search-header").autocomplete({
  source: function (request, response
    $.ajax({
      url: "Search",
      dataType: "json",
      data: {
        name: request.term,
        maxRows: 12
      },
      success: function (data) {
        response($.map(data.atomList, function (item) {
          console.log(item);
          return {
            label: "" + item.name + "",
            value: item.id
          }
        }));
      },
      error: function (data) {
        alert(data);
        console.log(typeof data);
        console.log(data);
        alert('error');
      },
      _renderItem: function (ul, item) {
        return $("

")
          .data("value", item)
          .append(item.label)
          .appendTo(ul);
      }
    });
},.....


text:
Q: Multiple calls to Raphael hover function only works 'sometimes' I have a function called drawPoint which is called several times using a for loop. The amount of iterations changes depending on which slide the user is viewing.  On average the loop is iterating 8 to 10 times. Sometimes the hover event sticks to all of the iterations, and sometimes it doesn't. Most of the time it misses 3 to 4 of the points. There is not really a pattern. However, if an element fails to receive an event once it will always fail, even after a browser refresh.
Can anyone think of a reason why some svg elements would receive the event and others wouldn't? At first I thought there was a handler cap, but the number of working events fluctuates. Here is the function that is called over and over in the for loop:
drawPoint
drawPoint:function (imgPoint, radius, index, arrowHead) {

    var div = document.createElement("div");
    //div.className = "point";
    //div.id = "p" + index;

    if(arrowHead == false){
        div.style.width = radius*2 +"px";
        div.style.height = radius*2 +"px";

    }else{ //TODO implement actual arrowhead instead of smaller dot
        div.style.width = radius/2 +"px";
        div.style.height = radius/2 + "px";

    }

    div.style.zIndex = 10000 + index + "";

    var paper = Raphael(div);
    var point;

    //console.log("leader x: " + leader.xLength + "\nleader y: " + leader.yLength + "\nmagnitude: " + leader.magnitude);
    if (arrowHead == false) {
        point = paper.circle(radius, radius, radius);
    }
    else if (arrowHead == true){
        point = paper.circle(radius/2, radius/2, radius/2);
    }

    point.node.setAttribute("id", "p" + index );
        point.attr({
            "stroke":Overlay.annoColor,
            "fill":Overlay.annoColor
        });

    point.hover(function(){
            if ($("#allAnno").is(":checked"))
                Overlay.showLabel(parseInt(this.node.getAttribute('id').substring(1)))},
        function(){
            if ($("#allAnno").is(":checked"))
                Overlay.hideAllLabels();

        }
    );

    /*$(".point").hover(function(){
            if ($("#allAnno").is(":checked"))
                Overlay.showLabel(parseInt($(this).attr('id').substring(1)))},
        function(){
            if ($("#allAnno").is(":checked"))
                Overlay.hideAllLabels();
        });*/

    return div;
}

And the loop that instantiates...
 for (var v = 0; v < Overlay.currentOverlaySet.length; v++) {
                    ImageProvider.viewer.drawer.addOverlay(Overlay.drawPoint(Overlay.currentOverlaySet[v].SDPoint,
                        pointRadius, Overlay.currentOverlaySet[v].matchIndex, Overlay.currentOverlaySet[v].arrowHead),
                        Overlay.currentOverlaySet[v].SDPoint, Seadragon.OverlayPlacement.CENTER);
                }

Thanks for your help!

A: Should anyone ever have this problem the solution is to modify the size of the Raphael paper, not the div passed to the Raphael object. For some reason, the divs are covering each other up, blocking the hover event for some of the elements. You can also fix this problem by altering the z-index of multiple objects, but its not as solid... depending on your application.


text:
Q: AngularJs Service Factory not working with IE11 I am writing an AngularJS front end which uses a REST back end. I have a service which uses the Angular $http service to post to the REST back end. I am using a .factory function to register the service. The service works fine using Chrome, but as soon as I tried my app with IE11, an exception is thrown that it cannot find 'myserviceProvider'.  I'm not using a Provider function to create the service I'm using a .factory function. Why cannot IE11 use the .factory function to find/create my service? Anyone with similar experience? I have several other services built with .factory functions and I have no problem; the difference with this service is that is uses the $http service.

A: I found my problem. I had tried to inject my service before the services were created by Angular. Chrome and FireFox let this go IE is more strict and threw an exception. BTW, after I found this, the IE11 console pointed out a syntax error that I had that Chrome and FireFox did not uncover. Lesson learned is that IE11 is more strict and actually can help uncover bugs you didn't know you had.


text:
Q: What is the fastest way to transpose a multi dimensional (n > 2) matrix in C++? I found an answer to this question very well described for a rectangle matrix n=2 in here
What is the fastest way to transpose a matrix in C++?
But my question is how to do the same in more general case. Let have B a transpose of A as
B[i1][i2][J][i4][K][i6][i7] = A[i1][i2][K][i4][J][i6][i7]

so in this particular case of n=7 we do transpose between 3th and 5th index marked as J, K. I assume that whole data structure is within compact memory block float*. Brackets above is used just for symbolic expression of transform operation.
I am about to deal with larger dimensions (possibly n=7) with a lots of data (some dimensions has lower rank about 3-5 and some of them are realatively large about 1000).
Is there a way how to make a really fast algorithm avoid chache-misses or even better how to use advatage of SSE (or AVX) intrinsics just like in the question mentioned above?

A: Have an index table to access your underlying matrix:
template <std::size_t N>
class Matrix {
  std::array<std::size_t, N> index; // init to 0, 1, 2, ..., N
  void transpose(std::size_t i, std::size_t j) {
    std::swap(index[i],index[j]);
  }
  // access M[index[i]...] instead of M[i...]
};


text:
Q: What is causing my wireless router to stop routing HTTP (port 80) connections? My 802.11g router (Belkin F5D7230-4 v2000) periodically stops transmitting HTTP data on port 80. My laptop is the sole client connected to it (on channel 9 with WPA-AES encryption), and there are about 10 to 15 other wireless networks in the vicinity. I've noticed that:

*

*The problem usually occurs after opening many concurrent HTTP connections (however, browsing Gmail or Facebook alone works fine). Also, exercising my bandwidth by downloading a file at 1.5MB/s appears to increase the likelihood of the problem.

*The problem doesn't fix itself. Turning my laptop's wireless switch on then off doesn't help. I need to restart the router or reset its LAN settings (e.g., router IP address, subnet mask, and DHCP lease time).

*I can access the router's admin interface over HTTP. However, I can't reach any external sites like http://google.com.

*Connections on ports other than 80 still work. Specifically, I can establish new ping, AIM, Skype, and HTTPS connections. In addition, HTTP connections on port 8080 do work.

*From looking at Apache logs, web servers listening on port 80 do not receive requests from my computer; therefore, the router seems to be failing to send outgoing HTTP requests.

*I don't have the equipment to verify this, but I seem to remember that even wired clients failed to establish HTTP connections once the router entered this state.

Unfortunately my lack of networking expertise and the strange symptoms are leaving me rather confused.
EDIT: It seems to be an inherent flaw with this model of router. It might be time to start looking into custom firmware...

*

*Belkin Wireless Router Dropping Port 80

*7230-4 v2000 strange connectivity issue

*F5D7230-4 v2000 Drops HTTP (Port 80) Connectivity

A: As you mention custom firmware but not updates to the devices firmware, it is worth looking at the manufacturer's site for updates. Even if you bought the device yesterday it could still have firmware a year or more out of date as and it will have sat on shelves in the store and warehouses for a while (and manufacturers don't always immediately change the outgoing kit on new firmware releases).


text:
Q: Bootstrap v2.3.1 vs v3.2.0: CSS / JS Issues I have been working on a rails application a while ago and adapted Bootstrap v2.3.1 and built the application on the framework. Now today, I brought in the newest versions of bootstrap (v3.2.0) through bower and implemented some features using it.
Due to the bootstrap upgrade, some styles implemented with the previous version got messy. (mainly css issues),
I fixed most of these issues by overriding the css to restore the original style, but Modal boxes (in particular) appear to be a pain to override.
The .hide class (and some others) do not seem to not be compatible between the 2 bootstrap versions. With bootstrap v2.3.1, my original modal box pop ups are hidden and displayed with:
.hide {
  visibility: hidden !important;
  width: 0 !important;
  height: 0 !important;
  line-height: 0;
  padding: 0 !important;
  margin: 0 !important;
}

and
.hide:after {
   visibility: hidden !important;
   width: 0 !important;
   height: 0 !important;
   line-height: 0 !important;
   padding: 0 !important;
   margin: 0 !important;
}

and several similar classes.
Now using bootstrap v3.2.0, the modal boxes implemented in the previous style simply show a darkend backdrop with the modal boxes hidden.
I want to solve this issue without going in and overriding the css on every single modal box.
Does anyone have any good solutions to this?
Perhaps an alternative class for modal boxes in the new bootstrap version?

A: Bootstrap 2.3.2 uses the following for modals:

....

Bootstrap 3.2.0 uses:

....

Easy fix


text:
Q: Detecting if the Activities Overview is open? I want to detect if the Activities Overview is open or not from a script. I have tried xdotool getwindowfocus but it just gives me the window that was focused before the Activities Overview panel was opened. Is this possible?

A: You can use command
qdbus org.gnome.Shell /org/gnome/Shell org.gnome.Shell.OverviewActive

to see whether activity overview is open or not. If the output is true it is open.
To use qdbus, you may have to run
sudo apt install qttools5-dev-tools


text: Q: When we talk about random variables being vectors, what is the vector space they inhabit? I understand framing random variables in terms of vectors can be useful, and has a lot of neat intuitive insights (correlation as the cosine between centered vectors etc.). But in a less hand-wavey sense what is this vector space? In particular, what are its dimensions? What determines how many there are? Intuitively it seems like it corresponds to how many discrete outcomes there are in the probability space, but I'm not sure if that's a good intuition


text:
Q: How to read json text with react-three-fiber I have my gltf data as a JSON, there fore variable gltf is like this
{
    "asset" : {
        "generator" : "Khronos glTF Blender I/O v3.2.43",
        "version" : "2.0"
    },
    "scene" : 0,
    "scenes" : [
        {
            "name" : "Scene",
            "nodes" : [
                0
            ]
        }
    ],
...........

I know how to load gltf by file path
  const gltf = useLoader(GLTFLoader, ". /filapath.gltf");
  return (
    <>
      <primitive object={gltf.scene} scale={0.4} />
    </>
  );

How can I view JSON directly in SCENE? not useLoader with filapath?
like
const gltf = "JSON FILE"
return (
    <>
      <primitive object={gltf.scene} scale={0.4} />
    </>
  );


text:
Q: Click an image to change a text and another image on the site Im new to JS so I need a little help here.
I'm building a website in html where I have 3 pictures working as buttons.

*

*When I click picture 1 I want text1 plus image1 to show up.

*When I click picture 2 I want text2 plus image2 to show up.

*When I click picture 3 I want text3 plus image3 to show up.

The text is working for me right now so:
When I click picture 1 text1 is showing up on the site.
So I need help to add the pictures.
Here is my codes:

function changeText(value) {
    var div = document.getElementById("div");
    var text = "";
    var image = "";

    if (value == 1) text += "this is picture one";
    if (value == 2) text += "this is picture two";
    if (value == 3) text += "this is picture tree";

    div.innerHTML = text;

A: This is What are You expecting??

function changeText(value) {
    var div = document.getElementById("div");
    var text = "";
    var image = "";

    if (value == 1) {
    document.getElementById("searchconsumers").style.cssText="transform: scale(2); transition: all 1s linear";
        document.getElementById("exploreconsumers").style.cssText="transform: scale(1);transition: all 1s linear";
    document.getElementById("funconsumers").style.cssText="transform: scale(1);transition: all 1s linear";

    text += "this is picture one";
     div.innerHTML = text;

    }
    if (value == 2){
     document.getElementById("searchconsumers").style.cssText="transform: scale(1);transition: all 1s linear";
        document.getElementById("exploreconsumers").style.cssText="transform: scale(2);transition: all 1s linear";
    document.getElementById("funconsumers").style.cssText="transform: scale(1);transition: all 1s linear";
    text += "this is picture two";
     div.innerHTML = text;}
    if (value == 3) {
       document.getElementById("searchconsumers").style.cssText="transform: scale(1);transition: all 1s linear";
        document.getElementById("exploreconsumers").style.cssText="transform: scale(1);transition: all 1s linear";
    document.getElementById("funconsumers").style.cssText="transform: scale(2);transition: all 1s linear";
    text += "this is picture tree";
     div.innerHTML = text;}

  }
<!DOCTYPE html>

    <link rel="stylesheet" href="style.css">

function a(value) {
    if (value == 1) {
    document.getElementById("image1").style.cssText="display:block";
          document.getElementById("image2").style.cssText="display:none";
    document.getElementById("image3").style.cssText="display:none";

  }
 if (value == 2) {
    document.getElementById("image1").style.cssText="display:none";
          document.getElementById("image2").style.cssText="display:block";
    document.getElementById("image3").style.cssText="display:none";

  }
   if (value == 3) {
    document.getElementById("image1").style.cssText="display:none";
          document.getElementById("image2").style.cssText="display:none";
    document.getElementById("image3").style.cssText="display:block";

  }
}
a{
text-decoration:none;
color:black;
}
#image1,#image2,#image3{
display:none;
}
#main1{
display:inline-block;
}
input[type="submit"] {
background: #0066A2;
color: white;
border-style: outset;
border-color: #0066A2;
height: 50px;
width: 100px;
font: bold 15px arial, sans-serif;

}
<!DOCTYPE html>

    <link rel="stylesheet" href="style.css">

<input type="submit" value="pika" onclick="a(1)">

This is image1

    <input type="submit" value="muss" onclick="a(2)">

This is image2

    <input type="submit" value="mario" onclick="a(3)">

This is image3

A: Do you want something like this ?

function changeText(value) {
  var div = document.getElementById("div");
  var text = "";
  var image = "";

  if (value == 1) text += "this is picture one
 ";
  if (value == 2) text += "this is picture two
 ";
  if (value == 3) text += "this is picture tree
 ";

  div.innerHTML = text;
}
.custom_h_w{
  top: 120px;
  right: 200px;
  position: absolute;
}


text:
Q: Как вытащить названия химических веществ? Есть файлы отчётов Росгидромета «Об аварийном, экстремально высоком и высоком загрязнении окружающей среды,
а также радиационной обстановке на территории России в <месяц> <года> года» с 2008 по 2021 год.
Нужно вытащить оттуда место, превышение ПДК и название химического вещества.
Нужные абзацы примерно такие:
Случай высокого загрязнения (ВЗ)** атмосферного воздуха веществом 1 класса опасности - бенз(а)пиреном, был зарегистрирован в Архангельске (1 случай, 13 ПДКм.р.).
В апреле 2020 года на территории Российской Федерации случаи ЭВЗ поверхностных вод веществами 1-го и 2-го классов опасности (превышение ПДК** в 5 и
более раз) наблюдательной сетью Росгидромета были зарегистрированы 19 раз на                        5 водных объектах (для сравнения: в апреле  2019 года – 5 раз на 4 водных объектах).

Slovnet и Navec выделяют только места и организации, а веществ («азотом нитритным») — нет. Можно ведь как-нибудь их вытащить?
                 LOC  LOC──────────────          LOC─
    Бугульмы Республики Татарстан было зарегистрировано высокое
             LOC─────────────────
    загрязнение (ВЗ) речной воды азотом нитритным (12 ПДК). По данным ФГБУ
                                                                      ORG─
     «УГМС Республики Татарстан» Росгидромета, ВЗ было обусловлено
    ───────────────────────────  ORG─────────  OR
    поступлением в реку недостаточно очищенных сточных вод с очистных
    сооружений ООО «Водоканал» г. Бугульмы Республики Татарстан.
               ORG────────────             LOC─────────────────


text:
Q: Deserialize json message - Performance Considerations I have big JSON message that I get from HttpClient GetAsync as a stream.
The returned JSON is an array of objects.
I need to parse only one attribute from the first JSON object, and one attribute from the last JSON object. What will be the best way to do it performance wise?
I use Newtonsoft JSON.
I don't want to parse the whole JSON string, just parse specific attributes.


text:
Q: Добраться до компонентов ItemRenderer в List Есть вот такая структура.
1) Надобно сделать сохранение и загрузку положений слайдеров. Не знаю как получить доступ сразу ко всем (шести) слайдерам, чтобы получить их значения.
<fx:Script>
    <![CDATA[
        [Bindable] private var namesLabel:ArrayCollection = new ArrayCollection();

        protected function group1_creationCompleteHandler(event:FlexEvent):void
        {
            listSlider.addEventListener(KeyboardEvent.KEY_DOWN, addValue, false, 0, true);

            namesLabel.addItem("Red");
            namesLabel.addItem("Green");
            namesLabel.addItem("Blue");
            namesLabel.addItem("Contrast");
            namesLabel.addItem("Saturation");
            namesLabel.addItem("Lightness");
        }

        protected function addValue(event:KeyboardEvent):void
        {
            if (String.fromCharCode(event.charCode) == "+") {
                event.target.value += 0.01;
            }

            if (String.fromCharCode(event.charCode) == "-") {
                event.target.value -= 0.01;
            }

        }

    ]]>
</fx:Script>

<s:HGroup>
    <s:Button  label="Reset" toolTip="Reset"/>
</s:HGroup>

<s:List  id="listSlider" dataProvider="{namesLabel}" >
    <s:itemRenderer>
        <fx:Component>
            <s:ItemRenderer>
                <components:SliderComponent id="slider" sliderName="{data}"/>
            </s:ItemRenderer>
        </fx:Component>
    </s:itemRenderer>
</s:List>

components:SliderComponent:
<fx:Script>
    <![CDATA[
        [Bindable] public var sliderName:String = "";
        [Bindable] public var sliderValue:Number = 1;

        protected function changeHandler(event:Event):void
        {
            this.sliderValue = slider.value;
        }

    ]]>
</fx:Script>

<s:HGroup toolTip="{this.sliderName}">
    <s:Label  id="labelShortName" text="{this.sliderName.charAt(0)}" />
    <s:HSlider  id="slider" value="{sliderValue}" minimum="0" maximum="2" snapInterval="0.01" change="changeHandler(event)" />
    <s:Label  id="labelValue" text="{slider.value}" width="25" />
</s:HGroup>

2) Еще проблема. Когда фокус стоит на списке. Выбираем мышкой слайдер под именем "R" ("Red") и нажимаем кнопки "+", "-" - все нормально, прибавляются значения у "R". Теперь нажмем клавишу "L", то выбор в списке переключится на последний слайдер с именем "L" ("Lightness"). И если нажимать на клавиши "+", "-" - то фокус стоит все еще на слайдере "R", и естественно прибавляются значения у него, а не у "L". Как поменять фокус при изменении выделенного элемента в листе?
A: Например так:
// исходный объект для данных чутка усложняем
namesLabel.addItem({name:"Red", value:10});
// добавляем в ArrayCollection более сложный объект с полем для значения слайдера
namesLabel.addItem({name:"5Red5", value:15});
listSlider.dataProvider = namesLabel;
// Убираем объявления внутри родительского списка
<s:List id="listSlider" itemRenderer="components.SliderComponent"/>
// Внутри ItemRender
protected function changeHandler(event:Event):void
{
    this.sliderValue = slider.value;
    data.value = slider.value; // Сохраняем значение
}
// Вносим данные в ItemRender
override public function set data(value:Object):void
{
    super.data = value;
    labelShortName.text = data.name;
    slider.value = data.value;
}

Теперь в namesLabel будет сохранятся значение для каждого слайдера.
 for each ( var o:Object in namesLabel )
 {
     trace( o.value );
 }

По второму вопросу: (проверять не буду)
Попробуйте ставить фокус менеджером внутри ItemRender.
focusManager.setFocus( slider);


text:
Q: how to make some part of the page as unauthenticated in django? I have a Django project which uses JWT as the authentication class. But for certain pages of my app has no authentication. But still when I make request it returns the following thing.
{
    "detail": "You do not have permission to perform this action."
}

My authentication classes are here
REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': [
        'rest_framework_simplejwt.authentication.JWTAuthentication',
    ],
    'DEFAULT_PERMISSION_CLASSES': [
                'rest_framework.permissions.IsAuthenticated',
    ],
}

My views file is here
class Hello(APIView):
    authentication_classes = []
    def post(self, request):
        return Response('Hello')

So how do I achieve this thing?

A: You can disable/bypass the authentication by setting authentication_classes as well as well as permission_classes as empty list like this:
class Hello(APIView):
    authentication_classes = []
    permission_classes = []
    def post(self, request):
        return Response('Hello')

or if you want to use a function based approach you could use decorators to set their values like this:
from rest_framework.decorators import authentication_classes, permission_classes

@api_view(['POST'])
@authentication_classes([])
@permission_classes([])
def hello(request):
   return Response('Hello')


text:
Q: WooCommerce Shipping: Show/Hide Delivery Date Selection based on Shipping Method So, I have a website using plugins:

*

*Order Delivery for WooCommerce for Delivery Date Selection

*Table Rate Shipping for Multiple Shipping Options and Shipping Cost Configuration based on Different Pincodes

*Conditional Shipping and Payments for Timing and Minimum Order Value Restrictions

We have Express Checkout for same-day deliveries and the cut-off time for the same is 8 am to 2 pm (IST) every day for which we use Plugin No 3. Conditional Shipping and Payments and hide it with help of restriction in this plugin if the time is not between 8 am to 2 pm
Now, I don't wish to display the (Shipping and Delivery Section) Delivery date section at all if Express Checkout is selected.
I tried to hide this with help of JQuery as follows:
jQuery(document).ready(function( $ ) {
$("input[name='shipping_method[0]']").click(function() {
    if ($("#shipping_method_0_table_rate1311").is(":checked")) {
        $("#wc-od").hide();
    } else {
        $("#wc-od").show();
    }
});});

My code is inserted properly and can be seen via Inspect Element but doesn't work and still shows the select date option on the Checkout Page

For testing the same you can add products worth ₹750+, using Pincode as 400080, City as Mumbai and as Maharashtra

Please help and let me know what I am doing wrong here or any other method that can be used instead of JQuery

Final Requirement: Want to Remove Section: Shipping and delivery on
the selection of Express Shipping (Time to test: 8 am to 2 pm)


text:
Q: Why my webpage title shows "Apache" when webserver was changed to nginx in AWS Elastic BeanStalk I have two issues:
When I first started Elastic BeanStalk it had Apache webserver for Java8 Tomcat8 combination.
I was able to access my webapp using the link shown
a) https://i.stack.imgur.com/PmEka.png
After working on Apache, I went to configurations and changed the server to
nginx as I would like to try nginx.
I re-deployed and restarted app server after changing my webserver to nginx in my configuration, and

*

*Issue 1: not able to access homepage by clicking link (as shown in a)  )

*Issue 2: The webpage title still shows as "Apache..."  Why is that?
https://i.stack.imgur.com/l17WJ.png
But when I checked chrome console, I see nginx there.

A: Tomcat is an Apache Software Foundation project. Your screenshot is of an "Apache Tomcat" error page. It is not telling you that the Elastic Beanstalk reverse-proxy is Apache Web Server, it is simply telling you that the application server is Apache Tomcat.


text:
Q: Size of a process/thread in Linux What is the size of a process/thread in Linux? When a process/thread is created, along with task_struct and other data structure inside it, is there anything else?
Is the stack of a process/thread allocated upon process/thread initialization (fixed size)? Or is it allocated when necessary (like virtual memory)?
How can I know what size a standard process/thread when it is created in memory?

A: When a large block of memory (> pagesize = 4096 bytes) is first allocated on Linux it uses special "null" memory pages in the pagetable that aren't backed by anything, so when a thread is started it will allocate ~1 MB of these zero pages for a thread stack.  As the stack grows the pages are then converted into real memory backed pages.  Because of this "null" page backing it is generally okay to have liberally large stacks.
Threads and processes are both created with the same underlying syscall called clone(2).  It has lots of options and does lots of stuff.  see man clone for a detailed explanation.
http://linux.die.net/man/2/clone
Large blocks of memory are allocated with an anonymous mmap(2) call.
You may also be interested in doing a web search for "linux overcommit bit"
(If you want to refine your question, I can be more specific.)

A: What Andrew said it true, but it doesn't mean your thread/process doesn't "use memory" from the moment it's created. The space reserved for stacks always consumes virtual address space in your process, which means with large thread stacks you'll quickly run out of addresses on 32-bit machines (just about 300 threads with default thread-stack-size on glibc will exhaust virtual address space). Also, stacks contribute to commit charge, which determines the total amount of memory that can be allocated when overcommit is disabled.
Linux by default pre-commits 128k for the main thread's stack, and allows more to be obtained automatically if commit charge has not been exhausted. Thread stacks are allocated entirely by userspace (glibc/NPTL, on most Linux systems) and cannot grow beyond their initial size. Depending on the version and system settings, glibc/NPTL usually defaults to allocating somewhere between 2 MB and 10 MB per thread.


text:
Q: Incorrect typescript eslint indentations after version update I have this class which I'm both specifying some types and initial values for.
However, when i run my command eslint -c ./.eslintrc.js --ext .ts --fix './src/**/*.ts'
it automatically formats the following block
class MyClass {
    createdBy: {
        firstName: string | null
        lastName: string | null
    } = {
        firstName: null,
        lastName: null,
    }
}

To this
class MyClass {
    createdBy: {
        firstName: string | null
        lastName: string | null
    } = {
            firstName: null,
            lastName: null,
        }
}

Which results in this

Also, VSCode's Format document also intends 3 times which throws the error above.
So the same config is used for both eslint and the editor, but eslint wants an extra indent while the editor does not.
This happened after i upgraded from typescript 4.5.4 to 4.7.3 and eslint 7.32.0 to 8.17.0. Before that, this worked just fine.
If i instead ignore the fix flag, this is what i get

.eslintrc.js config
module.exports = {
    root: true,
    parser: '@typescript-eslint/parser',
    env: {
        browser: false,
        node: true,
    },
    plugins: [
        '@typescript-eslint',
    ],
    extends: [
        'eslint:recommended',
        'plugin:@typescript-eslint/recommended',
    ],
    rules: {
        indent: [2, 'tab', { 'SwitchCase': 1 }],
    },
}

Versions

*

*typescript: 4.7.3

*eslint: 8.17.0

*@typescript-eslint/parser: 5.27.1

*@typescript-eslint/eslint-plugin: 5.27.1


text:
Q: How to perform Hardware disaster recovery with backup server I have a two windows server 2003 R2 servers with same configuration(same processor,same motherboard etc). One is original server and another one is backup server(Not to store backup files,it is a server used in case original server gets crashed). So in case any hardware problem in original server like motherboard problem then I remove all the hard disk from original server(Including drive containing OS) and connect it to backup server. So I will have low down time. The configuration was same OS was also working properly after changing drive having Windows OS.
Now we have plan to purchase new server with windows server 2012 and we will be purchasing Intel 2600 family processor and supporting motherboard as original server. For backup server I will be purchasing Intel 2400 family processor and its supported motherboard. So in case of any problem in original server Does shifting hard disk(like I was doing before) will work?(In ordinary windows 7 pc it was not working when hardware changes are there) . If it does not work then what is the solution? How this kind of hardware errors are handled by using backup server or any other methods to do the same.
Is there any procedures to take backup of existing server configurations like folder permissions, software configurations, users etc.? If yes, can i restore the backup of main server to alternate server in case of server failure?
Please suggest me on this.
We have our own backup program and we are taking backup in regular basis. Only thing we are confused about is hardware failure.

A: Your question could be more concise however I'll do my best to answer.
I would not count on being able to simply remove the disks from one machine and plant them into another, especially if the RAID controller is different. There are any number of factors (RAID controller, RAID level, etc) that would make this a risky operation and I would certainly not recommend it for a DR situation.
What you're looking to do can be accomplished with virtualization and shared storage. You would have your two physical servers (in this case your primary server and your secondary server) and your storage (hard drives) would be on an array separate from these two servers (ie storage array, SAN, NAS, etc).This allows for a seamless failover should the hardware on one of your two servers fail. The caveat here is that you now have all your data on a storage array, so you'd likely want two of those in case one or the other fails.
For more information (on vmware) you can look here : http://www.vmware.com/products/vsphere/features-high-availability


text:
Q: Writing a Main Method to call an Object? We are learning Java with BlueJ and I am finding BlueJ very unclear and confusing. We've been given an assignment and one of the first steps is 'create a main method to call the Train object'. I'm sure he meant 'to call the Train method'.
Anyway, I'm trying to get the main method to call the Train method in the code below so when you pass a string argument in BlueJ, it executes the code in main. That's it. The Train method passes in a String and two int values:
public static void main(String[] args)
{
    Train train = new Train();
    train.Train();
}

I keep getting an error when trying to do this though and not sure why.
This is the code for the Train Class:
public class Train
{
    //Fields
    /* Destination of the Train */
    private String destination = new String();

    /* Train number - identifies the Train */
    private int TrainNumber;

    /* Capacity of the Train - how many customers can be in it */
    private int capacity;

    /* Number of customers currently in the Train */
    private int numberInTrain;

    /* Ticket price - how much a ticket costs. */
    private int ticketPrice;

    public static void main(String[] args)
    {
        Train train = new Train();
        train.Train();
    }

    /** Constructor for Train
     * @param dest the destination of the Train
     * @param num the number of the Train
     * @param cap the capacity of the Train
     */
    public void Train(String dest, int num, int cap)
    {
        destination = dest;
        capacity = cap;
        TrainNumber = num;

        numberInTrain = 0;
        ticketPrice = 50;
    }

    //mutators
    /* Records customer taking Train */
    public void enterTrain ()
    {
        numberInTrain = numberInTrain + 1;
    }

    /* Records customer leaving Train */
    public void leaveTrain ()
    {
        numberInTrain = numberInTrain - 1;
    }

}

This however, gives me an error and I cannot run the program from main. Any hints to the right direction will be appreciated.
The error is:

Error:(30, 14) java: method Train in class TrainAssignment.Train cannot be applied to given types;
    required: java.lang.String,int,int
    found: no arguments
    reason: actual and formal argument lists differ in length

EDIT
I have tried
public static void main(String[] args)
{
    Train train = new Train();
    train.Train(dest, num, cap);
}

and this also gives an error of cannot find variables. The values need to come from user input. When an object is created, we input the destination, the number of people and the capacity for each object.

A: Your professor has it correct. You want to call the Train object. When you call Train train = new Train(); That is instantiating a Train object, and will call the constructor of the class.
Essentially, that is what you are trying to do here:
public void Train(String dest, int num, int cap)

This here, however, does not count as a constructor. The constructor has no return type, and as such it can't even be void. So it would be as such:
 public Train(String dest, int num, int cap)

With doing that, you can remove the train.Train(); and just have the Train train = new Train();. But there is one more issue regarding that. When you call the Train object, the constructor will be expecting 3 parameters, your String and two Ints. So when you call the object, you must fill it with the parameters that you want, such as Train train = new Train("Canada",2,3);
EDIT:
I see you now need the parameters to come from user input. I suggest looking up the Scanner class to find out how to get user input.


text:
Q: Pass additional variables to a function variable I am using a function in TensorFlow which maps a set of tensors to another arrangement of tensors. For example, you might write:
data = data.map(_function)

def _function(a, b, c):
    return (a + 1, b, c)

So here, you pass _function as a function variable to map, and map passes it three tensors, which are mutated in some way (here, just adding one) and returned.

My question is: Is there a way to pass in additional variables to _function?
If I want to perform a + x, and not a + 1, then how could I pass in the additional variable?
You can't do something like: data.map(_function(x)) because then you're passing the result of a function, not the function itself.
I've experimented with *arg, but I can't find a way. Any help is greatly appreciated.

A: You can do sth like
def extra_func(x):
    def _function(a, b, c):
        return (a + x, b, c)
    return _function

So you can do data.map(extra_func(x))
or you can use functools.partial to fix some of a function params


text:
Q: How can I solve this equation (contains error function)? Edited out incorrect formula
Can someone please solve this equation for x? I have no idea what to do with the $\mathrm{erf}$ (error function).
Edit: Hm, it did not work correctly... here is the function I meant to solve for x in symbolic form:
$$f(x) = a*\left(0.5*\mathrm{erf}\left(\frac{x-b}{c\sqrt{2}}+.5\right)\right)+d$$
Coefficients (with 99% confidence
bounds):
       a =       1.412  (1.411, 1.412)
       b =       1.259  (1.259, 1.259)
       c =       1.003  (1.002, 1.003)
       d =      0.3016  (0.3014, 0.3017)

When I solve for f(x) with x=1 I get ans =
    0.5460
I want to plug 0.5460 into a formula and get 1 back.
Chris, this is the Finv function you spoke of in my other question.

A: $$x = 1.003\sqrt{2}\left(\mathrm{erf}^{-1}\left(\frac{Y/1.42 + 0.4042}{0.5}\right) - 0.05\right) + 0.5501$$

A: Let's start with the "general form" you say you had:
$$a\left(\frac12\mathrm{erf}\left(\frac{x-b}{c\sqrt{2}}+\frac12\right)\right)+d=y$$
and go over the inversion slo-o-owly...
$$a\left(\frac12\mathrm{erf}\left(\frac{x-b}{c\sqrt{2}}+\frac12\right)\right)=y-d$$
$$\frac12\mathrm{erf}\left(\frac{x-b}{c\sqrt{2}}+\frac12\right)=\frac{y-d}{a}$$
$$\mathrm{erf}\left(\frac{x-b}{c\sqrt{2}}+\frac12\right)=2\frac{y-d}{a}$$
Now, we can employ the inverse error function:
$$\frac{x-b}{c\sqrt{2}}+\frac12=\mathrm{erf}^{-1}\left(2\frac{y-d}{a}\right)$$
$$\frac{x-b}{c\sqrt{2}}=\mathrm{erf}^{-1}\left(2\frac{y-d}{a}\right)-\frac12$$
$$x-b=c\sqrt{2}\left(\mathrm{erf}^{-1}\left(2\frac{y-d}{a}\right)-\frac12\right)$$
$$x=b+c\sqrt{2}\left(\mathrm{erf}^{-1}\left(2\frac{y-d}{a}\right)-\frac12\right)$$
and that's the inverse you need.
Now, if it were
$$a\left(\frac12\mathrm{erf}\left(\frac{x-b}{c\sqrt{2}}\right)+\frac12\right)+d=y$$
instead (which I think is more likely, since you're starting from the normal distribution CDF), things are a bit different. What you should end up with is
$$x=b+c\sqrt{2}\,\mathrm{erf}^{-1}\left(2\frac{y-d}{a}-1\right)$$
which is probably the expression you actually need for those confidence intervals...


text:
Q: hdparm doesn't read SSD? HDIO_DRIVE_CMD(identify) failed: Inappropriate ioctl for device I'm trying to use hdparm to do secure erase of my 512GB SSD SK Hynix.
SSD has Windows 10 installed in it.
I boot Ubuntu from a usb flash drive.
sudo fdisk -l

I get a lot of different disks, turns out /dev/sda is my 8gb flash drive, not SSD.
SSD is listed as:

Disk /dev/nvme0n1: 477 GiB, 512110190592 bytes, 1000215216 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
Disklabel type: gpt

Now when I try to run hdparm -I /dev/nvme0n1, terminal gives me error:

/dev/nvme0n1:
 HDIO_DRIVE_CMD(identify) failed: Inappropriate ioctl for device

how do I use hdparm secure erase option on my SSD? From suggestion in another page on the internet, nvme-cli package was suggested, but I don't understand how that helps.
using shred command isn't recommended for SSD because SSD has limited read/write cycles, and it works very differently than HDD.
Update: my SSD is an NVMe device, not ATA, therefore hdparm command isn't suitable, use nvme -format instead.

A: To erase an NVMe device using nvme-cli, run nvme format -s1 <device>.

nvme-cli package was suggested, but I don't understand how that helps.

hdparm works exclusively with devices which speak the ATA protocol, but your SSD is built to speak the NVMe protocol.
That difference is not limited to just physical connection (like IDE/SATA) – instead the OS has to use an entirely different set of commands when communicating with the device. None of the ATA commands apply to NVMe (the general idea of "secure erase" is present, but it's implemented differently).
Therefore nvme-cli was suggested to you because hdparm is the wrong tool for the job from the very beginning.

In theory, it would be possible for an OS to translate between the command sets (intercept ATA commands and issue equivalent NVMe commands), and indeed the Linux kernel internally does this to some extent for SCSI-to-ATA. At some point, Linux even used to support basic SCSI-to-NVMe translation, but this was eventually removed as the systems are just too different.
However, it wouldn't have helped you because Linux doesn't do it the other way around: you already can't use the ATA-specific hdparm against SCSI disks, and likewise you wouldn't have been able to use hdparm against NVMe disks.


text:
Q: Cannot set "setAsEdge" in Box2D on iPhone This code will create lines around the iPhone screen, but the bottom line should be in the middle (I need to change the .y but I don't know how).
How to do that?
And can someone explain these "setAsEdge" methods to me?
// Define the ground body.
b2BodyDef groundBodyDef;
groundBodyDef.position.Set(0,0); // bottom-left corner

// Call the body factory which allocates memory for the ground body
// from a pool and creates the ground box shape (also from a pool).
// The body is also added to the world.
b2Body* groundBody = world->CreateBody(&groundBodyDef);

// Define the ground box shape.
b2PolygonShape groundBox;

// bottom
groundBox.SetAsEdge(b2Vec2(0,0), b2Vec2(screenSize.width/PTM_RATIO,0));
groundBody->CreateFixture(&groundBox,0);

// top
groundBox.SetAsEdge(b2Vec2(0,screenSize.height/PTM_RATIO), b2Vec2(screenSize.width/PTM_RATIO,screenSize.height/PTM_RATIO));
groundBody->CreateFixture(&groundBox,0);

// left
groundBox.SetAsEdge(b2Vec2(0,screenSize.height/PTM_RATIO), b2Vec2(0,0));
groundBody->CreateFixture(&groundBox,0);

// right
groundBox.SetAsEdge(b2Vec2(screenSize.width/PTM_RATIO,screenSize.height/PTM_RATIO), b2Vec2(screenSize.width/PTM_RATIO,0));
groundBody->CreateFixture(&groundBox,0);

A: // bottom

float screenMid = screenSize.height/2;  // Y axis on screen middle

        groundBox.SetAsEdge(b2Vec2(0,screenMid/PTM_RATIO),b2Vec2(screenSize.width/PTM_RATIO,screenMid/PTM_RATIO));

This will shift your bottom line to screen middle.
The SetAsEdge method takes two points and draw a line from point-1 to point-2. In above statement the point one is "b2Vec2(0,screenMid/PTM_RATIO)". Where 0 is the x-axis and screenMid is the y-axis of first point. Same goes with the second point.
You have to divide every point by PTM_RATIO to translate it into box2d coordinates.


text:
Q: How to maintain the url for 404 page in angularjs We're working on an angularjs app, in which the user is able to publish his or her profile as a resumée.
So for instance if the user has a published profile the following url is valid:
www.page.com/public/johnsmith

However in case of
www.page.com/public/johnsmith2345

which isn't a public profile I would like to show a 404 page. The problem is that because of angular's routing I have to redirect to the 404 page, so the url will be rewritten as
www.page.com/404.

What would be the correct implementation to maintain the original url and even make it work in IE9?

A: The only way I know of to do this would be to deal with this in your controller/view. e.g.
$routeProvider.when('/public/:user',
    {
        templateUrl: 'profile.html',
        controller: 'profileCtrl',
        resolve: {
            userProfile: {
                //Try and load the user's profile. Resolve null if the profile can't be found
            }
        }
    }
);

var profileCtrl = function($scope, userProfile) {
    $scope.userProfile = userProfile;
}

profile.html:

    ... Profile view here


text:
Q: How to add from model data string of HTML to Razor Hi i have model with property content. model.Content is HTML tags like object string
when i try
@foreach (var user in @Model.Organizations){
     @user.Content
}

he is don`t create html tags just print text. how i can create tags from text?
enter image description here

A: Try to use @Html.Raw()
 @Html.Raw(user.Content)


text:
Q: Getting COM port of a bluetooth device by device name in c# I writing some code in C# to get the COM port where a bluetooth device with a specific name is mapped. I tried several solutions similar to the ones listed here, but with none of them I have access to the name as in the bluethooth settings window as in the picture below:

If it's on that window I'm sure there is a way to find it. Any help?
Thanks a lot

A: Try the following code snippet.  I use it to find serial devices by name in an application that I use every day.
    public static bool DoesSerialDeviceExist(string name)
    {
        using (var search = new ManagementObjectSearcher
            ("SELECT * FROM WIN32_SerialPort"))
        {
            string[] portnames = SerialPort.GetPortNames();
            var ports = search.Get().Cast<ManagementBaseObject>().ToList();

            var tList = (from n in portnames
                         join p in ports on n equals p["DeviceID"].ToString()
                         select n + " - " + p["Caption"]).ToList();

            string serial = tList.FirstOrDefault(o => o.Contains(name));

            bool isAvailable = false;
            if (serial != null)
            {
                isAvailable = true;
            }

            return isAvailable;
        }
    }

A:     private void FillInComportComboBox()
    {
        Hashtable PortNames = new Hashtable();
        string[] ports = System.IO.Ports.SerialPort.GetPortNames();

        //string st = ComPortList.Text;

        ComPortList.Items.Clear();

        if (ports.Length == 0)
        {
            ComPortList.Items.Add("ERROR: No COM ports exist");
        }
        else
        {
            PortNames = BuildPortNameHash(ports);
            //foreach (string s in ports)
            foreach(String s in PortNames.Keys)
            {
                //ComPortList.Items.Add(s + ":  " + (string)PortNames[s]);
                ComPortList.Items.Add(PortNames[s] + ": " + s);
            }
        }
    }

    // Begins recursive registry enumeration
    // <param name="oPortsToMap">array of port names (i.e. COM1, COM2, etc)</param>
    // <returns>a hashtable mapping Friendly names to non-friendly port values</returns>
    Hashtable BuildPortNameHash(string[] oPortsToMap)
    {
        Hashtable oReturnTable = new Hashtable();
        MineRegistryForPortName("SYSTEM\\CurrentControlSet\\Enum", oReturnTable, oPortsToMap);
        return oReturnTable;
    }
    // Recursively enumerates registry subkeys starting with strStartKey looking for
    // "Device Parameters" subkey. If key is present, friendly port name is extracted.
    // <param name="strStartKey">the start key from which to begin the enumeration</param>
    // <param name="oTargetMap">hashtable that will get populated with
    // friendly-to-nonfriendly port names</param>
    // <param name="oPortNamesToMatch">array of port names (i.e. COM1, COM2, etc)</param>
    void MineRegistryForPortName(string strStartKey, Hashtable oTargetMap, string[] oPortNamesToMatch)
    {
        if (oTargetMap.Count >= oPortNamesToMatch.Length)
            return;
        RegistryKey oCurrentKey = Registry.LocalMachine;

        try
        {
            oCurrentKey = oCurrentKey.OpenSubKey(strStartKey);

            string[] oSubKeyNames = oCurrentKey.GetSubKeyNames();
            if (((IList<string>)oSubKeyNames).Contains("Device Parameters") && strStartKey != "SYSTEM\\CurrentControlSet\\Enum")
            {
                object oPortNameValue = Registry.GetValue("HKEY_LOCAL_MACHINE\\" + strStartKey + "\\Device Parameters", "PortName", null);

                if (oPortNameValue == null || ((IList<string>)oPortNamesToMatch).Contains(oPortNameValue.ToString()) == false)
                    return;
                object oFriendlyName = Registry.GetValue("HKEY_LOCAL_MACHINE\\" + strStartKey, "FriendlyName", null);

                string strFriendlyName = "N/A";

                if (oFriendlyName != null)
                    strFriendlyName = oFriendlyName.ToString();
                if (strFriendlyName.Contains(oPortNameValue.ToString()) == false)
                    strFriendlyName = string.Format("{0} ({1})", strFriendlyName, oPortNameValue);
                oTargetMap[strFriendlyName] = oPortNameValue;
                //oTargetMap[oPortNameValue] = strFriendlyName;
            }
            else
            {
                foreach (string strSubKey in oSubKeyNames)
                    MineRegistryForPortName(strStartKey + "\\" + strSubKey, oTargetMap, oPortNamesToMatch);
            }
        }
        catch
        {

        }
    }

A: After looking for a solution,
This is what I found (I'm using this for my project)
Main()
{

    AvailablePorts ports = new AvailablePorts();
    ports.GetBluetoothCOMPort();
    System.Collections.ObjectModel.ObservableCollection<COMPort> obs = ports.COMPorts;

}

And now, create a new class and add those references
using System;
using System.Collections.Generic;
using System.Management;
using System.ComponentModel;
using System.Runtime.CompilerServices;
using System.Globalization;
using System.Collections.ObjectModel;
using System.Windows;
using System.Management.Automation;

public class AvailablePorts
{
    private ObservableCollection<COMPort> comPorts = new ObservableCollection<COMPort>();
    public ObservableCollection<COMPort> COMPorts
    {
        get => comPorts;
        set
        {
            comPorts = value;
        }
    }

    private string ExtractBluetoothDevice(string pnpDeviceID)
    {
        int startPos = pnpDeviceID.LastIndexOf('_') + 1;
        return pnpDeviceID.Substring(startPos);
    }

    private string ExtractDevice(string pnpDeviceID)
    {
        int startPos = pnpDeviceID.LastIndexOf('&') + 1;
        int length = pnpDeviceID.LastIndexOf('_') - startPos;
        return pnpDeviceID.Substring(startPos, length);
    }

    private string ExtractCOMPortFromName(string name)
    {
        int openBracket = name.IndexOf('(');
        int closeBracket = name.IndexOf(')');
        return name.Substring(openBracket + 1, closeBracket - openBracket - 1);
    }

    private string ExtractHardwareID(string fullHardwareID)
    {
        int length = fullHardwareID.LastIndexOf('_');
        return fullHardwareID.Substring(0, length);
    }

    private bool TryFindPair(string pairsName, string hardwareID, List<ManagementObject> bluetoothCOMPorts, out COMPort comPort)
    {
        foreach (ManagementObject bluetoothCOMPort in bluetoothCOMPorts)
        {
            string itemHardwareID = ((string[])bluetoothCOMPort["HardwareID"])[0];
            if (hardwareID != itemHardwareID && ExtractHardwareID(hardwareID) == ExtractHardwareID(itemHardwareID))
            {
                comPort = new COMPort(ExtractCOMPortFromName(bluetoothCOMPort["Name"].ToString()), Direction.INCOMING, pairsName);
                return true;
            }
        }
        comPort = null;
        return false;
    }

    private string GetDataBusName(string pnpDeviceID)
    {
        using (PowerShell PowerShellInstance = PowerShell.Create())
        {
            PowerShellInstance.AddScript($@"Get-PnpDeviceProperty -InstanceId '{pnpDeviceID}' -KeyName 'DEVPKEY_Device_BusReportedDeviceDesc' | select-object Data");

            Collection<PSObject> PSOutput = PowerShellInstance.Invoke();

            foreach (PSObject outputItem in PSOutput)
            {
                if (outputItem != null)
                {
                    Console.WriteLine(outputItem.BaseObject.GetType().FullName);
                    foreach (var p in outputItem.Properties)
                    {
                        if (p.Name == "Data")
                        {
                            return p.Value?.ToString();
                        }
                    }
                }
            }
        }
        return string.Empty;
    }

    public void GetBluetoothCOMPort()
    {
        COMPorts.Clear();

        ManagementObjectCollection results = new ManagementObjectSearcher(
            @"SELECT PNPClass, PNPDeviceID, Name, HardwareID FROM Win32_PnPEntity WHERE (Name LIKE '%COM%' AND PNPDeviceID LIKE '%BTHENUM%' AND PNPClass = 'Ports') OR (PNPClass = 'Bluetooth' AND PNPDeviceID LIKE '%BTHENUM\\DEV%')").Get();

        List<ManagementObject> bluetoothCOMPorts = new List<ManagementObject>();
        List<ManagementObject> bluetoothDevices = new List<ManagementObject>();

        foreach (ManagementObject queryObj in results)
        {
            if (queryObj["PNPClass"].ToString() == "Bluetooth")
            {
                bluetoothDevices.Add(queryObj);
            }
            else if (queryObj["PNPClass"].ToString() == "Ports")
            {
                bluetoothCOMPorts.Add(queryObj);
            }
        }

        foreach (ManagementObject bluetoothDevice in bluetoothDevices)
        {
            foreach (ManagementObject bluetoothCOMPort in bluetoothCOMPorts)
            {
                string comPortPNPDeviceID = bluetoothCOMPort["PNPDeviceID"].ToString();
                if (ExtractBluetoothDevice(bluetoothDevice["PNPDeviceID"].ToString()) == ExtractDevice(comPortPNPDeviceID))
                {
                    COMPort outgoingPort = new COMPort(ExtractCOMPortFromName(bluetoothCOMPort["Name"].ToString()), Direction.OUTGOING, $"{bluetoothDevice["Name"].ToString()} \'{GetDataBusName(comPortPNPDeviceID)}\'");

                    Application.Current.Dispatcher.Invoke(() => {
                        COMPorts.Add(outgoingPort);
                    });

                    if (TryFindPair(bluetoothDevice["Name"].ToString(), ((string[])bluetoothCOMPort["HardwareID"])[0], bluetoothCOMPorts, out COMPort incomingPort))
                    {
                        Application.Current.Dispatcher.Invoke(() => {
                            COMPorts.Add(incomingPort);
                        });
                    }
                }
            }
        }
    }
}

public class COMPort : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    private void RaisePropertyChanged([CallerMemberName] string propertyName = null)
    {
        PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
    }

    private string comPortPort;
    public string SerialPort
    {
        get => comPortPort;
        set
        {
            comPortPort = value;
            RaisePropertyChanged();
        }
    }

    private Direction comPortDirection;
    public Direction Direction
    {
        get => comPortDirection;
        set
        {
            comPortDirection = value;
            RaisePropertyChanged();
        }
    }

    private string comPortName;
    public string Name
    {
        get => comPortName;
        set
        {
            comPortName = value;
            RaisePropertyChanged();
        }
    }

    public COMPort(string comPortPort, Direction comPortDirection, string comPortName)
    {
        SerialPort = comPortPort;
        Direction = comPortDirection;
        Name = comPortName;
    }
}

public class DirectionConverter
{
    private const string UNDEFINED_DIRECTION = "UNDEFINED";
    private const string INCOMING_DIRECTION = "Incoming";
    private const string OUTGOING_DIRECTION = "Outgoing";

    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        switch ((Direction)value)
        {
            case Direction.UNDEFINED:
                return UNDEFINED_DIRECTION;
            case Direction.INCOMING:
                return INCOMING_DIRECTION;
            case Direction.OUTGOING:
                return OUTGOING_DIRECTION;
        }

        return string.Empty;
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

public enum Direction
{
    UNDEFINED,
    INCOMING,
    OUTGOING
}

Found at:
https://social.msdn.microsoft.com/Forums/Azure/en-US/b9d0adc3-b489-4245-91b9-6016a89302b9/get-bluetooth-com-ports?forum=csharpgeneral

A: You will get all available COM ports on the PC as a string array with:
SerialPort.GetPortNames()

But these are without the device name.
If you need more info, you might be helped by this link Getting Serial Port Information


text:
Q: How can I detect when a call is answered?
Possible Duplicate:
Detect if an outgoing call has been answered

I'm writing an android application.
What I have right now is:
I'm able to detect an outgoing call (by ACTION_NEW_OUTGOING_CALL),
and right after, I getting the OFFHOOK_STATE (It's still ringing...)
My question is how can I detect when a call is answered?


text:
Q: How i can use the id in the textbox from a moda form to do query using php and mysql to fill out the value of other textbox I had a form table and For the edit button, when i click the button the modal will come out.

The problem is how i can use the id in the textbox to do query using php and mysql to fill out the value of other textbox.

<input type="button" id="edit-group" name="edit-group" class="btn btn-primary btn-xs" data-id="<?php echo $row['group_id'];?>" data-toggle="modal" data-target="#modalEditGroup" value="Edit">

              <button type="button" class="close"
                 data-dismiss="modal">
                     ×
                     Close
              </button>

                  Edit Group

              <form class="form-horizontal" role="form" method="POST" action="<?php echo $_SERVER['PHP_SELF'] ?>">

                  Id

                          <input type="text" class="form-control" id="id" name="id" class="id" />

                  Group Name

                       <input type="text" id="group_name_edit" required="required" class="form-control col-md-7 col-xs-12" value=""  name="group_name_edit">

                  Access Level

                   <input type="text" id="access_level_edit" required="required" class="form-control col-md-7 col-xs-12" value=""  name="access_level_edit">

                  Approve By

                   <input type="text" id="approve_by_edit" required="required" class="form-control col-md-7 col-xs-12" value=""  name="approve_by_edit">

                      <button class="btn btn-primary" type="reset">Reset</button>
                      <button type="submit" class="btn btn-success" id="submit" name="submit">Submit</button>

              </form>

A: In the same way as setting id in #id field like,
$('#modalEditGroup').on('show.bs.modal', function(e) {
  var t=$(e.relatedTarget),
      id = t.data('id'),
      gname=t.data('gname'),
      alevel=t.data('alevel'),
      appby=t.data('appby');
     $('#id').val(id);
     $('#group_name_edit').val(gname);
     $('#access_level_edit').val(alevel);
     $('#approve_by_edit').val(appby);
});

Add data-* in HTML like,
<input type="button" id="edit-group" name="edit-group"
   class="btn btn-primary btn-xs"
   data-id="<?php echo $row['group_id'];?>"
   data-gname="<?php echo $row['group_name'];?>"
   data-alevel="<?php echo $row['access_level'];?>"
   data-appby="<?php echo $row['approve_by'];?>"
   data-toggle="modal" data-target="#modalEditGroup"
   value="Edit" />

And add on submit event like,
$('#submit').on('click',fucntion(){
   $.ajax({
      url:'YOUR-URL-TO-SUBMIT-DATA',
      type:'post',
      data:{
          id:$('#id').val(),group_name:$('#group_name_edit').val(),
          access_level:$('#access_level_edit').val(),
          approve_by:$('#approve_by_edit').val()
      },
      success:function(data){
          // check for success and error messages
          // if success then hide modal box and alert('Success');
      }
   });
});

A: On click of edit button before showing the modal, make an ajax call the ID and get the details of associated with that ID and fill it to the modal elements and than show the modal.
Ex:
$('#modalEditGroup').on('show.bs.modal', function(e) {
     var id = $(e.relatedTarget).data('id');
     // make ajax() call here with the id
     // fill the response in the the modal
     // show the modal
});