text:
Q: How to update the page for the next search from an API in JavaScript? In this app, When i submit a word (for eg help) for the first time then it will return the search results and renders it on the page, but if i searched for another word then the results wont be displayed until and unless i refresh the page. How can i render next search results on the page? The codepen link is here: https://codepen.io/nelsonuprety1/pen/KKWreRQ . To search for new results the page should be refreshed.

'use strict';

const submit = document.querySelector('#submit');

const meaningContainer = document.querySelector('.meanings');

const renderSynonym = function (data) {
  const html = `

${data.meanings[0].definitions[0].synonyms}

    `;
  meaningContainer.insertAdjacentHTML('beforeend', html);
  meaningContainer.style.opacity = 1;
};

function getSynonym() {
  const searches = document.querySelector('#search');
  const search = searches.value.trim();
  // searches.value = '';

  if (search === '') return;
  fetch(`https://api.dictionaryapi.dev/api/v2/entries/en_US/${search}`)
    .then(function (response) {
      console.log(response);
      return response.json();
    })
    .then(function ([data]) {
      renderSynonym(data);
    })
    .catch(function (error) {
      console.log(error);
    });
  // searches.value = '';
}

submit.addEventListener('click', getSynonym);
@import url('https://fonts.googleapis.com/css2?family=Lexend:wght@100;300;400;500&display=swap');

* {
  margin: 0;
  padding: 0;
}

/* css variables */
:root {
  --text-color: #001858;
}

body {
  background: #659999;
  /* fallback for old browsers */
  background: -webkit-linear-gradient(to right, #f4791f, #659999);
  /* Chrome 10-25, Safari 5.1-6 */
  background: linear-gradient(to right, #f4791f, #659999);
  /* W3C, IE 10+/ Edge, Firefox 16+, Chrome 26+, Opera 12+, Safari 7+ */
}

header {
  color: var(--text-color);
  display: flex;
  font-size: 2em;
  justify-content: center;
  margin-top: 15%;
  margin-bottom: 5%;
}

.searchBox {
  /* display: flex;
    justify-content: center; */
  background-color: #ced8c5;
  padding: 40px;
  width: 50%;
  /* center a div horizontally if we use margin:0 auto */
  margin: 0 auto;
}

.find {
  display: block;
  font-size: 30px;
  font-weight: 1000;
  line-height: 2.15;
  margin-bottom: 5px;
}

#search {
  /* width: 100%; */
  min-width: 100%;
  height: 50px;
  margin-bottom: 10px;
  outline-color: #659999;
}

#submit {
  height: 40px;
  width: 20%;
}

#submit:hover {
  background-color: #8fd9a8;
}

/*
.mean.hidden {
    display: inline-grid;
    grid-auto-flow: column;
    gap: 9px;
    list-style-type: none;
    margin-top: 40px;
    overflow-wrap: break-word;
    width: 50%;
    background-color: #fff;

} */

.container {
  display: flex;
  flex-flow: column;
  align-items: center;
  margin-top: 2rem;
}

.meanings {
  display: flex;
  font-size: 1rem;
  background-color: #ced8c5;
  margin-top: 1rem;
  min-width: 30rem;
  min-height: 50%;
  opacity: 0;
  padding: 2rem;
  transition: opacity 1s;
  font-family: inherit;
  overflow: hidden;
}

.mean {
  background-color: #fff;
  box-shadow: 0 2rem 5rem 1rem rgba(0, 0, 0, 0.1);
  font-size: 1.8rem;
  min-width: 100%;
  border-radius: 2rem;
  margin: 0 3rem;
  padding: 2rem;
  /* overflow: hidden; */
}
<!DOCTYPE html>

    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta name="description" content="Find synonyms, near synonyms." />
    <link rel="stylesheet" href="style.css" />

    <title>Synonymous : Find Similar Words</title>

Synonymous : Find Synonyms

      Find the Synonym
      <input
        type="search"
        id="search"
        placeholder="Search Synonymous"
        autocapitalize="off"
        autocomplete="off"
        autofocus
      />
      <input type="submit" value="Search" id="submit" />

Synonyms

A: In your code you are adding new results to the right. After some searches the new results leave the view port and you can't see them. You can remove display: flex; in .meanings to change this behavior:

'use strict';

const submit = document.querySelector('#submit');

const meaningContainer = document.querySelector('.meanings');

const renderSynonym = function (data) {
  const html = `

${data.meanings[0].definitions[0].synonyms}

    `;
  meaningContainer.insertAdjacentHTML('beforeend', html);
  meaningContainer.style.opacity = 1;
};

function getSynonym() {
  const searches = document.querySelector('#search');
  const search = searches.value.trim();
  // searches.value = '';

  if (search === '') return;
  fetch(`https://api.dictionaryapi.dev/api/v2/entries/en_US/${search}`)
    .then(function (response) {
      console.log(response);
      return response.json();
    })
    .then(function ([data]) {
      renderSynonym(data);
    })
    .catch(function (error) {
      console.log(error);
    });
  // searches.value = '';
}

submit.addEventListener('click', getSynonym);
@import url('https://fonts.googleapis.com/css2?family=Lexend:wght@100;300;400;500&display=swap');

* {
  margin: 0;
  padding: 0;
}

/* css variables */
:root {
  --text-color: #001858;
}

body {
  background: #659999;
  /* fallback for old browsers */
  background: -webkit-linear-gradient(to right, #f4791f, #659999);
  /* Chrome 10-25, Safari 5.1-6 */
  background: linear-gradient(to right, #f4791f, #659999);
  /* W3C, IE 10+/ Edge, Firefox 16+, Chrome 26+, Opera 12+, Safari 7+ */
}

header {
  color: var(--text-color);
  display: flex;
  font-size: 2em;
  justify-content: center;
  margin-top: 15%;
  margin-bottom: 5%;
}

.searchBox {
  /* display: flex;
    justify-content: center; */
  background-color: #ced8c5;
  padding: 40px;
  width: 50%;
  /* center a div horizontally if we use margin:0 auto */
  margin: 0 auto;
}

.find {
  display: block;
  font-size: 30px;
  font-weight: 1000;
  line-height: 2.15;
  margin-bottom: 5px;
}

#search {
  /* width: 100%; */
  min-width: 100%;
  height: 50px;
  margin-bottom: 10px;
  outline-color: #659999;
}

#submit {
  height: 40px;
  width: 20%;
}

#submit:hover {
  background-color: #8fd9a8;
}

/*
.mean.hidden {
    display: inline-grid;
    grid-auto-flow: column;
    gap: 9px;
    list-style-type: none;
    margin-top: 40px;
    overflow-wrap: break-word;
    width: 50%;
    background-color: #fff;

} */

.container {
  display: flex;
  flex-flow: column;
  align-items: center;
  margin-top: 2rem;
}

.meanings {
  font-size: 1rem;
  background-color: #ced8c5;
  margin-top: 1rem;
  min-width: 30rem;
  min-height: 50%;
  opacity: 0;
  padding: 2rem;
  transition: opacity 1s;
  font-family: inherit;
  overflow: hidden;
}

.mean {
  background-color: #fff;
  box-shadow: 0 2rem 5rem 1rem rgba(0, 0, 0, 0.1);
  font-size: 1.8rem;
  min-width: 100%;
  border-radius: 2rem;
  margin: 0 3rem;
  padding: 2rem;
  /* overflow: hidden; */
}
<!DOCTYPE html>

    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta name="description" content="Find synonyms, near synonyms." />
    <link rel="stylesheet" href="style.css" />

    <title>Synonymous : Find Similar Words</title>

Synonymous : Find Synonyms

      Find the Synonym
      <input
        type="search"
        id="search"
        placeholder="Search Synonymous"
        autocapitalize="off"
        autocomplete="off"
        autofocus
      />
      <input type="submit" value="Search" id="submit" />

Synonyms

or overwrite the previous result with

'use strict';

const submit = document.querySelector('#submit');

const meaningContainer = document.querySelector('.meanings');

const renderSynonym = function (data) {
  const html = `

${data.meanings[0].definitions[0].synonyms}

    `;
  meaningContainer.innerHTML = html;
  meaningContainer.style.opacity = 1;
};

function getSynonym() {
  const searches = document.querySelector('#search');
  const search = searches.value.trim();
  // searches.value = '';

  if (search === '') return;
  fetch(`https://api.dictionaryapi.dev/api/v2/entries/en_US/${search}`)
    .then(function (response) {
      console.log(response);
      return response.json();
    })
    .then(function ([data]) {
      renderSynonym(data);
    })
    .catch(function (error) {
      console.log(error);
    });
  // searches.value = '';
}

submit.addEventListener('click', getSynonym);
@import url('https://fonts.googleapis.com/css2?family=Lexend:wght@100;300;400;500&display=swap');

* {
  margin: 0;
  padding: 0;
}

/* css variables */
:root {
  --text-color: #001858;
}

body {
  background: #659999;
  /* fallback for old browsers */
  background: -webkit-linear-gradient(to right, #f4791f, #659999);
  /* Chrome 10-25, Safari 5.1-6 */
  background: linear-gradient(to right, #f4791f, #659999);
  /* W3C, IE 10+/ Edge, Firefox 16+, Chrome 26+, Opera 12+, Safari 7+ */
}

header {
  color: var(--text-color);
  display: flex;
  font-size: 2em;
  justify-content: center;
  margin-top: 15%;
  margin-bottom: 5%;
}

.searchBox {
  /* display: flex;
    justify-content: center; */
  background-color: #ced8c5;
  padding: 40px;
  width: 50%;
  /* center a div horizontally if we use margin:0 auto */
  margin: 0 auto;
}

.find {
  display: block;
  font-size: 30px;
  font-weight: 1000;
  line-height: 2.15;
  margin-bottom: 5px;
}

#search {
  /* width: 100%; */
  min-width: 100%;
  height: 50px;
  margin-bottom: 10px;
  outline-color: #659999;
}

#submit {
  height: 40px;
  width: 20%;
}

#submit:hover {
  background-color: #8fd9a8;
}

/*
.mean.hidden {
    display: inline-grid;
    grid-auto-flow: column;
    gap: 9px;
    list-style-type: none;
    margin-top: 40px;
    overflow-wrap: break-word;
    width: 50%;
    background-color: #fff;

} */

.container {
  display: flex;
  flex-flow: column;
  align-items: center;
  margin-top: 2rem;
}

.meanings {
  display: flex;
  font-size: 1rem;
  background-color: #ced8c5;
  margin-top: 1rem;
  min-width: 30rem;
  min-height: 50%;
  opacity: 0;
  padding: 2rem;
  transition: opacity 1s;
  font-family: inherit;
  overflow: hidden;
}

.mean {
  background-color: #fff;
  box-shadow: 0 2rem 5rem 1rem rgba(0, 0, 0, 0.1);
  font-size: 1.8rem;
  min-width: 100%;
  border-radius: 2rem;
  margin: 0 3rem;
  padding: 2rem;
  /* overflow: hidden; */
}
<!DOCTYPE html>

    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <meta name="description" content="Find synonyms, near synonyms." />
    <link rel="stylesheet" href="style.css" />

    <title>Synonymous : Find Similar Words</title>

Synonymous : Find Synonyms

      Find the Synonym
      <input
        type="search"
        id="search"
        placeholder="Search Synonymous"
        autocapitalize="off"
        autocomplete="off"
        autofocus
      />
      <input type="submit" value="Search" id="submit" />

Synonyms


text:
Q: How can I add a class to body but to choose name in Wordpress backend? I want to ask how I can make a option in backend to add a specific class to body on a category page. My idea is that i want to have a color sheme (Headlines, links, backgrounds..) to be the same color as the selected category.
For example when I'm on a category page with listed subcategories and the posts underneath, when i click on the post i want the post template to have the same color sheme as the parent subcategory and the category.
Is there a simple way to do this with Wordpress?
Thanks for any advice.

A: add this to functions.php. It will add category-slug to your body class
add_filter( 'body_class', function( $classes ) {
    if(is_category()){
        $cat = get_category( get_query_var( 'cat' ) );
        $classes = array_merge( $classes, array( $cat->slug ) );
    }
    return $classes;
} );

now you can  do css based on your category's slug.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Unable to seek audio file in chrome served by my own server I am trying to make a file server in Java which can serve seekable audio files. But my served files are not seekable in Google Chrome html5 audio player. When I seek forward it does nothing (even on downloaded content), if seek too much backward it starts from beginning. If I load the file from different location (http://www.vorbis.com/music/Epoq-Lepidoptera.ogg) then it is seekable.
Here is my server code
package com.company;

import com.sun.net.httpserver.Headers;
import com.sun.net.httpserver.HttpExchange;
import com.sun.net.httpserver.HttpHandler;
import com.sun.net.httpserver.HttpServer;

import java.io.*;
import java.net.InetSocketAddress;

public class Main {

    public static void main(String[] args) throws Exception {
        HttpServer server = HttpServer.create(new InetSocketAddress(8000), 0);
        server.createContext("/Epoq-Lepidoptera.ogg", new MyHandler());
        server.setExecutor(null); // creates a default executor
        server.start();
    }

    static class MyHandler implements HttpHandler {
        public void handle(HttpExchange httpExchange) throws IOException {

            long contentLength;
            File file = new File("Epoq-Lepidoptera.ogg");
            FileInputStream fis = new FileInputStream(file);
            BufferedInputStream bis = new BufferedInputStream(fis);
            contentLength = file.length();
            System.out.println(contentLength);

            Headers headers = httpExchange.getResponseHeaders();
            headers.add("content-type", "audio/ogg");

            // ok, we are ready to send the response.
            httpExchange.sendResponseHeaders(200, contentLength);
            OutputStream os = httpExchange.getResponseBody();
            byte[] data = new byte[1000];
            while (true) {
                int bytesRead = bis.read(data);
                if (bytesRead == -1) break;
                os.write(data, 0, bytesRead);
            }

            os.close();
            System.out.println("request served");
        }
    }
}

I am using this html file to test audio.
<html>
    <body>
        <audio controls="control" preload="auto" src="http://localhost:8000/Epoq-Lepidoptera.ogg"></audio>
    </body>
</html>

But following file is seekable
<html>
    <body>
        <audio controls="control" preload="auto" src="http://www.vorbis.com/music/Epoq-Lepidoptera.ogg"></audio>
    </body>
</html>

What I am doing wrong or what should I implement in my server to make file seekable, minimum on downloaded content (showed in white bar)
This problem is only Google Chrome, not in Firefox. Firefox can seek on loaded content.


text:
Q: What is responsible for generating the default constructor? If every class has a default constructor then who generates it, the compiler or the JVM?

A: The short answer is that the compiler will generate a default constructor if necessary.
It is definitely the Java to bytecode compiler that does it.  You can confirm this by examining an appropriate .class file using javap.  You should see the constructor that has been inserted.
However I also want to correct this possible misconception:

If every class has a default constructor ...

In fact, every class does NOT have a default constructor.
A default constructor is ONLY injected into a class if the class has NO declared constructors whatsoever.  If the source code declares any constructor at all, a default constructor is not injected.  For example:
/* This has a no-args constructor, but it is not a "default" constructor */
public class Foo {
   public Foo() {}
}

/* This has no no-args constructor and no "default" constructor */
public class Bar {
   public Bar(int arg) {}
}

/* This has a "default" constructor */
public class Baz {
}

(A default constructor is a no-args constructor, but an explicitly declared no-args constructor is not a default constructor.  And not all classes have a no-args constructor anyway.)
(At the JVM level, it is a requirement for a .class file to define at least one constructor.  However there is no specific constraint on the constructor's argument count and types, or on the constructor's access modifiers.)

Another answer includes a recommendation to explicitly declare no-args constructors rather than relying on Java to insert the default one (see above).
I think this is bad idea:

*

*It has zero impact on runtime performance.

*It has minimal impact1 on compilation times.  And indeed, it might even make compilation a bit slower.

*

*If there is no constructor, the compiler notices this, and injects and code generates a default constructor.

*If there is an explicit (empty) no-args constructor, the compiler must read, parse and typecheck the constructor, and then code generate an identical constructor to the first case.

*The readability benefit is doubtful.
The only (IMO) sound reasons to choose an explicit no-args constructor over a default constructor are:

*

*because there are other constructors (which means that there WON'T be a default no-args constructor!),

*because you want to restrict visibility of the constructor; e.g. declaring it private in a singleton class, or

*because you want to say something (meaningful) in the javadocs for the no-args constructor.

1 - My guess would be a few microseconds.  Too small to make a noticeable difference.

A: the Java compiler.
If you don't implement any constructor in your class, the Java compiler inserts default constructor into your code.
Of course both are same in result and you will not see the default constructor in your source code(the .java file).
And also my teacher told me it is better to add the constructor your self in your source code, even when you have no arguments!


text:
Q: Unselect all items when the SelectedItem is bound to something that doesn't exist in the list I have two lists with different ItemsSource but with SelectedItem bound to the same property - "Name".
First i'm choosing the item "c" in the right list so the item "c" in the left list is selected as well.
Than I selected another item in the right list but the "c" in the left list is still selected.
I understand why it do that, but can I make it unselect the "c" in the right list ?

XAML:
 <Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition  />
        <ColumnDefinition  />
    </Grid.ColumnDefinitions>

    <ListView SelectedItem="{Binding Name}" ItemsSource="{Binding lstNames1}"/>
    <ListView SelectedItem="{Binding Name}" ItemsSource="{Binding lstNames2}" Grid.Column="1"/>
</Grid>

Code behind:
 public partial class selected : Window
{
    public ObservableCollection<string> lstNames1 { get; set; }
    public ObservableCollection<string> lstNames2 { get; set; }

    public string Name { get; set; }

    public selected()
    {
        Names1 = new ObservableCollection<string> {"a1", "b1", "c"};
        Names2 = new ObservableCollection<string> { "a2", "b2", "c" };
        InitializeComponent();
        DataContext = this;
    }
}

A: If you switch the SelectedItem binding to SelectedValue this will behave how you want, The SelectedItem is not clearing because its not set to null because the other list has set a value, SelectedValue acts a bit differntly as it has to find an item or it will clear the SelectedItem on the list.
<ListView SelectedValue="{Binding Name}" ItemsSource="{Binding lstNames1}" />
<ListView SelectedValue="{Binding Name}" ItemsSource="{Binding lstNames2}" Grid.Column="1"/>

Hope that make sense :)


text:
Q: In Win10, I installed python library through "pip install XXX", "Collecting XXX "will be displayed, but the library is still not installed? This is a screenshot of my question
In Win10, I installed python library through "pip install XXX", "Collecting XXX "will be displayed, but the library is still not installed?


text:
Q: Stored Procedure gives out two sets of unwanted data I am trying to create a stored procedure to validate a user(login), everything is working except for when the user enters an email which is NOT registered. You see I have handled that exception wherein if the count of email address in the table is 0,it should give out:
  Select 0 as AccountLocked,0 as Authenticated,0 as RetryAttempts,0 as Registered

and if it is not 0, it will execute the next steps.The problem is when the enter an email which is not registered, it gives me back two sets of results which are as below:
  Select 0 as AccountLocked,0 as Authenticated,0 as RetryAttempts,0 as Registered

and
 Select 1 as AccountLocked,0 as Authenticated,0 as RetryAttempts,1 as Registered

The complete proc is given for reference.What am i missing here? why is it giving me the second result too which I don't want?
Alter proc spValidateUser
    @EmailAdd nvarchar(30),
    @Password nvarchar(20)
as
begin
    Set Nocount on;
    Declare @UserId nvarchar(10),@LastLogin datetime,@RoleId int,@AccountLocked bit,@RetryCount int,@Count int

    Select @Count=Count(EmailAdd) from tblAllUsers
    where EmailAdd=@EmailAdd
    if(@Count = 0) begin
        Select 0 as AccountLocked,0 as Authenticated,0 as RetryAttempts,0 as Registered
    end else
        Select @AccountLocked=IsLocked from tblAllUsers where EmailAdd=@EmailAdd

    ----if account is already locked------
    if(@AccountLocked = 1) begin
       Select 1 as AccountLocked,0 as Authenticated,0 as RetryAttempts,1 as Registered
    end else begin
        -----check if username and password match-----
        Select @UserId = UserId, @LastLogin=LastLogin, @RoleId=RoleId
        from tblAllUsers where EmailAdd=@EmailAdd and Password=@Password
          ----if match found--------
        If @UserId is not null Begin
            Update tblAllUsers
            SET LastLogin= GETDATE(),RetryAttempts=0 WHERE UserId=@UserId

            Select @UserId [UserId],
            (Select Role from tblRoles where RoleId=@RoleId) [Roles],0 as AccountLocked,1 as Authenticated,0 as RetryAttempts,1 as Registered
        End Else Begin
            ------if match not found--------
            Select @RetryCount=ISNULL(RetryAttempts,0) from tblAllUsers where EmailAdd=@EmailAdd

            Set @RetryCount=@RetryCount+1
            if(@RetryCount<=3) Begin
                ----if retry attempts are not completed------
                Update tblAllUsers Set RetryAttempts=@RetryCount where EmailAdd=@EmailAdd

                Select 0 as AccountLocked,0 as Authenticated,@RetryCount as RetryAttempts,1 as Registered
            End Else Begin
                ------if retry attempts are completed--------
                Update tblAllUsers Set RetryAttempts=@RetryCount,IsLocked=1,LockedDateTime=GETDATE()
                where EmailAdd=@EmailAdd

                Select 1 as AccountLocked,0 as Authenticated,0 as RetryAttempts,1 as Registered
            End
        End
    End
End

Edit: Looks like it is executing the below code too :
 Begin
      ------if retry attempts are completed--------
      Update tblAllUsers Set RetryAttempts=@RetryCount,IsLocked=1,LockedDateTime=GETDATE()
      where EmailAdd=@EmailAdd
      Select 1 as AccountLocked,0 as Authenticated,0 as RetryAttempts,1 as Registered
      End

but why should it execute the above when the emails don't match?

A: I would change your procedure logic a bit like below
        if exists(Select 1 from tblAllUsers where EmailAdd=@EmailAdd)
           Select 0 as AccountLocked,0 as
           Authenticated,0 as RetryAttempts,0 as Registered
        else
           Select 1 as AccountLocked,0 as Authenticated,
           0 as RetryAttempts,1 as Registered

A: The problem you have is here:
Select @Count=Count(EmailAdd) from tblAllUsers
where EmailAdd=@EmailAdd

Now the @count will be zero, and you'll return 0 as AccountLocked in following if:
if(@Count = 0) begin
    Select 0 as AccountLocked,0 as Authenticated,0 as Retry...
end else
    Select @AccountLocked=IsLocked from tblAllUsers where EmailAdd=@EmailAdd

This was just else, no begin + end block here.
Here you'll check if account is locked, but since it wasn't found @AccountLocked is still NULL
----if account is already locked------
if(@AccountLocked = 1) begin
   Select 1 as AccountLocked,0 as Authenticated,0 as Retry...
end else begin

Now you're here checking password, even though user wasn't even found, so this will never find anything:
    -----check if username and password match-----
    Select @UserId = UserId, @LastLogin=LastLogin, @RoleId=RoleId
    from tblAllUsers where EmailAdd=@EmailAdd and Password=@Password
      ----if match found--------
    If @UserId is not null Begin
   ....

And then the second result set comes from here:
    End Else Begin
        ------if match not found--------


text:
Q: Attempt to invoke virtual method 'void android.widget.ImageView.setImageBitmap(android.graphics.Bitmap)' on a null object reference I keep getting this error and i'm not sure why. I've tried googling it but no luck there.

04-21 15:43:24.822    2461-2461/com.example.s.myapplication D/AndroidRuntime﹕ Shutting down VM
      04-21 15:43:24.823    2461-2461/com.example.s.myapplication E/AndroidRuntime﹕ FATAL EXCEPTION: main
          Process: com.example.s.myapplication, PID: 2461
          java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1, result=-1, data=null} to activity {com.example.s.myapplication/com.example.s.myapplication.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ImageView.setImageBitmap(android.graphics.Bitmap)' on a null object reference
                  at android.app.ActivityThread.deliverResults(ActivityThread.java:3539)
                  at android.app.ActivityThread.handleSendResult(ActivityThread.java:3582)
                  at android.app.ActivityThread.access$1300(ActivityThread.java:144)
                  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1327)
                  at android.os.Handler.dispatchMessage(Handler.java:102)
                  at android.os.Looper.loop(Looper.java:135)
                  at android.app.ActivityThread.main(ActivityThread.java:5221)
                  at java.lang.reflect.Method.invoke(Native Method)
                  at java.lang.reflect.Method.invoke(Method.java:372)
                  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
           Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.ImageView.setImageBitmap(android.graphics.Bitmap)' on a null object reference
                  at com.example.s.myapplication.MainActivity.onActivityResult(MainActivity.java:46)
                  at android.app.Activity.dispatchActivityResult(Activity.java:6139)
                  at android.app.ActivityThread.deliverResults(ActivityThread.java:3535)
                  at android.app.ActivityThread.handleSendResult(ActivityThread.java:3582)
                  at android.app.ActivityThread.access$1300(ActivityThread.java:144)
                  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1327)
                  at android.os.Handler.dispatchMessage(Handler.java:102)
                  at android.os.Looper.loop(Looper.java:135)
                  at android.app.ActivityThread.main(ActivityThread.java:5221)
                  at java.lang.reflect.Method.invoke(Native Method)
                  at java.lang.reflect.Method.invoke(Method.java:372)
                  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
                  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
      a

This is my main activity. What the application is meant to do is:

*

*Take a photo

*Save the photo in a tmp location

*load the photo into a imageview

.
package com.example.s.myapplication;

import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Environment;
import android.provider.MediaStore;
import android.os.Bundle;
import android.view.View;
import android.widget.ImageView;

import java.io.File;

public class MainActivity extends Activity {

    static final int REQUEST_IMAGE_CAPTURE = 1;
    private ImageView imageView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        openCamera();
        setContentView(R.layout.activity_main);
    }

    public void openCamera() {
        Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        File file = new File(Environment.getExternalStorageDirectory() + File.separator + "image.jpg");
        takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
        startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        //Check that request code matches ours:
        if (requestCode == REQUEST_IMAGE_CAPTURE) {
            //Get our saved file into a bitmap object:
            File file = new File(Environment.getExternalStorageDirectory() + File.separator + "image.jpg");
            Bitmap image = decodeSampledBitmapFromFile(file.getAbsolutePath(), 1000, 700);
            imageView.setImageBitmap(image);
        }
    }

    public boolean isExternalStorageWritable() {
        String state = Environment.getExternalStorageState();
        if (Environment.MEDIA_MOUNTED.equals(state)) {
            return true;
        }
        return false;
    }

    public static Bitmap decodeSampledBitmapFromFile(String path, int reqWidth, int reqHeight) {

        //First decode with inJustDecodeBounds=true to check dimensions
        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(path, options);

        // Calculate inSampleSize, Raw height and width of image
        final int height = options.outHeight;
        final int width = options.outWidth;
        options.inPreferredConfig = Bitmap.Config.RGB_565;
        int inSampleSize = 1;

        if (height > reqHeight) {
            inSampleSize = Math.round((float) height / (float) reqHeight);
        }
        int expectedWidth = width / inSampleSize;

        if (expectedWidth > reqWidth) {
            //if(Math.round((float)width / (float)reqWidth) > inSampleSize) // If bigger SampSize..
            inSampleSize = Math.round((float) width / (float) reqWidth);
        }

        options.inSampleSize = inSampleSize;

        // Decode bitmap with inSampleSize set
        options.inJustDecodeBounds = false;

        return BitmapFactory.decodeFile(path, options);
    }

    public void capture_btn(View v) {
        Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        File file = new File(Environment.getExternalStorageDirectory() + File.separator + "image.jpg");
        takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(file));
        startActivityForResult(takePictureIntent, REQUEST_IMAGE_CAPTURE);
    }
}

A: imageView = (ImageView)findViewById(R.id.imageView2);

A: This worked for me:
I wrote wrong the id of my imageView. It supposed to be imageView2
imageView = findViewById(R.id.imageView2);

A: if above solutions did not work for you check
oncreate  method again it should be like this
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);imageView=findViewById(R.id.imageView);
setContentView(R.layout.activity_main);
imageView=findViewById(R.id.imageView);

                                             }


text:
Q: com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException with Json Array I'm reading a JSON from an API, converting to POJO, performing some logic and then writing the POJO to a JSON file.
This is what the JSON input from API looks like
String jsonStr = "[{\"LastUpdatedBy\":\"Bug 101510: VMukkanagoudar\",\"IATACountryCode\":\"US\",\"MetroCodeBool\":false,\"AirportName\":\"Sawyer County\",\"Latitude\":46,\"CityName\":\"Hayward\",\"MajorAirportBool\":false,\"Longitude\":-91,\"StatusCode\":\"A\",\"DisplayNameLocal\":\"Hayward, WI (HYR-Sawyer County)\",\"DisplayNameInternational\":\"Hayward, WI, United States (HYR-Sawyer County)\",\"UpdateDate\":\"2009-03-06 20:44:00.0\",\"AirportCode\":\"HYR\",\"AirportID\":5396808,\"RegionName\":\"Wisconsin\",\"IdenticalMetroCodeBool\":false,\"ExternalName\":\"HYR\",\"CountryCode\":\"USA\"}]";

It is a JSONArray with one Json Object inside it.
The POJO looks likes this
@JsonIgnoreProperties(ignoreUnknown = true)
public class AirConfig {

    String airportCode;
    Integer airportId;
    Boolean metroCodeBool;

    @JsonProperty("airportCode")
    public String getAirportCode() {
        return airportCode;
    }

    @JsonProperty("AirportCode")
    public void setAirportCode(String airportCode) {
        this.airportCode = airportCode;
    }

    @JsonProperty("airportId")
    public Integer getAirportId() {
        return airportId;
    }

    @JsonProperty("AirportID")
    public void setAirportId(Integer airportId) {
        this.airportId = airportId;
    }

    @JsonProperty("metroCodeBool")
    public Boolean getMetroCodeBool() {
        return metroCodeBool;
    }

    @JsonProperty("MetroCodeBool")
    public void setMetroCodeBool(Boolean metroCodeBool) {
        this.metroCodeBool = metroCodeBool;
    }
}

I have a different @JsonProprty value on setter and getter because the name of the field when I read from API (i.e. deserialization) is different from when I write the POJO to file (i.e. serialization).
This is how I read the String
ObjectMapper mapper = new ObjectMapper();
mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
TypeReference<List<AirConfig>> typeRef = new TypeReference<List<AirConfig>>() {};

List<AirConfig> configs = mapper.readValue(jsonStr, typeRef);

//Logic

But I keep getting this error -
com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "airportCode" (class org.json.JSONObject), not marked as ignorable (0 known properties: ])

How do I fix this?

A: You have duplicate property airportCode and AirportCode, I would just add @JsonProperty("AirportCode") to airportCode:
@JsonProperty("AirportCode")
String airportCode;

public String getAirportCode() {
    return airportCode;
}

public void setAirportCode(String airportCode) {
    this.airportCode = airportCode;
}


text:
Q: Fucntion parameter values to replace the integer from a string I have a function the parameter has more than one values which I'm passing them after a loop. I want to use the values Im getting to replace integers in a string by there older. This is my code below
onGetValues: function(response) {
            var message = response;
            var myValues = [];
            //Then Im looping it here to get all the value passed from the response ie "my name", "surname", "age"
            for (var i = 0;  i < message.length; i++) {
                myValues += message[i];
            }
            //global object with a string value like 12==12AND03==Im thirty
            var test == originalGlobalString
            //how can loop in the string above to replace the integers in the string with the values from  from the respnse parameter values and display like my name == surname AND age == im thirty?
            },

A: What you have put forward is not making sense to me, but here is part of what you are asking for:
Working Example: https://jsfiddle.net/Twisty/bo6s1e9r/
JavaScript
$(function() {
  var myData = [
    "My Name", "Surname", "Age", "I'm thirty"
  ];

  function pad(i) {
    if (i.toString().length < 2) {
      return "0" + i;
    } else {
      return i;
    }
  }

  function getValues(t) {
    var myValues = [];
    var myString = "";
    $.ajax({
      url: "/echo/json/",
      type: "post",
      data: {
        json: JSON.stringify(myData)
      },
      success: function(response) {
        console.log(response);
        $.each(response, function(i, v) {
          myValues.push(v);
          myString += pad(i) + "==" + v + "AND";
        });
        //Remove last "AND"
        myString = myString.slice(0, -3);
        console.log("Array: ", myValues);
        console.log("String: ", myString);
        if (t == "array") {
          $("#results").html(myValues.join(", "));
        } else {
          $("#results").html(myString);
        }
      }
    });
  }
  $("#btn-1").click(function(e) {
    console.log("Click Event fired.");
    getValues();
  });
});

Now if you want to get a string that says:
My Name==SurnameANDAge==I'm thirty

You can step past one of your steps and do something like:
function getValues(t) {
    var myString = "";
    $.ajax({
      url: "/echo/json/",
      type: "post",
      data: {
        json: JSON.stringify(myData)
      },
      success: function(response) {
        console.log(response);
        for (var i = 0; i < response.length; i += 2) {
          myString += response[i] + "==" + response[i + 1] + "AND";
        }
        console.log(myString);
        $("#results").html(myString.slice(0, -3));
      }
    });
  }

Since you didn't really clarify what you're doing with this, it's hard to help further.
Update
It took a bit of head scratching, but then I realized what you were trying to do. Basically we want to template, so seek in the string for a Integer and replace it with a corresponding string, based on that index in an array.
For example, if you have this string:
"0==1AND2==I'm thirty"

and you have this array:
["My Name", "Surname", "Age"]

The result would be a new string:
"My Name==SurnameANDAge==I'm thirty"

Working Example: https://jsfiddle.net/Twisty/bo6s1e9r/5/
  function getValues(response) {
    var partsA = testString.split("AND");
    console.log("A:", partsA);
    var partsB = [];
    var newString = "";
    $.each(partsA, function(k, v) {
      partsB = v.split("==");
      console.log("B-1:", partsB);
      if (!isNaN(partsB[0])) {
        partsB[0] = myData[parseInt(partsB[0])];
      }
      if (!isNaN(partsB[1])) {
        partsB[1] = myData[parseInt(partsB[1])];
      }
      console.log("B-2:", partsB);
      partsA[k] = partsB.join("==");
    });
    newString = partsA.join("AND");
    console.log("S:", newString);
    return newString;
  }

This chunks the string into pieces based on "AND". We then break those into chunks based on "==". We examine each part, using isNaN() (Is Not a Number function), and if we find a number, we substitute the number with the string value from our data array.
For the test data, our console will show:
A: Array [ "0==1", "2==Im thirty" ]
B-1: Array [ "0", "1" ]
B-2: Array [ "My Name", "Surname" ]
B-1: Array [ "2", "Im thirty" ]
B-2: Array [ "Age", "Im thirty" ]
S: My Name==SurnameANDAge==I'm thirty

The function then return the string. This could be improved to escape things like " or ' that could cause issues. Also if you have a string like:
"0 is Mary==1AND2==I'm Thirty"

This will fail and 0 will not be detected since isNaN() will return true on a string of this nature. Your result would be:
"0 is Mary==SurnameANDAge==I'm Thirty"

Hope that helps.


text:
Q: Accordion Icon is changing when Accordion-inner have some click events : Bootstrap 2.3 version I am using bootstrap 2.3 in my project. In that there is one popover inside of accordion body, also accordions icons I am changing based on show and hide function it's working fine. But when I have any popover inside accordion body, Once that event is trigger my icon is changing.
Steps to produce issue:

*

*open first Accordion

*click the "click for popover" button and check weather accordion header icon is changed or not.

*Try second time also, If it's not happened on first time.

My Fiddle

$('.accordion-group').on('show', function(event) {
    $(this).find('.accordion-toggle').removeClass('arrow-down').addClass('arrow-up');
    event.stopPropagation();
});
$('.accordion-group').on('hide', function(event) {
    $(this).find('.accordion-toggle').removeClass('arrow-up').addClass('arrow-down');
    event.stopPropagation();
});

$('#elem').popover();
.arrow-down {
background: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAwAAAAMCAYAAABWdVznAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAAAHwAAAB8ARUP7eQAAAAYdEVYdFNvZnR3YXJlAHBhaW50Lm5ldCA0LjAuNWWFMmUAAACISURBVChTvc+xCoNAEIThDXkQH8FCYhGwsRLEgJ2lEN81VQg2toIW2qVK7z9RREEtHfjg7liWOTslIZzxeJhgYhU+uOmykwQd3rpEaNEg1cMiFzyh4Rc82BU5fqjxf5xS4AstUwMtmJNBm0r4eKCHhtViMzFUTzSsGkd/W9XbrLGXO9zxeG7MBoKmGaM1wCzfAAAAAElFTkSuQmCC) no-repeat 300px 10px;
}

.arrow-up {
background: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAMCAYAAABr5z2BAAAABGdBTUEAALGPC/xhBQAAAAlwSFlzAAAbrQAAG60BIeRSlQAAABh0RVh0U29mdHdhcmUAcGFpbnQubmV0IDQuMC41ZYUyZQAAANpJREFUOE9jGJzAwsJCyM7OztPMzIwPKkQ8sLe353F2dl7v6ur6BEjPBmI1qBRxAGgAh6OjY4m7u/t/oCF/gQacBtJuUGmiAQvQC7YuLi5fgZr/Ozk5fQCyC6ByxANLS0sxoAsuAzX/dXNz+w9kzwKGDydUmijADPSSA9AVv4CG/Ae5CIhjoXL4gY2NjSjQxlKghtdQb5wGGhYClcYPgBotgQG5BqjxN9TpM4CaNaDS+AEoDQA13ABpBNr+G2hQkpWVFS9UmijABDTAEGj7DqAhIFuZIMLYAAMDAPuUQ9EUeG3QAAAAAElFTkSuQmCC) no-repeat 300px 10px;
}
.well {
    margin-top: 40px;
}

<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/2.3.2/css/bootstrap.min.css" rel="stylesheet"/>

   Collapsible Group Item #1

first table

First Content

     cliick for popover

   Collapsible Group Item #2

second table

second Content

A: you don't have to do the "extra" work for changing the arrow. Bootstrap adds/removes collpased class based on accordion-group state. you can use this class name to change the arrow state.
html
add collapsed class name to set the accordion in collapsed state
Collapsible Group Item #1

and remove in class name from corresponding content div

css
.accordion-toggle.collapsed {
    background: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAwAAAAMCAYAAABWdVznAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAAAHwAAAB8ARUP7eQAAAAYdEVYdFNvZnR3YXJlAHBhaW50Lm5ldCA0LjAuNWWFMmUAAACISURBVChTvc+xCoNAEIThDXkQH8FCYhGwsRLEgJ2lEN81VQg2toIW2qVK7z9RREEtHfjg7liWOTslIZzxeJhgYhU+uOmykwQd3rpEaNEg1cMiFzyh4Rc82BU5fqjxf5xS4AstUwMtmJNBm0r4eKCHhtViMzFUTzSsGkd/W9XbrLGXO9zxeG7MBoKmGaM1wCzfAAAAAElFTkSuQmCC) no-repeat 300px 10px;
}

.accordion-toggle {
    background: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAMCAYAAABr5z2BAAAABGdBTUEAALGPC/xhBQAAAAlwSFlzAAAbrQAAG60BIeRSlQAAABh0RVh0U29mdHdhcmUAcGFpbnQubmV0IDQuMC41ZYUyZQAAANpJREFUOE9jGJzAwsJCyM7OztPMzIwPKkQ8sLe353F2dl7v6ur6BEjPBmI1qBRxAGgAh6OjY4m7u/t/oCF/gQacBtJuUGmiAQvQC7YuLi5fgZr/Ozk5fQCyC6ByxANLS0sxoAsuAzX/dXNz+w9kzwKGDydUmijADPSSA9AVv4CG/Ae5CIhjoXL4gY2NjSjQxlKghtdQb5wGGhYClcYPgBotgQG5BqjxN9TpM4CaNaDS+AEoDQA13ABpBNr+G2hQkpWVFS9UmijABDTAEGj7DqAhIFuZIMLYAAMDAPuUQ9EUeG3QAAAAAElFTkSuQmCC) no-repeat 300px 10px;
}

js
remove the handles for show and hide
// $('.accordion-group').on('show', function(event) {
//     $(this).find('.accordion-toggle').removeClass('arrow-down').addClass('arrow-up');
//     event.stopPropagation();
// });
// $('.accordion-group').on('hide', function(event) {
//     $(this).find('.accordion-toggle').removeClass('arrow-up').addClass('arrow-down');
//     event.stopPropagation();
// });
$('#elem').popover();

check this fiddle

A: With the solution from above Fiddle , We need to add below line in bootstrap js plugin Where Accordion collapse options are there. We need to find "Show:function" for collapse and add line at end of that function
this.$element.prev().find('.accordion-toggle').removeClass('collapsed')


text:
Q: Dynamically Centre Align an Input Text Field in Flutter I have used a TextFormField() in my app for inserting an amount of money one can withdraw by inserting the number. But the issue after inserting the amount in the box the inputted text is not getting dynamically centred with reference to the box. I wanted to centre the inputted text dynamically like the one which is present in the Google Pay application. I have hereby attached the photo of the Gpay App like which I want it in my app.
Gpay Amount Entering Screen

Below I have attached my code and the image of my application where i am facing the issue of alignment.
`
Center(
                child: Container(
                  height: 124,
                  width: 224,
                  decoration: BoxDecoration(
                    borderRadius: BorderRadius.circular(4),
                    border: Border.all(
                      color: formInputFieldBortderColor,
                      width: 1,
                    ),
                  ),
                  child: Row(
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: [
                      Padding(
                        padding: const EdgeInsets.only(left: 82),
                        child: SvgPicture.asset(AssetRewards.rupees),
                      ),
                      Expanded(
                        child: TextFormField(
                          textDirection: TextDirection.ltr,
                          textAlignVertical: TextAlignVertical.center,
                          maxLength: 3,
                          controller: _textControllor,
                          cursorColor: individualDateColor,
                          keyboardType: TextInputType.number,
                          inputFormatters: [
                            FilteringTextInputFormatter.digitsOnly
                          ],
                          style: GoogleFonts.mulish(
                            color: activeTextColor,
                            fontSize: 44,
                            fontWeight: FontWeight.w400,
                            letterSpacing: 2,
                          ),
                          decoration: const InputDecoration(
                            hintText: "0",
                            hintStyle: TextStyle(color: textLightColor),
                            border: InputBorder.none,
                            counterText: "",
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
              ),

`
I have used this in my application but it doesn't makes the inputted text dynamically centre.

A: you are not able to set text in center cause of you rupees image dont give static padding to your image try to adjust it and give your TextFormField textAlign value center.
 textAlign: TextAlign.center,


text:
Q: Share data between specific instances of same class I have the following problem. Assume we have two instances of the class Assignment.
Each instance has a start and an end date. The second assignment starts when the first ends. Now I have some information in the first assignment which is also needed in the second assignment when the first one is expired.
I would need something like a static variable for this both instances, but not static for the whole class.
What is the best way to do this?
Thanks
Matthias
===============EDIT===============
I think my question was not specific enough.
I know how to copy data from one into another, but this is not appropriate in this situation.
My assignments are the linking between employees and projects to resolve a n:n relation. But one employee could have several assignments to the same project and I need information which is important for all assignments.
If I update the information in assignment1 this should be updated in all other assignments which connect the employee to this specific project.
For performance reasons, I would prefer to change this in one central place and not to copy the information by hand.
===============EDIT===============
I thought about the problem, and I think my problem could be solved if every assignment holds a reference to the information. With this, a change in one of the assignments should automatically be distributed to the others.
===============EDIT===============
Abaddon666 answer and annotation were correct, the remaining question is how to share that reference to all instances of assignment in a proper way. We solved it in such a way, that we use a table in the DB where we store the information with two foreign keys and load the information for an employee and for a specific project when it is needed. I will accept Abaddon666 answer, but maybe there is a better solution as the current one.

A: What you are trying to achieve is basic Composition.
You want 1 to x instances of a certain type to share the same value. This can be achieved by creating a class that models your shared Information and add it as a field to your assignment:
public class Assignment{
    private Date startDate;
    private Date endDate;
    private Information information;

    public Assignment(Information information){
         this.information = information
    }

    public Information getInformation(){
         return this.information
    }
...
}

...

Information sharedInformation = new Information();
Assignment assignment1 = new Assignment(sharedInformation);
Assignment assignment2 = new Assignment(sharedInformation);


text:
Q: Formulae for measures of the Koch snowflake in terms of side length? As part of the topic sequences and series, I'm completing a mathematical investigation which deals with the perimeter and area of the Koch snowflake.
Part of the assignment involves deriving general formulae for measures of the Koch snowflake.
A simple example — where $n$ = shape, iteration number; $N$ = number of sides; $l$ = length of each side (and $l_0$ = 1 unit); $P$ = total perimeter of shape; $n\geqslant0$:
\begin{array}{|c|c|c|c|}
\hline
n& N & l & P \\ \hline
 n_k=k & N_n=3*4^n & l_n={1\over3^n} & P_n=3*\left(\frac{4}{3}\right)^n\\ \hline
\end{array}
For another question (where $l_0$ is still $1$ unit; T = number of added triangles; e = area of each added triangle; a = area of all added triangles; A = total area of the shape), I deduced the following:
\begin{array}{|c|c|c|c|}
\hline
n& N & l & P\\ \hline
 n_k=3^kk*l_k,k\geqslant0 & N_n=3l_n*12^n,n\geqslant0 & l_n=l_n,n\geqslant0 & P_n=3l_n*4^n,n\geqslant0\\ \hline
T & e & a & A\\ \hline
T_n=9l_n*12^{n-1},n\geqslant1 & e_n={\sqrt 3\over 4}{l_n}^2,n\geqslant1 & a_n={\sqrt 3\over 4}l_n*\left(\frac{4}{3}\right)^{n-1},n\geqslant1 & A_n=?\\ \hline
\end{array}
Where $l_0=1$, what would be the difference between writing these formulae in terms of $l_n$ (as above) or $l_0$? Would both approaches be equally valid?
Next, for a question which asked for the formulae in terms of any $l_0$ value (different sizes of the Koch snowflake):
\begin{array}{|c|c|c|c|}
\hline
n& N & l & P\\ \hline
 n_k=? & N_n=? & l_n=l*\left(\frac{1}{3^n}\right),n\geqslant0 & P_n=3l*\left(\frac{4}{3}\right)^n,n\geqslant0\\ \hline
T & e & a & A\\ \hline
T_n=? & e_n={\sqrt 3\over 4}*\left(\frac{1}{9}\right)^n*l^2,n\geqslant1 & a_n={3\sqrt 3\over 16}l^2*\left(\frac{4}{9}\right)^n,n\geqslant1 & A_n={2\sqrt 3\over 5}l^2-{3\sqrt 3\over 20}l^2*\left(\frac{4}{9}\right)^n,n\geqslant0\\ \hline
\end{array}
How can I derive the missing formulae? $n$, $N$ and $T$ are the same for any side length, aren't they?
Note that these formulae are based on data obtained over the course of the investigation $(n_{0–3}$, $N_{0–1},$ $l_0$, $T_{0–1}$, $e_0$ and $a_0$ initially given$)$:
\begin{array}{|c|c|c|c|}
\hline
n& N & l & P & T & e & a & A\\ \hline
 0 & 3 & 1 & 3 & 0 & 0 & 0 & {\sqrt 3\over 4}\\ \hline
 1 & 12 & {1\over 3}& 4 & 3 & {\sqrt 3\over 36} & {\sqrt 3\over 12} & {\sqrt 3\over 3}\\ \hline
 2 & 48 & {1\over 9} & {16\over 3} & 12 & {\sqrt 3\over 324} & {\sqrt 3\over 27} & {10\sqrt 3\over 27}\\ \hline
 3 & 192 & {1\over 27} & {64\over 9} & 48 & {\sqrt 3\over 2916} & {4\sqrt 3\over 243} & {94\sqrt 3\over 243}\\ \hline
\end{array}

A: Putting this as an answer because it's a bit long for a comment and I think I now have enough information to diagnose the issue. It sounds to me like you're mis-reading the phrase "in terms of". "In terms of" never means "you must use"; for example, if I ask you to write $4$ in terms of $x$ the answer is still $4$. For the second question, it looks to me like it's telling you "you may use $l_k$ in your expressions", not "you must use $l_k$". For example, the correct expression for $n_k$ should still be $k$.
Likewise, in the third part, you don't have to use $l_0$ if you don't need to - you're just not allowed to use $l_k$ anymore. So write $n_k$ and $N_n$ without using $l_k$ - which should be simple, since you did exactly that in the first part.


text:
Q: Android: GPS Geocoding onLocationChanged method, how come View elements are updated asynchronously I've been testing LocationListener (http://developer.android.com/reference/android/location/LocationListener.html), and implemented the abstract onLocationChange.
In the onLocationChange method I've modofied the TextViews in the main activity to show the actual coordinates changes.
Once the activity starts and after the GPS has started the connection, the TextViews updates corectly on every coordinate change.

*

*Still I'm wondering how this is possibile since I've not implemented
an AsyncTask or a secondary thread targeted on the TextViews?

*If the process is not asynchronous how are TextViews updated every
time?

*Shoudn't I see just one update of the TextView or worse none?

This is my code:
package com.example.androidgps_get_coordinates;

import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.app.Activity;
import android.content.Context;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {

    TextView textView_lat;
    TextView textView_long;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        textView_lat=(TextView)findViewById(R.id.textV_lat);
        textView_long=(TextView)findViewById(R.id.textV_long);

        String serviceString=Context.LOCATION_SERVICE;
        LocationManager locationManager;    //remember to import LocationManager
        locationManager=(LocationManager)getSystemService(serviceString);

         locationManager.requestLocationUpdates(
                    LocationManager.GPS_PROVIDER, 0, 0,
                    new LocationListener() {
                      public void onLocationChanged(Location location) {
                          textView_lat.setText(String.valueOf(location.getLatitude()));
                          textView_long.setText(String.valueOf(location.getLongitude()));
                      }
                      public void onProviderDisabled(String provider) {}
                      public void onProviderEnabled(String provider) {}
                      public void onStatusChanged(String provider, int status,
                                                  Bundle extras) {}
                    }
                  );

        String provider=LocationManager.GPS_PROVIDER;
        Location l= locationManager.getLastKnownLocation(provider);
    }

A: onLocationChange is called every time you get a location, hence the TextView's will be updated since you are running it in the UI Thread. What makes you thing you need an AsyncTask or a separate Thread?
Another thing though, is a good practice to check for null value of Location before you try to read from it.

A: You have written listener (LocationListener) and called requestLocationUpdate*s*()
It means that you are asking provider to deliver locations periodically - usually every 1 s.
BTW I don't know why did you wrote the line:
Location l= locationManager.getLastKnownLocation(provider);

It does nothing.

A: onLocationChanged method works like other Listener like onClickListener. When your location change this listener will call and it's like user click a button. So no need to use Thread but if you want save th Locations data or something else it will be important to use Thread.
This is my example that use locationListener with thread ,but Thread used only for send data nothing else:
    public void onLocationChanged(final Location location) {
    // TODO Auto-generated method stub
    locationThread = new Thread(new Runnable() {

        public void run() {
            // TODO Auto-generated method stub
            int Status = 0;
            latitudeField=location.getLatitude();
            longitudeField=location.getLongitude();
            Date dt = new Date();
            dt.setDate(dt.getDate());
            Status=CallSoap.CurrentPosition(YarVisitLogin.UserName, YarVisitLogin.Password, YarVisitLogin.Visitor, latitudeField, longitudeField, PersianCalendar.getPersianDate(dt), PersianCalendar.getPersianTime());
            yardb.InsertIntoMyLocations(yardb.getMaxMyLocation_ID()+1, PersianCalendar.getPersianDate(dt), PersianCalendar.getPersianTime(), Double.toString(latitudeField), Double.toString(longitudeField), Status);

        }
    });
    locationThread.start();

}


text:
Q: How I can get full query from relation I have model Company with relation
public function contact()
{
    return $this->belongsToMany(\App\Models\Contact::class, 'company_contacts', 'company_id', 'contact_id')
        ->wherePivot('primary', '=', true)->withPivot('primary');
}

I need to sort items with contact.last_name column.
So I build query
$scope = $scope->leftJoin('company_contacts', "companies.id", '=', "company_contacts.company_id")
               ->leftJoin('contacts', "company_contacts.contact_id", '=', "contacts.id")
               ->groupBy(['companies.id', 'contacts.id'])
               ->select(['companies.*', 'contacts.last_name'])
               ->order('contacts.last_name');

But this should be more universal
Value of names and tables I can get from $relation
  $relation = $scope->getRelation('contact');
  $key = $relation->getQualifiedOwnerKeyName(); // etc

And then substitute values into the scope-builder. But I can not get this part::
 ->wherePivot('primary', '=', true)->withPivot('primary')

A: I found public property pivotWheres of BelongsToMany class and I can use that.
$relation->pivotWheres


text:
Q: How do I setup my application under WebSphere and IBM HTTP Server I have setup WebSphere and IBM HTTP Server on a machine and I have been able to test that the HTTP Server is working. The issue comes when I try to get the portal that was given to us by the company setting up our new system. I can copy the into the htdocs directory but index.jsp files do not detect as the default document and if I click on a .jsp file to try to load it that way I get an error that it cannot find *.jsp, which is the file I just clicked on and know is there.
Any help is greatly appreciated. I have never used WebSphere before and this is completely different from IIS and Apache which I have dealt with before. I did try running the files they sent over using XAMPP with Apache and Tomcat but I got basically the same results.

A: You shouldn't be copying JSP's into the htdocs/ directory.
httpd.conf should reference a file named plugin-cfg.xml. This file is generated by the application server and describes to the WAS WebServer Plugin which requests are dynamic resources that should be proxied (forwarded to the AppServer). Part of your setup should be to generate and propogate this XML file.
Likely you get a 404 because the host aliases or context roots contained in plugin-cfg.xml don't match what's being requested, so the core of Apache/IHS tries to serve it as a static file.
I'd suggest revisiting the setup steps wrt generating or propogating plugin-cfg.xml and double-checking the paths/contents vs. what you see in yur browser.

A: Make sure your application is mapped to right IHS server(s) and appserver(s) and then you can generate the plugin-cfg.xml and propagate the new xml file(May have to do it manually). Make sure the virtual hosts are correctly setup in the httpd.conf and in WebSphere Cell.
Check application mapped to modules.
Check right virtual host and host aliases are defined.
Generate the plugin either from the console or use command GenPluginCfg.sh(bat)
and Manually copy the new xml file (Can do it from admin console also)


text:
Q: Como ejecutar un PHP con Ionic 2 Al hacer la peticion de mi-php.php por medio de GET de Http me retorta literalmente el codigo del archivo php en una cadena de texto, lo que necesito es que se ejecute el archivo php y me retorne el resultado de la consulta a la base de datos en formato Json
Los codigos son:
src/providers/servi-productos.ts
import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';

/*
  Generated class for the ServiProductos provider.

  See https://angular.io/docs/ts/latest/guide/dependency-injection.html
  for more info on providers and Angular 2 DI.
*/
@Injectable()
export class ServiProductos {

  constructor(public http: Http) {
    console.log('Hello ServiProductos Provider');
  }

  getPHP(){
    this.http.get("assets/php/mi-php.php").subscribe(data => {
        console.log(data);
    });
  }

}

src/app/app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { ErrorHandler, NgModule } from '@angular/core';
import { IonicApp, IonicErrorHandler, IonicModule } from 'ionic-angular';

import { MyApp } from './app.component';
import { HomePage } from '../pages/home/home';
import { ListPage } from '../pages/list/list';
import { Perfil } from '../pages/perfil/perfil';

import { StatusBar } from '@ionic-native/status-bar';
import { SplashScreen } from '@ionic-native/splash-screen';
import { ServiProductos } from '../providers/servi-productos';

@NgModule({
  declarations: [
    MyApp,
    HomePage,
    Perfil,
    ListPage
  ],
  imports: [
    BrowserModule,
    IonicModule.forRoot(MyApp, {
      //backButtonText: 'Volver',
      iconMode: 'ios',
      modalEnter: 'modal-slide-in',
      modalLeave: 'modal-slide-out',
      tabsPlacement: 'bottom',
      pageTransition: 'ios-transition'
    }),
  ],
  bootstrap: [IonicApp],
  entryComponents: [
    MyApp,
    HomePage,
    Perfil,
    ListPage
  ],
  providers: [
    StatusBar,
    SplashScreen,
    ServiProductos,
    {provide: ErrorHandler, useClass: IonicErrorHandler}
  ]
})
export class AppModule {}

src/page/perfil/perfil.ts
import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import { ServiProductos } from '../../providers/servi-productos';

/**
 * Generated class for the Perfil page.
 *
 * See http://ionicframework.com/docs/components/#navigation for more info
 * on Ionic pages and navigation.
 */
@IonicPage()
@Component({
  selector: 'page-perfil',
  templateUrl: 'perfil.html',
})
export class Perfil {
    login: {username?: string, password?: string} = {};
  submitted = false;

  constructor(public navCtrl: NavController, public navParams: NavParams, public serviProduct: ServiProductos) {
  }

  ionViewDidLoad() {
    console.log('ionViewDidLoad Perfil');
    this.serviProduct.getPHP();
  }

}

src/assets/php/mi-php.php
<?php

header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
console.log("php corriendo");
system.out.println("some")
$conn = new mysqli("localhost", "root","","nombreBD");

$query="SELECT * FROM nombreTabla;

$result = $conn->query($query);
$rows = array();
while($r = mysqli_fetch_assoc($result)) {
    $rows[] = $r;
}

$conn->close();

echo json_encode($rows);

?>

A: Te falta esto
$result = $conn->query($query);
$rows = array();
while($r = mysqli_fetch_assoc($result)) {
    $rows[] = $r;
}
header('Content-Type: application/json');
echo json_encode($rows);

A: Veo un error en tu codigo de la pregunta y es que FALTA UNA DOBLE COMILLA EN TU SELECT :
$query="SELECT * FROM nombreTabla";

$result = $conn->query($query);
$conn->close();

echo $result;

Y segundo, si quieres obtener datos lo normal seria devolver un json. (Complementando con la respuesta de Jorge)
$result = $conn->query($query);
$rows = array();
while($r = mysqli_fetch_assoc($result)) {
    $rows[] = $r;
}
echo json_encode($rows);


text:
Q: Direct X Sprite Rendering Issue I have been writing my own library using Direct X and have hit an odd issue. Whilst trying to render an animating sprite I am simply seeing a big black square:

I have stepped through the code obsessively and have concluded that it must be something about the loading of the actual sprites, because everything that I can see in my code is fine. Obviously, I cannot step into the functions such as BltFast, and so cannot tell if my sprite surfaces are being blitted onto the backbuffer successfully.
Here are my load and render functions for the sprite:
SPRITE::LOAD
/**
 *  loads a bitmap file and copies it to a directdraw surface
 *
 *  @param  pID             wait
 *  @param  pFileName       name of the bitmap file to load into memory
 */
void Sprite::Load (const char *pID, const char *pFileName)
{
    //  initialises the member variables with the new image id and file name
    mID                 = pID;
    mFileName           = pFileName;

    //  creates the necessary variables
    HBITMAP             tHBM;
    BITMAP              tBM;
    DDSURFACEDESC2      tDDSD;
    IDirectDrawSurface7 *tDDS;

    //  stores bitmap image into HBITMAP handler
    tHBM                    = static_cast<HBITMAP> (LoadImage (NULL, pFileName, IMAGE_BITMAP, 0, 0, LR_LOADFROMFILE | LR_CREATEDIBSECTION));

    GetObject (tHBM, sizeof (tBM), &tBM);

    //  create surface for the HBITMAP to be copied onto
    ZeroMemory (&tDDSD, sizeof (tDDSD));
    tDDSD.dwSize            = sizeof (tDDSD);
    tDDSD.dwFlags           = DDSD_CAPS | DDSD_HEIGHT | DDSD_WIDTH;
    tDDSD.ddsCaps.dwCaps    = DDSCAPS_OFFSCREENPLAIN;
    tDDSD.dwWidth           = tBM.bmWidth;
    tDDSD.dwHeight          = tBM.bmHeight;
    DirectDraw::GetInstance ()->DirectDrawObject()->CreateSurface (&tDDSD, &tDDS, NULL);

    //  copying bitmap image onto surface
    CopyBitmap(tDDS, tHBM, 0, 0, 0, 0);

    //  deletes bitmap image now that it has been used
    DeleteObject(tHBM);

    //  stores the new width and height of the image
    mSpriteWidth            = tBM.bmWidth;
    mSpriteHeight           = tBM.bmHeight;

    //  sets the address of the bitmap surface to this temporary surface with the new bitmap image
    mBitmapSurface          = tDDS;
}

SPRITE::RENDER
/**
 *  renders the sprites surface to the back buffer
 *
 *  @param  pBackBuffer     surface to render the sprite to
 *  @param  pX              x co-ordinate to render to (default is 0)
 *  @param  pY              y co-ordinate to render to (default is 0)
 */
void Sprite::Render (LPDIRECTDRAWSURFACE7 &pBackBuffer, float pX, float pY)
{
    if (mSpriteWidth > 800)     mSpriteWidth = 800;

    RECT            tFrom;

    tFrom.left      = tFrom.top     =   0;
    tFrom.right     = mSpriteWidth;
    tFrom.bottom    = mSpriteHeight;

    //  bltfast parameters are (position x, position y, dd surface, draw rect, wait flag)
    //  pBackBuffer->BltFast (0 + DirectDraw::GetInstance()->ScreenWidth(), 0, mBitmapSurface, &tFrom, DDBLTFAST_WAIT);
    pBackBuffer->BltFast (static_cast<DWORD>(pX + DirectDraw::GetInstance()->ScreenWidth()),
        static_cast<DWORD>(pY), mBitmapSurface, &tFrom, DDBLTFAST_WAIT);
}

A: The surfaces were simply not a compatible format.
Here's the fixed copybitmap function which I now call in the load function:
extern "C" HRESULT
DDCopyBitmap(IDirectDrawSurface7 * pdds, HBITMAP hbm, int x, int y,
             int dx, int dy)
{
    HDC                     hdcImage;
    HDC                     hdc;
    BITMAP                  bm;
    DDSURFACEDESC2          ddsd;
    HRESULT                 hr;

    if (hbm == NULL || pdds == NULL)
        return E_FAIL;
    //
    // Make sure this surface is restored.
    //
    pdds->Restore();
    //
    // Select bitmap into a memoryDC so we can use it.
    //
    hdcImage = CreateCompatibleDC(NULL);
    if (!hdcImage)
        OutputDebugString("createcompatible dc failed\n");
    SelectObject(hdcImage, hbm);
    //
    // Get size of the bitmap
    //
    GetObject(hbm, sizeof(bm), &bm);
    dx = dx == 0 ? bm.bmWidth : dx;     // Use the passed size, unless zero
    dy = dy == 0 ? bm.bmHeight : dy;
    //
    // Get size of surface.
    //
    ddsd.dwSize = sizeof(ddsd);
    ddsd.dwFlags = DDSD_HEIGHT | DDSD_WIDTH;
    pdds->GetSurfaceDesc(&ddsd);

    if ((hr = pdds->GetDC(&hdc)) == DD_OK)
    {
        StretchBlt(hdc, 0, 0, ddsd.dwWidth, ddsd.dwHeight, hdcImage, x, y,
                   dx, dy, SRCCOPY);
        pdds->ReleaseDC(hdc);
    }
    DeleteDC(hdcImage);
    return hr;
}


text:
Q: Widget - Iframe versus JavaScript I have to develop a widget that will be used by a third party site. This is not an application to be deployed in a social networking site. I can give the site guys a link to be used as the src of an iframe or I can develop it as a JavaScript request.
Can someone please tell me the trade offs between the 2 approaches(IFrame versus JS)?

A: I'm sure many developers/site owners would appreciate a Javascript solution that they can style to their needs rather than using an iframe. If I was going to include a component from a third party, I would rather do it via Javascript because I would have more control.
As far as ease of use, both are similar in simplicity, so no real tradeoff there.
One other thought, make sure you get a SSL cert for whatever domain you're hosting this on and write out the include statement accordingly if the page is served over SSL. In case your site owners have a reason for using SSL, they would surely appreciate this, because Firefox and other browsers will complain when a page is served with a mix of secure/insecure content.

A: I was searching about the same question and I found this interesting article:
http://prettyprint.me/prettyprint.me/2009/05/30/widgets-iframe-vs-inline/

Widgets are small web applications that can easily be added to any web
  page. They are sometimes called Gadgets and are vastly used in growing
  number of web pages, blogs, social sites, personalized home pages such
  as iGoogle, my Yahoo, netvibes etc. In this blog I use several
  widgets, such as the RSS counter to the right which displays how many
  users are subscribed to this blog (don't worry, it'll grow, that's a
  new blog ;-) ). Widgets are great in the sense that they are small
  reusable piece of functionality that even non-programmers can utilize
  to enrich their site.
I've written several such widgets over the time both "raw" widgets
  that can get embedded in any site as well as iGoogle gadgets which are
  more structured, worpress*, typepad and blogger widgets, so I'm happy
  to share my experience.
As a widget author, for widgets that run on the client side (simple
  embeddable HTML code) you have the choice of writing your widget
  inside an iframe or simply inline the page and make it part of the dom
  of the hosting page. The rest of the post discusses the pros and cons
  of both methods.
How is it technically done? How to use an iframe or how to implement
  an inline widget?
Iframes are somewhat easier to implement. The following example
  renders a simple iframe widget: http://my-great-widget.com/widgwt' width="100" height="100"
  frameborder='0'>
frameborder='0′ is used to make sure the ifrmae doesn't have a border
  so it looks more natural on the page. The
  http://my-great-widget.com/widget is responsible of serving the widget
  content as a complete HTML page.
Inline gadgets might look like this:
function createMyWidgetHtml() {  return "Hello world of widgets"; }
  document.getElementById('myWidget').innerHTML = createMyWidgetHtml();
  As you can see, the function createMyWidgetHtml() it responsible for
  creating the actual widget content and does not necessarily have to
  talk to a server to do that. In the iframe example there must be a
  server. In the inline example there does not need to be a server,
  although if needed, it's possible to get data from the server, which
  actually is a very common case, widgets typically do call server side
  code. Using the inline method server side code is invoked by means of
  on-demmand javascript.
So, to summarize, in the iframe case we simply place an iframe HTML
  code and point the source of the iframe to a sever location which
  actually serves the content of the widget. In the inline case we
  create the content locally using javascript. You may of course combine
  usage of iframe with javascript as well as use of the inline method
  with server side calls, you're not restricted by that, but the paths
  start differentially.
So what is the big deal? What's the difference? There are several
  important differences, so here starts the interesting part of the
  post.
Security. iFrame widgets are more secure.
What risks do gadgets impose and who's actually being put at risk? The
  user of the site and the site's reputation are at risk.
With inline gadgets the browser thinks that the source of the gadget
  code code comes from the hosting site. Let's assume you're browsing
  your favorite mail application http://my-wonderful-email.com and this
  mail application has installed a widget that displays a clock from
  http://great-clock-widgets.com/. If that widgets is implemented as an
  inline widget the browser thinks that the widget's code originated at
  my-wonderful-email.com and not at great-clock-widgets.com and so it'll
  let the widget's code ultimately get access to the cookies owned by
  my-wonderful-email.com and the widget's evil author will steal your
  email. It's important to realize that browsers don't care about where
  the javascript file is hosted; as long as the code runs on the same
  frame, the browser regards all code as originationg at the frame's
  domain. So, you as a user get hurt by losing control over your email
  account and my-wonderful-email gets hurt by losing its reputation.
If the same clock would have gotten implemented inside an iframe and
  the iframe source is different from the page source (which is the
  common case, e.g. the page source is my-wonderful-email.com and the
  gadget source is great-clock-widgets.com) then the browser would not
  allow the clock widgets access to the page cookies, nor will it allow
  access to any other part of the hosting document, including the host
  page dom. That's way more secure. As a matter of fact, personal home
  pages such as iGoogle don't even allow inline gadgets, only iframe
  gadgets are allowed. (inline gadgets are allowed only in rare cases,
  only after thorough inspection by the iGoogle team to make sure
  they're not malicious)
To sum up, iframe widgets are way more secure. However, they are also
  way more limited in functionality. Next we'll discuss what you lose in
  functionality.
Look and feel In the look and feel battle inline gadgets (usually**)
  win. The nice thing about them is that they can be made to look as
  part of the page. They can inherit CSS styles from the page, including
  fonts, colors, text size etc. Iframes, OTHO must define their CSS from
  the grounds up so it's pretty hard for them to blend nicely in the
  page.
But what's even more important is that iframes must declare what their
  size is going to be. When adding an iframe to a page you must include
  a width and a height property and if you don't, the browser will use
  some default settings. Now, if your widget is a clock widget that's
  easy enough b/c you know exacly what size you want it to be, but in
  many cases you don't know ahead of time how much space your widget is
  going to take. If, for example you're authoring a widget that displays
  a list of some sort and you don't know how long this list is going to
  be or how wide each item is going to be. Usually in HTML this is not a
  big deal because HTML is a declarative based language so all you need
  to do is tell the browser what you want to display and the browser
  will figure out a reasonable layout for it, however with iframe this
  is not the case; with ifrmaes browsers demand that you tell it exactly
  what the iframe size is and it will not figure it out by itself. This
  is a real problem for widget authors that want to use iframes – if you
  require too much space the page will have voids in it and if you
  specify too little the page will have scrollbars in it, god forbids.
Look and feel wise, inline wins. But note that this really depends on
  your widget application. If all you want to do is a clock, you may get
  along with an iframe just as well.
Server side vs. Client side IFrmaes require you specify a src URL so
  when implementing a widget using an iframe you must have server side
  code. This could both be a limitation and a headache to some (owning a
  server, domain name etc, dealing with load, paying network bills etc)
  but to others this is actually a point in favor of iframes b/c it
  let's you completely write your widgets in server side technologies,
  so you can write a lot of the code and actually almost all of it using
  your favorite server side technology whether it be asp.net, django,
  ror, jsp, struts , perl or other dinosaurs. When implementing an
  inline gadget you'll find yourself more and more practicing your
  javascript Ninja.
What's the decision algorithm then? Widget authors: If the widget can
  be implemented as an iframe, prefer an Iframe simply for preserving
  users security and trust. If a widget requires inlining (and the
  medium allows that, e.g. not iGoogle and friends) use inline but dare
  not exploit users trust!
Widget installers: When installing a widget in your blog you don't see
  a "safe for users" ribbon on the widgets. How can you tell if the
  widget is safe or not? There are two alternatives I can suggest: 1)
  trust the vendor 2) read the code. Either you trust the widget
  provider and install it anyway or you take the time to read its code
  and determine yourself whether it's trustworthy or not. Reality is
  that most site owners don't bother reading code or are not even aware
  of the risk they're putting their users at, and so widget providers
  are blindly trusted. In many cases this is not an issue since blogs
  don't usually hold personal information about their readers. I suspect
  things will start changing once there are few high profile exploits
  (and I hope it'll never get to it).
Users: Usres are kept in the dark. Just as there are no "safe for
  users" ribbons on widgets site owners install, there are no "safe to
  use" sites and basically users are kept in the dark and have no idea,
  even if they have the technical skills, whether or not the site they
  are using contains widgets, whether the widgets are inline or not and
  whether they are malicious. Although in theory a trained developer can
  inspect the code up-front, before running it in her browser and losing
  her email account to a hacker, however this is not practical and there
  should be no expectation that users en mass will do that. IMO this is
  an unfortunate condition and I only hope attackers will not find a way
  of taking advantage of that and doom the wonderful open widget culture
  on the web.
Happy widgeting folks!

*

*Some blog platforms have a somewhat different structures for widgets and they may sometimes have both widgets and plugins that may
  correlate in their functionality, but for the matter of the discussion
  here I'll lously use the term widget to discuss the "raw" type which
  consists of client side javascript code
  ** Although in most cases you'd want widgets to inherit styles from the hosting page to make them look consistent with it, sometimes you
  actually don't want the widget to inherit styles from the page, so in
  this case iFrames let you start your CSS from scratch.

A: If the widget can be embedded in an iframe, it will be better for the frontend performance of the hosting site as iframes do not block content download. However, as others have commented there are other drawbacks to using iframes.
If you do implement in javascript, please consider frontend performance best practices when developing.  In particular, you should look at Non blocking javascript loading.  Google analytics and other 3rd party widget providers support this method of loading.  It would also help if you can load the javascript at the bottom of the page.

A: Nice to know that it's not to be deployed in a social networking site... that merely leaves the rest of the web ;-)
What would be most useful depends on your widget.  IFrames and javascript generally serve quite different purposes, and can be mixed (i.e. javascript inside an iframe, or javascript creating an iframe).

*

*IFrames got sizing issues;  if it's supposed to be an exact fit to the page, do you know  that it renders the same on all browsers, the data won't overflow it's container etc?

*IFrames are simple.  They can be a simple, static HTML-page.

*When using IFrames, you expose your widget quite plainly.

*But then again, why not have your third party site simply include the HMTL at a given url?  The HTML can then be extended to contain javascript when/if you need it.

*Pure Javascript allows for more flexibility but at the cost of some complexity.

A: Why not doing both ?
I prefer to offer third party sites a script like:
 <script type="text/javascript" src="urlToYourScript"></script>

the file on your server looks like :
document.writeln('<iframe src="pathToYourWidget"
name="MagicIframe" width="300" height="600" align="left" scrolling="no"
marginheight="0" marginwidth="0" frameborder="0"></iframe>');

UPDATE:
one disadvantage of using an iframe that points to an url on your server is that you do not generate a "real" backlink if someone clicks on an url from your server pointing to your server.

A: The big plus of iframes: all CSS and JS is separated from the host page, so your existing CSS just works. (If you want the host site to style your content to fit in, that's a minus of course.)
The big minus of iframes: they have a fixed width and height and scroll-bars will appear if your content is larger.


text:
Q: React Router doesn't working when i follow the steps from tutorials I'm new in reacting and I have this in the App.js, I've been watching tutorials but all tell me what needs to make is this but doesn't work on me.

import logo from './logo.svg';
import './App.css';
import CoinElement from './Components/Coins/CoinElement';
import CoinHead from './Components/Coins/CoinHead';
import NavigationBar from './Components/Common/NavigationBar';
import { BrowserRouter, Route, Routes, Link } from 'react-router-dom';
import CoinsPage from './Components/Coins/CoinsPage';
import ExchangesPage from './Components/Exchanges/ExchangesPage';
import * as React from 'react';

export default class App extends React.Component {
  render(){
  return (

        <NavigationBar></NavigationBar>
        <BrowserRouter>

Welcome to React Router Tutorial

<Link to={'/'} className="nav-link"> Home </Link>

<Link to={'/coins'} className="nav-link">Contact</Link>

<Link to={'/exchanges'} className="nav-link">About</Link>

            <Routes>
             <Route path="/coins" component={CoinsPage}/>
             <Route path="/exchanges" component={ExchangesPage}/>
            <Route component={Error}/>
           </Routes>
           </BrowserRouter>

  );
}
}

A: I think you are missing the <Switch>
   <Switch>
        <Route path="/coins" component={CoinsPage}/>
        <Route path="/exchanges" component={ExchangesPage}/>
        <Route component={Error}/>
   </Switch>

https://v5.reactrouter.com/web/guides/quick-start


text:
Q: How to remove AM/PM from DateTime Column in SQl? Please help me, How to remove AM/PM from varchar datetime.
For example 2/14/2017 2:21:18 PM , I want to remove PM from that.
I have DateTime as  a string  -
'2022-03-11 11:13:24 AM'

I want to remove AM/PM
I tried using this query but it is not working
REPLACE(REPLACE(src.[ApprovedDate],'AM',''),'PM','')

A: Maybe use FORMAT function of sql assuming your are in MS SQL world
SELECT FORMAT(CAST(src.[ApprovedDate] AS DATETIME),'yyyy-MM-dd HH:mm')

in MYSQL you could use DATE_FORMAT
see demo link

A: DECLARE @myDatetime varchar(50);
SET @myDatetime = '2/14/2017 2:21:18 PM';
SELECT CONVERT(varchar(50), CONVERT(datetime, @myDatetime), 101) + ' ' +
CONVERT(varchar(50), CONVERT(datetime, @myDatetime), 108);


text:
Q: Efficient mysql queries I'm trying to get a report down from the 20+ minute run time and I've tracked the bottleneck to this monster of a mysql query that uses 5 joins and 3 subqueries to return all the results in one data set. My big bottleneck so far seems to be: join the stock table on the payments table is the stock.id matches a payment.stock_id and the payment.type is this type and the payment.status is this status. I'm slowly breaking this apart into various queries and letting Java decide what records to keep and throw away but I'm wondering if there is an efficient way in mysql to get a couple of resultsets, perhaps as tables stored in memory and then query against those? Some of my result sets will be pretty big, a few hundred thousand entries in the worst cases.
Thanks in advance

A: You have some choices of create materialized view so that you can run this on a time interval, but you'll have basically a delay effect on the validity of your data. But sure is faster.
Second is index the joining columns.
Sub select are usually more expensive than a JOIN, so try to merge your subselect into a join instead.
There are a lot of SQL optimization book out there that is worth reading that deals with these questions. But without knowing your DB or schema or indexes and how the joins and subselects are. Its almost like catching a ball in the dark.


text:
Q: Getting strings as a list into a single line with beautifulsoup I want to get address content in a signle line as it creates a problem when I try to write them to csv
text = """
<B721>
<PARTY-US>
<NAM><FNM><PDAT>Minhua</PDAT></FNM><SNM><STEXT><PDAT>Lu</PDAT></STEXT></SNM></NAM>
<ADR>
<CITY><PDAT>Mohegan Lake</PDAT></CITY>
<STATE><PDAT>NY</PDAT></STATE>
</ADR>
</PARTY-US>
</B721>
<B721>
<PARTY-US>
<NAM><FNM><PDAT>Nobushige</PDAT></FNM><SNM><STEXT><PDAT>Korenaga</PDAT></STEXT></SNM></NAM>
<ADR>
<CITY><PDAT>Utsunomiya</PDAT></CITY>
<CTRY><PDAT>JP</PDAT></CTRY>
</ADR>
</PARTY-US>
</B721>
"""

from bs4 import BeautifulSoup
soup = BeautifulSoup(text, 'lxml')

### Address info
inventors = main_inventor.find_all("b721")
address_info = inventor_address = ", ".join([i.find("adr").text.strip() for i in inventors])

I get the following output:
Mohegan Lake
NY, Utsunomiya
JP

How could I do that ?

A: If you want to replace all newlines/breaks:
# you probably want to use a space ' ' to replace  newlines/breaks '\n'
# `\n` is used in unix like environments; `\r\n` is used in windows.

address_info = address_info.replace('\n', ' ').replace('\r', '')