问:
How to reuse the code Intent intent=new Intent(context,Activity.class) from a superclass to a subclass?

How the code Intent intent=new Intent(context,Activity.class) which is in the superclass can be reused by its subclasses given that the subclasses have different context and different activities to start after on click listener is called. Is it possible?

This is the superclass:

```<code>public class CommonPost extends AppCompatActivity {

    public void on_create(final Context context, final Class aclass) {
        post.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                CommonPost commonPost = new CommonPost();
                MyTask task = commonPost.new MyTask(context, aclass);
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
                    task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
                else
                    task.execute();
            }
        });
    }

class MyTask extends AsyncTask<Void,Void,Void> {
          Context context;
          Class aclass;

        public MyTask(Context context,Class aclass){
             this.context=context;
             this.aclass=aclass;
        }

        @Override
        protected void onPreExecute() {
            // do something
        }

        @Override
        protected Void doInBackground(Void... voids) {
            // do something
            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            Intent intent = new Intent(context, aclass);
            startActivity(intent);
        }
}
</code>```

One of the subclass:

```<code>public class PlacementPost extends CommonPost {
            Context context=PlacementPost.this;
            Class aclass=Placements.class;

            @Override
            protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                on_create(context,aclass);
            }
        }
</code>```

I am getting the following error when I try the above code:

```<code>java.lang.NullPointerException: Attempt to invoke virtual method 'android.app.ActivityThread$ApplicationThread android.app.ActivityThread.getApplicationThread()' on a null object reference
       at android.app.Activity.startActivityForResult(Activity.java:4266)
       at android.support.v4.app.BaseFragmentActivityJB.startActivityForResult(BaseFragmentActivityJB.java:50)

at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:79)
   at android.app.Activity.startActivityForResult(Activity.java:4224)
   at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:859)
   at android.app.Activity.startActivity(Activity.java:4548)
   at android.app.Activity.startActivity(Activity.java:4516)
   at studentapp.notefi.CommonPost$PlaceTask.onPostExecute(CommonPost.java:240)
   at studentapp.notefi.CommonPost$PlaceTask.onPostExecute(CommonPost.java:177)
   at android.os.AsyncTask.finish(AsyncTask.java:660)
   at android.os.AsyncTask.-wrap1(AsyncTask.java)
   at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:677)
   at android.os.Handler.dispatchMessage(Handler.java:102)
   at android.os.Looper.loop(Looper.java:154)
   at android.app.ActivityThread.main(ActivityThread.java:6077)
   at java.lang.reflect.Method.invoke(Native Method)
   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)
</code>```

I am not sure where I am wrong or what I am missing. I just tried out whatever logically I felt correct. Please do correct me out where I am wrong!

答:
You need to make the variable a class scope not an inner class scope.

This is an inner class scope variables:

```<code>public class CommonPost extends AppCompatActivity {

  ...
  class MyTask extends AsyncTask<Void,Void,Void> {
     Context context;
     Class aclass;

     ...

  }
}
</code>```

You can't access the Context context and Class aclass; from the child class.

You need to make it a class scope:

```<code>public class CommonPost extends AppCompatActivity {

  // set to protected to only allow child class access.
  protected Context context;
  protected Class aclass;

  ...
  class MyTask extends AsyncTask<Void,Void,Void> {

  }
}
</code>```

Then, in your child class, change the variables to:

```<code>public class PlacementPost extends CommonPost {

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // set the value to the base class.
    context = PlacementPost.this;
    aclass = Placements.class;

    on_create(context,aclass);
  }
}
</code>```

Body:
How the code Intent intent=new Intent(context,Activity.class) which is in the superclass can be reused by its subclasses given that the subclasses have different context and different activities to start after on click listener is called. Is it possible?

This is the superclass:

public class CommonPost extends AppCompatActivity {

    public void on_create(final Context context, final Class aclass) {
        post.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                CommonPost commonPost = new CommonPost();
                MyTask task = commonPost.new MyTask(context, aclass);
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
                    task.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
                else
                    task.execute();
            }
        });
    }

class MyTask extends AsyncTask<Void,Void,Void> {
          Context context;
          Class aclass;

        public MyTask(Context context,Class aclass){
             this.context=context;
             this.aclass=aclass;
        }

        @Override
        protected void onPreExecute() {
            // do something
        }

        @Override
        protected Void doInBackground(Void... voids) {
            // do something
            return null;
        }

        @Override
        protected void onPostExecute(Void aVoid) {
            Intent intent = new Intent(context, aclass);
            startActivity(intent);
        }
}

One of the subclass:

public class PlacementPost extends CommonPost {
            Context context=PlacementPost.this;
            Class aclass=Placements.class;

            @Override
            protected void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                on_create(context,aclass);
            }
        }

I am getting the following error when I try the above code:

java.lang.NullPointerException: Attempt to invoke virtual method 'android.app.ActivityThread$ApplicationThread android.app.ActivityThread.getApplicationThread()' on a null object reference
       at android.app.Activity.startActivityForResult(Activity.java:4266)
       at android.support.v4.app.BaseFragmentActivityJB.startActivityForResult(BaseFragmentActivityJB.java:50)

at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:79)
   at android.app.Activity.startActivityForResult(Activity.java:4224)
   at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:859)
   at android.app.Activity.startActivity(Activity.java:4548)
   at android.app.Activity.startActivity(Activity.java:4516)
   at studentapp.notefi.CommonPost$PlaceTask.onPostExecute(CommonPost.java:240)
   at studentapp.notefi.CommonPost$PlaceTask.onPostExecute(CommonPost.java:177)
   at android.os.AsyncTask.finish(AsyncTask.java:660)
   at android.os.AsyncTask.-wrap1(AsyncTask.java)
   at android.os.AsyncTask$InternalHandler.handleMessage(AsyncTask.java:677)
   at android.os.Handler.dispatchMessage(Handler.java:102)
   at android.os.Looper.loop(Looper.java:154)
   at android.app.ActivityThread.main(ActivityThread.java:6077)
   at java.lang.reflect.Method.invoke(Native Method)
   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:865)
   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:755)

I am not sure where I am wrong or what I am missing. I just tried out whatever logically I felt correct. Please do correct me out where I am wrong!

Body:
You need to make the variable a class scope not an inner class scope.

This is an inner class scope variables:

public class CommonPost extends AppCompatActivity {

  ...
  class MyTask extends AsyncTask<Void,Void,Void> {
     Context context;
     Class aclass;

     ...

  }
}

You can't access the Context context and Class aclass; from the child class.

You need to make it a class scope:

public class CommonPost extends AppCompatActivity {

  // set to protected to only allow child class access.
  protected Context context;
  protected Class aclass;

  ...
  class MyTask extends AsyncTask<Void,Void,Void> {

  }
}

Then, in your child class, change the variables to:

public class PlacementPost extends CommonPost {

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // set the value to the base class.
    context = PlacementPost.this;
    aclass = Placements.class;

    on_create(context,aclass);
  }
}


来源: stackexchange

问:
What is the fastest way to return a range of numbers from a sorted array of numbers?
For C++ language, what's the fastest way in processing run-time (in multi core processors), from an algorithm design viewpoint, to search numbers (e.g. between 100 and 1000) that are within an array (or splice or whatever faster data structures for the purpose of this) and return the range of numbers limited to only 10 items returned? e.g. pseudocode in golang:

```<code>var listofnums := []uint64
var numcounter := 1
// splice of [1,2,3,4,5,31,32 .. 932536543] this list has 1 billion numeric items.
// the listofnums are already sorted each time an item is added but we do not know the lower_bound or upper_bound of the item list.
// I know I can use binary search to find listofnums[i] where it is smallest at [i] too... I'm asking for suggestions.
for i:=uint(0); i < len(listofnums); i++ {
    if listofnums[i] > 100 && listofnums[i] < 1000 {
         if listofnums[i]> 1000 || numcounter == 10 {
             return
         }
         fmt.Println("%d",listofnums[i])
         numcounter++
    }
}
</code>```

is this the fastest way? I saw bitmap structures in C++ but not sure if can be applied here.

I've come across this question, which is perfectly fine for veteran programmers to ask but I have no idea why it's down voted.
What is the fastest search method for array?

Can someone please not remove this question but let me rephrase it? Thanks in advance. I hope to find the most optimum way to return a range of numbers from a large array of numeric items.

答:
My first attempt.

Features:

logN time complexity

creates an array slice, no copying of data

second binary search minimises the search space on the basis of the first

possible improvements:

if n is small, the second binary search would be a pessimisation. Better to simply count forward up to n times.

```<code>#include <vector>
#include <cstdint>
#include <algorithm>
#include <iterator>
#include <iostream>

template <class Iter> struct range
{
    range(Iter first, std::size_t size) : begin_(first), end_(first + size) {}

    auto begin() const { return begin_; }
    auto end() const { return end_; }

    Iter begin_, end_;
};

template<class Iter> range(Iter, std::size_t) -> range<Iter>;

auto find_first_n_between(std::vector<std::int64_t>& vec,
                          std::size_t n,
                          std::int64_t from, std::int64_t to)
{
    auto lower = std::lower_bound(begin(vec), end(vec), from);
    auto upper = std::upper_bound(lower, end(vec), to);
    auto size = std::min(n, std::size_t(std::distance(lower, upper)));
    return range(lower, size);
}

int main()
{
    std::vector<std::int64_t> vec { 1,2,3,4,5,6,7,8,15,17,18,19,20 };
    auto slice = find_first_n_between(vec, 5, 6, 15);

    std::copy(std::begin(slice), std::end(slice), std::ostream_iterator<std::int64_t>(std::cout, ", "));
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
For C++ language, what's the fastest way in processing run-time (in multi core processors), from an algorithm design viewpoint, to search numbers (e.g. between 100 and 1000) that are within an array (or splice or whatever faster data structures for the purpose of this) and return the range of numbers limited to only 10 items returned? e.g. pseudocode in golang:

var listofnums := []uint64
var numcounter := 1
// splice of [1,2,3,4,5,31,32 .. 932536543] this list has 1 billion numeric items.
// the listofnums are already sorted each time an item is added but we do not know the lower_bound or upper_bound of the item list.
// I know I can use binary search to find listofnums[i] where it is smallest at [i] too... I'm asking for suggestions.
for i:=uint(0); i < len(listofnums); i++ {
    if listofnums[i] > 100 && listofnums[i] < 1000 {
         if listofnums[i]> 1000 || numcounter == 10 {
             return
         }
         fmt.Println("%d",listofnums[i])
         numcounter++
    }
}

is this the fastest way? I saw bitmap structures in C++ but not sure if can be applied here.

I've come across this question, which is perfectly fine for veteran programmers to ask but I have no idea why it's down voted.
What is the fastest search method for array?

Can someone please not remove this question but let me rephrase it? Thanks in advance. I hope to find the most optimum way to return a range of numbers from a large array of numeric items.

Body:
My first attempt.

Features:

logN time complexity

creates an array slice, no copying of data

second binary search minimises the search space on the basis of the first

possible improvements:

if n is small, the second binary search would be a pessimisation. Better to simply count forward up to n times.

#include <vector>
#include <cstdint>
#include <algorithm>
#include <iterator>
#include <iostream>

template <class Iter> struct range
{
    range(Iter first, std::size_t size) : begin_(first), end_(first + size) {}

    auto begin() const { return begin_; }
    auto end() const { return end_; }

    Iter begin_, end_;
};

template<class Iter> range(Iter, std::size_t) -> range<Iter>;

auto find_first_n_between(std::vector<std::int64_t>& vec,
                          std::size_t n,
                          std::int64_t from, std::int64_t to)
{
    auto lower = std::lower_bound(begin(vec), end(vec), from);
    auto upper = std::upper_bound(lower, end(vec), to);
    auto size = std::min(n, std::size_t(std::distance(lower, upper)));
    return range(lower, size);
}

int main()
{
    std::vector<std::int64_t> vec { 1,2,3,4,5,6,7,8,15,17,18,19,20 };
    auto slice = find_first_n_between(vec, 5, 6, 15);

    std::copy(std::begin(slice), std::end(slice), std::ostream_iterator<std::int64_t>(std::cout, ", "));
}


问:
What should the value of Windows.Current.Content be after opening a secondary window?
This is the suggested code in the App class from the Template10 article on implementing a shell:

```<code>public override Task OnInitializeAsync(IActivatedEventArgs args)
{
    var nav = NavigationServiceFactory(BackButton.Attach, ExistingContent.Include);
    Window.Current.Content = new Views.Shell(nav);
    return Task.FromResult<object>(null);
}
</code>```

The new shell object is assigned to Windows.Current.Content.

This is the suggested code for opening a secondary window (not with a shell), from the Template10 Secondary window example code:

```<code> var control = await NavigationService.OpenAsync(typeof(MySecondaryPage), null, Guid.NewGuid().ToString());

                control.Released += Control_Released;
</code>```

What is the relationship between Windows.Current.Content and the secondary window?

答:
What is the relationship between Windows.Current.Content and the secondary window?

Actually, The NavigationService.OpenAsync method internally invoke ViewService.OpenAsync.

```<code>public async Task<IViewLifetimeControl> OpenAsync(UIElement content, string title = null,
    ViewSizePreference size = ViewSizePreference.UseHalf)
{
    this.Log($"Frame: {content}, Title: {title}, Size: {size}");

    var currentView = ApplicationView.GetForCurrentView();
    title = title ?? currentView.Title;

    var newView = CoreApplication.CreateNewView();
    var dispatcher = DispatcherEx.Create(newView.Dispatcher);
    var newControl = await dispatcher.Dispatch(async () =>
    {
        var control = ViewLifetimeControl.GetForCurrentView();
        var newWindow = Window.Current;
        var newAppView = ApplicationView.GetForCurrentView();
        newAppView.Title = title;

        // TODO: (Jerry)
        // control.NavigationService = nav;

        newWindow.Content = content;
        newWindow.Activate();

        await ApplicationViewSwitcher
            .TryShowAsStandaloneAsync(newAppView.Id, ViewSizePreference.Default, currentView.Id, size);
        return control;
    }).ConfigureAwait(false);
    return newControl;
}
</code>```

From the above code, you could get the app's Window(Singleton) has not been changed, when the second window activated, the Content of Window was replaced with second page. And when the previous window activated the Windows.Current.Content will turn the fist page back. And you could verify this with Window.Current.Activated event.

```<code>Window.Current.Activated += Current_Activated;

private void Current_Activated(object sender, Windows.UI.Core.WindowActivatedEventArgs e)
{
 // check the sender
}
</code>```

Body:
This is the suggested code in the App class from the Template10 article on implementing a shell:

public override Task OnInitializeAsync(IActivatedEventArgs args)
{
    var nav = NavigationServiceFactory(BackButton.Attach, ExistingContent.Include);
    Window.Current.Content = new Views.Shell(nav);
    return Task.FromResult<object>(null);
}

The new shell object is assigned to Windows.Current.Content.

This is the suggested code for opening a secondary window (not with a shell), from the Template10 Secondary window example code:

 var control = await NavigationService.OpenAsync(typeof(MySecondaryPage), null, Guid.NewGuid().ToString());

                control.Released += Control_Released;

What is the relationship between Windows.Current.Content and the secondary window?

Body:
What is the relationship between Windows.Current.Content and the secondary window?

Actually, The NavigationService.OpenAsync method internally invoke ViewService.OpenAsync.

public async Task<IViewLifetimeControl> OpenAsync(UIElement content, string title = null,
    ViewSizePreference size = ViewSizePreference.UseHalf)
{
    this.Log($"Frame: {content}, Title: {title}, Size: {size}");

    var currentView = ApplicationView.GetForCurrentView();
    title = title ?? currentView.Title;

    var newView = CoreApplication.CreateNewView();
    var dispatcher = DispatcherEx.Create(newView.Dispatcher);
    var newControl = await dispatcher.Dispatch(async () =>
    {
        var control = ViewLifetimeControl.GetForCurrentView();
        var newWindow = Window.Current;
        var newAppView = ApplicationView.GetForCurrentView();
        newAppView.Title = title;

        // TODO: (Jerry)
        // control.NavigationService = nav;

        newWindow.Content = content;
        newWindow.Activate();

        await ApplicationViewSwitcher
            .TryShowAsStandaloneAsync(newAppView.Id, ViewSizePreference.Default, currentView.Id, size);
        return control;
    }).ConfigureAwait(false);
    return newControl;
}

From the above code, you could get the app's Window(Singleton) has not been changed, when the second window activated, the Content of Window was replaced with second page. And when the previous window activated the Windows.Current.Content will turn the fist page back. And you could verify this with Window.Current.Activated event.

Window.Current.Activated += Current_Activated;

private void Current_Activated(object sender, Windows.UI.Core.WindowActivatedEventArgs e)
{
 // check the sender
}


问:
Read user input and send it to MySQL
So I am attempting to make my first Linux script and its just to setup a MySQL user and I'm trying to do that all with a script, but I can not seem to find how I can send the MySQL command from the script. This is what I have right now.

```<code>#!/bin/bash
read -p "Please enter your desired MySQL username:  " USER
    echo $USER
read -p "Please enter your desired MySQL password:  " PASS
    echo $PASS
mysql CREATE USER $USER@'localhost' IDENTIFIED BY $PASS;
</code>```

any help would be appreciated

Thanks
-Jamie

答:
You cannot mixup mysql queries in bash script.So, you have to save the mysql queries to a mysql file i.e .sql file and then run the mysql command

To append the create user line to a .sql file use

echo 'mysql CREATE USER $USER@'localhost' IDENTIFIED BY $PASS' >> filename.sql

Now the .sql file will contain the sql queries and you can run

$ mysql -h "server-name" -u "root" "-pXXXXXXXX" "database-name" < "filename.sql"

Title: Read user input and send it to MySQL

Body:
So I am attempting to make my first Linux script and its just to setup a MySQL user and I'm trying to do that all with a script, but I can not seem to find how I can send the MySQL command from the script. This is what I have right now.

#!/bin/bash
read -p "Please enter your desired MySQL username:  " USER
    echo $USER
read -p "Please enter your desired MySQL password:  " PASS
    echo $PASS
mysql CREATE USER $USER@'localhost' IDENTIFIED BY $PASS;

any help would be appreciated

Thanks
-Jamie


问:
MySQL JOIN from 3 relative tables
I have 3 tables

1. role (id, ...)

2. permission (id, ...)

3. role_permission (id, role_id, permission_id)

I want to do the next: i should select all roles and all permissions for this roles with help of one query. My test query:

```<code>SELECT `rp`.*, `r`.`role`, `r`.`id` AS `role_id`, `p`.`id` AS
`permission_id`,`p`.`name` AS `permission` FROM `role_permission` AS `rp` RIGHT JOIN
`role` AS `r` ON r.id = rp.role_id RIGHT JOIN `permission` AS `p` ON p.id = rp.permission_id
</code>```

But this query select only those roles, what have permissions. But i need to select all roles and all permissions (exist row in role_permission or not).

Thank you in advance. Sorry for my english.

答:
You want a left join.

```<code>select
    r.role,
    r.id as role_id,
    p.id as permission_id

from role

left join role_permission rp on rp.role_id = role.id
left join permission p on p.id = rp.permission_id
</code>```

This will give you the permissions for all roles with permissions, as well as a null permission_id for roles without permissions.

ContentLicense: CC BY-SA 2.5

Title: MySQL JOIN from 3 relative tables

Body:
I have 3 tables

1. role (id, ...)

2. permission (id, ...)

3. role_permission (id, role_id, permission_id)

I want to do the next: i should select all roles and all permissions for this roles with help of one query. My test query:

SELECT `rp`.*, `r`.`role`, `r`.`id` AS `role_id`, `p`.`id` AS
`permission_id`,`p`.`name` AS `permission` FROM `role_permission` AS `rp` RIGHT JOIN
`role` AS `r` ON r.id = rp.role_id RIGHT JOIN `permission` AS `p` ON p.id = rp.permission_id

But this query select only those roles, what have permissions. But i need to select all roles and all permissions (exist row in role_permission or not).

Thank you in advance. Sorry for my english.

Body:
You want a left join.

select
    r.role,
    r.id as role_id,
    p.id as permission_id

from role

left join role_permission rp on rp.role_id = role.id
left join permission p on p.id = rp.permission_id

This will give you the permissions for all roles with permissions, as well as a null permission_id for roles without permissions.


问:
Building Opencv using cmake giving errors involving c++11
I am facing problem with the cmake command while compiling opencv on Ubuntu 16.04. When I execute the cmake command, I get the error

CMake Error at CMakeLists.txt:11 (message):
FATAL: In-source builds are not allowed.
You should create a separate directory for build files.

I have extracted the opencv source file in a folder named opencv-3.3.1
Then I have followed all the processes mentioned in this site

https://www.pyimagesearch.com/2016/10/24/ubuntu-16-04-how-to-install-opencv/

I use the following commands ::

cd opencv-3.3.1/
mkdir build/
cd build/
cmake -D CMA
KE_BUILD_TYPE=RELEASE -D CMAKE_INSTALL_PREFIX=/usr/local -D INSTALL_PYTHON_EXAMPLES=ON -D INSTALL_C_EXAMPLES=OFF -D OPENCV_EXTRA_MODULES_PATH=~/opencv_contrib-3.3.1/modules -D PYTHON_EXECUTABLE=~/.virtualenvs/cv/bin/python -D BUILD_EXAMPLES=ON ..

But I am getting this error!

What can be the possible problem?

The CMakeError.log shows

error "C++11 is not supported

I have tried adding set(CMAKE_CXX_FLAGS "-std=c++11") to the beginning of the CMakeLists.txt and also included the flag -DENABLE_CXX11=ON to the CMAKE command flags. But nothing seems to work.

Please help!!

答:
Maybe there is a file called CMakeCache.txt in your OpenCV root directory  opencv-3.3.1.

Just remove it!

That's because someone have executed cmake . inside the root directory opencv-3.3.1 before.


问:
htaccess replacing PHP file.php?id=dynamic_id with file/id
I am wanting to use htaccess to make a url such as http://example.com/news/news_post.php?id=dynamic_id with a URL that looks like http://example.com/news/news_post/dynamic_id. So basically remove the .php file extension, as well as make ?id=dynamic_id to /dynamic_id for my news_post.php page.

I have searched around at other examples to find something that may help, but I haven't been able to find anything that helps.

If someone can help me with this, it would be much appreciated!

答:
Try this

I tested this and it's working perfectly in my the system.

.htaccess

```<code>Options +FollowSymLinks
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^(.*)$ $1.php
//above code is use for remove the .php

RewriteRule ^news/news_post/([\w-]+) news_post.php?id=$1
</code>```

Index.php

In this, I set the href="javascript:void(0);" and added onclick fucntion and pass the parameter to the function. In the function I set window.location="news/news_post/"+user_id+""; so your URL will look like news/news_post/1

```<code><!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
<?php
$userdata['Id']=1;
 ?>
<a href="javascript:void(0);" onclick="myfunciton(<?php echo $userdata['Id']; ?>)">Click me</a>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
<script type="text/javascript">
        function myfunciton(user_id){
                window.location="news/news_post/"+user_id+"";
        }

</script>
</body>
</html>
</code>```

news_post.php

You can get the URL value using $_REQUEST

```<code><?php
echo $_REQUEST['id'];//output is 1
 ?>
</code>```

Output

You will get output

```<code>domain.com/news/news_post/1
</code>```

Body:
Try this

I tested this and it's working perfectly in my the system.

.htaccess

Options +FollowSymLinks
RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME}\.php -f
RewriteRule ^(.*)$ $1.php
//above code is use for remove the .php

RewriteRule ^news/news_post/([\w-]+) news_post.php?id=$1

Index.php

In this, I set the href="javascript:void(0);" and added onclick fucntion and pass the parameter to the function. In the function I set window.location="news/news_post/"+user_id+""; so your URL will look like news/news_post/1

<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
<?php
$userdata['Id']=1;
 ?>
<a href="javascript:void(0);" onclick="myfunciton(<?php echo $userdata['Id']; ?>)">Click me</a>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"></script>
<script type="text/javascript">
        function myfunciton(user_id){
                window.location="news/news_post/"+user_id+"";
        }

</script>
</body>
</html>

news_post.php

You can get the URL value using $_REQUEST

<?php
echo $_REQUEST['id'];//output is 1
 ?>

Output

You will get output

domain.com/news/news_post/1


问:
Locating Core Data’s sqlite database on Mac OS X app
Where I can find Core Data’s sqlite database of Mac OS X application?

I have found it, but it's *.momd folder with 3 files (VersionInfo.plist, *.mom *.omo). How can I see the contents of it?

答: In High Sierra, SQLite file is saved in ~/Library/Application Support/[YourAppName]


问:
Check if span contains value but value is after another nestled span
Trying to check if span .woocommerce-Price-amount contains 19.76. I don't think it's working since there is $  before the value I'm trying to target.

How can I ignore the currencySymbol span?

jQuery(document).ready(function($) {
  $(".ivpa_term").click(function() {
    setTimeout(function() {
      $(".woocommerce-Price-amount").each(function() {
        var inner = $(this).text();
        if (!isNaN(inner) && 19.75 < inner && inner <= 19.76) {
          console.log("Exists!");
        }
      });
    }, 0001);
  });
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<span class="quantity">2 ×
  <del>
    <span class="woocommerce-Price-amount amount">
      <span class="woocommerce-Price-currencySymbol">$</span> 21.95
    </span>
  </del>
  <span class="woocommerce-Price-amount amount">
    <span class="woocommerce-Price-currencySymbol">$</span>19.76
  </span>
</span></code>```

答:
For a specific value you can use :contains selector

var res= $(".woocommerce-Price-amount:contains(19.76)").css('color', 'red');
if(res.length){
   console.log('Exists');
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<span class="quantity">2 × <del>
<span class="woocommerce-Price-amount amount">
<span class="woocommerce-Price-currencySymbol">$</span>21.95</span>
</del>
<span class="woocommerce-Price-amount amount">
<span class="woocommerce-Price-currencySymbol">$</span>19.76</span>
</span></code>```

Body:
Trying to check if span .woocommerce-Price-amount contains 19.76. I don't think it's working since there is $  before the value I'm trying to target.

How can I ignore the currencySymbol span?

jQuery(document).ready(function($) {
  $(".ivpa_term").click(function() {
    setTimeout(function() {
      $(".woocommerce-Price-amount").each(function() {
        var inner = $(this).text();
        if (!isNaN(inner) && 19.75 < inner && inner <= 19.76) {
          console.log("Exists!");
        }
      });
    }, 0001);
  });
});

2 ×

      $ 21.95

    $19.76

Body:
For a specific value you can use :contains selector

var res= $(".woocommerce-Price-amount:contains(19.76)").css('color', 'red');
if(res.length){
   console.log('Exists');
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<span class="quantity">2 × <del>
<span class="woocommerce-Price-amount amount">
<span class="woocommerce-Price-currencySymbol">$</span>21.95</span>
</del>
<span class="woocommerce-Price-amount amount">
<span class="woocommerce-Price-currencySymbol">$</span>19.76</span>
</span>


问:
Popper, Bootstrap 4 and ES2015: Popper not defined
I am pretty confused on how to make the Javascript utilities in Bootstrap 4 work.

I am using ES2015 style requires. I've installed jQuery, the latest beta of Bootstrap 4 (beta 2) and Popper.js using node modules. Here's how I am loading my JS:

```<code>window.$ = window.jQuery = require('jquery');

$(function() {

  require('popper');
  require('./vendor/bootstrap/index');

});
</code>```

Popper's docs state that you need code like this to instantiate Popper:

```<code>  var reference = document.querySelector('#dropdownLanguageButton');
  var popper = document.querySelector('div[aria-labelledby="dropdownLanguageButton"]');
  var anotherPopper = new Popper(
      reference,
      popper,
      {
          // popper options here
      }
  );
</code>```

However, it is not clear if you need to instantiate for something as simple as a Bootstrap dropdown.

There is no clear example in the Bootstrap 4 docs.

The error I am getting is index.js:10 Uncaught ReferenceError: Popper is not defined.

Help appreciated!

答: Maybe problem in path to popper.js. Popper's required file located in 'node_modules/popper.js/dist/umd/popper.min.js'</p>

Body:
I am pretty confused on how to make the Javascript utilities in Bootstrap 4 work.

I am using ES2015 style requires. I've installed jQuery, the latest beta of Bootstrap 4 (beta 2) and Popper.js using node modules. Here's how I am loading my JS:

window.$ = window.jQuery = require('jquery');

$(function() {

  require('popper');
  require('./vendor/bootstrap/index');

});

Popper's docs state that you need code like this to instantiate Popper:

  var reference = document.querySelector('#dropdownLanguageButton');
  var popper = document.querySelector('div[aria-labelledby="dropdownLanguageButton"]');
  var anotherPopper = new Popper(
      reference,
      popper,
      {
          // popper options here
      }
  );

However, it is not clear if you need to instantiate for something as simple as a Bootstrap dropdown.

There is no clear example in the Bootstrap 4 docs.

The error I am getting is index.js:10 Uncaught ReferenceError: Popper is not defined.

Help appreciated!


问:
Promo Code Validation
I need to validate a Promo Code for one of my html Booking form field. If the entered promo code is correct, users can submit the Booking details. Only one unique promo code. Something like "15OFFNOW" How should I do it? Please help.

Thanks.

答:
You can use Javascript for that , I fyou want to match promocode or you can validate it at backend using any backend language like PHP or java

for JQuery

```<code>//previous Ajax code here
if($("#input_id").val() !== "15OFFNOW"){

   return false ;
}
 // here you can proceed for Ajax request
</code>```

Title: Promo Code Validation

Body:
You can use Javascript for that , I fyou want to match promocode or you can validate it at backend using any backend language like PHP or java

for JQuery

//previous Ajax code here
if($("#input_id").val() !== "15OFFNOW"){

   return false ;
}
 // here you can proceed for Ajax request


问:
Selenium can not click on one element
I am using Selenium Chromedriver and my problem looks like this:

My program is clicking element on website and a list of elements appear.

Than it is choosing one of element from list using checkbox.

Nextly it is trying to click other element but the program crashes.

When the mentioned list appear if I am clicking anywhere on website using inspect option the code of inspected element looking like this:

```<code><div id="__selectOverlay" style="display: block;"></div>
</code>```

how can I click any element from website after the list appear?

答:
As per the HTML you have shared the WebElement seems to me as a Overlay within a div tag. Moreover this div tag doesn't have a onClick() event associated. So we won't be able to click the WebElement straight away. Possibly you might be trying to invoke click() method on some other element which is having this temporary / permanent Overlay through the div tag.

Solution

Depending on the type of Overlay there are two possible solutions as follows :

Temporary Overlay :

In this case induce ExplicitWait with  ExpectedConditions set to invisibilityOfElementLocated for the Overlay to be invisible.

```<code>WebDriverWait wait1 = new WebDriverWait(driver, 10);
wait1.until(ExpectedConditions.invisibilityOfElementLocated(By.xpath("ele_to_inv")));
</code>```

Permanent Overlay :

Use JavascriptExecutor to send the click directly on the element.

```<code>WebElement ele = driver.findElement(By.xpath("element_xpath"));
JavascriptExecutor executor = (JavascriptExecutor)driver;
executor.executeScript("arguments[0].click();", ele);
</code>```

Title: Selenium can not click on one element

Body:
I am using Selenium Chromedriver and my problem looks like this:

My program is clicking element on website and a list of elements appear.

Than it is choosing one of element from list using checkbox.

Nextly it is trying to click other element but the program crashes.

When the mentioned list appear if I am clicking anywhere on website using inspect option the code of inspected element looking like this:

how can I click any element from website after the list appear?

Body:
As per the HTML you have shared the WebElement seems to me as a Overlay within a div tag. Moreover this div tag doesn't have a onClick() event associated. So we won't be able to click the WebElement straight away. Possibly you might be trying to invoke click() method on some other element which is having this temporary / permanent Overlay through the div tag.

Solution

Depending on the type of Overlay there are two possible solutions as follows :

Temporary Overlay :

In this case induce ExplicitWait with  ExpectedConditions set to invisibilityOfElementLocated for the Overlay to be invisible.

WebDriverWait wait1 = new WebDriverWait(driver, 10);
wait1.until(ExpectedConditions.invisibilityOfElementLocated(By.xpath("ele_to_inv")));

Permanent Overlay :

Use JavascriptExecutor to send the click directly on the element.

WebElement ele = driver.findElement(By.xpath("element_xpath"));
JavascriptExecutor executor = (JavascriptExecutor)driver;
executor.executeScript("arguments[0].click();", ele);


问:
What are the advantages of developing applications in C++ as compared to managed languages?
Hi I want to know why people develop library applications and employee management applications in C++ (this application, for example), when clearly the same thing can be done in C# and VB.NET in a much prettier way. Even banking applications are mostly in C++. Is there a good reason why, apart from the fact that compiled C++ code executes faster?

Can anyone shed some light on this?

答:
Apart from technical reasons (such that C++ is an "unmanaged" language with quite different capabilities and properties than .NET languages), this can simply be due to preferences. Not all people find that C# and VB.NET are the best tool for every task. Or the prettiest. Why do you think so? And why should others not have similarly good reasons for choosing another tool of their liking?

Update, in reply to Konrad's comment:

It's correct that "preference" is indeed too narrow a term. There's other facets to it:

Managers / bosses can turn their (possibly badly informed) preferences into business policies;

A corporation's decade-old codebase can mean that when it comes to choosing the programming language for some new task, you'll evaluate languages with a different perspective. You want to or need to reuse the existing code, so interop with the old code's language must be possible.


问:
how to bind multiple checkbox in different session
I have some data with check boxes. Now I want, when any one click on check boxes then all data of checked should be bind in session and should go on next page. And again if any one click on check boxes then new clicked data should be in session. But old data should not delete. I tried but not working, any thing. Please help.

```<code>                            <form  name="reservation_form" class="reservation-form mb-0" action="second.php" method="post" novalidate>

            <div class="col-xs-12 col-sm-6 col-md-4">
            <div class="form-group mb-15">
              <input name="name1" class="form-control required " type="text" placeholder="Enter Name" aria-required="true">
            </div>
          </div>
          <div class="col-xs-12 col-sm-6 col-md-4">
            <div class="form-group mb-15">
              <input name="email1" class="form-control required " type="email" placeholder="Enter Email" aria-required="true">
            </div>
          </div>
          <div class="col-xs-12 col-sm-6 col-md-4">
            <div class="form-group mb-15">
              <input name="phone1" class="form-control required " type="text" placeholder="Enter Phone" aria-required="true">
            </div>
          </div>
     <?php
            $query1=mysql_query("select * from lab_location_package_rel where city_id='$selectcity1' AND area_id='$selectarea1' AND lab_id='$selectlab1'") or die (mysql_error());
             while($value = mysql_fetch_array($query1)) {
                 $mrp=$value['mrp'];
                 $opp=$value['offer_price_perc'];
                 $package_id=$value['package_id'];

                 $per=$mrp*$opp/100;
                 $total=$mrp-$per;

             $query2=mysql_query("select * from package_master where id='$package_id'") or die (mysql_error());
             $value2 = mysql_fetch_array($query2);
             ?>
                    <li class="list-group-item">
                        <div class="checkbox">
                            <input type="checkbox" id="checkbox" name="name[]" />
                            <label for="checkbox">
                               <b>Package Name:</b> <?php echo $value2['package_title']; ?> <br>
                               <b>MRP:</b>  <strike><?php echo $value['mrp']; ?>  </strike><br>
                               <b>Offer Price:</b>  <?php echo $total; ?>
                            </label>
                        </div>
                        <div class="pull-right action-buttons">
                            <a href="#" class="btn btn-info">View Details</a>
                       </div>
                    </li>
              <?php } ?>

                </ul>
            </div>
       <input type="button" class="pull-right btn btn-warning" value="Submit">
    </form>
</code>```

In given code, when any one fill all fields and click check boxes-

```<code><input type="checkbox" id="checkbox" name="name[]" />
                        <label for="checkbox">
                           <b>Package Name:</b> <?php echo $value2['package_title']; ?> <br>
                           <b>MRP:</b>  <strike><?php echo $value['mrp']; ?>  </strike><br>
                           <b>Offer Price:</b>  <?php echo $total; ?>
                        </label>
</code>```

then all filled fields and Package Name, MRP, Offer Price (these name will be selected for each checkbox) should be bind in session.

答:
Pass like this and when submitting form get the value by

input type="checkbox" id="checkbox" name="names[]"  value="$value2['package_title']">

input type="checkbox" id="checkbox" name="names[]" value="$value['mrp']">

input type="checkbox" id="checkbox" name="names[]" value="$total"/>

$name=$_POST['names'];
$answer = implode($name, ",");

then assign the name value to a session.

$_SEESION['name']=$answer;

Body:
I have some data with check boxes. Now I want, when any one click on check boxes then all data of checked should be bind in session and should go on next page. And again if any one click on check boxes then new clicked data should be in session. But old data should not delete. I tried but not working, any thing. Please help.

                            <form  name="reservation_form" class="reservation-form mb-0" action="second.php" method="post" novalidate>

              <input name="name1" class="form-control required " type="text" placeholder="Enter Name" aria-required="true">

              <input name="email1" class="form-control required " type="email" placeholder="Enter Email" aria-required="true">

              <input name="phone1" class="form-control required " type="text" placeholder="Enter Phone" aria-required="true">

     <?php
            $query1=mysql_query("select * from lab_location_package_rel where city_id='$selectcity1' AND area_id='$selectarea1' AND lab_id='$selectlab1'") or die (mysql_error());
             while($value = mysql_fetch_array($query1)) {
                 $mrp=$value['mrp'];
                 $opp=$value['offer_price_perc'];
                 $package_id=$value['package_id'];

                 $per=$mrp*$opp/100;
                 $total=$mrp-$per;

             $query2=mysql_query("select * from package_master where id='$package_id'") or die (mysql_error());
             $value2 = mysql_fetch_array($query2);
             ?>

                            <input type="checkbox" id="checkbox" name="name[]" />

                               Package Name: <?php echo $value2['package_title']; ?>

                               MRP:  <?php echo $value['mrp']; ?>

                               Offer Price:  <?php echo $total; ?>

                            View Details

              <?php } ?>

       <input type="button" class="pull-right btn btn-warning" value="Submit">
    </form>

In given code, when any one fill all fields and click check boxes-

<input type="checkbox" id="checkbox" name="name[]" />

                           Package Name: <?php echo $value2['package_title']; ?>

                           MRP:  <?php echo $value['mrp']; ?>

                           Offer Price:  <?php echo $total; ?>

then all filled fields and Package Name, MRP, Offer Price (these name will be selected for each checkbox) should be bind in session.


问:
App crashing after theme update
The app I was working on so far was working fine until I added a couple of new activities and tried applied some changes to the theme.

The following is my styles.xml file. I looked into other results and added a parent to AppTheme as I was getting an error regarding AppCompat earlier. I also made AppTheme parent of NoActionBar. One thing I noticed was when I apply AppBarOverlay to Register User Activity it crashes and when I apply other it doesn't. Main Activity is crashing regardless.

```<code><resources>

<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
    <!-- Customize your theme here. -->
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>
</style>

<style name="AppTheme.NoActionBar" parent ="AppTheme">
    <item name="windowActionBar">false</item>
    <item name="windowNoTitle">true</item>
</style>

<style name="AppTheme.AppBarOverlay" parent="ThemeOverlay.AppCompat.Dark.ActionBar" />

<style name="AppTheme.PopupOverlay" parent="ThemeOverlay.AppCompat.Light" />
</resources>
</code>```

Below is the Android Manifest file:

```<code><?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.ati.activate">
<application
    android:allowBackup="true"
    android:icon="@drawable/footprintblue"
    android:label="@string/app_name"
    android:roundIcon="@drawable/footprintgreen"
    android:theme="@style/AppTheme"
    android:supportsRtl="true">

    <activity android:name=".UserManagement.LoginActivity"
        android:theme="@style/AppTheme.NoActionBar">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <activity android:name=".UserManagement.RegisterUserActivity"
        android:label="@string/app_name"
        android:theme="@style/AppTheme.AppBarOverlay">
    </activity>

    <activity
        android:name=".MainActivity"
        android:label="@string/app_name"
        android:theme="@style/AppTheme">
    </activity>

 </application>
</manifest>
</code>```

I have applied AppTheme to android and then overridden the desired themes to other activities. Note: Login screen works and is using AppTheme.NoTitleBar, Register User works without AppBarOverLay theme but crashes when this theme is used.

This is my activity_main.xml file

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/main_content"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fitsSystemWindows="true"
tools:context="com.ati.activate.MainActivity">

<android.support.design.widget.AppBarLayout
    android:id="@+id/appbar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:paddingTop="@dimen/appbar_padding_top"
    android:theme="@style/AppTheme.AppBarOverlay">

    <!--android:paddingTop="@dimen/appbar_padding_top"-->

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        app:popupTheme="@style/AppTheme.PopupOverlay"
        app:layout_scrollFlags="scroll|enterAlways">
    </android.support.v7.widget.Toolbar>

    <android.support.design.widget.TabLayout
        android:id="@+id/tabs"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@drawable/login_background" />

</android.support.design.widget.AppBarLayout>

<android.support.v4.view.ViewPager
    android:id="@+id/pager"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior" />
</code>```

And this is the snippet of my MainActivity.Java file:

```<code>import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.AppCompatActivity;

import android.support.v4.view.ViewPager;
import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;

import com.ati.activate.Fragments.SettingsFragment.AppSettingsFragment;
import com.ati.activate.Fragments.SettingsFragment.ProfileSettingsFragment;

public class MainActivity extends AppCompatActivity{
private AppPagerAdapter mAppPagerAdapter;
private ViewPager mViewPager;

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

    Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    createMenu();
}
</code>```

I have tried every solution discussed on the internet but still have not found any solution. Could anyone please help? Thanking you in advance.

Below is the error when Register User Activity is opened with AppTheme.AppBarOverlay:

```<code>    12-08 04:55:08.217 17843-17850/? E/zygote: Failed writing handshake bytes (-1
    of 14): Broken pipe
    12-08 04:55:16.704 17843-17986/com.ati.activate E/StudioProfiler: JVMTI
    error: 15(JVMTI_ERROR_THREAD_NOT_ALIVE)
    12-08 04:55:16.706 17843-17986/com.ati.activate E/StudioProfiler: JVMTI
    error: 15(JVMTI_ERROR_THREAD_NOT_ALIVE)
    12-08 04:55:16.818 17843-17843/com.ati.activate E/AndroidRuntime: FATAL
    EXCEPTION: main
                                                                  Process:
    com.ati.activate, PID: 17843

    java.lang.RuntimeException: Unable to start activity

ComponentInfo{com.ati.activate/com.ati.activate.UserManagement.RegisterUserActivity}: java.lang.IllegalStateException: You need to use a Theme.AppCompat theme (or descendant) with this activity.

                                                                      at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2817)
                                                                      at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2892)
                                                                      at android.app.ActivityThread.-wrap11(Unknown Source:0)
                                                                      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1593)
                                                                      at android.os.Handler.dispatchMessage(Handler.java:105)
                                                                      at android.os.Looper.loop(Looper.java:164)
                                                                      at android.app.ActivityThread.main(ActivityThread.java:6541)
                                                                      at java.lang.reflect.Method.invoke(Native Method)
                                                                      at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
                                                                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
                                                                   Caused by: java.lang.IllegalStateException: You need to use a Theme.AppCompat theme (or descendant) with this activity.
                                                                      at android.support.v7.app.AppCompatDelegateImplV9.createSubDecor(AppCompatDelegateImplV9.java:359)
                                                                      at android.support.v7.app.AppCompatDelegateImplV9.ensureSubDecor(AppCompatDelegateImplV9.java:328)
                                                                      at android.support.v7.app.AppCompatDelegateImplV9.setContentView(AppCompatDelegateImplV9.java:289)
                                                                      at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:140)
                                                                      at com.ati.activate.UserManagement.RegisterUserActivity.onCreate(RegisterUserActivity.java:13)
                                                                      at android.app.Activity.performCreate(Activity.java:6975)
                                                                      at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1213)
                                                                      at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2770)
                                                                      at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2892)
                                                                      at android.app.ActivityThread.-wrap11(Unknown Source:0)
                                                                      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1593)
                                                                      at android.os.Handler.dispatchMessage(Handler.java:105)
                                                                      at android.os.Looper.loop(Looper.java:164)
                                                                      at android.app.ActivityThread.main(ActivityThread.java:6541)
                                                                      at java.lang.reflect.Method.invoke(Native Method)
                                                                      at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
                                                                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
</code>```

And this is the error when Main Activity is opened:

```<code>12-08 04:59:50.431 21418-21586/com.ati.activate E/StudioProfiler: JVMTI

error: 15(JVMTI_ERROR_THREAD_NOT_ALIVE)
12-08 04:59:50.432 21418-21586/com.ati.activate E/StudioProfiler: JVMTI error: 15(JVMTI_ERROR_THREAD_NOT_ALIVE)
12-08 04:59:50.518 21418-21418/com.ati.activate E/AndroidRuntime: FATAL EXCEPTION: main
                                                                  Process: com.ati.activate, PID: 21418
                                                                  java.lang.RuntimeException: Unable to start activity ComponentInfo{com.ati.activate/com.ati.activate.MainActivity}: java.lang.IllegalStateException: You need to use a Theme.AppCompat theme (or descendant) with this activity.
                                                                      at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2817)
                                                                      at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2892)
                                                                      at android.app.ActivityThread.-wrap11(Unknown Source:0)
                                                                      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1593)
                                                                      at android.os.Handler.dispatchMessage(Handler.java:105)
                                                                      at android.os.Looper.loop(Looper.java:164)
                                                                      at android.app.ActivityThread.main(ActivityThread.java:6541)
                                                                      at java.lang.reflect.Method.invoke(Native Method)
                                                                      at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
                                                                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
                                                                   Caused by: java.lang.IllegalStateException: You need to use a Theme.AppCompat theme (or descendant) with this activity.
                                                                      at android.support.v7.app.AppCompatDelegateImplV9.createSubDecor(AppCompatDelegateImplV9.java:359)
                                                                      at android.support.v7.app.AppCompatDelegateImplV9.ensureSubDecor(AppCompatDelegateImplV9.java:328)
                                                                      at android.support.v7.app.AppCompatDelegateImplV9.setContentView(AppCompatDelegateImplV9.java:289)
                                                                      at android.support.v7.app.AppCompatActivity.setContentView(AppCompatActivity.java:140)
                                                                      at com.ati.activate.MainActivity.onCreate(MainActivity.java:26)
                                                                      at android.app.Activity.performCreate(Activity.java:6975)
                                                                      at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1213)
                                                                      at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2770)
                                                                      at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2892)
                                                                      at android.app.ActivityThread.-wrap11(Unknown Source:0)
                                                                      at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1593)
                                                                      at android.os.Handler.dispatchMessage(Handler.java:105)
                                                                      at android.os.Looper.loop(Looper.java:164)
                                                                      at android.app.ActivityThread.main(ActivityThread.java:6541)
                                                                      at java.lang.reflect.Method.invoke(Native Method)
                                                                      at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
                                                                      at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
</code>```

答:
Put this code in your style.xml

```<code><style name="AppTheme.NoActionBar">
    <item name="windowActionBar">false</item>
    <item name="windowNoTitle">true</item>
</style>
</code>```

and don't add parent ="AppTheme" in the above code.

Title: App crashing after theme update

Body:
The app I was working on so far was working fine until I added a couple of new activities and tried applied some changes to the theme.

The following is my styles.xml file. I looked into other results and added a parent to AppTheme as I was getting an error regarding AppCompat earlier. I also made AppTheme parent of NoActionBar. One thing I noticed was when I apply AppBarOverlay to Register User Activity it crashes and when I apply other it doesn't. Main Activity is crashing regardless.

<resources>

Body:
Put this code in your style.xml

<style name="AppTheme.NoActionBar">
    <item name="windowActionBar">false</item>
    <item name="windowNoTitle">true</item>
</style>

and don't add parent ="AppTheme" in the above code.


问:
Spring hibernate more than one row with the given foreign key was found
i have a problem using findByProfileId() method of JPA repository

this is my sample entries (rows) on my database.

When i try to request via REST (http://localhost:8080/rest/test/21234) where 21234 is the profile_id in the above table.

Here is my RESTservice.

```<code>@RequestMapping(path="/{id}", method = RequestMethod.GET)
public ResponseEntity<?> get(@PathVariable Long id){
    try {
        logger.info("get({})",id);
        logger.info("get({})",Lists.transform(wishlistService.get(id), toRestWishlist));
        return new ResponseEntity<>(Lists.transform(wishlistService.get(id), toRestWishlist), HttpStatus.OK);
    } catch (Exception e) {
        // TODO: handle exception
        logger.error("{}",e.getMessage());
        return new ResponseEntity<>(e.getMessage(), HttpStatus.BAD_REQUEST);
    }
}
</code>```

Here is the WishlistServiceImpl

```<code>@Override
public List<Wishlist> get(Long id) {
    // TODO Auto-generated method stub
    return repo.findByProfileId(id);
}
</code>```

Here is the Repository

```<code>@Repository
public interface WishlistRepository extends JpaRepository<Wishlist, Long> {

    List<Wishlist> findByProfileId(Long id);

}
</code>```

Here is my Wishlist entity

```<code>@Entity
@Table(name = "wishlist")
public class Wishlist {

    @Id
    @GeneratedValue
    @Column(name="wish_Id")
    private Long wishId;

    @OneToOne(cascade= CascadeType.DETACH)
    @JoinColumn(name = "profile_id")
    private Profile profile;

    @OneToMany(
        mappedBy = "wishlist",
        cascade = CascadeType.DETACH,
        orphanRemoval = true
    )
    private List<Comment> comments;

    @NotNull
    @Column(name="description")
    private String description;

    @NotNull
    @Column(name="images")
    private String images;

    @Column(name="created_at")
    private Long createAt;

    @Column(name="updated_at")
    private Long updatedAt;

    /* Getters and Setters and toString() */

}
</code>```

Everytime i send the request i get this error on the logs

```<code>2017-12-08 14:15:54.854  INFO 2620 --- [nio-8080-exec-2] c.s.s.web.controller.WishlistController  : get(21234)
2017-12-08 14:15:54.858  INFO 2620 --- [nio-8080-exec-2] o.h.e.internal.DefaultLoadEventListener  : HHH000327: Error performing load command : org.hibernate.HibernateException: More than one row with the given identifier was found: 21234, for class: com.secret.santa.core.models.Wishlist
2017-12-08 14:15:54.858 ERROR 2620 --- [nio-8080-exec-2] c.s.s.web.controller.WishlistController  : More than one row with the given identifier was found: 21234, for class: com.secret.santa.core.models.Wishlist; nested exception is org.hibernate.HibernateException: More than one row with the given identifier was found: 21234, for class: com.secret.santa.core.models.Wishlist
</code>```

答:
Declare method signature in Repository as:

```<code>List<Wishlist> findAllByProfile(Profile profile);
</code>```

And you have to pass something like new Profile(profileId).

Also, you might have to change @OneToOne annotation in field Profile to @ManyToOne.

Body:
i have a problem using findByProfileId() method of JPA repository

this is my sample entries (rows) on my database.

When i try to request via REST (http://localhost:8080/rest/test/21234) where 21234 is the profile_id in the above table.

Here is my RESTservice.

@RequestMapping(path="/{id}", method = RequestMethod.GET)
public ResponseEntity<?> get(@PathVariable Long id){
    try {
        logger.info("get({})",id);
        logger.info("get({})",Lists.transform(wishlistService.get(id), toRestWishlist));
        return new ResponseEntity<>(Lists.transform(wishlistService.get(id), toRestWishlist), HttpStatus.OK);
    } catch (Exception e) {
        // TODO: handle exception
        logger.error("{}",e.getMessage());
        return new ResponseEntity<>(e.getMessage(), HttpStatus.BAD_REQUEST);
    }
}

Here is the WishlistServiceImpl

@Override
public List<Wishlist> get(Long id) {
    // TODO Auto-generated method stub
    return repo.findByProfileId(id);
}

Here is the Repository

@Repository
public interface WishlistRepository extends JpaRepository<Wishlist, Long> {

    List<Wishlist> findByProfileId(Long id);

}

Here is my Wishlist entity

@Entity
@Table(name = "wishlist")
public class Wishlist {

    @Id
    @GeneratedValue
    @Column(name="wish_Id")
    private Long wishId;

    @OneToOne(cascade= CascadeType.DETACH)
    @JoinColumn(name = "profile_id")
    private Profile profile;

    @OneToMany(
        mappedBy = "wishlist",
        cascade = CascadeType.DETACH,
        orphanRemoval = true
    )
    private List<Comment> comments;

    @NotNull
    @Column(name="description")
    private String description;

    @NotNull
    @Column(name="images")
    private String images;

    @Column(name="created_at")
    private Long createAt;

    @Column(name="updated_at")
    private Long updatedAt;

    /* Getters and Setters and toString() */

}

Everytime i send the request i get this error on the logs

2017-12-08 14:15:54.854  INFO 2620 --- [nio-8080-exec-2] c.s.s.web.controller.WishlistController  : get(21234)
2017-12-08 14:15:54.858  INFO 2620 --- [nio-8080-exec-2] o.h.e.internal.DefaultLoadEventListener  : HHH000327: Error performing load command : org.hibernate.HibernateException: More than one row with the given identifier was found: 21234, for class: com.secret.santa.core.models.Wishlist
2017-12-08 14:15:54.858 ERROR 2620 --- [nio-8080-exec-2] c.s.s.web.controller.WishlistController  : More than one row with the given identifier was found: 21234, for class: com.secret.santa.core.models.Wishlist; nested exception is org.hibernate.HibernateException: More than one row with the given identifier was found: 21234, for class: com.secret.santa.core.models.Wishlist

Body:
Declare method signature in Repository as:

List<Wishlist> findAllByProfile(Profile profile);

And you have to pass something like new Profile(profileId).

Also, you might have to change @OneToOne annotation in field Profile to @ManyToOne.


答:
You are looking for an input pattern, also called regexp (though I would instead suggest doing it js way (but not global) or on server side as advanced users can simply inspect html code). Most probably something like this

```<code><input type="text" name="promo" pattern="15OFFNOW" required >
</code>```

Also, please try googling it, there're similar  questions like this answered also on StackOwerflow, e.g.

html: Can we match an exact string using html pattern attribute only?

js & php: check if input value not equal to integer then don't submit form

Title: Promo Code Validation

Body:
I need to validate a Promo Code for one of my html Booking form field. If the entered promo code is correct, users can submit the Booking details. Only one unique promo code. Something like "15OFFNOW" How should I do it? Please help.

Thanks.

Body:
You are looking for an input pattern, also called regexp (though I would instead suggest doing it js way (but not global) or on server side as advanced users can simply inspect html code). Most probably something like this

<input type="text" name="promo" pattern="15OFFNOW" required >

Also, please try googling it, there're similar  questions like this answered also on StackOwerflow, e.g.

html: Can we match an exact string using html pattern attribute only?

js & php: check if input value not equal to integer then don't submit form


问:
how do I update and array of users with rails 3
I am trying to pass an array of user objects from flash to rails 3 and update them all at once. Here is the code that I am using.

```<code>  def update_by_fbid
    if params[:users]

     params[:users].each do |u|
       puts u
        user = User.find_by_fbid(u.fbid)
        user.update_attributes(:first_name => u.first_name, :last_name => u.last_name)
      end
    end
    render :json => {:updated_users => true}
  end
</code>```

Here is my code from Flash

```<code>private function updateUsers(e:Event):void
{
    var users:Array = [{fbid:"93847566", first_name:"Joe", last_name:"Blow"},
        {fbid:"7654321", first_name:"Ronda", last_name:"Smith"}
        ];

    var vars : URLVariables = new URLVariables();
        vars.users = users;

    var request : URLRequest = new URLRequest("http://localhost:3000/update");
    request.method = URLRequestMethod.POST;
    request.data = vars;

    var loader : URLLoader = new URLLoader();
    loader.addEventListener(Event.COMPLETE, registerHandler);
    loader.addEventListener(IOErrorEvent.IO_ERROR, onIOError);
    loader.load(request);
    }
</code>```

here is the error that I am seeing in the terminal

```<code>Started POST "/update" for 127.0.0.1 at Sat Jan 22 13:41:42 -0600 2011
  Processing by UsersController#update_by_fbid as HTML
  Parameters: {"users"=>"[object Object]"}
Completed   in 8ms

NoMethodError (undefined method `fbid' for "[object Object]":String):
  app/controllers/users_controller.rb:68:in `update_by_fbid'
  app/controllers/users_controller.rb:66:in `each'
  app/controllers/users_controller.rb:66:in `update_by_fbid'

Rendered /Library/Ruby/Gems/1.8/gems/actionpack-3.0.2/lib/action_dispatch/middleware/templates/rescues/_trace.erb (1.1ms)
Rendered /Library/Ruby/Gems/1.8/gems/actionpack-3.0.2/lib/action_dispatch/middleware/templates/rescues/_request_and_response.erb (3.8ms)
Rendered /Library/Ruby/Gems/1.8/gems/actionpack-3.0.2/lib/action_dispatch/middleware/templates/rescues/diagnostics.erb within rescues/layout (8.9ms)
</code>```

Still a little new at rails so I am sure I am just selecting my objects from the parmas incorrectly or something of that nature. Hoping someone can school me a bit on what I am doing wrong on the rails side of things.

-m

答:
What @coreyward says is definitely correct. But i think the error happens even earlier. In the log i see:

```<code>Parameters: {"users"=>"[object Object]"}
</code>```

and Rails does not expects objects, but hashes, so something like

```<code>Parameters: {"users"=>"[{:first_name => 'Fred', last_name => 'Kruger'},
                        {:first_name => "Harrison", :last_name => 'Ford'}]"}
</code>```

Now, i am not sure how you can do this from flash/flex. Convert to json?
But i think that's where you should start looking.

[EDIT: handle the json]

Ah, i can see from your edit that you are now receiving json indeed! Json is actually a string in a special format. That work with that, you need to use the json gem (add it to your Gemfile), and then you can write something like:

```<code>rcvd_users = JSON.parse(param[:users])
rcvd_users.each do |u|
  user = User.find_by_fbid(u[:fbid])
  puts u[:fbid]
  unless user.nil?
    user.update_attributes u
  end
end
</code>```

Hope this helps :)

Body:
I am trying to pass an array of user objects from flash to rails 3 and update them all at once. Here is the code that I am using.

  def update_by_fbid
    if params[:users]

     params[:users].each do |u|
       puts u
        user = User.find_by_fbid(u.fbid)
        user.update_attributes(:first_name => u.first_name, :last_name => u.last_name)
      end
    end
    render :json => {:updated_users => true}
  end

Here is my code from Flash

private function updateUsers(e:Event):void
{
    var users:Array = [{fbid:"93847566", first_name:"Joe", last_name:"Blow"},
        {fbid:"7654321", first_name:"Ronda", last_name:"Smith"}
        ];

    var vars : URLVariables = new URLVariables();
        vars.users = users;

    var request : URLRequest = new URLRequest("http://localhost:3000/update");
    request.method = URLRequestMethod.POST;
    request.data = vars;

    var loader : URLLoader = new URLLoader();
    loader.addEventListener(Event.COMPLETE, registerHandler);
    loader.addEventListener(IOErrorEvent.IO_ERROR, onIOError);
    loader.load(request);
    }

here is the error that I am seeing in the terminal

Started POST "/update" for 127.0.0.1 at Sat Jan 22 13:41:42 -0600 2011
  Processing by UsersController#update_by_fbid as HTML
  Parameters: {"users"=>"[object Object]"}
Completed   in 8ms

NoMethodError (undefined method `fbid' for "[object Object]":String):
  app/controllers/users_controller.rb:68:in `update_by_fbid'
  app/controllers/users_controller.rb:66:in `each'
  app/controllers/users_controller.rb:66:in `update_by_fbid'

Rendered /Library/Ruby/Gems/1.8/gems/actionpack-3.0.2/lib/action_dispatch/middleware/templates/rescues/_trace.erb (1.1ms)
Rendered /Library/Ruby/Gems/1.8/gems/actionpack-3.0.2/lib/action_dispatch/middleware/templates/rescues/_request_and_response.erb (3.8ms)
Rendered /Library/Ruby/Gems/1.8/gems/actionpack-3.0.2/lib/action_dispatch/middleware/templates/rescues/diagnostics.erb within rescues/layout (8.9ms)

Still a little new at rails so I am sure I am just selecting my objects from the parmas incorrectly or something of that nature. Hoping someone can school me a bit on what I am doing wrong on the rails side of things.

-m

Body:
What @coreyward says is definitely correct. But i think the error happens even earlier. In the log i see:

Parameters: {"users"=>"[object Object]"}

and Rails does not expects objects, but hashes, so something like

Parameters: {"users"=>"[{:first_name => 'Fred', last_name => 'Kruger'},
                        {:first_name => "Harrison", :last_name => 'Ford'}]"}

Now, i am not sure how you can do this from flash/flex. Convert to json?
But i think that's where you should start looking.

[EDIT: handle the json]

Ah, i can see from your edit that you are now receiving json indeed! Json is actually a string in a special format. That work with that, you need to use the json gem (add it to your Gemfile), and then you can write something like:

rcvd_users = JSON.parse(param[:users])
rcvd_users.each do |u|
  user = User.find_by_fbid(u[:fbid])
  puts u[:fbid]
  unless user.nil?
    user.update_attributes u
  end
end

Hope this helps :)


问:
How to split an SQL Table into half and send the other half of the rows to new columns with SQL Query?
```<code>Country    Percentage

India      12%
USA        20%
Australia  15%
Qatar      10%
</code>```

Output :

```<code>Country1    Percentage1     Country2     Percentage2
India       12%             Australia    15%
USA         20%             Qatar        10%
</code>```

For example there is a table Country which has percentages, I need to divide the table in Half and show the remaining half (i.e. the remaining rows) in the new columns. I've also provided the table structure in text.

答:
Assuming you want descending alphabetic country names, but the left column is determined by where India is located in the result:

```<code>with CoutryCTE as (
      select c.*
           , row_number() over (order by country)-1 as rn
      from country c
      )
, Col as (
     select rn % 2 as num from CoutryCTE
     where Country = 'India'
     )
select max(case when rn % 2 =  Col.num then country end) as country_1
     , max(case when rn % 2 =  Col.num then percentage end) as percentage_1
     , max(case when rn % 2 <> Col.num then country end) as country_2
     , max(case when rn % 2 <> Col.num then percentage end) as percentage_2
from CoutryCTE
cross join Col
group by rn / 2
;
</code>```

SQLFiddle Demo

```<code>| country_1 | percentage_1 | country_2 | percentage_2 |
|-----------|--------------|-----------|--------------|
|     India |          12% | Australia |          15% |
|       USA |          20% |     Qatar |          10% |
</code>```

nb: this is extremely similar to an earlier answer by Gordon Linoff

Body:
Country    Percentage

India      12%
USA        20%
Australia  15%
Qatar      10%

Output :

Country1    Percentage1     Country2     Percentage2
India       12%             Australia    15%
USA         20%             Qatar        10%

For example there is a table Country which has percentages, I need to divide the table in Half and show the remaining half (i.e. the remaining rows) in the new columns. I've also provided the table structure in text.

Body:
Assuming you want descending alphabetic country names, but the left column is determined by where India is located in the result:

with CoutryCTE as (
      select c.*
           , row_number() over (order by country)-1 as rn
      from country c
      )
, Col as (
     select rn % 2 as num from CoutryCTE
     where Country = 'India'
     )
select max(case when rn % 2 =  Col.num then country end) as country_1
     , max(case when rn % 2 =  Col.num then percentage end) as percentage_1
     , max(case when rn % 2 <> Col.num then country end) as country_2
     , max(case when rn % 2 <> Col.num then percentage end) as percentage_2
from CoutryCTE
cross join Col
group by rn / 2
;

SQLFiddle Demo

| country_1 | percentage_1 | country_2 | percentage_2 |
|-----------|--------------|-----------|--------------|
|     India |          12% | Australia |          15% |
|       USA |          20% |     Qatar |          10% |

nb: this is extremely similar to an earlier answer by Gordon Linoff


问:
populate tabItems in dashboardBody
How to populate tabItems in shinydashboard with tabItem elements using code that takes some dynamic input?

Example of what I am doing is below. The code works and generates extra tabs when the button is clicked.
TODO line explains where I have the difficulty. I want to add tabItem for each tab by code, instead of putting tab0, tab1 etc explicitly.

ui.R

```<code>library(shiny)
library(shinydashboard)

dashboardPage(

  dashboardHeader(title = "EXAMPLE MULTI TABS"),
  dashboardSidebar(
    sidebarMenuOutput("menu"),
    actionButton("add", label = "Add tab")),
  dashboardBody(uiOutput("body1"))
)
</code>```

server.R

```<code>library(shiny)
library(shinydashboard)
# example server
function(input, output) {
    output$menu <- renderMenu(

      sidebarMenu(
        # adding sub items if action button pressed
        do.call(menuItem, c(text = "Example tabs", tabName = "settings", startExpanded = T,
                            lapply(0:input$add, function(i) {
                              menuSubItem(text = paste0("sub menu ", i), tabName=paste0("tab",i))
                        }
                        )))
  ))

# body for different tabs
output$body1 <- renderUI({
  tabItems(
    #TODO: add tabs content based on number of tabs that is defined by action button value
    tabItem(tabName = "tab0",
            uiOutput("tab0")),
    tabItem(tabName = "tab1",
            uiOutput("tab1"))
  )
})

# add tab content for each tab
observe({
  for (i in 0:input$add) {
    local({
      my_i <- i
      tabname <- paste0("tab",my_i)
      output[[tabname]] <- renderUI({
        box(
          renderText(paste0("tab",my_i))
          )
        })
      })
    }
  })
}
</code>```

答:
Thank you for the link.
I got it working.

Here is working server.R:

```<code>library(shiny)
library(shinydashboard)
# example server
function(input, output) {
    output$menu <- renderMenu(

      sidebarMenu(id = "tabs",
        # adding sub items if action button pressed

        do.call(menuItem, c(text = "Example tabs", tabName = "settings", startExpanded = T,
                            lapply(0:input$add, function(i) {
                              menuSubItem(text = paste0("sub menu ", i), tabName=paste0("tab",i))
                        }
                        )))
  ))

# body for different tabs
output$body1 <- renderUI({
  if (input$add == 0) {
    return(NULL)
  }
  Tabs <- vector("list", input$add)
  for(i in 1:input$add) {
      tabname <- paste0("tab",i)
      Tabs[[i]] <- tabItem(tabName = tabname, uiOutput(tabname))
  }
  do.call(tabItems, Tabs)
})

tabContent <- reactive(input[[input$tabs]])

# add tab content for each tab
observe({
  if (input$add == 0) {
    return(NULL)
  }

  for (i in 1:input$add) {
    local({
      my_i <- i
      tabname <- paste0("tab",my_i)
      output[[tabname]] <- renderUI({
        box(
          renderText(paste0("tab",my_i))
          )
        })
      })

    }
  })
}
</code>```

Title: populate tabItems in dashboardBody

Body:
How to populate tabItems in shinydashboard with tabItem elements using code that takes some dynamic input?

Example of what I am doing is below. The code works and generates extra tabs when the button is clicked.
TODO line explains where I have the difficulty. I want to add tabItem for each tab by code, instead of putting tab0, tab1 etc explicitly.

ui.R

library(shiny)
library(shinydashboard)

dashboardPage(

  dashboardHeader(title = "EXAMPLE MULTI TABS"),
  dashboardSidebar(
    sidebarMenuOutput("menu"),
    actionButton("add", label = "Add tab")),
  dashboardBody(uiOutput("body1"))
)

server.R

library(shiny)
library(shinydashboard)
# example server
function(input, output) {
    output$menu <- renderMenu(

      sidebarMenu(
        # adding sub items if action button pressed
        do.call(menuItem, c(text = "Example tabs", tabName = "settings", startExpanded = T,
                            lapply(0:input$add, function(i) {
                              menuSubItem(text = paste0("sub menu ", i), tabName=paste0("tab",i))
                        }
                        )))
  ))

# body for different tabs
output$body1 <- renderUI({
  tabItems(
    #TODO: add tabs content based on number of tabs that is defined by action button value
    tabItem(tabName = "tab0",
            uiOutput("tab0")),
    tabItem(tabName = "tab1",
            uiOutput("tab1"))
  )
})

# add tab content for each tab
observe({
  for (i in 0:input$add) {
    local({
      my_i <- i
      tabname <- paste0("tab",my_i)
      output[[tabname]] <- renderUI({
        box(
          renderText(paste0("tab",my_i))
          )
        })
      })
    }
  })
}

Body:
Thank you for the link.
I got it working.

Here is working server.R:

library(shiny)
library(shinydashboard)
# example server
function(input, output) {
    output$menu <- renderMenu(

      sidebarMenu(id = "tabs",
        # adding sub items if action button pressed

        do.call(menuItem, c(text = "Example tabs", tabName = "settings", startExpanded = T,
                            lapply(0:input$add, function(i) {
                              menuSubItem(text = paste0("sub menu ", i), tabName=paste0("tab",i))
                        }
                        )))
  ))

# body for different tabs
output$body1 <- renderUI({
  if (input$add == 0) {
    return(NULL)
  }
  Tabs <- vector("list", input$add)
  for(i in 1:input$add) {
      tabname <- paste0("tab",i)
      Tabs[[i]] <- tabItem(tabName = tabname, uiOutput(tabname))
  }
  do.call(tabItems, Tabs)
})

tabContent <- reactive(input[[input$tabs]])

# add tab content for each tab
observe({
  if (input$add == 0) {
    return(NULL)
  }

  for (i in 1:input$add) {
    local({
      my_i <- i
      tabname <- paste0("tab",my_i)
      output[[tabname]] <- renderUI({
        box(
          renderText(paste0("tab",my_i))
          )
        })
      })

    }
  })
}


问:
Execute Alert Before location.reload
I am using jQuery confirm min js. and use alert in my ajax code.

The problem is when my ajax code runs first it gives priority to locationReload and reload. I want to run alert first then reload.

One thing I note that if I use Simple ALERT('some') so it works but this can't.

My code is as follow

```<code>success:   function(data) {
  $.alert({
      title: 'Message!',
      content: data,
      theme: 'material',
      animation: 'zoom',
      animationBounce: 2.5,
  });
  //$('#thmb_prev').html(data);
  $('#loader').hide();
  location.reload();
}
</code>```

答:
Since JavaScript interpreter executes the code in one thread, it doesn't wait for the dialog to close. The alert() blocks the thread until it is closed. That's why it seems to work fine in your case.

But to do what you want here, you need to use callbacks, as described in the documentation.

```<code>success: function(data) {
  $.alert({
      title: 'Message!',
      content: data,
      theme: 'material',
      animation: 'zoom',
      animationBounce: 2.5,
      onClose: function () {
        // Do whatever you want when the dialog is about to be closed
        location.reload();
      }
  });
  //$('#thmb_prev').html(data);
  $('#loader').hide();
}
</code>```

Title: Execute Alert Before location.reload

Body:
I am using jQuery confirm min js. and use alert in my ajax code.

The problem is when my ajax code runs first it gives priority to locationReload and reload. I want to run alert first then reload.

One thing I note that if I use Simple ALERT('some') so it works but this can't.

My code is as follow

success:   function(data) {
  $.alert({
      title: 'Message!',
      content: data,
      theme: 'material',
      animation: 'zoom',
      animationBounce: 2.5,
  });
  //$('#thmb_prev').html(data);
  $('#loader').hide();
  location.reload();
}

Body:
Since JavaScript interpreter executes the code in one thread, it doesn't wait for the dialog to close. The alert() blocks the thread until it is closed. That's why it seems to work fine in your case.

But to do what you want here, you need to use callbacks, as described in the documentation.

success: function(data) {
  $.alert({
      title: 'Message!',
      content: data,
      theme: 'material',
      animation: 'zoom',
      animationBounce: 2.5,
      onClose: function () {
        // Do whatever you want when the dialog is about to be closed
        location.reload();
      }
  });
  //$('#thmb_prev').html(data);
  $('#loader').hide();
}


答:
It might be a factor of the knowledge economy of a particular company. For example, the bigger a company gets, or the less staff turnover they have, the harder it will be to replace competence, process and tooling to accommodate, for example, a new language. C/C++ has been around for quite some time, and many developers as well as development shops have that background.

Concerning banking applications, the reason is, I would guess, mostly because you have a close to metal environment which allows you to utilise realtime programming in a dependable fashion.

Title: What are the advantages of developing applications in C++ as compared to managed languages?

Body:
Hi I want to know why people develop library applications and employee management applications in C++ (this application, for example), when clearly the same thing can be done in C# and VB.NET in a much prettier way. Even banking applications are mostly in C++. Is there a good reason why, apart from the fact that compiled C++ code executes faster?

Can anyone shed some light on this?


问:
Testflight - Build is there but not showing?
So I just got an email telling me that my build has completed processing.
I go to iTunes connect and sure enough there it is. I go to add testers, and it asks me to input some contact info before it adds the testers.

Somewhere here the whole thing just stops working, so I reload the page and this is all I can see now:

My Build is there, it is the correct version, but I cant see it, or do anything with it, really weird. What is this?

答:
To create .ipa file i'm using Ad Hoc option. But for testing apple send an email like this ....

```<code>Missing beta entitlement - Your app does not include the beta-reports-active entitlement. If you intend to distribute this build via TestFlight for beta testing, please re-build this app with an App Store Distribution provisioning profile. Do not use ad-hoc profiles.

 After you’ve corrected the issues, you can use Xcode or Application Loader to upload a new binary to iTunes Connect.

Regards,
The App Store team
</code>```

Now i selected App Store option to create .ipa file. Now i uploaded the .ipa through application builder. Then only i'm getting my build in TestFlight. I think this will help you...

Body:
To create .ipa file i'm using Ad Hoc option. But for testing apple send an email like this ....

Missing beta entitlement - Your app does not include the beta-reports-active entitlement. If you intend to distribute this build via TestFlight for beta testing, please re-build this app with an App Store Distribution provisioning profile. Do not use ad-hoc profiles.

 After you’ve corrected the issues, you can use Xcode or Application Loader to upload a new binary to iTunes Connect.

Regards,
The App Store team

Now i selected App Store option to create .ipa file. Now i uploaded the .ipa through application builder. Then only i'm getting my build in TestFlight. I think this will help you...


问:
how to call method inside class using MooseX::Declare
here "info_vcf" is a class where "info_vcf_function" is a method. "getValueFromInfoColum" and "getValueFromFormatColum" both are method which are present inside the "info_vcf_function" method.
now i want to call "getValueFromInfoColum" and "getValueFromFormatColum" both method from inside "info_vcf_function" method. how to do this ?

it gives me error " Validation failed for 'Tuple[Tuple[Object,Any],Dict[]]' with value "[ [ info_vcf=HASH(0x1ac7fd0), info_vcf=HASH(0x1ac7fd0), "anop" ], {  } ], Internal Validation Error is: \n [+] Valida
tion failed for 'Tuple[Object,Any]' with value "[ info_vcf={  }, info_vcf={  }, "anop" ]"\n  [+] More values than Type Constraints!" at /usr/local/share/perl/5.22.1/MooseX/Method/Signat
ures/Meta/Method.pm line 432.
        MooseX::Method::Signatures::Meta::Method::validate(MooseX::Method::Signatures::Meta::Method=HASH(0x3bd0e60), ARRAY(0x3154e80)) called at /usr/local/share/perl/5.22.1/MooseX/Meth
od/Signatures/Meta/Method.pm line 148
        info_vcf::info_vcf_function(info_vcf=HASH(0x1ac7fd0), info_vcf=HASH(0x1ac7fd0), "anop") called at testone.pl line 24 "

```<code>#!/usr/bin/perl -w
use MooseX::Declare;

class info_vcf {

    method info_vcf_function($selectedVariant) {

        print "$selectedVariant";
        getValueFromInfoColum("singh");
        getValueFromFormatColum("ranawat");

    }
        method getValueFromInfoColum($flag){
            print "$flag\n";
        }
        method getValueFromFormatColum($flag){
            print "$flag\n";
        }

}
1;

my $object = info_vcf->new();
$object->info_vcf_function("anop");
</code>```

答:
thanks everyone, finally its working </p>

```<code>#!/usr/bin/perl -w
use MooseX::Declare;

class info_vcf {

    method info_vcf_function($selectedVariant) {
        print "$selectedVariant";
        $self->getValueFromInfoColum("singh");
        $self->getValueFromFormatColum("ranawat");
    }

    method getValueFromInfoColum($flag){
        print "$flag\n";
    }

    method getValueFromFormatColum($flag){
        print "$flag\n";
    }
}
1;

my $object = info_vcf->new();
$object->info_vcf_function("anop");
</code>```

Body:
here "info_vcf" is a class where "info_vcf_function" is a method. "getValueFromInfoColum" and "getValueFromFormatColum" both are method which are present inside the "info_vcf_function" method.
now i want to call "getValueFromInfoColum" and "getValueFromFormatColum" both method from inside "info_vcf_function" method. how to do this ?

it gives me error " Validation failed for 'Tuple[Tuple[Object,Any],Dict[]]' with value "[ [ info_vcf=HASH(0x1ac7fd0), info_vcf=HASH(0x1ac7fd0), "anop" ], {  } ], Internal Validation Error is: \n [+] Valida
tion failed for 'Tuple[Object,Any]' with value "[ info_vcf={  }, info_vcf={  }, "anop" ]"\n  [+] More values than Type Constraints!" at /usr/local/share/perl/5.22.1/MooseX/Method/Signat
ures/Meta/Method.pm line 432.
        MooseX::Method::Signatures::Meta::Method::validate(MooseX::Method::Signatures::Meta::Method=HASH(0x3bd0e60), ARRAY(0x3154e80)) called at /usr/local/share/perl/5.22.1/MooseX/Meth
od/Signatures/Meta/Method.pm line 148
        info_vcf::info_vcf_function(info_vcf=HASH(0x1ac7fd0), info_vcf=HASH(0x1ac7fd0), "anop") called at testone.pl line 24 "

#!/usr/bin/perl -w
use MooseX::Declare;

class info_vcf {

    method info_vcf_function($selectedVariant) {

        print "$selectedVariant";
        getValueFromInfoColum("singh");
        getValueFromFormatColum("ranawat");

    }
        method getValueFromInfoColum($flag){
            print "$flag\n";
        }
        method getValueFromFormatColum($flag){
            print "$flag\n";
        }

}
1;

my $object = info_vcf->new();
$object->info_vcf_function("anop");

Body:
thanks everyone, finally its working

#!/usr/bin/perl -w
use MooseX::Declare;

class info_vcf {

    method info_vcf_function($selectedVariant) {
        print "$selectedVariant";
        $self->getValueFromInfoColum("singh");
        $self->getValueFromFormatColum("ranawat");
    }

    method getValueFromInfoColum($flag){
        print "$flag\n";
    }

    method getValueFromFormatColum($flag){
        print "$flag\n";
    }
}
1;

my $object = info_vcf->new();
$object->info_vcf_function("anop");


问:
Convert Excel XML 2003 Worksheet file into .XLSX file in C#
I'm implementing a solution where users load .XLS,.XLSX and .CSV files into an ASP MVC application. I'm using Gembox Spreadsheet plugin to read files and so far it works well, but the user requires to load an .XML file with a particular schema. I don't know which Excel version is supposed to be equivalent for this file, but I found this on the XML file and it states its a schema for Excel:

```<code><?xml version="1.0"?>
<?mso-application progid="Excel.Sheet"?>
<Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet"
 xmlns:o="urn:schemas-microsoft-com:office:office"
 xmlns:x="urn:schemas-microsoft-com:office:excel"
 xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet"
 xmlns:html="http://www.w3.org/TR/REC-html40">
</code>```

Which hints me that is and old .XLS document schema, same conclusion I have found after a quick google search, but I don't know which protocol this file is or which standard/library it belongs to. Could anyone shed some light on how exactly to read this? If I open this file with Microsoft Excel it can be read but I don'w know how.

EDIT

Following Sunil's answer I have researched a bit more and this is an Microsoft Excel 2003 XML file, so I tried using Microsoft's Open XML SDK to try reading this file, I found this code:

```<code>public static void ConvertExcelXmltoXlsx(Stream fileStream, string filePath, string fileName)
{
    string excelFileName = Path.GetFileNameWithoutExtension(fileName) + ".xslx";
    OpenXmlReader reader = OpenXmlReader.Create(fileStream);
    while (reader.Read())
    {
        if (reader.ElementType == typeof(CellValue))
        {
            reader.GetText();
        }
    }
}
</code>```

However the file was not recognized, and when I tried opening it with Open SDK Productivity Tool it says the file is corrupt.

But I can open this file with Microsoft Excel without any issues

So far all libraries I have found are for generating this types of files, but not reading and outputting them to a different format. Maybe I'm making the wrong research.

答:
I have worked on a similar document. These files are called Excel XML files.

Look for Carlos Ag Excel Xml Writer on Google. Also search for "Excel XML reader" you will get lot of code samples.

Body:
I'm implementing a solution where users load .XLS,.XLSX and .CSV files into an ASP MVC application. I'm using Gembox Spreadsheet plugin to read files and so far it works well, but the user requires to load an .XML file with a particular schema. I don't know which Excel version is supposed to be equivalent for this file, but I found this on the XML file and it states its a schema for Excel:

<?xml version="1.0"?>
<?mso-application progid="Excel.Sheet"?>
<Workbook xmlns="urn:schemas-microsoft-com:office:spreadsheet"
 xmlns:o="urn:schemas-microsoft-com:office:office"
 xmlns:x="urn:schemas-microsoft-com:office:excel"
 xmlns:ss="urn:schemas-microsoft-com:office:spreadsheet"
 xmlns:html="http://www.w3.org/TR/REC-html40">

Which hints me that is and old .XLS document schema, same conclusion I have found after a quick google search, but I don't know which protocol this file is or which standard/library it belongs to. Could anyone shed some light on how exactly to read this? If I open this file with Microsoft Excel it can be read but I don'w know how.

EDIT

Following Sunil's answer I have researched a bit more and this is an Microsoft Excel 2003 XML file, so I tried using Microsoft's Open XML SDK to try reading this file, I found this code:

public static void ConvertExcelXmltoXlsx(Stream fileStream, string filePath, string fileName)
{
    string excelFileName = Path.GetFileNameWithoutExtension(fileName) + ".xslx";
    OpenXmlReader reader = OpenXmlReader.Create(fileStream);
    while (reader.Read())
    {
        if (reader.ElementType == typeof(CellValue))
        {
            reader.GetText();
        }
    }
}

However the file was not recognized, and when I tried opening it with Open SDK Productivity Tool it says the file is corrupt.

But I can open this file with Microsoft Excel without any issues

So far all libraries I have found are for generating this types of files, but not reading and outputting them to a different format. Maybe I'm making the wrong research.