问:
How to start hazelcast client from console
How do I run a Hazelcast client from the console?

I have this config in xml:

```<code><hazelcast-client xsi:schemaLocation="http://www.hazelcast.com/schema/client-config hazelcast-client-config-3.3.xsd"
       xmlns="http://www.hazelcast.com/schema/client-config"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">

<network>
    <port auto-increment="true" port-count="100">5701</port>
    <outbound-ports>
        <!--
        Allowed port range when connecting to other nodes.
        0 or * means use system provided port.
        -->
        <ports>0</ports>
    </outbound-ports>
    <join>
        <multicast enabled="true">
            <multicast-group>224.2.2.3</multicast-group>
            <multicast-port>54327</multicast-port>
        </multicast>
    </join>
</network>

</hazelcast-client>
</code>```

and I need a console like this when I run run.sh or run.bat, but I want it to be a client not a member.

答:
You can use the clientConsole.bat given by Hazelcast to connect to any Hazelcast server and get a console for that. Using the console you can query any existing map or queue in your Hazelcast server.

I use hazelcast-3.8.1.
In the demo directory you can find clientConsole.bat/clientConsole.sh.
To connect to an existing server you need to provide the details in a "hazelcast-client.xml" file. Here is the content of "hazelcast-client.xml" file:

```<code><hazelcast-client xmlns="http://www.hazelcast.com/schema/client-config">
    <group>
        <name>[GROUP_NAME]</name>
        <password>[GROUP_PASSWORD]</password>
    </group>
    <network>
        <cluster-members>
            <address>[HAZELCAST_SERVER_HOST_NAME_OR_IP]</address>
        </cluster-members>
    </network>
</hazelcast-client>
</code>```

Above [HAZELCAST_SERVER_HOST_NAME_OR_IP] is the ip or hostname of hazelcast server which you want to connect and get client console.

[GROUP_NAME] and [GROUP_PASSWORD] should be same what is mentioned in "hazelcast.xml" file on Hazelcast server.

Body:
How do I run a Hazelcast client from the console?

I have this config in xml:

<hazelcast-client xsi:schemaLocation="http://www.hazelcast.com/schema/client-config hazelcast-client-config-3.3.xsd"
       xmlns="http://www.hazelcast.com/schema/client-config"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">

<network>
    <port auto-increment="true" port-count="100">5701</port>
    <outbound-ports>

        <ports>0</ports>
    </outbound-ports>
    <join>
        <multicast enabled="true">
            <multicast-group>224.2.2.3</multicast-group>
            <multicast-port>54327</multicast-port>
        </multicast>
    </join>
</network>

</hazelcast-client>

and I need a console like this when I run run.sh or run.bat, but I want it to be a client not a member.

Body:
You can use the clientConsole.bat given by Hazelcast to connect to any Hazelcast server and get a console for that. Using the console you can query any existing map or queue in your Hazelcast server.

I use hazelcast-3.8.1.
In the demo directory you can find clientConsole.bat/clientConsole.sh.
To connect to an existing server you need to provide the details in a "hazelcast-client.xml" file. Here is the content of "hazelcast-client.xml" file:

<hazelcast-client xmlns="http://www.hazelcast.com/schema/client-config">
    <group>
        <name>[GROUP_NAME]</name>
        <password>[GROUP_PASSWORD]</password>
    </group>
    <network>
        <cluster-members>
            <address>[HAZELCAST_SERVER_HOST_NAME_OR_IP]</address>
        </cluster-members>
    </network>
</hazelcast-client>

Above [HAZELCAST_SERVER_HOST_NAME_OR_IP] is the ip or hostname of hazelcast server which you want to connect and get client console.

[GROUP_NAME] and [GROUP_PASSWORD] should be same what is mentioned in "hazelcast.xml" file on Hazelcast server.


来源: stackexchange

问:
How to explain the reverse of a sequence by slice notation a[::-1]
From the python.org tutorial

Slice indices have useful defaults; an omitted first index defaults to zero, an omitted second index defaults to the size of the string being sliced.

```<code>>>> a = "hello"
>>> print(a[::-1])
olleh
</code>```

As the tutorial says a[::-1] should equals to a[0:5:-1]

but a[0:5:-1] is empty as follows:

```<code>>>> print(len(a[0:5:-1]))
0
</code>```

The question is not a duplicate of explain-slice-notation. That question is about the general use of slicing in python.

答:
I think the docs are perhaps a little misleading on this, but the optional arguments of slicing if omitted are the same as using None:

```<code>>>> a = "hello"
>>> a[::-1]
'olleh'
>>> a[None:None:-1]
'olleh'
</code>```

You can see that these 2 above slices are identical from the CPython bytecode:

```<code>>>> import dis
>>> dis.dis('a[::-1]') # or dis.dis('a[None:None:-1]')
  1           0 LOAD_NAME                0 (a)
              3 LOAD_CONST               0 (None)
              6 LOAD_CONST               0 (None)
              9 LOAD_CONST               2 (-1)
             12 BUILD_SLICE              3
             15 BINARY_SUBSCR
             16 RETURN_VALUE
</code>```

For a negative step, the substituted values for None are len(a) - 1 for the start and -len(a) - 1 for the end:

```<code>>>> a[len(a)-1:-len(a)-1:-1]
'olleh'
>>> a[4:-6:-1]
'olleh'
>>> a[-1:-6:-1]
'olleh'
</code>```

This may help you visualize it:

```<code>    h  e  l  l  o
    0  1  2  3  4  5
-6 -5 -4 -3 -2 -1
</code>```

ContentLicense: CC BY-SA 3.0

Body:
From the python.org tutorial

Slice indices have useful defaults; an omitted first index defaults to zero, an omitted second index defaults to the size of the string being sliced.

>>> a = "hello"
>>> print(a[::-1])
olleh

As the tutorial says a[::-1] should equals to a[0:5:-1]

but a[0:5:-1] is empty as follows:

>>> print(len(a[0:5:-1]))
0

The question is not a duplicate of explain-slice-notation. That question is about the general use of slicing in python.

Body:
I think the docs are perhaps a little misleading on this, but the optional arguments of slicing if omitted are the same as using None:

>>> a = "hello"
>>> a[::-1]
'olleh'
>>> a[None:None:-1]
'olleh'

You can see that these 2 above slices are identical from the CPython bytecode:

>>> import dis
>>> dis.dis('a[::-1]') # or dis.dis('a[None:None:-1]')
  1           0 LOAD_NAME                0 (a)
              3 LOAD_CONST               0 (None)
              6 LOAD_CONST               0 (None)
              9 LOAD_CONST               2 (-1)
             12 BUILD_SLICE              3
             15 BINARY_SUBSCR
             16 RETURN_VALUE

For a negative step, the substituted values for None are len(a) - 1 for the start and -len(a) - 1 for the end:

>>> a[len(a)-1:-len(a)-1:-1]
'olleh'
>>> a[4:-6:-1]
'olleh'
>>> a[-1:-6:-1]
'olleh'

This may help you visualize it:

    h  e  l  l  o
    0  1  2  3  4  5
-6 -5 -4 -3 -2 -1


问:
laravel 5.4 undefined variable in view
I'm kind of new to laravel and trying to pull data from a database but keep hitting an error page saying there's an undefined variable within the view.

I'm supposing there's something I'm doing wrong (or not doing) within the controller. So I have a create.blade.php that posts data from a form to the database and everything works fine, however I want it such that after posting to the database to redirect to the show.blade.php showing the uploaded data and here is where I hit a brick wall with the error messages.

This is my store function within the controller -

```<code>public function store(Request $request)
    {
     $data4page = new Data4page;

     $data4page->h1Ttle = $request->h1Ttle;
     $data4page->h4Ttle = $request->h4Ttle;
     $data4page->description = $request->description;
     $data4page->save();

     /*redirecting to the content's show page*/
     return redirect()->route('content.show', $data4page->id);
}
</code>```

And this is the show function within the same controller -

```<code>public function show($id)
    {
        //
        $data4page = Data4page::find($id);
        return view('digital.show')->with(compact('data4page'));
    }
</code>```

The error message I'm getting is -

```<code>Undefined variable: data4page (View: /var/www/html/theproject/resources/views/content/show.blade.php)
</code>```

And in the show.blade.php this is a sample of what I have -

```<code><h1>{{ $data4page->h4Ttle }}</h1>
<p>{{ $data4page->description }}</p>
<h4>{{ $data4page->h4Ttle }}</h4>
</code>```

Having said all that, I have also tried various means of returning the view within the show function of the controller but all these result in the same error message above. These variants include -

```<code>return view('content.show')->with('data4page', $data4page);
return view('content.show',['data4page'=>$data4page]);
</code>```

Update: I earlier had typos but now the error I get is -

```<code>undefined variable: {"id":9,"h1Ttle":"h1 sample text","h4Ttle":"h4 sample text","description":"body text goes here"} (View: /var/www/html/theproject/resources/views/content/show.blade.php)
</code>```

This is the show.blade.php -

```<code>@extends('main')
@section('title')
@section('content')
      <div class="app-template">
         <main class="wrapperMain">
            <div class="">
               <aside class="navSidebar">
                  <nav class="navProperty">
                     <h1 class="navProperty-title">{{ $data4page->h1Ttle }}</h1>
                  </nav>
                  <footer class="footerProperty">
                     <div class="upcomingSchedule">
                        <h4 class="upcomingSchedule-heading">{{ $data4page->h4Ttle }}</h4>
                     </div>
                  </footer>
               </aside>
            </div>
            <div class="content content--withSidebar">
               <div class="lead--Home">
                  <p>{{ $data4page->description }}</p>
               </div>
            </div>
         </main>
@endsection
</code>```

答:
Changed this

```<code>return view('content.show')->with(['name' => $data4page]);
</code>```

To:-

```<code>return view('content.show')->with(compact('data4page'));
</code>```

Hope it hepls!

Title: laravel 5.4 undefined variable in view

Body:
I'm kind of new to laravel and trying to pull data from a database but keep hitting an error page saying there's an undefined variable within the view.

I'm supposing there's something I'm doing wrong (or not doing) within the controller. So I have a create.blade.php that posts data from a form to the database and everything works fine, however I want it such that after posting to the database to redirect to the show.blade.php showing the uploaded data and here is where I hit a brick wall with the error messages.

This is my store function within the controller -

public function store(Request $request)
    {
     $data4page = new Data4page;

     $data4page->h1Ttle = $request->h1Ttle;
     $data4page->h4Ttle = $request->h4Ttle;
     $data4page->description = $request->description;
     $data4page->save();

     /*redirecting to the content's show page*/
     return redirect()->route('content.show', $data4page->id);
}

And this is the show function within the same controller -

public function show($id)
    {
        //
        $data4page = Data4page::find($id);
        return view('digital.show')->with(compact('data4page'));
    }

The error message I'm getting is -

Undefined variable: data4page (View: /var/www/html/theproject/resources/views/content/show.blade.php)

And in the show.blade.php this is a sample of what I have -

{{ $data4page->h4Ttle }}

{{ $data4page->description }}

{{ $data4page->h4Ttle }}

Having said all that, I have also tried various means of returning the view within the show function of the controller but all these result in the same error message above. These variants include -

return view('content.show')->with('data4page', $data4page);
return view('content.show',['data4page'=>$data4page]);

Update: I earlier had typos but now the error I get is -

undefined variable: {"id":9,"h1Ttle":"h1 sample text","h4Ttle":"h4 sample text","description":"body text goes here"} (View: /var/www/html/theproject/resources/views/content/show.blade.php)

This is the show.blade.php -

@extends('main')
@section('title')
@section('content')

{{ $data4page->h1Ttle }}

{{ $data4page->h4Ttle }}

{{ $data4page->description }}

@endsection

Body:
Changed this

return view('content.show')->with(['name' => $data4page]);

To:-

return view('content.show')->with(compact('data4page'));

Hope it hepls!


问:
First
 element in
 in same line
```<code><ul>
  <li>1</li>
  <ul>
    <li>a</li>
    <li>b</li>
    <li>c</li>
  </ul>
</ul>
</code>```

How would I display this list like so:

答:
.aligned-innerlist {
  margin-top: -17px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code>  <ul>
    <li>1
    <ul class="aligned-innerlist">
      <li>a</li>
      <li>b</li>
      <li>c</li>
    </ul>
    </li>
  </ul></code>```

Title: First <li> element in <ul> in same line

Body:
1

a

b

c

How would I display this list like so:

Body:
.aligned-innerlist {
  margin-top: -17px;
}

  <ul>
    <li>1
    <ul class="aligned-innerlist">
      <li>a</li>
      <li>b</li>
      <li>c</li>
    </ul>
    </li>
  </ul>


问:
Passing data via intent in android
I have 5 activities, say activity A,B,C,D and E.

Each activity has two buttons yes & no,buttons have the data which I want to pass to activity E only.

I need to do following things:

--> When user press yes/no button of A_activity, the user move to B_activity but data passed to activity E via intent.
Similarly at activity B user press yes/no button, user will move to activity C but data passed to activity E and so on.

I have done lot of search but couldn't find solution is there any way to do this.

答:
Use SharedPreferences class to pass the data:

```<code>SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("key", "Value");
editor.commit();
</code>```

Then in the Activity E:

```<code>SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
String value = sharedPref.getString("key", defaultValue);
</code>```

Hope this helps.

Title: Passing data via intent in android

Body:
Use SharedPreferences class to pass the data:

SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
SharedPreferences.Editor editor = sharedPref.edit();
editor.putString("key", "Value");
editor.commit();

Then in the Activity E:

SharedPreferences sharedPref = getActivity().getPreferences(Context.MODE_PRIVATE);
String value = sharedPref.getString("key", defaultValue);

Hope this helps.


问:
jQuery - Hide DIV which has a span element with certain text inside
I have several divs with the same class names and varying IDs. The ID is not set for the text I need to target

I need to target the Telephone Call text. If the div contains that text, how do I hide the containing div

```<code><div id="rn_FieldDisplay_155" class="rn_FieldDisplay rn_Output">
   <span class="rn_DataLabel">Telephone Call </span>
   <div class="rn_DataValue">No</div>
</div>
</code>```

I have tried the following to no avail

```<code><script>
$(document).ready(function() {
  $(".rn_FieldDisplay > span:contains('Telephone Call')").hide ();
});
</script>
</code>```

答:
Well you can try this:</p>

```<code>if ($(".rn_FieldDisplay > span:contains('Telephone Call')").length > 0) {
    $(".rn_FieldDisplay > span").hide();
}
</code>```

Body:
I have several divs with the same class names and varying IDs. The ID is not set for the text I need to target

I need to target the Telephone Call text. If the div contains that text, how do I hide the containing div

   Telephone Call

No

I have tried the following to no avail

Body:
Well you can try this:

if ($(".rn_FieldDisplay > span:contains('Telephone Call')").length > 0) {
    $(".rn_FieldDisplay > span").hide();
}


问:
Set text in the centre of AppBar
I this is my xml:

```<code><RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.design.widget.AppBarLayout
        android:id="@+id/appbar"
        android:layout_height="57dp"
        android:layout_width="match_parent">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:text="Ranger"
            android:id="@+id/logoSign"/>
    </android.support.design.widget.AppBarLayout>
</RelativeLayout>
</code>```

I want to do the TextView in the centre of the AppBar. But I get this:

Thanks for your help. :)

答:
Try this </p>

```<code><TextView
        android:layout_width="wrap_content"
        android:layout_height="match_content"
        android:layout_gravity="center_horizontal|center_vertical"
        android:text="Ranger"
        android:id="@+id/logoSign"/>
</code>```

Title: Set text in the centre of AppBar

Body:
I this is my xml:

<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.design.widget.AppBarLayout
        android:id="@+id/appbar"
        android:layout_height="57dp"
        android:layout_width="match_parent">

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_gravity="center"
            android:text="Ranger"
            android:id="@+id/logoSign"/>
    </android.support.design.widget.AppBarLayout>
</RelativeLayout>

I want to do the TextView in the centre of the AppBar. But I get this:

Thanks for your help. :)

Body:
Try this

<TextView
        android:layout_width="wrap_content"
        android:layout_height="match_content"
        android:layout_gravity="center_horizontal|center_vertical"
        android:text="Ranger"
        android:id="@+id/logoSign"/>


问:
Error not found: git when install npm package on windows
I'm trying to install this package through npm npm install bigwheel on windows using webstorm IDE.

I'm getting

"Error: not found: git" "This is most likely not a problme with npm itself. Please check if you have git installed and in yout Path"

I have https://git-for-windows.github.io/ installed, how do i check the path and fix this error?

答:
Please find at which location on your machine git is installed. e.g. C:\Program Files\Git\cmd and append this to your PATH variable in environment variables.

To append to path please follow below steps:

Right click on This PC or My Computer & select Properties

Select Advanced System Settings

Select Environment Variables

In System Variables locate PATH variable

Select Edit and append this path

Click OK & restart command prompt

Execute below command from new command prompt after appending this:

```<code>git --version
</code>```

It should display something like:

```<code>git version 2.9.0.windows.1
</code>```

After following these steps, try to install npm package and see whether the problem is resolved.

ContentLicense: CC BY-SA 4.0

Body:
Please find at which location on your machine git is installed. e.g. C:\Program Files\Git\cmd and append this to your PATH variable in environment variables.

To append to path please follow below steps:

Right click on This PC or My Computer & select Properties

Select Advanced System Settings

Select Environment Variables

In System Variables locate PATH variable

Select Edit and append this path

Click OK & restart command prompt

Execute below command from new command prompt after appending this:

git --version

It should display something like:

git version 2.9.0.windows.1

After following these steps, try to install npm package and see whether the problem is resolved.


问:
Getting -nil- values for ActiveRecord attributes in Rails database when parsing spreadsheet using roo-gem
So I am trying to build a feature within my application that will allow a User to upload a spreadsheet file filled with new products. I installed the Roo gem. I created a link for the User to download a templated Google Spreadsheet to use to upload Products to my app. For the purposes of testing this feature I am using this templated sheet to upload to my application.

The first row headers have the names of the attributes necessary to create a product in the database.

I am able to upload the file, however, no matter how many products are listed in the file it will only upload one product. Also, the product that is imported has -nil- values associated with the attributes from the file. I can verify this through the Rails Console.

For instance:
  name: nil, description: nil, etc.

This is the corresponding code in my Product.rb file:

```<code>def self.import(file)
    spreadsheet = open_spreadsheet(file)
    header = spreadsheet.row(1)
    (2..spreadsheet.last_row).each do |i|
      row = Hash[[header, spreadsheet.row(i)].transpose]
      product = find_by_id(row["id"]) || new
      product.attributes = row.to_hash.slice(*accessible_attributes)
      product.save!
    end
end

def self.accessible_attributes
   ['name', 'description', 'category', 'barcode', 'quantity',
   'capacity', 'threshold']
end

def self.open_spreadsheet(file)
  case File.extname(file.original_filename)
  when ".csv" then Roo::Csv.new(file.path, file_warning: :ignore)
  when ".xls" then Roo::Excel.new(file.path, file_warning: :ignore)
  when ".xlsx" then Roo::Excelx.new(file.path, file_warning: :ignore)
  else raise "Unknown file type: #{file.original_filename}"
  end
end
</code>```

This is how I have my route setup:

```<code>resources :products do
   collection { post :import }
end
</code>```

答:
Note: one spreadsheet has multiple sheets, so what you want to do is this</p>

```<code>spreadsheet = open_spreadsheet(file) # this return a spreadsheet
sheet1 = spreadsheet.sheet(0) # this will return the first sheet
puts spreadsheet.sheets # show all sheets
</code>```

Body:
So I am trying to build a feature within my application that will allow a User to upload a spreadsheet file filled with new products. I installed the Roo gem. I created a link for the User to download a templated Google Spreadsheet to use to upload Products to my app. For the purposes of testing this feature I am using this templated sheet to upload to my application.

The first row headers have the names of the attributes necessary to create a product in the database.

I am able to upload the file, however, no matter how many products are listed in the file it will only upload one product. Also, the product that is imported has -nil- values associated with the attributes from the file. I can verify this through the Rails Console.

For instance:
  name: nil, description: nil, etc.

This is the corresponding code in my Product.rb file:

def self.import(file)
    spreadsheet = open_spreadsheet(file)
    header = spreadsheet.row(1)
    (2..spreadsheet.last_row).each do |i|
      row = Hash[[header, spreadsheet.row(i)].transpose]
      product = find_by_id(row["id"]) || new
      product.attributes = row.to_hash.slice(*accessible_attributes)
      product.save!
    end
end

def self.accessible_attributes
   ['name', 'description', 'category', 'barcode', 'quantity',
   'capacity', 'threshold']
end

def self.open_spreadsheet(file)
  case File.extname(file.original_filename)
  when ".csv" then Roo::Csv.new(file.path, file_warning: :ignore)
  when ".xls" then Roo::Excel.new(file.path, file_warning: :ignore)
  when ".xlsx" then Roo::Excelx.new(file.path, file_warning: :ignore)
  else raise "Unknown file type: #{file.original_filename}"
  end
end

This is how I have my route setup:

resources :products do
   collection { post :import }
end

Body:
Note: one spreadsheet has multiple sheets, so what you want to do is this

spreadsheet = open_spreadsheet(file) # this return a spreadsheet
sheet1 = spreadsheet.sheet(0) # this will return the first sheet
puts spreadsheet.sheets # show all sheets


问:
Representing Complex objects in Entity Framework Core
For example, lets say I had this object that I wanted to put into a SQL database with EntityFramework:

```<code>public class Shift
{
    public Guid Id { get; set; }

    public Attendance Attendance { get; set; }
    public Managers Managers { get; set; }

    // other properties
}

public class Attendance
{
    public int AM { get; set; }
    public int MidDay { get; set; }
    public int PM { get; set; }
}

public class Managers
{
    public string AM { get; set; }
    public string MidDay { get; set; }
    public string PM { get; set; }
}
</code>```

Normally, I would figure this cannot be done, and I would just flatten everything into a simple collection of properties:

```<code>public class Shift
{
    public Guid Id { get; set; }

    public int Attendance_AM { get; set; }
    public int Attendance_MidDay { get; set; }
    public int Attendance_PM { get; set; }

    public string Managers_AM { get; set; }
    public string Managers_MidDay { get; set; }
    public string Managers_PM { get; set; }
}
</code>```

But is there a way to make EF store the complex object as a single table?

EDIT

This might help illustrate my question.

The goal is to have both code blocks above, work with the same Table in SQL:

答:
This feature will be available in Entity Framework Core 2.
Currently Entity Framework Core 2 is in Preview, but the feature is not complete in Preview 1, but can instead be used by using their nightly builds.

You can read about it here: https://blogs.msdn.microsoft.com/dotnet/2017/05/12/announcing-ef-core-2-0-preview-1/

(The feature is already available for "regular" Entity Framework)

Body:
For example, lets say I had this object that I wanted to put into a SQL database with EntityFramework:

public class Shift
{
    public Guid Id { get; set; }

    public Attendance Attendance { get; set; }
    public Managers Managers { get; set; }

    // other properties
}

public class Attendance
{
    public int AM { get; set; }
    public int MidDay { get; set; }
    public int PM { get; set; }
}

public class Managers
{
    public string AM { get; set; }
    public string MidDay { get; set; }
    public string PM { get; set; }
}

Normally, I would figure this cannot be done, and I would just flatten everything into a simple collection of properties:

public class Shift
{
    public Guid Id { get; set; }

    public int Attendance_AM { get; set; }
    public int Attendance_MidDay { get; set; }
    public int Attendance_PM { get; set; }

    public string Managers_AM { get; set; }
    public string Managers_MidDay { get; set; }
    public string Managers_PM { get; set; }
}

But is there a way to make EF store the complex object as a single table?

EDIT

This might help illustrate my question.

The goal is to have both code blocks above, work with the same Table in SQL:


答:
AppBar is actually a Linearlayout.
Try this:

```<code>   <TextView
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="center"
        android:gravity="center"
        android:text="Ranger"
        android:id="@+id/logoSign"/>
</code>```

Title: Set text in the centre of AppBar

Body:
AppBar is actually a Linearlayout.
Try this:

   <TextView
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="center"
        android:gravity="center"
        android:text="Ranger"
        android:id="@+id/logoSign"/>


问:
Recovering presenters for the ViewPager fragments (MVP)
I'm trying to refactor an existing application to use the MVP architecture. One of the activities has a ViewPager with three fragments. Each fragment is linked with a presenter. To be precise - each presenter, when created, is given a View to work with, i.e. a Fragment. For now, I'm creating these presenters inside the ViewPager's adapter - specifically in the getItem(int position) method.

```<code>Fragment fragment = FirstFragment.newInstance();
FirstPresenter presenter = new FirstPresenter(repo, (FirstContract.View) fragment, projectId, userId);
</code>```

The problem I'm facing is if the process is killed and then restarted, ViewPager has its own lifecycle and therefore getItem is not called again - the fragments are recreated automagically with no presenters.

Is there a known solution to this problem?

答:
The suggested answer didn't work for me since mFragmentManager is a private member of FragmentStatePagerAdapter. No idea how it worked for vkislicins. Instead, I just called got the parent class to do restoreState then grabbed the fragments with 'instantiateItem'. For example:

```<code>@Override
public void restoreState(Parcelable state, ClassLoader loader) {
    // this will load all the fragments again
    super.restoreState(state, loader);

    // since the fragments are now loaded, instantiate can be used because it just returns them
    MyFragmentClass tab1 = (MyFragmentClass) instantiateItem(null, 0);
    tab1Presenter.setView(tab1);
    tab1.setPresenter(tab1Presenter);

    // then just do the same for the other fragments
    ...
}
</code>```

Feels a bit hacky, but it works.

Body:
I'm trying to refactor an existing application to use the MVP architecture. One of the activities has a ViewPager with three fragments. Each fragment is linked with a presenter. To be precise - each presenter, when created, is given a View to work with, i.e. a Fragment. For now, I'm creating these presenters inside the ViewPager's adapter - specifically in the getItem(int position) method.

Fragment fragment = FirstFragment.newInstance();
FirstPresenter presenter = new FirstPresenter(repo, (FirstContract.View) fragment, projectId, userId);

The problem I'm facing is if the process is killed and then restarted, ViewPager has its own lifecycle and therefore getItem is not called again - the fragments are recreated automagically with no presenters.

Is there a known solution to this problem?

Body:
The suggested answer didn't work for me since mFragmentManager is a private member of FragmentStatePagerAdapter. No idea how it worked for vkislicins. Instead, I just called got the parent class to do restoreState then grabbed the fragments with 'instantiateItem'. For example:

@Override
public void restoreState(Parcelable state, ClassLoader loader) {
    // this will load all the fragments again
    super.restoreState(state, loader);

    // since the fragments are now loaded, instantiate can be used because it just returns them
    MyFragmentClass tab1 = (MyFragmentClass) instantiateItem(null, 0);
    tab1Presenter.setView(tab1);
    tab1.setPresenter(tab1Presenter);

    // then just do the same for the other fragments
    ...
}

Feels a bit hacky, but it works.


问:
Focus abstraction
UserControl with buttons (some of them are disabled) is nested inside other UserControl. There are several of such displayed in the window at once.

Now I need to set focus to first enabled button of nested UserControl, while the logic to choose focus will run on the level of window (e.g. when window will enable certain UserControl).

I need to be able to pass that focus request (via properties?) through several ViewModels and finally trigger it in the View of nested UserControl.

Ho can I abstract focus request? E.g. I want to be able to tell "set focus to this high level UserControl" and that should somehow automatically go through nested UserControl and its buttons, because only button is the element what can receive focus.

Pseudo-code:

```<code>// in window
UserControlA.Focus();

// should in fact set focus to 4th button of nested user control
UserControlA.UserControlB.ButtonD.Focus();

// because of data templates it is actually more like this
var nested = UserControlA.ContentControl.Content as UserControlB;
var firstEnabledButton = nested.ItemsControl[3] as Button;
firstEnabledButton.SetFocus();

// and because of MVVM it may be as simple as
ViewModelA.IsFocused = true;
// but then A should run
ViewModelB.IsFocused = true;
// and then B should set property of button ViewModel
Buttons.First(o => o.IsEnabled).IsFocused = true.
// and then this has to be somehow used by the view (UserControlB) to set focus...
</code>```

Problem is not with how to set focus in MVVM, this can be done somehow (with triggers it needs ugly workaround where property is first set to false). My problem is how to pass that request ("and then ..., and then ..., and then..." in example above).

Any ideas?

I am looking for a simple and intuitive xaml solution with the most reusability. I don't want to spam every ViewModel and views with ...IsFocused properties and bindings.

I can use some side effect to my advantage, e.g. consider this behavior

```<code>public static bool GetFocusWhenEnabled(DependencyObject obj) => (bool)obj.GetValue(FocusWhenEnabledProperty);
public static void SetFocusWhenEnabled(DependencyObject obj, bool value) => obj.SetValue(FocusWhenEnabledProperty, value);

public static readonly DependencyProperty FocusWhenEnabledProperty =
    DependencyProperty.RegisterAttached("FocusWhenEnabled", typeof(bool), typeof(FocusBehavior), new PropertyMetadata(false, (d, e) =>
    {
        var element = d as UIElement;
        if (element == null)
            throw new ArgumentException("Only used with UIElement");
        if ((bool)e.NewValue)
            element.IsEnabledChanged += FocusWhenEnabled_IsEnabledChanged;
        else
            element.IsEnabledChanged -= FocusWhenEnabled_IsEnabledChanged;
    }));

static void FocusWhenEnabled_IsEnabledChanged(object sender, DependencyPropertyChangedEventArgs e)
{
    var element = (UIElement)sender;
    if (element.IsEnabled)
        element.Dispatcher.InvokeAsync(() => element.Focus()); // invoke is a must
}
</code>```

which can be used to automatically focus enabled element. This require some IsEnabled logic in addition and will easily stop working in some complicated scenarios (where enabling should not cause the focusing).

I am thinking if I can add some attached property to pass focus requests all the way through xaml (using only xaml) when attempting to set focus to container, which is not focusable.

答:
I think you should consider using the FrameworkElement.MoveFocus method together with FocusNavigationDirection.Next - this should in general give you the expected result, i.e. give focus to the first encountered control which can receive keyboard focus. In particular that means that non-focusable controls, disabled controls, and controls that cannot receive keyboard focus (such as ItemsControl, UserControl etc.) will be omitted. The only catch here is that the controls will be traversed in tab order, but unless you're messing around with that it should traverse the visual tree in depth-first pre-order manner. So this code:

```<code>UserControlA.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));
</code>```

should give focus to UserControlA.UserControlB.ButtonD if it is the first keyboard-focusable and enabled descendant of UserControlA.

In terms of dismissing the necessity to use code-behind what I'd do is the following. First of all I'd drop using view-model properties to control focus. Moving focus seems to me a lot more like request-based concept rather than state-based, so I'd use events (e.g. FocusRequested) instead. To make it reusable I'd create a one-event interface (e.g. IRequestFocus). The final touch would be to create a behavior that would automatically inspect if DataContext of the attached object implements IRequestFocus and call MoveFocus each time the FocusRequested event is raised.

With such setup all you'd need to do is to implement IRequestFocus in ViewModelA, and attach the behavior to UserControlA. Then simply raising the FocusRequested in ViewModelA would result in moving focus to UserControlA.UserControlB.ButtonD.

Title: Focus abstraction

Body:
UserControl with buttons (some of them are disabled) is nested inside other UserControl. There are several of such displayed in the window at once.

Now I need to set focus to first enabled button of nested UserControl, while the logic to choose focus will run on the level of window (e.g. when window will enable certain UserControl).

I need to be able to pass that focus request (via properties?) through several ViewModels and finally trigger it in the View of nested UserControl.

Ho can I abstract focus request? E.g. I want to be able to tell "set focus to this high level UserControl" and that should somehow automatically go through nested UserControl and its buttons, because only button is the element what can receive focus.

Pseudo-code:

// in window
UserControlA.Focus();

// should in fact set focus to 4th button of nested user control
UserControlA.UserControlB.ButtonD.Focus();

// because of data templates it is actually more like this
var nested = UserControlA.ContentControl.Content as UserControlB;
var firstEnabledButton = nested.ItemsControl[3] as Button;
firstEnabledButton.SetFocus();

// and because of MVVM it may be as simple as
ViewModelA.IsFocused = true;
// but then A should run
ViewModelB.IsFocused = true;
// and then B should set property of button ViewModel
Buttons.First(o => o.IsEnabled).IsFocused = true.
// and then this has to be somehow used by the view (UserControlB) to set focus...

Problem is not with how to set focus in MVVM, this can be done somehow (with triggers it needs ugly workaround where property is first set to false). My problem is how to pass that request ("and then ..., and then ..., and then..." in example above).

Any ideas?

I am looking for a simple and intuitive xaml solution with the most reusability. I don't want to spam every ViewModel and views with ...IsFocused properties and bindings.

I can use some side effect to my advantage, e.g. consider this behavior

public static bool GetFocusWhenEnabled(DependencyObject obj) => (bool)obj.GetValue(FocusWhenEnabledProperty);
public static void SetFocusWhenEnabled(DependencyObject obj, bool value) => obj.SetValue(FocusWhenEnabledProperty, value);

public static readonly DependencyProperty FocusWhenEnabledProperty =
    DependencyProperty.RegisterAttached("FocusWhenEnabled", typeof(bool), typeof(FocusBehavior), new PropertyMetadata(false, (d, e) =>
    {
        var element = d as UIElement;
        if (element == null)
            throw new ArgumentException("Only used with UIElement");
        if ((bool)e.NewValue)
            element.IsEnabledChanged += FocusWhenEnabled_IsEnabledChanged;
        else
            element.IsEnabledChanged -= FocusWhenEnabled_IsEnabledChanged;
    }));

static void FocusWhenEnabled_IsEnabledChanged(object sender, DependencyPropertyChangedEventArgs e)
{
    var element = (UIElement)sender;
    if (element.IsEnabled)
        element.Dispatcher.InvokeAsync(() => element.Focus()); // invoke is a must
}

which can be used to automatically focus enabled element. This require some IsEnabled logic in addition and will easily stop working in some complicated scenarios (where enabling should not cause the focusing).

I am thinking if I can add some attached property to pass focus requests all the way through xaml (using only xaml) when attempting to set focus to container, which is not focusable.

Body:
I think you should consider using the FrameworkElement.MoveFocus method together with FocusNavigationDirection.Next - this should in general give you the expected result, i.e. give focus to the first encountered control which can receive keyboard focus. In particular that means that non-focusable controls, disabled controls, and controls that cannot receive keyboard focus (such as ItemsControl, UserControl etc.) will be omitted. The only catch here is that the controls will be traversed in tab order, but unless you're messing around with that it should traverse the visual tree in depth-first pre-order manner. So this code:

UserControlA.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));

should give focus to UserControlA.UserControlB.ButtonD if it is the first keyboard-focusable and enabled descendant of UserControlA.

In terms of dismissing the necessity to use code-behind what I'd do is the following. First of all I'd drop using view-model properties to control focus. Moving focus seems to me a lot more like request-based concept rather than state-based, so I'd use events (e.g. FocusRequested) instead. To make it reusable I'd create a one-event interface (e.g. IRequestFocus). The final touch would be to create a behavior that would automatically inspect if DataContext of the attached object implements IRequestFocus and call MoveFocus each time the FocusRequested event is raised.

With such setup all you'd need to do is to implement IRequestFocus in ViewModelA, and attach the behavior to UserControlA. Then simply raising the FocusRequested in ViewModelA would result in moving focus to UserControlA.UserControlB.ButtonD.


问:
Set Variable Varchar2 to date fields
I have a Script that I update a Date field

this is a part of my script

```<code>    var VARCHAR2(8 char);

var = '01/01/22';
    update table1 t set t.date = to_date(var,'dd/mm/yy');
</code>```

and then I got a null value in field date

why I dont have a 01/01/22 value ??

could you help me please !!

ANSWER       :::::::::::     PETIT PAPA merci :D

I created I new Varible with Date type

and I affecte the to_date to this variable

```<code>date_var Date;

date_var :=to_date(var,'dd/mm/yy');

update table1 t set t.date = date_var where ...;
</code>```

and it work THANK YOU everyONE

答:
try this:

```<code>var := '01/01/22';
    update table1 t set t.date = to_date(var,'dd/mm/yy');

commit;
</code>```

Title: Set Variable Varchar2 to date fields

Body:
I have a Script that I update a Date field

this is a part of my script

    var VARCHAR2(8 char);

var = '01/01/22';
    update table1 t set t.date = to_date(var,'dd/mm/yy');

and then I got a null value in field date

why I dont have a 01/01/22 value ??

could you help me please !!

ANSWER       :::::::::::     PETIT PAPA merci :D

I created I new Varible with Date type

and I affecte the to_date to this variable

date_var Date;

date_var :=to_date(var,'dd/mm/yy');

update table1 t set t.date = date_var where ...;

and it work THANK YOU everyONE

Body:
try this:

var := '01/01/22';
    update table1 t set t.date = to_date(var,'dd/mm/yy');

commit;


问:
Return job titles from Get-ADUser that match csv
I want to import job titles from a csv file into Powershell then use the Get-ADUser to return all active users with those titles and then export to a new csv

Can someone please help?

```<code>$csvjobtitle = Import-Csv -Header csvTitle -Path c:\Job_titles.csv

Get-ADUser -Filter {enabled -eq "true" -and Title -eq "$csvjobtitle"} -
Properties SamAccountName, GivenName, Surname, EmailAddress, Title | select
SamAccountName, GivenName, Surname, EmailAddress, Title | Export-CSV "C:\Ad
Extract.csv"
</code>```

答:
Here's one possible solution:

```<code>$csvjobtitle = (Import-Csv -Header csvTitle -Path c:\Job_titles.csv).'csvTitle'

$csvjobtitle | ForEach-Object {
    Get-ADUser -Filter {enabled -eq "true" -and Title -eq "$_"} -Properties SamAccountName, GivenName, Surname, EmailAddress, Title | Select SamAccountName, GivenName, Surname, EmailAddress, Title
} | Export-CSV "C:\Ad Extract.csv"
</code>```

There are two changes to your previous code:

We get back just the 'csvTitle' values from the CSV, rather than an object which has a csvTitle property.

We loop through those values with a ForEach-Object loop which gets the AD user for each title (where the current title is represented via $_).

Because ForEach-Object supports the pipeline (and our Get-ADUser cmdlet returns its result to the pipeline), we can simply pipe the results of the ForEach-Object to Export-CSV.

Body:
I want to import job titles from a csv file into Powershell then use the Get-ADUser to return all active users with those titles and then export to a new csv

Can someone please help?

$csvjobtitle = Import-Csv -Header csvTitle -Path c:\Job_titles.csv

Get-ADUser -Filter {enabled -eq "true" -and Title -eq "$csvjobtitle"} -
Properties SamAccountName, GivenName, Surname, EmailAddress, Title | select
SamAccountName, GivenName, Surname, EmailAddress, Title | Export-CSV "C:\Ad
Extract.csv"

Body:
Here's one possible solution:

$csvjobtitle = (Import-Csv -Header csvTitle -Path c:\Job_titles.csv).'csvTitle'

$csvjobtitle | ForEach-Object {
    Get-ADUser -Filter {enabled -eq "true" -and Title -eq "$_"} -Properties SamAccountName, GivenName, Surname, EmailAddress, Title | Select SamAccountName, GivenName, Surname, EmailAddress, Title
} | Export-CSV "C:\Ad Extract.csv"

There are two changes to your previous code:

We get back just the 'csvTitle' values from the CSV, rather than an object which has a csvTitle property.

We loop through those values with a ForEach-Object loop which gets the AD user for each title (where the current title is represented via $_).

Because ForEach-Object supports the pipeline (and our Get-ADUser cmdlet returns its result to the pipeline), we can simply pipe the results of the ForEach-Object to Export-CSV.


问:
mvvm light - messaging
I'm curently teaching myself the MVVM pattern.
I've hit my first snag with the concept of messaging.
I know messaging is contained in the mvvm-light toolkit. But I cannot find an example of usage anywhere (no sample projects are provided in the download).

If anyone can direct me to some information as to how to use messaging in that toolkit, that would be ace.

Thanks

答:
http://blog.galasoft.ch/archive/2009/09/27/mvvm-light-toolkit-messenger-v2-beta.aspx

Here abit about it.

/Bo

ContentLicense: CC BY-SA 2.5

Title: mvvm light - messaging


问:
MSKLC under Windows 10: Create custom keyboard layout which supports IME (input method) for Chinese and combined input in Spanish
This question is originally posted by me in Microsoft Community at:

https://answers.microsoft.com/en-us/windows/forum/windows_10-other_settings/msklc-under-windows-10-create-custom-keyboard/8c5a7137-d575-4247-8ab3-b4dd1e5fb437?tm=1495318604424

In summary: I have created a custom keyboard layout with Microsoft Keyboard Layout Creator 1.4 in Windows 10, it is working but only partially. It cannot:

combine two keystrokes into one to type a "combined letter", e.g, "¨"+"u" = "ü". It should not exist in Chinese but I want to achieve this.

type Chinese pinyin and Chinese punctuation. In MS pinyin IME, I can press shift to switch between Chinese pinyin mode and English mode. Under pinyin mode I can convert letters into pinyin and thus get Chinese characters, but my layout lacks this. And, if I press "," in Microsoft Pinyin in pinyin mode, it should give me "，"(full length comma), but this layout is not able to do this.

I am thinking about two ways to solve this:

Substitute Microsoft Pinyin's keyboard layout to my layout(replace the English part of MS Pinyin with my layout)

Copy the pinyin part of MS pinyin to my layout.

So, how can I solve this?

答:
I have solved it.

For the first problem, you must define some "dead keys combinations". The details are explained here:

http://www.angelfire.com/planet/linguisticsisfun/Creating_a_Keyboard_Using_MSKLC.pdf

For the second problem, basically you do:

Create your keyboard layout.

Edit the .klc file with a Text Editor, to change the VK code mapping. That is because most of the applications in Microsoft Windows, when you press the hotkeys, detects VK code sent to OS, not the "key chars"(the characters output as you type in a text processing software). So in order to make the key chars of your keyboard layout to match with their VK code, you must do this manually. MSKLC will not change that for you. Some details here:

http://www.sensefulsolutions.com/2010/08/how-to-fix-keyboard-shortcuts-in-klc-eg.html

Install the layout.

Open your registry editor, enter HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Keyboard Layouts\, find your new keyboard layout at the bottom (mine with name like a0000xxxx). Copy the dll file name. That is the DLL file containing your newly created keyboard layout info.

Go back to the registry father branch, search the language you want to apply this layout, like Chinese or Spanish. You will find several variations with names alike, but the descriptions are self-explanatory and can help you differentiate them.

Simplified Chinese uses KBDUS.dll, that means "keyboard layout for US keyboard". This will apply to MS Pinyin, too. Change this value to your copied DLL name, so that it will load your DLL next time the OS launches.

Restart.

The result:

I can type English and Chinese pinyin with Microsoft Pinyin with my custom keyboard layout, and I can navigate next/previous page with , and ..

With this keyboard layout I can type Spanish special characters, like ï, á, ç, ñ and € without switching to Spanish keyboard.

Hotkeys in any software are working as expected, because now VK code are matched with letters printed on the keys.


答:
just use this code for textview</p>

```<code><TextView
        android:layout_width="match_content"
        android:layout_height="match_content"
        android:layout_gravity="center"
        android:gravity="center"
        android:text="Ranger"
        android:id="@+id/logoSign"/>
</code>```

Title: Set text in the centre of AppBar

Body:
just use this code for textview

<TextView
        android:layout_width="match_content"
        android:layout_height="match_content"
        android:layout_gravity="center"
        android:gravity="center"
        android:text="Ranger"
        android:id="@+id/logoSign"/>


问:
About the screen on in android application
I have an Android application and I want to keep the screen on. But sometimes I don't want to keep the screen on. What can I do to that?

EDIT: I have already used this code to set my screen on:

```<code>getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
</code>```

答:
Find the root layout of the activity. for example if the root layout is a LinearLayout

```<code>@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_xml);
    LinearLayout root = (LinearLayout) findViewById(R.id.root_container):

    // and according to your preference you can set
    root.setKeepScreenOn(true/false);
</code>```

offical doc says

```<code> /**
 * Controls whether the screen should remain on, modifying the
 * value of {@link #KEEP_SCREEN_ON}.
 *
 * @param keepScreenOn Supply true to set {@link #KEEP_SCREEN_ON}.
 *
 * @see #getKeepScreenOn()

 */
</code>```

For more reference please follow this link

Body:
I have an Android application and I want to keep the screen on. But sometimes I don't want to keep the screen on. What can I do to that?

EDIT: I have already used this code to set my screen on:

getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

Body:
Find the root layout of the activity. for example if the root layout is a LinearLayout

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_xml);
    LinearLayout root = (LinearLayout) findViewById(R.id.root_container):

    // and according to your preference you can set
    root.setKeepScreenOn(true/false);

offical doc says

 /**
 * Controls whether the screen should remain on, modifying the
 * value of {@link #KEEP_SCREEN_ON}.
 *
 * @param keepScreenOn Supply true to set {@link #KEEP_SCREEN_ON}.
 *
 * @see #getKeepScreenOn()

 */

For more reference please follow this link


问:
getting null pass String from fragment to the activiy using bundle
Well this will sound silly but I am using bundle to store my Data within, and trying to pass this bundle from the fragment to the hosting activity, and testing the data using a toast, but the toast is empty! I cant find the reason why this is happening since i made sure to fill the data correctly
My code in the fragment is:

```<code> @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.fragment_parent_register, container, false);
        return rootView;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        setUpViews();
        setRecyclerAdapter();
    }

    private void setUpViews() {
        fullNameEditText = (EditText) rootView.findViewById(R.id.fragment_parent_register_fullName);
        emailEditText = (EditText) rootView.findViewById(R.id.fragment_parent_register_email);
        passwordEditText = (EditText) rootView.findViewById(R.id.fragment_parent_register_password);
        fullName = fullNameEditText.getText().toString();
        email= emailEditText.getText().toString();
        password = passwordEditText.getText().toString();
        Bundle parentData = new Bundle();
        parentData.putString(KEY_PARENT_FULL_NAME,fullName);
        parentData.putString(KEY_PARENT_EMAIL,email);
        parentData.putString(KEY_PARENT_PASSWORD,password);

        Intent intent = getActivity().getIntent();
        intent.putExtras(parentData);
</code>```

in the activity is :

```<code>  registerButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (DataHolder.getInstance().getAccountType() == 0) {
                    Intent intent = new Intent(RegisterActivity.this, TeacherLocationActivity.class);
                    startActivity(intent);
                } else {
                /*    Intent intent = new Intent(RegisterActivity.this, StudentLocationActivity.class);
                    startActivity(intent);*/
                    Bundle parentData = getIntent().getExtras();
                    if (parentData != null)
                    {
                        Toast.makeText(RegisterActivity.this, parentData.getString(KEY_PARENT_FULL_NAME)+parentData.getString(KEY_PARENT_EMAIL)+parentData.getString(KEY_PARENT_PASSWORD), Toast.LENGTH_SHORT).show();
                    }
                    else if (parentData == null)
                    {
                        Toast.makeText(RegisterActivity.this, "Bundle is empty", Toast.LENGTH_SHORT).show();                    }
                }
            }
        });
</code>```

答:
Try this for send data from Fragment:-

```<code>Intent intent=new Intent(getContext(),YourActivityName.class);
            intent.putExtra(KEY_PARENT_FULL_NAME,fullName);
            intent.putExtra(KEY_PARENT_EMAIL,email);
            intent.putExtra(KEY_PARENT_PASSWORD,password);
</code>```

try this for getting data in Activity:-

```<code>String data=this.getIntent().getStringextra(KEY_PARENT_FULL_NAME);
</code>```

Body:
Well this will sound silly but I am using bundle to store my Data within, and trying to pass this bundle from the fragment to the hosting activity, and testing the data using a toast, but the toast is empty! I cant find the reason why this is happening since i made sure to fill the data correctly
My code in the fragment is:

 @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.fragment_parent_register, container, false);
        return rootView;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        setUpViews();
        setRecyclerAdapter();
    }

    private void setUpViews() {
        fullNameEditText = (EditText) rootView.findViewById(R.id.fragment_parent_register_fullName);
        emailEditText = (EditText) rootView.findViewById(R.id.fragment_parent_register_email);
        passwordEditText = (EditText) rootView.findViewById(R.id.fragment_parent_register_password);
        fullName = fullNameEditText.getText().toString();
        email= emailEditText.getText().toString();
        password = passwordEditText.getText().toString();
        Bundle parentData = new Bundle();
        parentData.putString(KEY_PARENT_FULL_NAME,fullName);
        parentData.putString(KEY_PARENT_EMAIL,email);
        parentData.putString(KEY_PARENT_PASSWORD,password);

        Intent intent = getActivity().getIntent();
        intent.putExtras(parentData);

in the activity is :

  registerButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (DataHolder.getInstance().getAccountType() == 0) {
                    Intent intent = new Intent(RegisterActivity.this, TeacherLocationActivity.class);
                    startActivity(intent);
                } else {
                /*    Intent intent = new Intent(RegisterActivity.this, StudentLocationActivity.class);
                    startActivity(intent);*/
                    Bundle parentData = getIntent().getExtras();
                    if (parentData != null)
                    {
                        Toast.makeText(RegisterActivity.this, parentData.getString(KEY_PARENT_FULL_NAME)+parentData.getString(KEY_PARENT_EMAIL)+parentData.getString(KEY_PARENT_PASSWORD), Toast.LENGTH_SHORT).show();
                    }
                    else if (parentData == null)
                    {
                        Toast.makeText(RegisterActivity.this, "Bundle is empty", Toast.LENGTH_SHORT).show();                    }
                }
            }
        });

Body:
Try this for send data from Fragment:-

Intent intent=new Intent(getContext(),YourActivityName.class);
            intent.putExtra(KEY_PARENT_FULL_NAME,fullName);
            intent.putExtra(KEY_PARENT_EMAIL,email);
            intent.putExtra(KEY_PARENT_PASSWORD,password);

try this for getting data in Activity:-

String data=this.getIntent().getStringextra(KEY_PARENT_FULL_NAME);


问:
Wordpress uploads limited to logged in users
Im using a Gist from Github to limit only logged in users to visit images present in the WP-Content / Uploads folder. Now the script works for the login required part, but when logged in the returned image is invalid.
When i inspect the returned image, im seeing a filesize thats ok, good content headers. But its still a corrupt file.

```<code>https://gist.github.com/hakre/1552239
</code>```

Using latest WP version.

Anyone knows where i should look into this script?

```<code><?php
/*
 * dl-file.php
 *
 * Protect uploaded files with login.
 *
 * @link http://wordpress.stackexchange.com/questions/37144/protect-        wordpress-uploads-if-user-is-not-logged-in
 *
 * @author hakre <http://hakre.wordpress.com/>
 * @license GPL-3.0+
 * @registry SPDX
 */
ob_start();
require_once('wp-load.php');
require_once ABSPATH . WPINC . '/formatting.php';
require_once ABSPATH . WPINC . '/capabilities.php';
require_once ABSPATH . WPINC . '/user.php';
require_once ABSPATH . WPINC . '/meta.php';
require_once ABSPATH . WPINC . '/post.php';
require_once ABSPATH . WPINC . '/pluggable.php';
wp_cookie_constants();
ob_end_clean();
ob_end_flush();

is_user_logged_in() ||  auth_redirect();

list($basedir) = array_values(array_intersect_key(wp_upload_dir(),                 array('basedir' => 1)))+array(NULL);

$file =  rtrim($basedir,'/').'/'.str_replace('..', '', isset($_GET[ 'file'     ])? ''.$_GET[ 'file' ]:'');

if (!$basedir || !is_file($file)) {
status_header(404);
wp_redirect(home_url());
exit();
}

$mime = wp_check_filetype($file);
if( false === $mime[ 'type' ] && function_exists( 'mime_content_type' ) )
$mime[ 'type' ] = mime_content_type( $file );

if( $mime[ 'type' ] )
$mimetype = $mime[ 'type' ];
else
$mimetype = 'image/' . substr( $file, strrpos( $file, '.' ) + 1 );

header( 'Content-Type: ' . $mimetype ); // always send this
if ( false === strpos( $_SERVER['SERVER_SOFTWARE'], 'Microsoft-IIS' ) )
header( 'Content-Length: ' . filesize( $file ) );

$last_modified = gmdate( 'D, d M Y H:i:s', filemtime( $file ) );
$etag = '"' . md5( $last_modified ) . '"';
header( "Last-Modified: $last_modified GMT" );
header( 'ETag: ' . $etag );
header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', time() + 100000000 ) . ' GMT' );

// Support for Conditional GET
$client_etag = isset( $_SERVER['HTTP_IF_NONE_MATCH'] ) ? stripslashes(         $_SERVER['HTTP_IF_NONE_MATCH'] ) : false;

if( ! isset( $_SERVER['HTTP_IF_MODIFIED_SINCE'] ) )
$_SERVER['HTTP_IF_MODIFIED_SINCE'] = false;

$client_last_modified = trim( $_SERVER['HTTP_IF_MODIFIED_SINCE'] );
// If string is empty, return 0. If not, attempt to parse into a timestamp
$client_modified_timestamp = $client_last_modified ? strtotime(     $client_last_modified ) : 0;

// Make a timestamp for our most recent modification...
$modified_timestamp = strtotime($last_modified);

if ( ( $client_last_modified && $client_etag )
? ( ( $client_modified_timestamp >= $modified_timestamp) && ( $client_etag == $etag ) )
: ( ( $client_modified_timestamp >= $modified_timestamp) || ( $client_etag == $etag ) )
) {
status_header( 304 );
exit;
}

 // If we made it this far, just serve the file
 readfile( $file );
</code>```

答:
Fixed by modifying the ReadFile to return a clean output of the file only:</p>

```<code>while (ob_get_level()) {
ob_end_clean();
}
readfile($file);
exit();
</code>```

Body:
Im using a Gist from Github to limit only logged in users to visit images present in the WP-Content / Uploads folder. Now the script works for the login required part, but when logged in the returned image is invalid.
When i inspect the returned image, im seeing a filesize thats ok, good content headers. But its still a corrupt file.

https://gist.github.com/hakre/1552239

Using latest WP version.

Anyone knows where i should look into this script?

<?php
/*
 * dl-file.php
 *
 * Protect uploaded files with login.
 *
 * @link http://wordpress.stackexchange.com/questions/37144/protect-        wordpress-uploads-if-user-is-not-logged-in
 *
 * @author hakre <http://hakre.wordpress.com/>
 * @license GPL-3.0+
 * @registry SPDX
 */
ob_start();
require_once('wp-load.php');
require_once ABSPATH . WPINC . '/formatting.php';
require_once ABSPATH . WPINC . '/capabilities.php';
require_once ABSPATH . WPINC . '/user.php';
require_once ABSPATH . WPINC . '/meta.php';
require_once ABSPATH . WPINC . '/post.php';
require_once ABSPATH . WPINC . '/pluggable.php';
wp_cookie_constants();
ob_end_clean();
ob_end_flush();

is_user_logged_in() ||  auth_redirect();

list($basedir) = array_values(array_intersect_key(wp_upload_dir(),                 array('basedir' => 1)))+array(NULL);

$file =  rtrim($basedir,'/').'/'.str_replace('..', '', isset($_GET[ 'file'     ])? ''.$_GET[ 'file' ]:'');

if (!$basedir || !is_file($file)) {
status_header(404);
wp_redirect(home_url());
exit();
}

$mime = wp_check_filetype($file);
if( false === $mime[ 'type' ] && function_exists( 'mime_content_type' ) )
$mime[ 'type' ] = mime_content_type( $file );

if( $mime[ 'type' ] )
$mimetype = $mime[ 'type' ];
else
$mimetype = 'image/' . substr( $file, strrpos( $file, '.' ) + 1 );

header( 'Content-Type: ' . $mimetype ); // always send this
if ( false === strpos( $_SERVER['SERVER_SOFTWARE'], 'Microsoft-IIS' ) )
header( 'Content-Length: ' . filesize( $file ) );

$last_modified = gmdate( 'D, d M Y H:i:s', filemtime( $file ) );
$etag = '"' . md5( $last_modified ) . '"';
header( "Last-Modified: $last_modified GMT" );
header( 'ETag: ' . $etag );
header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', time() + 100000000 ) . ' GMT' );

// Support for Conditional GET
$client_etag = isset( $_SERVER['HTTP_IF_NONE_MATCH'] ) ? stripslashes(         $_SERVER['HTTP_IF_NONE_MATCH'] ) : false;

if( ! isset( $_SERVER['HTTP_IF_MODIFIED_SINCE'] ) )
$_SERVER['HTTP_IF_MODIFIED_SINCE'] = false;

$client_last_modified = trim( $_SERVER['HTTP_IF_MODIFIED_SINCE'] );
// If string is empty, return 0. If not, attempt to parse into a timestamp
$client_modified_timestamp = $client_last_modified ? strtotime(     $client_last_modified ) : 0;

// Make a timestamp for our most recent modification...
$modified_timestamp = strtotime($last_modified);

if ( ( $client_last_modified && $client_etag )
? ( ( $client_modified_timestamp >= $modified_timestamp) && ( $client_etag == $etag ) )
: ( ( $client_modified_timestamp >= $modified_timestamp) || ( $client_etag == $etag ) )
) {
status_header( 304 );
exit;
}

 // If we made it this far, just serve the file
 readfile( $file );

Body:
Fixed by modifying the ReadFile to return a clean output of the file only:

while (ob_get_level()) {
ob_end_clean();
}
readfile($file);
exit();


问:
How to convert hexadecimal in python?
I have file which contains in each line some hexadecimal numbers. For example:

```<code>5B35E8DF4A709CA16A1C8BC29022E83C
28958FA134D53BE6F382D04DC9891922
C67FC50F905F043EBEFEBFAF243B8744
99DCD61A89EE5553DDCA44378C3CE3C6
...........
</code>```

I want to  convert them from uppercase to lowercase. For example:

```<code>5b35e8df4a709ca16a1c8bc29022e83c

Srcpath  ='Uppercase_File'
Destpath ='Lowercase_File'
with open(Srcpath, 'r') as f:
    with open(Destpath, 'w') as fp:
        for key in f:
            print(key)
            #key_Separated=[key[i:i+2] for i in range(0, len(key), 2)]
            rejoined = key.replace(" ","").decode('hex')
            print(rejoined)
            fp.write(rejoined)
    fp.close()
</code>```

My code gives me this error:

```<code>rejoined = key.decode('hex')
File "/usr/lib64/python2.7/encodings/hex_codec.py", line 42, in hex_decode
    output = binascii.a2b_hex(input)
TypeError: Non-hexadecimal digit found
</code>```

答:
You can use this to convert a value from decimal to hex:

```<code>>>> hex(65)
'0x41'
</code>```

But if you only want to convert the letters to lowercase, why don't you use .lower() method:

```<code>>>> s = "AABA67A79A"
>>> s.lower()
'aaba67a79a'
</code>```

https://docs.python.org/2/library/string.html

Title: How to convert hexadecimal in python?

Body:
I have file which contains in each line some hexadecimal numbers. For example:

5B35E8DF4A709CA16A1C8BC29022E83C
28958FA134D53BE6F382D04DC9891922
C67FC50F905F043EBEFEBFAF243B8744
99DCD61A89EE5553DDCA44378C3CE3C6
...........

I want to  convert them from uppercase to lowercase. For example:

5b35e8df4a709ca16a1c8bc29022e83c

Srcpath  ='Uppercase_File'
Destpath ='Lowercase_File'
with open(Srcpath, 'r') as f:
    with open(Destpath, 'w') as fp:
        for key in f:
            print(key)
            #key_Separated=[key[i:i+2] for i in range(0, len(key), 2)]
            rejoined = key.replace(" ","").decode('hex')
            print(rejoined)
            fp.write(rejoined)
    fp.close()

My code gives me this error:

rejoined = key.decode('hex')
File "/usr/lib64/python2.7/encodings/hex_codec.py", line 42, in hex_decode
    output = binascii.a2b_hex(input)
TypeError: Non-hexadecimal digit found

Body:
You can use this to convert a value from decimal to hex:

>>> hex(65)
'0x41'

But if you only want to convert the letters to lowercase, why don't you use .lower() method:

>>> s = "AABA67A79A"
>>> s.lower()
'aaba67a79a'

https://docs.python.org/2/library/string.html


问:
debugging deobfuscated javascript
I am trying to reverse-engineer a website I don't own, figuring out how some dumb "encryption" works, in order to be able to carry out some operations automatically, by taking the functionality outside the browser.

One of the files is of particular interest, let's call it javascript.js. It is linked in the HTML document like this

```<code><script src="/javascript.js" type="text/javascript"></script>
</code>```

I have

deobfuscated javascript.js

pretty-printed its code

My question is now, considering that I'm using venkman and firefox, how to replace the on-site obfuscated javascript.js with my own pretty-printed code, in order to learn how it works.

Any other tool beside venkman should do, as long as I can still step through the deobfuscated code.

Additional question (just in case I may come cross this related situation):

How to do the same if the javascript.js would be emdedded inline in the html code like ?

For those of you wondering about how legal this is, my question is not the first about reverse-engineering on SO: https://stackoverflow.com/questions/tagged/reverse-engineering

Apparently there's no problem with those questions, why should there be one with mine?

My objective is to understand the code AND my question is about the TOOLS, as in "where to point and click" or which tool could help me (if venkman cannot).

答: You could also always use an intercepting proxy (something like Paros) which will allow you to replace any part of the response any way you like. So when the browser requests the JS file, you can catch the response in Paros, replace the content with your version, and you're done. I often use Paros for other things where I need that interception or observation point, and it's pretty simple and quite numerous in its possible applications. It's basically just a matter of running it and setting your browser proxy settings to use a proxy at localhost on the port Paros is listening on. You can then tell Paros to actually stop and allow you to edit the request or response just by checking a couple of boxes. Hope that helps. </p>

Title: debugging deobfuscated javascript

Body:
I am trying to reverse-engineer a website I don't own, figuring out how some dumb "encryption" works, in order to be able to carry out some operations automatically, by taking the functionality outside the browser.

One of the files is of particular interest, let's call it javascript.js. It is linked in the HTML document like this

I have

deobfuscated javascript.js

pretty-printed its code

My question is now, considering that I'm using venkman and firefox, how to replace the on-site obfuscated javascript.js with my own pretty-printed code, in order to learn how it works.

Any other tool beside venkman should do, as long as I can still step through the deobfuscated code.

Additional question (just in case I may come cross this related situation):

How to do the same if the javascript.js would be emdedded inline in the html code like ?

For those of you wondering about how legal this is, my question is not the first about reverse-engineering on SO: https://stackoverflow.com/questions/tagged/reverse-engineering

Apparently there's no problem with those questions, why should there be one with mine?

My objective is to understand the code AND my question is about the TOOLS, as in "where to point and click" or which tool could help me (if venkman cannot).


问:
What is wrong with this code? App should get the location
The application (It should read my location) crashes when I try to start it:

I did everything to fix it, but in my opinion, there are some basic issues which I have overseen.

Main Activity:

```<code>import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.support.v4.content.LocalBroadcastManager;
import java.util.Locale;

public class MainActivity extends Activity {
    public static final String TAG = "MainActivity";
    private LocalBroadcastManager mLocalBroadcastManager;
    private BroadcastReceiver mBroadcastReceiver;
    private Intent mServiceIntent;
    private TextView mLatitude;
    private TextView mLongitude;

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

        mLatitude = (TextView) findViewById(R.id.latitude);
        mLongitude = (TextView) findViewById(R.id.longitude);

        mServiceIntent = new Intent(this, LocationService.class);

        mLocalBroadcastManager = LocalBroadcastManager.getInstance(this);
        mBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            Log.d(TAG, "onReceive()");
            mLatitude.setText(String.format(Locale.getDefault(), "%.6f", intent.getDoubleExtra(LocationService.EXTRA_LATITUDE, 0.0)));
            mLongitude.setText(String.format(Locale.getDefault(), "%.6f", intent.getDoubleExtra(LocationService.EXTRA_LONGITUDE, 0.0)));
        }
    };

    mLocalBroadcastManager.registerReceiver(mBroadcastReceiver, new IntentFilter(LocationService.INTENT_NAME));

    mLatitude.setText(savedInstanceState.getString(LocationService.EXTRA_LATITUDE, "0.0"));
    mLongitude.setText(savedInstanceState.getString(LocationService.EXTRA_LONGITUDE, "0.0"));
}

@Override
protected void onSaveInstanceState(Bundle bundle){
    super.onSaveInstanceState(bundle);
    bundle.putString(LocationService.EXTRA_LONGITUDE, mLatitude.getText().toString());
    bundle.putString(LocationService.EXTRA_LATITUDE, mLongitude.getText().toString());
    Log.d(TAG, bundle.toString());
}

@Override
protected void onDestroy(){
    mLocalBroadcastManager.unregisterReceiver(mBroadcastReceiver);
}

public void startGps(){
    startService(mServiceIntent);
}

public void stopGps(){
    stopService(mServiceIntent);
}
</code>```

}

Location Service:

```<code>import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;

public class LocationService extends Service {
    public static final String TAG = "LocationService";
    public static final String INTENT_NAME = "location_changed";
    public static final String EXTRA_LATITUDE = "latitude";
    public static final String EXTRA_LONGITUDE = "longitude";
    private LocationManager mLocationManager;
    private LocationListener mLocationListener;
    private LocalBroadcastManager mLocalBroadcastManager;

    public void onCreate(Bundle bundle){
        mLocalBroadcastManager = LocalBroadcastManager.getInstance(this);

        mLocationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
        mLocationListener = new LocationListener() {
            @Override
            public void onLocationChanged(final Location location) {
                Log.d(TAG, "onLocationChanged()");

                Intent intent = new Intent(INTENT_NAME);
                intent.putExtra("Latitude", location.getLatitude());
                intent.putExtra("Longitude", location.getLongitude());

                mLocalBroadcastManager.sendBroadcast(intent);
            }

            // we do not need the following function, but they have to be implemented (even if they are just empty)
            @Override
            public void onStatusChanged(String provider, int status, Bundle extras) {}
            @Override
            public void onProviderEnabled(String provider) {}
            @Override
            public void onProviderDisabled(String provider) {}
        };
    }

    @Override
    public void onDestroy() throws SecurityException{
        mLocationManager.removeUpdates(mLocationListener);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) throws SecurityException{
        super.onStartCommand(intent, flags, startId);
        mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, mLocationListener);
        return Service.START_NOT_STICKY;
    }

    @Override
    public IBinder onBind(Intent intent){
        return null;
    }
}
</code>```

答:
The javadoc for onCreate(savedInstanceState) states:

savedInstanceState Bundle: If the activity is being re-initialized after previously being shut down then this Bundle contains the data it most recently supplied in onSaveInstanceState(Bundle). Note: Otherwise it is null.

You are getting an NPE when you call savedInstanceState.getString, with a message that tells you that savedInstanceState.

Solution: modify your onCreate method to cope with the case where there is no saved instance yet; i.e. when savedInstanceState is null.

Body:
The application (It should read my location) crashes when I try to start it:

I did everything to fix it, but in my opinion, there are some basic issues which I have overseen.

Main Activity:

import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.support.v4.content.LocalBroadcastManager;
import java.util.Locale;

public class MainActivity extends Activity {
    public static final String TAG = "MainActivity";
    private LocalBroadcastManager mLocalBroadcastManager;
    private BroadcastReceiver mBroadcastReceiver;
    private Intent mServiceIntent;
    private TextView mLatitude;
    private TextView mLongitude;

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

        mLatitude = (TextView) findViewById(R.id.latitude);
        mLongitude = (TextView) findViewById(R.id.longitude);

        mServiceIntent = new Intent(this, LocationService.class);

        mLocalBroadcastManager = LocalBroadcastManager.getInstance(this);
        mBroadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            Log.d(TAG, "onReceive()");
            mLatitude.setText(String.format(Locale.getDefault(), "%.6f", intent.getDoubleExtra(LocationService.EXTRA_LATITUDE, 0.0)));
            mLongitude.setText(String.format(Locale.getDefault(), "%.6f", intent.getDoubleExtra(LocationService.EXTRA_LONGITUDE, 0.0)));
        }
    };

    mLocalBroadcastManager.registerReceiver(mBroadcastReceiver, new IntentFilter(LocationService.INTENT_NAME));

    mLatitude.setText(savedInstanceState.getString(LocationService.EXTRA_LATITUDE, "0.0"));
    mLongitude.setText(savedInstanceState.getString(LocationService.EXTRA_LONGITUDE, "0.0"));
}

@Override
protected void onSaveInstanceState(Bundle bundle){
    super.onSaveInstanceState(bundle);
    bundle.putString(LocationService.EXTRA_LONGITUDE, mLatitude.getText().toString());
    bundle.putString(LocationService.EXTRA_LATITUDE, mLongitude.getText().toString());
    Log.d(TAG, bundle.toString());
}

@Override
protected void onDestroy(){
    mLocalBroadcastManager.unregisterReceiver(mBroadcastReceiver);
}

public void startGps(){
    startService(mServiceIntent);
}

public void stopGps(){
    stopService(mServiceIntent);
}

}

Location Service:

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;

public class LocationService extends Service {
    public static final String TAG = "LocationService";
    public static final String INTENT_NAME = "location_changed";
    public static final String EXTRA_LATITUDE = "latitude";
    public static final String EXTRA_LONGITUDE = "longitude";
    private LocationManager mLocationManager;
    private LocationListener mLocationListener;
    private LocalBroadcastManager mLocalBroadcastManager;

    public void onCreate(Bundle bundle){
        mLocalBroadcastManager = LocalBroadcastManager.getInstance(this);

        mLocationManager = (LocationManager) this.getSystemService(Context.LOCATION_SERVICE);
        mLocationListener = new LocationListener() {
            @Override
            public void onLocationChanged(final Location location) {
                Log.d(TAG, "onLocationChanged()");

                Intent intent = new Intent(INTENT_NAME);
                intent.putExtra("Latitude", location.getLatitude());
                intent.putExtra("Longitude", location.getLongitude());

                mLocalBroadcastManager.sendBroadcast(intent);
            }

            // we do not need the following function, but they have to be implemented (even if they are just empty)
            @Override
            public void onStatusChanged(String provider, int status, Bundle extras) {}
            @Override
            public void onProviderEnabled(String provider) {}
            @Override
            public void onProviderDisabled(String provider) {}
        };
    }

    @Override
    public void onDestroy() throws SecurityException{
        mLocationManager.removeUpdates(mLocationListener);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) throws SecurityException{
        super.onStartCommand(intent, flags, startId);
        mLocationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 0, 0, mLocationListener);
        return Service.START_NOT_STICKY;
    }

    @Override
    public IBinder onBind(Intent intent){
        return null;
    }
}


问:
how to send each input value to ajax function along with specific id?
I am having one issue and i am confsued about it so much. I am not getting how i can send a particular input id so that i can send it to ajax and then save to database. I want to send all the data to ajax and in my table the input fields are generating dynamically. Let's have a look at below image.

my jquery function  :

```<code>function addnewrow() {
    var n = ($('.detail tr').length - 0) + 1;

    var tr = '<tr>' +
        '<td class="no">' + n + '</td>' +
        '<td><input type="checkbox" class="till_check" name="till_check[' + till_check_counter + ']" id="till_check[' + till_check_counter + ']"></td>' +
        '<td><select class="form-control barcode selectpicker  dyselect_' + product_barcode_counter + '" data-live-search="true" name="barcode[' + product_barcode_counter + ']" id="barcode[' + product_barcode_counter + ']">' + '<option>Please select a bar code</option>' + '</select></td>' +
        '<td><input type="text" class="form-control prdctn_' + product_name_counter + ' productname"  id="brcode_product['+product_name_counter+']"  name="productname[' + product_name_counter + ']" id="productname[' + product_name_counter + ']"></td>' +
        '<td><select class="form-control selectpicker dysm_' + sm_counter + ' sm " data-live-search="true" name="sm[' + sm_counter + ']" id="sm[' + sm_counter + ']">' + '<option>Please select a Employee code</option>' + '</select></td>' +
        '<td><input type="text" class="form-control spl" name="spl[' + spl_counter + ']" id="spl[' + spl_counter + ']"></td>' +
        '<td><input type="text" class="form-control quantity" name="quantity[' + product_quantity_counter + ']" id="quantity[' + product_quantity_counter + ']"></td>' +
        '<td><input type="text" class="form-control price" name="price[' + product_price_counter + ']" id="price[' + product_price_counter + ']"></td>' +
        '<td><input type="text" class="form-control discount" name="discount[' + product_discount_counter + ']" id="discount[' + product_discount_counter + ']"></td>' +
        '<td><input type="text" class="form-control amount" name="amount[' + product_amount_counter + ']" id="amount[' + product_amount_counter + ']"></td>' +
        '<td><a href="#" class="remove">Delete</td>' +
        '</tr>';
    $('.detail').append(tr);

        var barcode = $('#barcode[' + product_barcode_counter + '] option:selected').val();
        var productname = $('#brcode_product[' + product_name_counter + ']').val();
        var quantity = $('#barcode[' + product_quantity_counter + ']').val();
        var sm = $('#sm[' + sm_counter + ']').val();
        var spl = $('#spl[' + spl_counter + ']').val();
        var price = $('#price[' + product_price_counter + ']').val();
        var discount = $('#discount[' + product_discount_counter + ']').val();
        var amount = $('#amount[' + product_amount_counter + ']').val();

        $('#save_btn').on('click', function (id) {

            $.ajax({
                url: "http://localhost/retail/main/store",
                type: "POST",
                data: {
                    barcode: barcode,
                    productname: productname,
                    sm: sm,
                    spl: spl,
                    quantity: quantity,
                    price: price,
                    discount: discount,
                    amount: amount
                },
                success: function (res) {
                    alert(res);
                }

            });

        })

    //increamenting the counter
    ++product_barcode_counter;
    ++till_check_counter;
    ++product_name_counter;
    ++product_quantity_counter;
    ++sm_counter;
    ++spl_counter;
    ++product_price_counter;
    ++product_discount_counter;
    ++product_amount_counter;

    //setting the validation rules for every product attribute by calling the function
    createValidation();
    get_barcodes();
    get_employee_codes();

    //Send ajax request to the function on pressing the save button

}
</code>```

My Controller:

```<code>public function store(){

            /* echo ($_POST['barcode']);
             echo "<br/>";
             echo ($_POST['productname']);
             echo "<br/>";
             echo ($_POST['smsm']);
             echo "<br/>";
             echo ($_POST['spl']);
             echo "<br/>";
             echo ($_POST['quantity']);
             echo "<br/>";
             echo ($_POST['price']);
             echo "<br/>";
             echo ($_POST['discount']);
             echo "<br/>";
             echo ($_POST['amount']);
             echo "<br/>";*/

        //echo $this->input->post('barcode');

    if ($this->session->userdata('status')== 1) {
         for ($i = 0; $i < count($this->input->post['productname']); $i++) {

         $order_id = $this->session->userdata('id');
         $product_name = $this->input->post('productname')[$i];
         $barcode = $this->input->post('barcode')[$i];
         $spl= $this->input->post('spl')[$i];
         $sm= $this->input->post('sm')[$i];
         $quantity = $this->input->post('quantity')[$i];
         $price = $this->input->post('price')[$i];
         $discount =$this->input->post('discount')[$i];
         $amount = $this->input->post('amount')[$i];

        $data = array(

             'order_id'=> $order_id,
             'product_name'=>$product_name,
             'barcode'=> $barcode,
             'sm'=> $sm,
             'spl'=> $spl,
             'quantity'=>$quantity,
             'price'=>$price,
             'discount'=> $discount,
             'amount'=> $amount,

        );

             $this->Sale_model->insert_sales_data($data);
             echo "Data inserted successfully!";

         }
      }

      else
      {
          redirect('login');
      }

    }
</code>```

When you will click on the blue button the same row is added below first so i just want to ask how can i send the value of each row to the ajax function so that i can save the records in my database accordingly when i will click on  the save button (green) . I am not getting how can i achive this using jquery,and php with the help of ajax function.!

答:
use the below code for your purpose

```<code><form role="form" name="form_name" method="post" action="javascript:;">
  <!--Form Elements-->
</form>
</code>```

Use FormData objects to pass through AJAX Request

```<code>var data = new FormData($('form')[0]);
$.post({
        method: "POST",
        url: "http://localhost/retail/main/store",
        data: data,
        cache: false,
        contentType: false,
        processData: false,
}).done(function( response ) {

}).error(function(response){

});
</code>```

Body:
I am having one issue and i am confsued about it so much. I am not getting how i can send a particular input id so that i can send it to ajax and then save to database. I want to send all the data to ajax and in my table the input fields are generating dynamically. Let's have a look at below image.

my jquery function  :

function addnewrow() {
    var n = ($('.detail tr').length - 0) + 1;

    var tr = '
' +
        '' + n + '	' +
        '<input type="checkbox" class="till_check" name="till_check[' + till_check_counter + ']" id="till_check[' + till_check_counter + ']">	' +
        '<select class="form-control barcode selectpicker  dyselect_' + product_barcode_counter + '" data-live-search="true" name="barcode[' + product_barcode_counter + ']" id="barcode[' + product_barcode_counter + ']">' + '<option>Please select a bar code</option>' + '</select>	' +
        '<input type="text" class="form-control prdctn_' + product_name_counter + ' productname"  id="brcode_product['+product_name_counter+']"  name="productname[' + product_name_counter + ']" id="productname[' + product_name_counter + ']">	' +
        '<select class="form-control selectpicker dysm_' + sm_counter + ' sm " data-live-search="true" name="sm[' + sm_counter + ']" id="sm[' + sm_counter + ']">' + '<option>Please select a Employee code</option>' + '</select>	' +
        '<input type="text" class="form-control spl" name="spl[' + spl_counter + ']" id="spl[' + spl_counter + ']">	' +
        '<input type="text" class="form-control quantity" name="quantity[' + product_quantity_counter + ']" id="quantity[' + product_quantity_counter + ']">	' +
        '<input type="text" class="form-control price" name="price[' + product_price_counter + ']" id="price[' + product_price_counter + ']">	' +
        '<input type="text" class="form-control discount" name="discount[' + product_discount_counter + ']" id="discount[' + product_discount_counter + ']">	' +
        '<input type="text" class="form-control amount" name="amount[' + product_amount_counter + ']" id="amount[' + product_amount_counter + ']">	' +
        'Delete	' +
        '
';
    $('.detail').append(tr);

        var barcode = $('#barcode[' + product_barcode_counter + '] option:selected').val();
        var productname = $('#brcode_product[' + product_name_counter + ']').val();
        var quantity = $('#barcode[' + product_quantity_counter + ']').val();
        var sm = $('#sm[' + sm_counter + ']').val();
        var spl = $('#spl[' + spl_counter + ']').val();
        var price = $('#price[' + product_price_counter + ']').val();
        var discount = $('#discount[' + product_discount_counter + ']').val();
        var amount = $('#amount[' + product_amount_counter + ']').val();

        $('#save_btn').on('click', function (id) {

            $.ajax({
                url: "http://localhost/retail/main/store",
                type: "POST",
                data: {
                    barcode: barcode,
                    productname: productname,
                    sm: sm,
                    spl: spl,
                    quantity: quantity,
                    price: price,
                    discount: discount,
                    amount: amount
                },
                success: function (res) {
                    alert(res);
                }

            });

        })

    //increamenting the counter
    ++product_barcode_counter;
    ++till_check_counter;
    ++product_name_counter;
    ++product_quantity_counter;
    ++sm_counter;
    ++spl_counter;
    ++product_price_counter;
    ++product_discount_counter;
    ++product_amount_counter;

    //setting the validation rules for every product attribute by calling the function
    createValidation();
    get_barcodes();
    get_employee_codes();

    //Send ajax request to the function on pressing the save button

}

My Controller:

public function store(){

            /* echo ($_POST['barcode']);
             echo "
";
             echo ($_POST['productname']);
             echo "
";
             echo ($_POST['smsm']);
             echo "
";
             echo ($_POST['spl']);
             echo "
";
             echo ($_POST['quantity']);
             echo "
";
             echo ($_POST['price']);
             echo "
";
             echo ($_POST['discount']);
             echo "
";
             echo ($_POST['amount']);
             echo "
";*/

        //echo $this->input->post('barcode');

    if ($this->session->userdata('status')== 1) {
         for ($i = 0; $i < count($this->input->post['productname']); $i++) {

         $order_id = $this->session->userdata('id');
         $product_name = $this->input->post('productname')[$i];
         $barcode = $this->input->post('barcode')[$i];
         $spl= $this->input->post('spl')[$i];
         $sm= $this->input->post('sm')[$i];
         $quantity = $this->input->post('quantity')[$i];
         $price = $this->input->post('price')[$i];
         $discount =$this->input->post('discount')[$i];
         $amount = $this->input->post('amount')[$i];

        $data = array(

             'order_id'=> $order_id,
             'product_name'=>$product_name,
             'barcode'=> $barcode,
             'sm'=> $sm,
             'spl'=> $spl,
             'quantity'=>$quantity,
             'price'=>$price,
             'discount'=> $discount,
             'amount'=> $amount,

        );

             $this->Sale_model->insert_sales_data($data);
             echo "Data inserted successfully!";

         }
      }

      else
      {
          redirect('login');
      }

    }

When you will click on the blue button the same row is added below first so i just want to ask how can i send the value of each row to the ajax function so that i can save the records in my database accordingly when i will click on  the save button (green) . I am not getting how can i achive this using jquery,and php with the help of ajax function.!

Body:
use the below code for your purpose

<form role="form" name="form_name" method="post" action="javascript:;">
  <!--Form Elements-->
</form>

Use FormData objects to pass through AJAX Request

var data = new FormData($('form')[0]);
$.post({
        method: "POST",
        url: "http://localhost/retail/main/store",
        data: data,
        cache: false,
        contentType: false,
        processData: false,
}).done(function( response ) {

}).error(function(response){

});


问:
Click event not working on dcmads
I want to make an ajax call whenever someone clicks on a dcmads ad placed on my website. But I am unable to do so. I think that it is somewhat because of event bubbling and capturing and even tried to resolve it but this made no effect.

HTML -

```<code><div class="ad-snippet">
  <ins class='dcmads' style='display:inline-block;width:728px;height:90px'
    data-dcm-placement='N8897.1919357DBM_CA/B10148853.136150045'
    data-dcm-rendering-mode='iframe'
    data-dcm-https-only
    data-dcm-resettable-device-id=''>
    <script src='https://www.googletagservices.com/dcm/dcmads.js'></script>
  </ins>
</div>
</code>```

JS -

```<code>var ad_click = document.querySelectorAll('.ad-snippet');
[].forEach.call(ad_click, function(key,value){
  key.onclick = function(){
    alert("hi");
 }
});
</code>```

Any help will be highly appreciated as to why this is happening and how can we handle this?

答:
For anyone facing the same issue I have finally found a solution to this using the below mentioned amazing plugin

https://github.com/vincepare/iframeTracker-jquery

Reason of issue -
It's impossible to read iframe content (DOM) from the parent page due to the same origin policy

How does this plugin work -
Tracking is based on the blur event associated to a page/iframe boundary monitoring system telling over which iframe is the mouse cursor at any time.

```<code>jQuery(document).ready(function($){
    $('.iframe_wrap iframe').iframeTracker({
        blurCallback: function(){
            // Do something when the iframe is clicked (like firing an XHR request)
        }
    });
});
</code>```

Title: Click event not working on dcmads

Body:
I want to make an ajax call whenever someone clicks on a dcmads ad placed on my website. But I am unable to do so. I think that it is somewhat because of event bubbling and capturing and even tried to resolve it but this made no effect.

HTML -

JS -

var ad_click = document.querySelectorAll('.ad-snippet');
[].forEach.call(ad_click, function(key,value){
  key.onclick = function(){
    alert("hi");
 }
});

Any help will be highly appreciated as to why this is happening and how can we handle this?

Body:
For anyone facing the same issue I have finally found a solution to this using the below mentioned amazing plugin

https://github.com/vincepare/iframeTracker-jquery

Reason of issue -
It's impossible to read iframe content (DOM) from the parent page due to the same origin policy

How does this plugin work -
Tracking is based on the blur event associated to a page/iframe boundary monitoring system telling over which iframe is the mouse cursor at any time.

jQuery(document).ready(function($){
    $('.iframe_wrap iframe').iframeTracker({
        blurCallback: function(){
            // Do something when the iframe is clicked (like firing an XHR request)
        }
    });
});


问:
Disable Laravel's built-in error handling methods
Is there anyway to disable the Laravel error handler all together?

I want to simply display standard PHP errors, not the Whoops, looks like something went wrong errors.

答:
In file .env, just change:

```<code>APP_DEBUG=true
</code>```

To:

```<code>APP_DEBUG=false
</code>```

Body:
In file .env, just change:

APP_DEBUG=true

To:

APP_DEBUG=false


答:
When you need your application not to keep screen on, you can clear the FLAG_KEEP_SCREEN_ON flag using this code:

```<code>getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
</code>```

Title: About the screen on in android application

Body:
When you need your application not to keep screen on, you can clear the FLAG_KEEP_SCREEN_ON flag using this code:

getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);