问:
Compiling a specific boost library
I only require a single .lib and .dll but I don't want to go through compiling process of all using bjam.exe How can i do that?

答: to compile specific library you just need to specify it with --with-library option, e.g. --with-date_time, more info here

Title: Compiling a specific boost library


来源: stackexchange

问:
Real-time with Flask and JS
I'm trying to create a chat app using Flask and JavaScript, but I'm running into a problem. I used jQuery to accept the username and message, and Flask to put the message on the page. Is there anyway I can do this in real-time, and without reloading the page?

(to collect data and convert to JSON)

```<code>$(function () {
    $('#send').bind('click', function () {
        $.getJSON('/send', {
            user: $('#username').val(),
            mess: $('#message').val()
        }, function (data) {
            console.log('message sent')
            //$("#result").append(data.result + '<br>');
        });
        return false;
    });
});
</code>```

(app.py)

```<code>messages = []
@app.route('/')
def index():
    return render_template('index.html', messages=messages)

@app.route('/send',)
def send():
    try:
        username = request.args.get('user')
        message = request.args.get('mess')
        messages.append([username, message])
        return jsonify(result=username + ': ' + message + '; ')
    except Exception as e:
        return e
</code>```

答:
There is. However, not in your current setup. The HTTP standard, which Flask uses only returns data when it is called. So only when you call the '/' route in your flask app it will return data. The easy solution is to call every 5 seconds to see if there are changes. This can be implemented with the JavaScript setInterval function.

The other option that you have is to start using websockets with the socketio library. You can connect Flask with this library through the flask-socketio extension.

Find information below:

https://socket.io/

https://flask-socketio.readthedocs.io/en/latest/

Obviously, these are not the only solutions. There are more ways to get what you want. However, explaining this would be more complicated and I think that with these two options you can already implement something.

ContentLicense: CC BY-SA 3.0

Title: Real-time with Flask and JS

Body:
I'm trying to create a chat app using Flask and JavaScript, but I'm running into a problem. I used jQuery to accept the username and message, and Flask to put the message on the page. Is there anyway I can do this in real-time, and without reloading the page?

(to collect data and convert to JSON)

$(function () {
    $('#send').bind('click', function () {
        $.getJSON('/send', {
            user: $('#username').val(),
            mess: $('#message').val()
        }, function (data) {
            console.log('message sent')
            //$("#result").append(data.result + '
');
        });
        return false;
    });
});

(app.py)

messages = []
@app.route('/')
def index():
    return render_template('index.html', messages=messages)

@app.route('/send',)
def send():
    try:
        username = request.args.get('user')
        message = request.args.get('mess')
        messages.append([username, message])
        return jsonify(result=username + ': ' + message + '; ')
    except Exception as e:
        return e


问:
rotate the marker with move direction
Iam developing android app with google map implemented. I have tried to make the marker rotate with the direction of moving (like navigation in google maps) but all tried codes failed. Below are the code. Any suggestion. Note(Iam getting the bearing from method that returns the location, speed and bering and I can see the float value of the bearing changes while changing the direction.</p>

```<code>                float bearing = setterandGetter.getBearing();
                double lat = setterandGetter.getLatitude();
                double lon = setterandGetter.getLongitude();
                LatLng currentPosition = new LatLng(latitudelongitude);

                googleMap.moveCamera(CameraUpdateFactory.newLatLng(currentPosition));

Marker marker = googleMap.addMarker(new MarkerOptions().position(currentPosition).icon(BitmapDescriptorFactory.fromBitmap(blueIcon)).flat(true).rotation(bearing));
</code>```

答: use map.clear() to clear the map and then create marker so whenever your Location changed old  marker will automatically  be cleared and new marker is created so it seems like marker is moving with the location

Title: rotate the marker with move direction

Body:
Iam developing android app with google map implemented. I have tried to make the marker rotate with the direction of moving (like navigation in google maps) but all tried codes failed. Below are the code. Any suggestion. Note(Iam getting the bearing from method that returns the location, speed and bering and I can see the float value of the bearing changes while changing the direction.

                float bearing = setterandGetter.getBearing();
                double lat = setterandGetter.getLatitude();
                double lon = setterandGetter.getLongitude();
                LatLng currentPosition = new LatLng(latitudelongitude);

                googleMap.moveCamera(CameraUpdateFactory.newLatLng(currentPosition));

Marker marker = googleMap.addMarker(new MarkerOptions().position(currentPosition).icon(BitmapDescriptorFactory.fromBitmap(blueIcon)).flat(true).rotation(bearing));


问:
ant design recursive nested table don't work
i want to use  recursive nested table in react's component framework:antd, but it doesn't  work like this :

```<code>import {Table, Badge, Menu, Dropdown, Icon} from 'antd';
export  default  class TreeTable extends React.Component {

    constructor(props) {
        super(props)
        this.state = {
            dataSource: [],
            nestedData: []
        }
    }

    expandedRowRender(e) {

        const nested_source = e.nest_data

        const columns = this.props.nest_columns

        return (
            <Table
                columns={columns}
                dataSource={nested_source}
                pagination={false}
                expandedRowRender={(e)=>{this.expandedRowRender(e)}}
                title={()=>"一级岗位列表"}
                showHeader={false}
                size={"middle"}
            />

        );
    }

    render() {
        const data_source = this.props.data_source.map((v, i)=> {
            return {key: i, ...v}
        })

        return (
            <div >
                <Table
                    className="components-table-demo-nested"
                    columns={this.props.columns}
                    expandedRowRender={(e)=>::this.expandedRowRender(e)}
                    dataSource={data_source}
                />
                { this.props.children }
            </div>
        )
    }

}
</code>```

nothing happened when i click second level plus button on table , how to solve this ? is this a bug?

答:
first of all i like to answer your first Question

is this a bug?

No,this is not a Bug.
This occurs when you don't set the unique key value to the each table row.
add this code snipt in to your both "Table" tags.

rowKey = {e=> e._id}

ex:-

```<code>         <Table
                rowKey = {e=> e._id}
                className="components-table-demo-nested"
                columns={this.props.columns}
                expandedRowRender={(e)=>::this.expandedRowRender(e)}
                dataSource={data_source}
            />
</code>```

Body:
i want to use  recursive nested table in react's component framework:antd, but it doesn't  work like this :

import {Table, Badge, Menu, Dropdown, Icon} from 'antd';
export  default  class TreeTable extends React.Component {

    constructor(props) {
        super(props)
        this.state = {
            dataSource: [],
            nestedData: []
        }
    }

    expandedRowRender(e) {

        const nested_source = e.nest_data

        const columns = this.props.nest_columns

        return (

{this.expandedRowRender(e)}}
                title={()=>"一级岗位列表"}
                showHeader={false}
                size={"middle"}
            />

        );
    }

    render() {
        const data_source = this.props.data_source.map((v, i)=> {
            return {key: i, ...v}
        })

        return (

::this.expandedRowRender(e)}
                    dataSource={data_source}
                />
                { this.props.children }

        )
    }

}

nothing happened when i click second level plus button on table , how to solve this ? is this a bug?

Body:
first of all i like to answer your first Question

is this a bug?

No,this is not a Bug.
This occurs when you don't set the unique key value to the each table row.
add this code snipt in to your both "Table" tags.

rowKey = {e=> e._id}

ex:-

         <Table
                rowKey = {e=> e._id}
                className="components-table-demo-nested"
                columns={this.props.columns}
                expandedRowRender={(e)=>::this.expandedRowRender(e)}
                dataSource={data_source}
            />


问:
Best way to check for null parameters (Guard Clauses)
For example, you usually don't want parameters in a constructor to be null, so it's very normal to see some thing like

```<code>if (someArg == null)
{
    throw new ArgumentNullException(nameof(someArg));
}

if (otherArg == null)
{
    throw new ArgumentNullException(nameof(otherArg));
}
</code>```

It does clutter the code a bit.

Is there any way to check an argument of a list of arguments better than this?

Something like "check all of the arguments and throw an ArgumentNullException if any of them is null and that provides you with the arguments that were null.

By the way, regarding duplicate question claims, this is not about marking arguments with attributes or something that is built-in, but what some call it Guard Clauses to guarantee that an object receives initialized dependencies.

答:
There is a nuget package called SwissKnife. Install SwissKnife from nuget gallery. It provides you with many options starting with null checking for arguments
Argument.IsNotNullOrEmpty(args,"args") under SwissKnife.Diagnostics.Contracts namespace alongwith with option idoim and many more. You can set Option<Class_Name> _someVar and then check if _someVar.IsSome or _someVar.IsNone. This helps against nullable classes as well. Hope this helps.

Body:
For example, you usually don't want parameters in a constructor to be null, so it's very normal to see some thing like

if (someArg == null)
{
    throw new ArgumentNullException(nameof(someArg));
}

if (otherArg == null)
{
    throw new ArgumentNullException(nameof(otherArg));
}

It does clutter the code a bit.

Is there any way to check an argument of a list of arguments better than this?

Something like "check all of the arguments and throw an ArgumentNullException if any of them is null and that provides you with the arguments that were null.

By the way, regarding duplicate question claims, this is not about marking arguments with attributes or something that is built-in, but what some call it Guard Clauses to guarantee that an object receives initialized dependencies.

ContentLicense: CC BY-SA 4.0


问:
Order of thread activation in a c# program on a 4 cores PC
I am confused about the thread activation order of the following C# code. It creates 10 threads, starts them randomly, each thread simulates to execute a time-consuming work 10 times, if you check the debug output, the thread seems not to be picked up not randomly, please see below output example, notice thread #3, #5, #6 is always picked up, when #3 #5 #6 is finished, then #10 #2 #8 is always picked up, etc... (I know the design is bad, please focus on the phenomenon)

My PC has i7-7820HQ cpu which has 4 cores, and is running windows 10.

Could someone explain why these threads are not picked randomly and they seemed to be grouped somehow.

Thanks a lot!

---- Debug output ----

```
Thread #10 acquired the lock and is working for task #0
Thread #5 acquired the lock and is working for task #0
Thread #3 acquired the lock and is working for task #0
Thread #6 acquired the lock and is working for task #0
Thread #5 acquired the lock and is working for task #1
Thread #3 acquired the lock and is working for task #1
Thread #6 acquired the lock and is working for task #1
...
Thread #5 acquired the lock and is working for task #9
Thread #3 acquired the lock and is working for task #9
Thread #6 acquired the lock and is working for task #9
...
Thread #8 acquired the lock and is working for task #0
Thread #2 acquired the lock and is working for task #0
Thread #8 acquired the lock and is working for task #1
Thread #2 acquired the lock and is working for task #1
Thread #10 acquired the lock and is working for task #1
...
Thread #8 acquired the lock and is working for task #9
Thread #2 acquired the lock and is working for task #9
Thread #10 acquired the lock and is working for task #9
...
```

```<code>using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace ConsoleApp1
{
    class Program
    {
        static Hashtable _sharedBetweenThreads = new Hashtable();

        static void Main(string[] args)
        {
            Random random = new Random(DateTime.Now.Second);
            var startOrders = new int[10];
            for (int i = 0; i < startOrders.Length; i++)
            {
                startOrders[i] = i;
            }

            //shuffle the array
            for (int i = startOrders.Length - 1; i >= 0; i--)
            {
                int j = random.Next(0, i);
                int temp = startOrders[i];
                startOrders[i] = startOrders[j];
                startOrders[j] = temp;
            }

            Thread[] threads = new Thread[startOrders.Length];
            for(int i = 0; i < startOrders.Length; i++)
            {
                threads[i] = new Thread(new ThreadStart(ThreadProc));
            }

            for (int i = 0; i < startOrders.Length; i++)
            {
                threads[startOrders[i]].Start();
            }

            Console.ReadLine();
        }

        static void ThreadProc()
        {
            // simulates there are 10 tasks needs to do.
            for (int i = 0; i < 10; i++)
            {
                lock (_sharedBetweenThreads.SyncRoot)
                {
                    Debug.Print(string.Format("Thread #{0} acquired the lock and is working for task #{1}", Thread.CurrentThread.ManagedThreadId, i));

                    // simulates a work.
                    Thread.Sleep(500);
                }

            }
        }
    }
}
</code>```

The screenshot of debug output

--- Additional infos ---

The program is not a parallel program at all because there is lock shared among 10 threads.

If the count of the loop is changed from 10 to infinite, the 3 threads are always activated and the rest 7 threads cannot get a chance of activating, and they are something like "deadlocked" forever.

答:
Usings threads doesn't really mean you are using the 4 cores you have.

You have to use Parallel:

```<code>class Program
{
    private static object _lock = new Object();

    static void Main(string[] args)
    {
        Random random = new Random(DateTime.Now.Second);

        int[] startOrders = new int[10];
        for (int i = 0; i < startOrders.Length; i++)
        {
            startOrders[i] = i;
        }

        //shuffle the array
        for (int i = startOrders.Length - 1; i >= 0; i--)
        {
            int j = random.Next(0, i);
            int temp = startOrders[i];
            startOrders[i] = startOrders[j];
            startOrders[j] = temp;
        }

        Thread[] threads = new Thread[startOrders.Length];
        for (int i = 0; i < startOrders.Length; i++)
        {
            threads[i] = new Thread(ThreadProc)
                             {
                                 Name = $"#{startOrders[i]}"

                             };
        }

        Parallel.ForEach(threads, thread => thread.Start());

        Console.ReadLine();
    }

    static void ThreadProc()
    {
        // simulates there are 10 tasks needs to do.
        for (int i = 0; i < 10; i++)
        {
            lock (_lock)
            {
                Debug.Print(
                    $"Thread {Thread.CurrentThread.Name} acquired the lock and is working for task #{i}");

                // simulates a work.
                Thread.Sleep(5);
            }
        }
    }
}
</code>```

Output

```<code>Thread #6 acquired the lock and is working for task #0
Thread #4 acquired the lock and is working for task #0
Thread #8 acquired the lock and is working for task #0
Thread #6 acquired the lock and is working for task #1
Thread #5 acquired the lock and is working for task #0
Thread #3 acquired the lock and is working for task #0
Thread #6 acquired the lock and is working for task #2
Thread #7 acquired the lock and is working for task #0
Thread #9 acquired the lock and is working for task #0
Thread #6 acquired the lock and is working for task #3
Thread #4 acquired the lock and is working for task #1
Thread #8 acquired the lock and is working for task #1
Thread #0 acquired the lock and is working for task #0
Thread #5 acquired the lock and is working for task #1
Thread #3 acquired the lock and is working for task #1
Thread #7 acquired the lock and is working for task #1
Thread #9 acquired the lock and is working for task #1
Thread #2 acquired the lock and is working for task #0
Thread #1 acquired the lock and is working for task #0
Thread #0 acquired the lock and is working for task #1
Thread #6 acquired the lock and is working for task #4
Thread #4 acquired the lock and is working for task #2
Thread #8 acquired the lock and is working for task #2
Thread #3 acquired the lock and is working for task #2
Thread #7 acquired the lock and is working for task #2
Thread #5 acquired the lock and is working for task #2
Thread #9 acquired the lock and is working for task #2
Thread #2 acquired the lock and is working for task #1
Thread #0 acquired the lock and is working for task #2
Thread #1 acquired the lock and is working for task #1
Thread #6 acquired the lock and is working for task #5
Thread #4 acquired the lock and is working for task #3
Thread #8 acquired the lock and is working for task #3
Thread #5 acquired the lock and is working for task #3
Thread #3 acquired the lock and is working for task #3
Thread #7 acquired the lock and is working for task #3
Thread #6 acquired the lock and is working for task #6
Thread #4 acquired the lock and is working for task #4
Thread #8 acquired the lock and is working for task #4
Thread #5 acquired the lock and is working for task #4
Thread #3 acquired the lock and is working for task #4
Thread #7 acquired the lock and is working for task #4
Thread #6 acquired the lock and is working for task #7
Thread #4 acquired the lock and is working for task #5
Thread #8 acquired the lock and is working for task #5
Thread #5 acquired the lock and is working for task #5
Thread #3 acquired the lock and is working for task #5
Thread #7 acquired the lock and is working for task #5
Thread #9 acquired the lock and is working for task #3
Thread #6 acquired the lock and is working for task #8
Thread #4 acquired the lock and is working for task #6
Thread #5 acquired the lock and is working for task #6
Thread #8 acquired the lock and is working for task #6
Thread #4 acquired the lock and is working for task #7
Thread #3 acquired the lock and is working for task #6
Thread #6 acquired the lock and is working for task #9
Thread #7 acquired the lock and is working for task #6
The thread 0xfa0 has exited with code 0 (0x0).
Thread #5 acquired the lock and is working for task #7
Thread #8 acquired the lock and is working for task #7
Thread #9 acquired the lock and is working for task #4
Thread #4 acquired the lock and is working for task #8
Thread #3 acquired the lock and is working for task #7
Thread #0 acquired the lock and is working for task #3
Thread #7 acquired the lock and is working for task #7
Thread #5 acquired the lock and is working for task #8
Thread #8 acquired the lock and is working for task #8
Thread #4 acquired the lock and is working for task #9
Thread #3 acquired the lock and is working for task #8
The thread 0x329c has exited with code 0 (0x0).
Thread #9 acquired the lock and is working for task #5
Thread #7 acquired the lock and is working for task #8
Thread #5 acquired the lock and is working for task #9
The thread 0x3fcc has exited with code 0 (0x0).
Thread #8 acquired the lock and is working for task #9
The thread 0xe2c has exited with code 0 (0x0).
Thread #0 acquired the lock and is working for task #4
Thread #3 acquired the lock and is working for task #9
The thread 0x22ec has exited with code 0 (0x0).
Thread #2 acquired the lock and is working for task #2
Thread #7 acquired the lock and is working for task #9
The thread 0x2bfc has exited with code 0 (0x0).
Thread #9 acquired the lock and is working for task #6
Thread #1 acquired the lock and is working for task #2
Thread #0 acquired the lock and is working for task #5
Thread #2 acquired the lock and is working for task #3
Thread #2 acquired the lock and is working for task #4
Thread #9 acquired the lock and is working for task #7
Thread #2 acquired the lock and is working for task #5
Thread #1 acquired the lock and is working for task #3
Thread #0 acquired the lock and is working for task #6
Thread #0 acquired the lock and is working for task #7
Thread #9 acquired the lock and is working for task #8
Thread #2 acquired the lock and is working for task #6
Thread #1 acquired the lock and is working for task #4
Thread #1 acquired the lock and is working for task #5
Thread #0 acquired the lock and is working for task #8
Thread #9 acquired the lock and is working for task #9
The thread 0x1f44 has exited with code 0 (0x0).
Thread #1 acquired the lock and is working for task #6
Thread #2 acquired the lock and is working for task #7
Thread #2 acquired the lock and is working for task #8
Thread #0 acquired the lock and is working for task #9
The thread 0x1fc8 has exited with code 0 (0x0).
Thread #1 acquired the lock and is working for task #7
Thread #1 acquired the lock and is working for task #8
Thread #1 acquired the lock and is working for task #9
The thread 0x2ab0 has exited with code 0 (0x0).
Thread #2 acquired the lock and is working for task #9
The thread 0x2944 has exited with code 0 (0x0).
The thread 0x322c has exited with code 0 (0x0).
The thread 0x146c has exited with code 0 (0x0).
The thread 0x3dcc has exited with code 0 (0x0).
The thread 0x3928 has exited with code 0 (0x0).
</code>```

I'm not sure, but if I use the Thread.Name, instead Thread.CurrentThread.ManagedThreadId seems to work as you want. It can be that the ManagedThreadId is assigned when the thread start, so it makes sense that the #12 is the last one on the execute, because it is actually the last one.

Body:
I am confused about the thread activation order of the following C# code. It creates 10 threads, starts them randomly, each thread simulates to execute a time-consuming work 10 times, if you check the debug output, the thread seems not to be picked up not randomly, please see below output example, notice thread #3, #5, #6 is always picked up, when #3 #5 #6 is finished, then #10 #2 #8 is always picked up, etc... (I know the design is bad, please focus on the phenomenon)

My PC has i7-7820HQ cpu which has 4 cores, and is running windows 10.

Could someone explain why these threads are not picked randomly and they seemed to be grouped somehow.

Thanks a lot!

---- Debug output ----

Thread #10 acquired the lock and is working for task #0
Thread #5 acquired the lock and is working for task #0
Thread #3 acquired the lock and is working for task #0
Thread #6 acquired the lock and is working for task #0
Thread #5 acquired the lock and is working for task #1
Thread #3 acquired the lock and is working for task #1
Thread #6 acquired the lock and is working for task #1
...
Thread #5 acquired the lock and is working for task #9
Thread #3 acquired the lock and is working for task #9
Thread #6 acquired the lock and is working for task #9
...
Thread #8 acquired the lock and is working for task #0
Thread #2 acquired the lock and is working for task #0
Thread #8 acquired the lock and is working for task #1
Thread #2 acquired the lock and is working for task #1
Thread #10 acquired the lock and is working for task #1
...
Thread #8 acquired the lock and is working for task #9
Thread #2 acquired the lock and is working for task #9
Thread #10 acquired the lock and is working for task #9
...

using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace ConsoleApp1
{
    class Program
    {
        static Hashtable _sharedBetweenThreads = new Hashtable();

        static void Main(string[] args)
        {
            Random random = new Random(DateTime.Now.Second);
            var startOrders = new int[10];
            for (int i = 0; i < startOrders.Length; i++)
            {
                startOrders[i] = i;
            }

            //shuffle the array
            for (int i = startOrders.Length - 1; i >= 0; i--)
            {
                int j = random.Next(0, i);
                int temp = startOrders[i];
                startOrders[i] = startOrders[j];
                startOrders[j] = temp;
            }

            Thread[] threads = new Thread[startOrders.Length];
            for(int i = 0; i < startOrders.Length; i++)
            {
                threads[i] = new Thread(new ThreadStart(ThreadProc));
            }

            for (int i = 0; i < startOrders.Length; i++)
            {
                threads[startOrders[i]].Start();
            }

            Console.ReadLine();
        }

        static void ThreadProc()
        {
            // simulates there are 10 tasks needs to do.
            for (int i = 0; i < 10; i++)
            {
                lock (_sharedBetweenThreads.SyncRoot)
                {
                    Debug.Print(string.Format("Thread #{0} acquired the lock and is working for task #{1}", Thread.CurrentThread.ManagedThreadId, i));

                    // simulates a work.
                    Thread.Sleep(500);
                }

            }
        }
    }
}

The screenshot of debug output

--- Additional infos ---

The program is not a parallel program at all because there is lock shared among 10 threads.

If the count of the loop is changed from 10 to infinite, the 3 threads are always activated and the rest 7 threads cannot get a chance of activating, and they are something like "deadlocked" forever.

Body:
Usings threads doesn't really mean you are using the 4 cores you have.

You have to use Parallel:

class Program
{
    private static object _lock = new Object();

    static void Main(string[] args)
    {
        Random random = new Random(DateTime.Now.Second);

        int[] startOrders = new int[10];
        for (int i = 0; i < startOrders.Length; i++)
        {
            startOrders[i] = i;
        }

        //shuffle the array
        for (int i = startOrders.Length - 1; i >= 0; i--)
        {
            int j = random.Next(0, i);
            int temp = startOrders[i];
            startOrders[i] = startOrders[j];
            startOrders[j] = temp;
        }

        Thread[] threads = new Thread[startOrders.Length];
        for (int i = 0; i < startOrders.Length; i++)
        {
            threads[i] = new Thread(ThreadProc)
                             {
                                 Name = $"#{startOrders[i]}"

                             };
        }

        Parallel.ForEach(threads, thread => thread.Start());

        Console.ReadLine();
    }

    static void ThreadProc()
    {
        // simulates there are 10 tasks needs to do.
        for (int i = 0; i < 10; i++)
        {
            lock (_lock)
            {
                Debug.Print(
                    $"Thread {Thread.CurrentThread.Name} acquired the lock and is working for task #{i}");

                // simulates a work.
                Thread.Sleep(5);
            }
        }
    }
}

Output

Thread #6 acquired the lock and is working for task #0
Thread #4 acquired the lock and is working for task #0
Thread #8 acquired the lock and is working for task #0
Thread #6 acquired the lock and is working for task #1
Thread #5 acquired the lock and is working for task #0
Thread #3 acquired the lock and is working for task #0
Thread #6 acquired the lock and is working for task #2
Thread #7 acquired the lock and is working for task #0
Thread #9 acquired the lock and is working for task #0
Thread #6 acquired the lock and is working for task #3
Thread #4 acquired the lock and is working for task #1
Thread #8 acquired the lock and is working for task #1
Thread #0 acquired the lock and is working for task #0
Thread #5 acquired the lock and is working for task #1
Thread #3 acquired the lock and is working for task #1
Thread #7 acquired the lock and is working for task #1
Thread #9 acquired the lock and is working for task #1
Thread #2 acquired the lock and is working for task #0
Thread #1 acquired the lock and is working for task #0
Thread #0 acquired the lock and is working for task #1
Thread #6 acquired the lock and is working for task #4
Thread #4 acquired the lock and is working for task #2
Thread #8 acquired the lock and is working for task #2
Thread #3 acquired the lock and is working for task #2
Thread #7 acquired the lock and is working for task #2
Thread #5 acquired the lock and is working for task #2
Thread #9 acquired the lock and is working for task #2
Thread #2 acquired the lock and is working for task #1
Thread #0 acquired the lock and is working for task #2
Thread #1 acquired the lock and is working for task #1
Thread #6 acquired the lock and is working for task #5
Thread #4 acquired the lock and is working for task #3
Thread #8 acquired the lock and is working for task #3
Thread #5 acquired the lock and is working for task #3
Thread #3 acquired the lock and is working for task #3
Thread #7 acquired the lock and is working for task #3
Thread #6 acquired the lock and is working for task #6
Thread #4 acquired the lock and is working for task #4
Thread #8 acquired the lock and is working for task #4
Thread #5 acquired the lock and is working for task #4
Thread #3 acquired the lock and is working for task #4
Thread #7 acquired the lock and is working for task #4
Thread #6 acquired the lock and is working for task #7
Thread #4 acquired the lock and is working for task #5
Thread #8 acquired the lock and is working for task #5
Thread #5 acquired the lock and is working for task #5
Thread #3 acquired the lock and is working for task #5
Thread #7 acquired the lock and is working for task #5
Thread #9 acquired the lock and is working for task #3
Thread #6 acquired the lock and is working for task #8
Thread #4 acquired the lock and is working for task #6
Thread #5 acquired the lock and is working for task #6
Thread #8 acquired the lock and is working for task #6
Thread #4 acquired the lock and is working for task #7
Thread #3 acquired the lock and is working for task #6
Thread #6 acquired the lock and is working for task #9
Thread #7 acquired the lock and is working for task #6
The thread 0xfa0 has exited with code 0 (0x0).
Thread #5 acquired the lock and is working for task #7
Thread #8 acquired the lock and is working for task #7
Thread #9 acquired the lock and is working for task #4
Thread #4 acquired the lock and is working for task #8
Thread #3 acquired the lock and is working for task #7
Thread #0 acquired the lock and is working for task #3
Thread #7 acquired the lock and is working for task #7
Thread #5 acquired the lock and is working for task #8
Thread #8 acquired the lock and is working for task #8
Thread #4 acquired the lock and is working for task #9
Thread #3 acquired the lock and is working for task #8
The thread 0x329c has exited with code 0 (0x0).
Thread #9 acquired the lock and is working for task #5
Thread #7 acquired the lock and is working for task #8
Thread #5 acquired the lock and is working for task #9
The thread 0x3fcc has exited with code 0 (0x0).
Thread #8 acquired the lock and is working for task #9
The thread 0xe2c has exited with code 0 (0x0).
Thread #0 acquired the lock and is working for task #4
Thread #3 acquired the lock and is working for task #9
The thread 0x22ec has exited with code 0 (0x0).
Thread #2 acquired the lock and is working for task #2
Thread #7 acquired the lock and is working for task #9
The thread 0x2bfc has exited with code 0 (0x0).
Thread #9 acquired the lock and is working for task #6
Thread #1 acquired the lock and is working for task #2
Thread #0 acquired the lock and is working for task #5
Thread #2 acquired the lock and is working for task #3
Thread #2 acquired the lock and is working for task #4
Thread #9 acquired the lock and is working for task #7
Thread #2 acquired the lock and is working for task #5
Thread #1 acquired the lock and is working for task #3
Thread #0 acquired the lock and is working for task #6
Thread #0 acquired the lock and is working for task #7
Thread #9 acquired the lock and is working for task #8
Thread #2 acquired the lock and is working for task #6
Thread #1 acquired the lock and is working for task #4
Thread #1 acquired the lock and is working for task #5
Thread #0 acquired the lock and is working for task #8
Thread #9 acquired the lock and is working for task #9
The thread 0x1f44 has exited with code 0 (0x0).
Thread #1 acquired the lock and is working for task #6
Thread #2 acquired the lock and is working for task #7
Thread #2 acquired the lock and is working for task #8
Thread #0 acquired the lock and is working for task #9
The thread 0x1fc8 has exited with code 0 (0x0).
Thread #1 acquired the lock and is working for task #7
Thread #1 acquired the lock and is working for task #8
Thread #1 acquired the lock and is working for task #9
The thread 0x2ab0 has exited with code 0 (0x0).
Thread #2 acquired the lock and is working for task #9
The thread 0x2944 has exited with code 0 (0x0).
The thread 0x322c has exited with code 0 (0x0).
The thread 0x146c has exited with code 0 (0x0).
The thread 0x3dcc has exited with code 0 (0x0).
The thread 0x3928 has exited with code 0 (0x0).

I'm not sure, but if I use the Thread.Name, instead Thread.CurrentThread.ManagedThreadId seems to work as you want. It can be that the ManagedThreadId is assigned when the thread start, so it makes sense that the #12 is the last one on the execute, because it is actually the last one.


问:
Turn a page like a Book with UIView?
I am trying to switch between UIViews by making it look like you are turning a page in a book.

The UIViewAnimationTransitionCurlUp is pretty close if I could get it to curl toward the Left or Right. Is this possible?

I have tried to use the CATRansition but none of the animation types come close to a page turning.

Any suggestions on how to create this page animation transition that would turn a page toward the left or right?

答: There's nothing in the SDK that will do this for you. If you want this effect, you'll have to roll your own. "Classics" does a nice job with the page-flip animation.</p>

Title: Turn a page like a Book with UIView?

OwnerDisplayName: August

ContentLicense: CC BY-SA 2.5


问:
simpleXML node access by index prob!em
I am receiving an XML response based on a request I place to a server and it does in fact return a valid set of results that I can dump on the screen using print_r()
Result set looks like this(edit: this is the exact structure of the file):

```<code><root>
     <main_node1>
         <value1>one</value1>
         <value2>two</value2>
     </main_node1>
     <main_node2>
         <anothervalue>whatever</anothervalue>
     </main_node2>
     <recordset>
        <record>
            <value1>one</value1>
            <value2>two</value2>
        </reocrd>
        <record>
            <value1>one</value1>
            <value2>two</value2>
        </reocrd>
        <record>
            <value1>one</value1>
            <value2>two</value2>
        </reocrd>
     </recordset>
</root>
</code>```

when I use the line:

```<code>$xml = simplexml_load_string($xmlRequest);
$records = $xml->recordset->record;
</code>```

I can walk through the $records array with a foreach loop without any problems however, when I try to access a specific record within the recordset using an index such as

```<code>$record = $xml->recordset->record[$index];
</code>```

I am getting a NULL valeu back. I also tried to cast the result into an (array) with no success so far.

Every document I looked at regarding simpleXML says that it is possible to access the XML node by index, can someone please tell me what I might be doing wrong here?

Edit: so recordset is not the root of the document yet I am able to use the $xml->recordset->record notation to load a list of records in to my $records variable and print it out using the foreach loop.

答:
I resolved my issue by using

```<code>$records = $xml->xpath('//record');
</code>```

notation and I am now able to access any record by their index.

Thank you for trying, I appreciate your efforts.

Title: simpleXML node access by index prob!em

Body:
I am receiving an XML response based on a request I place to a server and it does in fact return a valid set of results that I can dump on the screen using print_r()
Result set looks like this(edit: this is the exact structure of the file):

<root>
     <main_node1>
         <value1>one</value1>
         <value2>two</value2>
     </main_node1>
     <main_node2>
         <anothervalue>whatever</anothervalue>
     </main_node2>
     <recordset>
        <record>
            <value1>one</value1>
            <value2>two</value2>
        </reocrd>
        <record>
            <value1>one</value1>
            <value2>two</value2>
        </reocrd>
        <record>
            <value1>one</value1>
            <value2>two</value2>
        </reocrd>
     </recordset>
</root>

when I use the line:

$xml = simplexml_load_string($xmlRequest);
$records = $xml->recordset->record;

I can walk through the $records array with a foreach loop without any problems however, when I try to access a specific record within the recordset using an index such as

$record = $xml->recordset->record[$index];

I am getting a NULL valeu back. I also tried to cast the result into an (array) with no success so far.

Every document I looked at regarding simpleXML says that it is possible to access the XML node by index, can someone please tell me what I might be doing wrong here?

Edit: so recordset is not the root of the document yet I am able to use the $xml->recordset->record notation to load a list of records in to my $records variable and print it out using the foreach loop.

Body:
I resolved my issue by using

$records = $xml->xpath('//record');

notation and I am now able to access any record by their index.

Thank you for trying, I appreciate your efforts.


问:
pyspark 2.2 'DataFrame' object has no attribute 'map' , backward compatibility is missing how to solve it
When I am working with Spark 1.6  below code is working fine:

ddl = sqlContext.sql("""show create table {mytable }""".format(mytable="""mytest.my_dummytable"""))
map(''.join, ddl\
.map(lambda my_row: [str(data).replace("`", "'") for data in my_row])\
.collect())
```

<p>However, when I moved to spark 2.2 I got the following exception:</p>

<pre class="lang-python prettyprint-override"><code>---------------------------------------------------------------------------

AttributeError                            Traceback (most recent call last)
<ipython-> in <module>()
      1 ddl = sqlContext.sql("""show create table {mytable }""".format(mytable ="""mytest.my_dummytable"""))
----> 2 map(''.join, ddl..map(lambda my_row: [str(data).replace("`", "'") for data in my_row]).collect())

spark2/python/pyspark/sql/dataframe.py in __getattr__(self, name)
            if name not in self.columns:
                raise AttributeError(
->                  "'%s' object has no attribute '%s'" % (self.__class__.__name__, name))
            jc = self._jdf.apply(name)
            return Column(jc)

AttributeError: 'DataFrame' object has no attribute 'map'
</code>```

答: You have to call .rdd first. Spark 2.0 stopped aliasing df.map() to df.rdd.map(). See this.

Body:
When I am working with Spark 1.6  below code is working fine:

ddl = sqlContext.sql("""show create table {mytable }""".format(mytable="""mytest.my_dummytable"""))
map(''.join, ddl\
.map(lambda my_row: [str(data).replace("`", "'") for data in my_row])\
.collect())

However, when I moved to spark 2.2 I got the following exception:

---------------------------------------------------------------------------

AttributeError                            Traceback (most recent call last)
<ipython-> in <module>()
      1 ddl = sqlContext.sql("""show create table {mytable }""".format(mytable ="""mytest.my_dummytable"""))
----> 2 map(''.join, ddl..map(lambda my_row: [str(data).replace("`", "'") for data in my_row]).collect())

spark2/python/pyspark/sql/dataframe.py in __getattr__(self, name)
            if name not in self.columns:
                raise AttributeError(
->                  "'%s' object has no attribute '%s'" % (self.__class__.__name__, name))
            jc = self._jdf.apply(name)
            return Column(jc)

AttributeError: 'DataFrame' object has no attribute 'map'


问:
Reshape arrays from MNIST

I am working with the mnist dataset and want to plot some numbers at once. This dataset provides me arrays with the shape (784, ) and represent an image with 28x28 pixels.

Let's say I want to draw 4 numbers in a 2x2 grid. This grid should have the shape (2*28, 2*28). This is the result I want:

```<code>+---+---+
| 0 | 9 |
+---+---+
| 9 | 0 |
+---+---+
</code>```

This here is my code:

```<code>zero # an array from the mnist dataset
nine # another array from the mnist dataset

zero.shape
#(784,)
nine.shape
#(784,)

x = np.stack([zero, nine, zero, nine])
x.shape
# (4, 784)

imshow(x.reshape(2*28, 2*28))
show()
</code>```

This is what I get:

答:
The problem is with the way you are stacking the arrays, and then reshaping. Numpy reshapes arrays by going row-wise. The following code achieves what you want:

```<code>upper_layer = np.append(zero.reshape(28, 28), nine.reshape(28, 28), axis=1)
lower_layer = np.append(nine.reshape(28, 28), zero.reshape(28, 28), axis=1)

layout = np.stack([upper_layer, lower_layer])
plt.imshow(layout.reshape(2*28, 2*28))
</code>```

(I have used randomly generated np arrays since I did not have quick access to the MNIST data)

What your code does:

If you notice very carefully, the two zeros that appear side by side are not identical. What is happening is that the first 28 pixels are the first row of the zero array. The next 28 in the same row are the second row of the zero array. Thus it renders two zeros side by side, where the first (left) one is every even numbered pixel row (0-based index), and the right one is every odd numbered pixel row.

```<code>reshaped = np.stack([zero, nine, zero, nine]).reshape(2*28, 2*28)
plt.imshow(reshaped)
</code>```

Notice how the blue values only reach 14 on the y-axis from the top, this is because it rendered two original (1x28) rows into a single (1x56) row.

Title: Reshape arrays from MNIST

Body:
I am working with the mnist dataset and want to plot some numbers at once. This dataset provides me arrays with the shape (784, ) and represent an image with 28x28 pixels.

Let's say I want to draw 4 numbers in a 2x2 grid. This grid should have the shape (2*28, 2*28). This is the result I want:

+---+---+
| 0 | 9 |
+---+---+
| 9 | 0 |
+---+---+

This here is my code:

zero # an array from the mnist dataset
nine # another array from the mnist dataset

zero.shape
#(784,)
nine.shape
#(784,)

x = np.stack([zero, nine, zero, nine])
x.shape
# (4, 784)

imshow(x.reshape(2*28, 2*28))
show()

This is what I get:

Body:
The problem is with the way you are stacking the arrays, and then reshaping. Numpy reshapes arrays by going row-wise. The following code achieves what you want:

upper_layer = np.append(zero.reshape(28, 28), nine.reshape(28, 28), axis=1)
lower_layer = np.append(nine.reshape(28, 28), zero.reshape(28, 28), axis=1)

layout = np.stack([upper_layer, lower_layer])
plt.imshow(layout.reshape(2*28, 2*28))

(I have used randomly generated np arrays since I did not have quick access to the MNIST data)

What your code does:

If you notice very carefully, the two zeros that appear side by side are not identical. What is happening is that the first 28 pixels are the first row of the zero array. The next 28 in the same row are the second row of the zero array. Thus it renders two zeros side by side, where the first (left) one is every even numbered pixel row (0-based index), and the right one is every odd numbered pixel row.

reshaped = np.stack([zero, nine, zero, nine]).reshape(2*28, 2*28)
plt.imshow(reshaped)

Notice how the blue values only reach 14 on the y-axis from the top, this is because it rendered two original (1x28) rows into a single (1x56) row.


问:
Counting the number of a specific word inside a php string
I have a php string like as follows :

```<code> $string = 'www absjdjjd www123 dkkd www wwww ghy ww';
</code>```

How to count the no. of words just only "www" present in this string.There are two words in this string so result should be 2.
I have tried something like below but not working.

```<code>$val = 'www';
$count = substr_count($string, $val);
</code>```

答:
With regex, which is faster and uses less memory then exploding, looping and counting:</p>

```<code><?php
$string = 'www absjdjjd www123 dkkd www wwww ghy ww';
echo preg_match_all('/\bwww\b/', $string, $matches); // 2
</code>```

Body:
I have a php string like as follows :

 $string = 'www absjdjjd www123 dkkd www wwww ghy ww';

How to count the no. of words just only "www" present in this string.There are two words in this string so result should be 2.
I have tried something like below but not working.

$val = 'www';
$count = substr_count($string, $val);

Body:
With regex, which is faster and uses less memory then exploding, looping and counting:

<?php
$string = 'www absjdjjd www123 dkkd www wwww ghy ww';
echo preg_match_all('/\bwww\b/', $string, $matches); // 2


问:
Better way to test (automatically) a parser?
I’m recently writing a small programming language, and have finished writing its parser. I want to write an automated test for the parser (that its result is an abstract syntax tree), but I’m not sure which way is better.

First what I tried is just to serialize AST to S-expression text and compare it to the expected output text I wrote by hand, but it has some problems:

There are trivial meaningless differences between a serialized text and the expected output like whitespaces. For example, there is no difference between:

```<code>(attribute (symbol str) (symbol length))
</code>```

(that is serialized) and:

```<code>(attribute (symbol str)
           (symbol length))
</code>```

(that is handwritten by me) in their meanings, but string comparison distincts them of course. Okay, I could resolve it by normalization.

When a test fails, it doesn’t show the difference between actual tree and expected tree concisely. I want to show only a difference node, not whole tree.

Second what I tried is to write S-expression parser and compare AST that parser (to be tested) generates to AST that S-expression parser (that I just implemented) generates from the handwritten expected output. However I realized that S-expression have to be tested also and it could be really nonsense.

I wonder what is the typical and easy way to test the parser.

PS. I am using Java, and dont’t want any dependencies to third-party libraries.

答:
Providing you are looking for a completely automated and extensible unit testing framework for your parser I'd recommend the following approach:

Incorrect input

Create a set of samples of incorrect inputs. Then feed the parse with each of them making sure the parser rejects them. I's a good idea to provide metadata for each test case that defines the expected output — the specific error code / message the parser is supposed to produce.

Correct input

As in the previous case, create a set of samples representing various correct inputs. Besides the simple validation that the parser accepts all inputs, there's still the problem of validating that the actual Abstract Syntax Tree makes sense.

To address this problem I'd do the following: Describing the expected AST for each test case in some well-known format that can be safely parsed — deserialized into the actual in-memory AST structures — by a 3rd party parser considered bug-free (for your case). The natural choice is XML since most languages / programming frameworks cover XML support and provide the respective (de)serialization facilities. The best solution would be to deserialize right into the AST node types. Since convenient visual editing tools for XML exist it's feasible to construct even large test cases.

Then I'd construct an AST comparer using the visitor pattern which pair-up the two ASTs and compare both nodes in each pair for equality. However, equality is a per-AST-node-type specific operation.

Notes:

This approach would work with most unit-testing frameworks like JUnit.

AST to XML serialization is a welcome tool for debugging the compiler.

The visitor pattern implementation can easily serve as the backbone for multiple processing stages within the compiler.

There are compiler test suites freely available that can provide some inspiration to your project — see for example the Ada Conformity Assesment Test Suite for the Ada programming language, although this test suite deals with higher-level testing, not just parser testing.

Body:
I’m recently writing a small programming language, and have finished writing its parser. I want to write an automated test for the parser (that its result is an abstract syntax tree), but I’m not sure which way is better.

First what I tried is just to serialize AST to S-expression text and compare it to the expected output text I wrote by hand, but it has some problems:

There are trivial meaningless differences between a serialized text and the expected output like whitespaces. For example, there is no difference between:

(attribute (symbol str) (symbol length))

(that is serialized) and:

(attribute (symbol str)
           (symbol length))

(that is handwritten by me) in their meanings, but string comparison distincts them of course. Okay, I could resolve it by normalization.

When a test fails, it doesn’t show the difference between actual tree and expected tree concisely. I want to show only a difference node, not whole tree.

Second what I tried is to write S-expression parser and compare AST that parser (to be tested) generates to AST that S-expression parser (that I just implemented) generates from the handwritten expected output. However I realized that S-expression have to be tested also and it could be really nonsense.

I wonder what is the typical and easy way to test the parser.

PS. I am using Java, and dont’t want any dependencies to third-party libraries.


问:
FabricDnsService is not preferred DNS server on the node
I had a local cluster of Service Fabric (SDK version 2.6, Windows 10) running successfully.

I have now a new machine (Windows 10 Pro) and installed Service Fabric SDK 2.8.232. Some time (one minute?) after I start/reset the cluster, the System/DnsService has the warning message "FabricDnsService is not preferred DNS server on the node.".

I tried to install another SDK version (2.7, I could not find version 2.6) and I added a firewall rule to make sure it is not blocking SF (port 53 - UDP, which is the endpoint of the System/DnsService replica), but the problem remains.
I installed SDK version 2.1, but my application has a more recent SF version, which made the application fail, and I do not want to downgrade it.

I can deploy my project successfully with SDK 2.8, but I cannot access the API.

I do not see any DNS-specific error on C:\SfDevCluster\Log\Traces.

How can I fix this?

Where can I find a more specified error message?

Is there any known workaround to make my SF application work?

Edit: I just noticed that I can access the API of my application, so it is not blocking me. Anyway, it would be nice to have that warning message removed.

答: This is a known issue, and it will be fixed in a coming release.</p>


问:
change text of active admin has_many_remove button?
How do I change the text on the Remove (the one assigned class 'has_many_remove') button on an active admin f.has_many stanza from 'Remove' to 'Hide'?  Only for the current page/model and not site-wide.</p>

答:
For application-wide change, you just need to add the following inside config/locales/en.yml:

```<code>en:
  active_admin:
    has_many_remove: "Hide"
</code>```

But for page-specific change, you need some help from JS.

p.s. I can update the answer with js solution if you can provide your specific needs.

Body:
For application-wide change, you just need to add the following inside config/locales/en.yml:

en:
  active_admin:
    has_many_remove: "Hide"

But for page-specific change, you need some help from JS.

p.s. I can update the answer with js solution if you can provide your specific needs.


问:
How to count the number of code lines in a C# solution, without comments and empty lines, and other redundant stuff, etc?
By redundant stuff, I mean the namespaces, as I know they are necessary but if there are 10k of them, it doesn't add valuable info to the table.

Could this be done using Linq?

答:
Ctrl+Shift+f (Find in files) -> put ";" in the "Find what:"-textbox -> Press "Find All"-button.

This extremly simple method makes use of the fact, that any C# statement is terminated with a semicolon. And, at least I dont't use semicolons at any other place (e.g. in comments)...


问:
Detecte and delete data if user click go back button in the broswer
I am working an application where each time the user open the page atomatically genrate an id for that page using the database.
 All data is stored with that id when the user click save button (the saving button in a server side ) . But how I can do that, If the user click the go back or close buttons in the brower I want a window appear with some text like "You forget to click save button to save your work , If you leave you will lose your work!". In the same time I want to delete the id if the user did not click save button and leave the page.</p>

答:
```<code><script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

     <script type="text/javascript">
        jQuery(document).ready(function ($) {

            if (window.history && window.history.pushState) {

                window.history.pushState('forward', null, './#forward');

                $(window).on('popstate', function () {
                    alert('hey wait You Clicked Back Button');
                    //your Code here

                });

            }
        });
     </script>
</code>```


问:
How to set crlf endings in QtCreator on linux
I want to set QtCreator to use CRLF instead of LF in unix. Is there a way to do that?

PS: I know I can use dos2unix on the files however I don't want to do that.

答:
It is bug in QtCreator - https://bugreports.qt.io/browse/QTCREATORBUG-3590
May be some one reopen it again.</p>


问:
Re-draw Charts on Resize
After checking the forum I couldn't find anything for the following issue:

I have three charts that are triggered after the user clicks on the below buttons and then, when the window resizes, the chart is drawn again.

```<code>//Calling the different button clicks
      document.getElementById('traffBut').onclick = drawTrafficAndResize;
      document.getElementById('convBut').onclick = drawConversionsAndResize;
      document.getElementById('revBut').onclick = drawRevenueAndResize;
      document.getElementById('tranBut').onclick = drawTransactionsAndResize;

    //functions to draw and then redraw on resize
        function drawTrafficAndResize() {
                drawTraffic();
                resizeMode(drawTraffic);
              }
              function drawConversionsAndResize() {
                drawConversions();
                resizeMode(drawConversions);
                }
                function drawRevenueAndResize() {
                drawRevenue();
                resizeMode(drawRevenue);
                }
                function drawTransactionsAndResize() {
                drawTransactions();
                resizeMode(drawTranctions);
                }
   //And this is the resizing function:
      function resizeMode (metric){
      window.onresize = metric;
                                   }
</code>```

For any reason it works for all buttons with the exception of the last one, if you click the last button which runs drawTransactionsAndResize, it draws the chart triggered by the previous button..

For example if I click the traffic button, and then click the transactions button and then resize the screen, it triggers drawTraffic.

It only happens with this last element, the other buttons run the drawing function and then execute the drawing function again on window resize.

I just can't get my head around this, so any help would be much appreciated,

Many thanks
J.

答:
Torches on me:
 resizeMode(drawTranctions);
should be
 resizeMode(drawTransactions);

Sorry everyone :( and thanks!

Title: Re-draw Charts on Resize

Body:
After checking the forum I couldn't find anything for the following issue:

I have three charts that are triggered after the user clicks on the below buttons and then, when the window resizes, the chart is drawn again.

//Calling the different button clicks
      document.getElementById('traffBut').onclick = drawTrafficAndResize;
      document.getElementById('convBut').onclick = drawConversionsAndResize;
      document.getElementById('revBut').onclick = drawRevenueAndResize;
      document.getElementById('tranBut').onclick = drawTransactionsAndResize;

    //functions to draw and then redraw on resize
        function drawTrafficAndResize() {
                drawTraffic();
                resizeMode(drawTraffic);
              }
              function drawConversionsAndResize() {
                drawConversions();
                resizeMode(drawConversions);
                }
                function drawRevenueAndResize() {
                drawRevenue();
                resizeMode(drawRevenue);
                }
                function drawTransactionsAndResize() {
                drawTransactions();
                resizeMode(drawTranctions);
                }
   //And this is the resizing function:
      function resizeMode (metric){
      window.onresize = metric;
                                   }

For any reason it works for all buttons with the exception of the last one, if you click the last button which runs drawTransactionsAndResize, it draws the chart triggered by the previous button..

For example if I click the traffic button, and then click the transactions button and then resize the screen, it triggers drawTraffic.

It only happens with this last element, the other buttons run the drawing function and then execute the drawing function again on window resize.

I just can't get my head around this, so any help would be much appreciated,

Many thanks
J.


问:
Way to differentiate ActiveRecord::Base.connection mysql joined query result?
My query:

```<code>records = ActiveRecord::Base.connection.execute("SELECT * FROM leads WHERE leads.status=1 AND leads.account_id=1 AND leads.id > 253380")
</code>```

Result:

```<code>    records.first
[253381, 1, "first", "king", "CEO", "Jewelry & Toys", "11111", "22222", nil, nil, nil, nil]

    records.fields
["id", "account_id", "first_name", "last_name", "job_title", "department", "work_number", "mobile_number", "address", "city", "state", "zipcode"]
</code>```

So far all good, but now when I do left join in the query like below:

```<code>records = ActiveRecord::Base.connection.execute("SELECT * FROM leads LEFT JOIN lead_details ON lead_details.id=leads.id AND lead_details.account_id = leads.account_id WHERE leads.status=1 AND leads.account_id=1 AND leads.id > 253380")
</code>```

Result:

```<code>    records.first
[253381, 1, "first", "king", "CEO", "Jewelry & Toys", "11111", "22222", nil, nil, nil, nil, nil, nil, nil, nil]

    records.fields
["id", "account_id", "first_name", "last_name", "job_title", "department", "work_number", "mobile_number", "address", "city", "state", "zipcode", "id", "account_id", "stars", "score"]
</code>```

Note: In the last array "id", "account_id", "stars", "score" are the columns of joined table

When I try to convert the records to hash The second id, account_id will overwrite the first id, account_id and the result will be like this

```<code>{"id"=>nil,
   "account_id"=>nil,
   "first_name"=>"first",
   "last_name"=>"king",
   "job_title"=>"CEO",
   "department"=>"Jewelry & Toys",
   "work_number"=>"11111",
   "mobile_number"=>"22222",
   "address"=>nil,
   "city"=>nil,
   "state"=>nil,
   "zipcode"=>nil,
   "stars"=>nil,
   "score"=>nil
  }
</code>```

How to solve this overwriting of the data? Any way to partition the query result to nested array based on table name or something?

答:
So if I understand it right, the columns from second table overwrites columns from first table.

I would propose not to select the unwanted columns.

You can achieved that by defining in SQL explicitly which columns from second table you want to load: "stars" and "score".

```<code>"SELECT leads.*, lead_details.stars, lead_details.score FROM leads LEFT JOIN lead_details ON lead_details.id=leads.id AND lead_details.account_id = leads.account_id WHERE leads.status=1 AND leads.account_id=1 AND leads.id > 253380"
</code>```

Body:
My query:

records = ActiveRecord::Base.connection.execute("SELECT * FROM leads WHERE leads.status=1 AND leads.account_id=1 AND leads.id > 253380")

Result:

    records.first
[253381, 1, "first", "king", "CEO", "Jewelry & Toys", "11111", "22222", nil, nil, nil, nil]

    records.fields
["id", "account_id", "first_name", "last_name", "job_title", "department", "work_number", "mobile_number", "address", "city", "state", "zipcode"]

So far all good, but now when I do left join in the query like below:

records = ActiveRecord::Base.connection.execute("SELECT * FROM leads LEFT JOIN lead_details ON lead_details.id=leads.id AND lead_details.account_id = leads.account_id WHERE leads.status=1 AND leads.account_id=1 AND leads.id > 253380")

Result:

    records.first
[253381, 1, "first", "king", "CEO", "Jewelry & Toys", "11111", "22222", nil, nil, nil, nil, nil, nil, nil, nil]

    records.fields
["id", "account_id", "first_name", "last_name", "job_title", "department", "work_number", "mobile_number", "address", "city", "state", "zipcode", "id", "account_id", "stars", "score"]

Note: In the last array "id", "account_id", "stars", "score" are the columns of joined table

When I try to convert the records to hash The second id, account_id will overwrite the first id, account_id and the result will be like this

{"id"=>nil,
   "account_id"=>nil,
   "first_name"=>"first",
   "last_name"=>"king",
   "job_title"=>"CEO",
   "department"=>"Jewelry & Toys",
   "work_number"=>"11111",
   "mobile_number"=>"22222",
   "address"=>nil,
   "city"=>nil,
   "state"=>nil,
   "zipcode"=>nil,
   "stars"=>nil,
   "score"=>nil
  }

How to solve this overwriting of the data? Any way to partition the query result to nested array based on table name or something?

Body:
So if I understand it right, the columns from second table overwrites columns from first table.

I would propose not to select the unwanted columns.

You can achieved that by defining in SQL explicitly which columns from second table you want to load: "stars" and "score".

"SELECT leads.*, lead_details.stars, lead_details.score FROM leads LEFT JOIN lead_details ON lead_details.id=leads.id AND lead_details.account_id = leads.account_id WHERE leads.status=1 AND leads.account_id=1 AND leads.id > 253380"


问:
SD card files with encrypted data (_CONSOLE text in it), how to get my files back?
I have an micro SD card, that was in a Galaxy J5 with Android 7, and all the files are messed up now. (jpg, pdf, mp3)

Following characters can be found in the beginning in all of the files, with minor changes in each one.

<ŕ’Ż4i“µŢî      Ś-         `6Sĺş§uť?ŃÖ0Ü]@Î.0€Ň(QlüŚíď¦îRíb_CONSOLE    sżăm:Ń  ..

.. and then a lot of NULLs following.

The _CONSOLE part is there in every file. That's why I think that all files were manipulated with the same method.

I am looking for somebody who has seen this kind of files.

答: Seems the OS has written something along the lines of a table into the start of file/a way to read them. I am pretty sure the data is still there, just not visible. Try opening them via a hex editor and check if the NULL's are really null bytes or unreadable data</p>


问:
Speed up split and write out to file in python
I'm curious if there is a faster way to deal with big text files...
I need to read quite a huge TXT file ( around 40MB :-/ ) which contains data separated by ";", remove the first 10 line as they are informative and not the main data, and then output just the first instance from each line so line[0] after split...

My current code does what it needs to, but it takes forever...

```<code>def remove_lines(input, output):
    lines = open(input).readlines()
    # clean the file before use
    open('output', 'w').close()
    # remove first lines and split by ; then output
    for l in lines[10:]:
        l = l.split(';')
        open(output, 'a').write(l[0] + "\n")
</code>```

Its not like I need to do it often, maybe once a week so I can let it crunch as long as I want, but I'm curious if it can be speed up somehow...

答:
First of all, you shouldn't open your output file in a loop. That would make your OS very unhappy. Then, you only need to split up to the first instance of ";". Splitting by all instances is useless work. There is no need in calling write manually in your case, use the print function instead. and there sure is no need in storing all your data in RAM.

```<code>def remove_lines(input, output):
    with open(output, 'w') as out, open(input) as lines:
        # remove the first 10 lines
        for _ in range(10):
            next(lines)
        for l in map(str.strip, lines):
            print(l.split(";", 1)[0], file=out)
</code>```

Body:
I'm curious if there is a faster way to deal with big text files...
I need to read quite a huge TXT file ( around 40MB :-/ ) which contains data separated by ";", remove the first 10 line as they are informative and not the main data, and then output just the first instance from each line so line[0] after split...

My current code does what it needs to, but it takes forever...

def remove_lines(input, output):
    lines = open(input).readlines()
    # clean the file before use
    open('output', 'w').close()
    # remove first lines and split by ; then output
    for l in lines[10:]:
        l = l.split(';')
        open(output, 'a').write(l[0] + "\n")

Its not like I need to do it often, maybe once a week so I can let it crunch as long as I want, but I'm curious if it can be speed up somehow...

Body:
First of all, you shouldn't open your output file in a loop. That would make your OS very unhappy. Then, you only need to split up to the first instance of ";". Splitting by all instances is useless work. There is no need in calling write manually in your case, use the print function instead. and there sure is no need in storing all your data in RAM.

def remove_lines(input, output):
    with open(output, 'w') as out, open(input) as lines:
        # remove the first 10 lines
        for _ in range(10):
            next(lines)
        for l in map(str.strip, lines):
            print(l.split(";", 1)[0], file=out)


问:
How to interpret aiRadioChannel(1.3.6.1.4.1.14823.2.3.3.1.2.2.1.4) SNMP OID result
I am trying to interpret Aruba AP's radio channels using aiRadioChannel(1.3.6.1.4.1.14823.2.3.3.1.2.2.1.4), which is not understandable in OID's description

```<code>    SNMPv2-SMI::enterprises.x.x.x.x.0 = INTEGER: 1076
    SNMPv2-SMI::enterprises.x.x.x.x.1 = INTEGER: 6
    SNMPv2-SMI::enterprises.x.x.x.x.0 = INTEGER: 1140
    SNMPv2-SMI::enterprises.x.x.x.x.1 = INTEGER: 11
</code>```

I want to derive channel numbers from this SNMP OID.

答:
From [the MIB reference guide] (https://community.arubanetworks.com/aruba/attachments/aruba/IAP/4680/1/Aruba%20Instant%206.3.1.1-4.0%20MIB%20Reference%20Guide.pdf) (this one is for ArubaOs 6.3.1.1-4.0 but it probably doesn't change that often):

aiRadioChannel

Syntax Integer32

Max-Access read-only

Status current

Description Radio channel. The first byte contains primary channel and first two bits of second byte contains indicator for the secondary channel. If first two bits of second byte are 0, it is a 20MHz channel. If first two bits of second byte are 01, the secondary channel is above primary channel, if first two bits of second byte are 10, the secondary channel is below the primary channel.

Does that help you any further?

Body:
I am trying to interpret Aruba AP's radio channels using aiRadioChannel(1.3.6.1.4.1.14823.2.3.3.1.2.2.1.4), which is not understandable in OID's description

    SNMPv2-SMI::enterprises.x.x.x.x.0 = INTEGER: 1076
    SNMPv2-SMI::enterprises.x.x.x.x.1 = INTEGER: 6
    SNMPv2-SMI::enterprises.x.x.x.x.0 = INTEGER: 1140
    SNMPv2-SMI::enterprises.x.x.x.x.1 = INTEGER: 11

I want to derive channel numbers from this SNMP OID.


问:
Use client secret hashed value
I am following this doc http://docs.identityserver.io/en/release/topics/clients.html
which says to create a client with ClientSecrets = "secret".Sha256() and I get the hashed value is of K7gNU3sdo+OL0wNhqoVWhr3g6s1xYv72ol/pe/Unols=

When I try to use the client with the hashed value:
options.ClientSecret = "K7gNU3sdo+OL0wNhqoVWhr3g6s1xYv72ol/pe/Unols=";
I get an error saying "invalid_client".
But If I use options.ClientSecret = "secret"; it works.

How can I use my client with the hashed value?

答:
Hashing is for storage. So when you data store gets compromised, the attacked cannot easily get to the real secrets.

The client sends secrets unhashed.

Title: Use client secret hashed value


问:
How to add data to a Arraylist from a diffrent class
I have seen all the other questions to his topic but I didnt realy get much from it.Just started learning java so pls try to make  the explanation for me as simple as you can.

How do I add to my Arraylist "Fish" anything at all? I coudlnt even add something to it in the same class(line3 class question)... but I need to know how to add it in different a class.(I tried it in the end of class question 2 but it didnt work too)

```<code>import java.util.ArrayList;

public class question {

    private String name;

    public ArrayList<String> Fish = new ArrayList<>();

    Fish.add(name); // <--- this for some reason doesnt work the point is red underlined as well as the ")"

    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }

    public ArrayList<String> getFish() {
        return Fish;
    }
}
</code>```

second class

```<code>public class question2 {

    public String name;

    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }

    // First try : question.getFish().add(nam1);
    // Second try   question.Fish.add(name1);
    //how do I add the name1 into my ArrayList "Fish".How can I transport my ArrayList from question1 to question2?
}
</code>```

Any help will be appreciated, Thank you.

答:
You might expecting this , I just updated your source code

Just copy paste, it should work :

import java.util.ArrayList;

class Question {

 private String name;

 public ArrayList<String> fish;

 public String getName() {
  return name;
 }

 public void setName(String name) {
  this.name = name;
 }

 public ArrayList<String> getFish() {
  return fish;
 }

 public void setFish(ArrayList<String> fish) {
  this.fish = fish;
 }

 public void addToFish(String name) {

  if(this.fish == null){
   this.fish = new ArrayList<>();
  }
  this.fish.add(name);
 }

}```
</div>
</div>
</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>public class Question2 {

 private String name;
 Question question = new Question();

 public String getName() {
     return name;
 }
 public void setName(String name) {
     this.name = name;
 }

  public static void main(String[] args) {

  Question question = new Question();
  question.addToFish("question1");
  question.addToFish("question2");
  question.addToFish("question3");
  question.addToFish("question4");

  for(String fish : question.getFish()){
   System.out.println(fish);
  }
 }

}</code>```

Body:
I have seen all the other questions to his topic but I didnt realy get much from it.Just started learning java so pls try to make  the explanation for me as simple as you can.

How do I add to my Arraylist "Fish" anything at all? I coudlnt even add something to it in the same class(line3 class question)... but I need to know how to add it in different a class.(I tried it in the end of class question 2 but it didnt work too)

import java.util.ArrayList;

public class question {

    private String name;

    public ArrayList<String> Fish = new ArrayList<>();

    Fish.add(name); // <--- this for some reason doesnt work the point is red underlined as well as the ")"

    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }

    public ArrayList<String> getFish() {
        return Fish;
    }
}

second class

public class question2 {

    public String name;

    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }

    // First try : question.getFish().add(nam1);
    // Second try   question.Fish.add(name1);
    //how do I add the name1 into my ArrayList "Fish".How can I transport my ArrayList from question1 to question2?
}

Any help will be appreciated, Thank you.

Body:
You might expecting this , I just updated your source code

Just copy paste, it should work :

import java.util.ArrayList;

class Question {

 private String name;

 public ArrayList<String> fish;

 public String getName() {
  return name;
 }

 public void setName(String name) {
  this.name = name;
 }

 public ArrayList<String> getFish() {
  return fish;
 }

 public void setFish(ArrayList<String> fish) {
  this.fish = fish;
 }

 public void addToFish(String name) {

  if(this.fish == null){
   this.fish = new ArrayList<>();
  }
  this.fish.add(name);
 }

}

public class Question2 {

 private String name;
 Question question = new Question();

 public String getName() {
     return name;
 }
 public void setName(String name) {
     this.name = name;
 }

  public static void main(String[] args) {

  Question question = new Question();
  question.addToFish("question1");
  question.addToFish("question2");
  question.addToFish("question3");
  question.addToFish("question4");

  for(String fish : question.getFish()){
   System.out.println(fish);
  }
 }

}


问:
Why can Android Studio not connect to physical devices?
Up until very recently Android Studio had no problems sending APKs to Android devices over USB. But now, although it works fine with the emulator, I cannot send APKs to either of the two physical devices I have tried.

"adb devices" shows no devices connected, even when the phone is connected over a USB cable (I tried other cables too) and when USB debugging IS enabled on the device.

I have tried revoking USB debugging authorisation on the devices, but on restarting adb and reconnecting the device am not asked to authorise the new access.

I've tried rebooting the phones, rebooting the dev machine (a MacBook) and killing and restarting adb, but with no success. I wonder if a recent Android tools update has reset the USB device auth, but how do I re-auth?

It's a problem as the app I'm working on scans barcodes so I really do need a physical device for testing.

UPDATE 1
Ah, so it seems if a USB device is not authorised, it still shows in the list but marked as such. The devices do not show in the list at all so it seems it is not an authorisation issue.

On a Samsung J5, when it is connected to the MacBook, no notification shows. When a Pixel 2 XL is connected to USB, the phone shows the "USB debugging connected" notification, but adb devices does not list it.

UPDATE 2
On making sure adb is running, then connecting both devices to the MacBook with USB and then running "adb devices", I am seeing this:

List of devices attached
* daemon not running; starting now at tcp:5037
ADB server didn't ACK
Full server startup log: /var/folders/_3/zzf_y_vx2rnc685ysjf1hqr40000gn/T//adb.501.log
Server had pid: 13977
--- adb starting (pid 13977) ---
adb I 12-08 10:10:52 13977 807310 main.cpp:57] Android Debug Bridge version 1.0.39
adb I 12-08 10:10:52 13977 807310 main.cpp:57] Version 27.0.0-4455170
adb I 12-08 10:10:52 13977 807310 main.cpp:57] Installed as /Users/admin/android-sdk/platform-tools/adb
adb I 12-08 10:10:52 13977 807310 main.cpp:57]
adb I 12-08 10:10:52 13977 807310 adb_auth_host.cpp:416] adb_auth_init...
adb I 12-08 10:10:52 13977 807310 adb_auth_host.cpp:174] read_key_file '/Users/admin/.android/adbkey'...
adb F 12-08 10:10:52 13977 807320 transport_usb.cpp:37] Check failed: usb_packet_size < 4096ULL (usb_packet_size=5120, 4096ULL=4096)

failed to start daemon
error: cannot connect to daemon

If I then use kill-server and start-server, adb fails to start, showing the same output.

答: Go to Tools->Android. Uncheck Enable ADB Integration and Run the app sure you will get device suggestions. Once after getting device suggestions again Re-check Enable ADB Integration


问:
View Image via controller function with absolue Path Yii1
I want to View Original Image when i click on thubnail image in gridview.

```<code>$file =  'http://localhost/myapp/upload/item_original/'.$model->image;
$type = 'image/jpg';
header('Content-Type:'.$type);
header('Content-Length: ' . filesize($file));
readfile($file);
</code>```

i tried above code and it didn't work.
then i tried easyimage extension.

```<code>public function actionViewImg($id){
    $model = $this->loadModel($id);
Yii::import('application.extensions.easyimage.EasyImage');
$image = new Image('http://localhost/obhre/upload/item_original/1235.jpg'); //get the image
$image->save('upload/viewimg/1235.jpg');//save it to another folder
echo Yii::app()->easyImage->thumbOf('upload/viewimg/1235.jpg'); //view the image
}
</code>```

above code is working if i put relative path.but not with the absolute path.
error is "Dont have a image"

答:
This code should work:</p>

```<code>public function actionViewImg($id)
{
    $model = $this->loadModel($id);
    $file = 'http://localhost/myapp/upload/item_original/'.$model->image;

    header('Content-Type: image/jpg');
    header('Content-Length: '.filesize($file));
    echo file_get_contents($file);

    exit;
}
</code>```

Body:
I want to View Original Image when i click on thubnail image in gridview.

$file =  'http://localhost/myapp/upload/item_original/'.$model->image;
$type = 'image/jpg';
header('Content-Type:'.$type);
header('Content-Length: ' . filesize($file));
readfile($file);

i tried above code and it didn't work.
then i tried easyimage extension.

public function actionViewImg($id){
    $model = $this->loadModel($id);
Yii::import('application.extensions.easyimage.EasyImage');
$image = new Image('http://localhost/obhre/upload/item_original/1235.jpg'); //get the image
$image->save('upload/viewimg/1235.jpg');//save it to another folder
echo Yii::app()->easyImage->thumbOf('upload/viewimg/1235.jpg'); //view the image
}

above code is working if i put relative path.but not with the absolute path.
error is "Dont have a image"

Body:
This code should work:

public function actionViewImg($id)
{
    $model = $this->loadModel($id);
    $file = 'http://localhost/myapp/upload/item_original/'.$model->image;

    header('Content-Type: image/jpg');
    header('Content-Length: '.filesize($file));
    echo file_get_contents($file);

    exit;
}


问:
gradle file error when i changed recyclerview version from 23.0.1 to 23.2.1
```<code>apply plugin: 'com.android.application'

android {
    compileSdkVersion 23
    buildToolsVersion "25.0.0"
    defaultConfig {
    applicationId "adhoc.mlm_app"
    minSdkVersion 15
    targetSdkVersion 23
    versionCode 4
    versionName "1.0.4"
   testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}
dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
     exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support.constraint:constraint-layout:1.0.2'//getting error

    compile 'com.android.support:appcompat-v7:23.2.1'
    compile 'com.android.support:design:23.0.1'
    compile 'com.squareup.picasso:picasso:2.5.2'
    compile 'com.android.support:cardview-v7:23.2.1'
    compile 'com.android.support:recyclerview-v7:23.2.1'
    testCompile 'junit:junit:4.12'
}
</code>```

All com.android.support libraries must use the exact same version
  specification (mixing versions can lead to runtime crashes). Found
  versions 23.2.1, 23.0.1. Examples include
  com.android.support:animated-vector-drawable:23.2.1 and
  com.android.support:design:23.0.1 )

答:
Use

```<code> compile `'com.android.support:design:23.2.1'`
</code>```

instead of

compile 'com.android.support:design:23.0.1'

Body:
apply plugin: 'com.android.application'

android {
    compileSdkVersion 23
    buildToolsVersion "25.0.0"
    defaultConfig {
    applicationId "adhoc.mlm_app"
    minSdkVersion 15
    targetSdkVersion 23
    versionCode 4
    versionName "1.0.4"
   testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}
dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
     exclude group: 'com.android.support', module: 'support-annotations'
    })
    compile 'com.android.support.constraint:constraint-layout:1.0.2'//getting error

    compile 'com.android.support:appcompat-v7:23.2.1'
    compile 'com.android.support:design:23.0.1'
    compile 'com.squareup.picasso:picasso:2.5.2'
    compile 'com.android.support:cardview-v7:23.2.1'
    compile 'com.android.support:recyclerview-v7:23.2.1'
    testCompile 'junit:junit:4.12'
}

All com.android.support libraries must use the exact same version
  specification (mixing versions can lead to runtime crashes). Found
  versions 23.2.1, 23.0.1. Examples include
  com.android.support:animated-vector-drawable:23.2.1 and
  com.android.support:design:23.0.1 )

Body:
Use

 compile `'com.android.support:design:23.2.1'`

instead of

compile 'com.android.support:design:23.0.1'


问:
php object oriented calculator
Hello im trying to make an object as learning task which takes a number and calculate it three times and echos every step.

```<code><?

// neues Objekt der Klasse erzeugen
$stringManager = new StringManager();

// output String initialisieren
$meinString = "";
$zahl = "100";
$stringManager->setMeinString($meinString);
$stringManager->setZahl($zahl);

// Schritte ausführen
for ($i=1; $i<=3; $i++) {
  $stringManager->machSchritt($i,$zahl);
}

// String ausgeben
echo $stringManager->getMeinString();

// Klasse StringManager
class StringManager {
  var $meinString;
  var $zahl;

  function StringManager() {
  }

  function machSchritt($welchenSchritt,$zahl) {
    switch ($welchenSchritt) {
      case 1:
        $zahl + 50;
        break;
      case 2:
        $zahl / 2;
        break;
      case 3:
        $zahl * 5;
        break;
      default:
        break;
    }
    $this->append("schritt".$welchenSchritt." fertig...");
    $this->append("Zahl:".$zahl." ");
  }

  function append($what) {
    $this->meinString .= $what;
  }
  //function append($what) {
    //$this->zahl .= $what;
  //}
  function setMeinString($value) {
    $this->meinString = $value;
  }

  function getMeinString() {
    return $this->meinString;
  }

  function setZahl($value) {
    $this->zahl = $value;
  }

  function getZahl() {
    return $this->zahl;
  }
}

?>
</code>```

My output is: "schritt1 fertig...Zahl:100 schritt2 fertig...Zahl:100 schritt3 fertig...Zahl:100"

But I expect it to be "schritt1 fertig...Zahl:150 schritt2 fertig...Zahl:75 schritt3 fertig...Zahl:375

Please help me find what im doing wrong.

答:
your problem is between this lines:

```<code>    $zahl + 50;
    break;
  case 2:
    $zahl / 2;
    break;
  case 3:
    $zahl * 5;
</code>```

if you want to increase/manipulate the variable $zahl so you have to use it:

```<code>    $zahl += 50;
    break;
  case 2:
    $zahl /= 2;
    break;
  case 3:
    $zahl *= 5;
</code>```

btw: your code is deprecated.

```<code>class StringManager {
  var $meinString;
  var $zahl;

  function StringManager() {
  }
}
</code>```

should replace with

```<code>class StringManager {
  private $meinString;
  private $zahl;

  public function __construct() {
  }
}
</code>```

update:

ah, now i understand, you need to work with your value.
so use this instead:

```<code>    $this->zahl += 50;
    break;
  case 2:
    $this->zahl /= 2;
    break;
  case 3:
    $this->zahl *= 5;

$this->append("Zahl:".$this->zahl." ");
</code>```

But it would be better, to use your setter (with typecasting) and getter methods.

warning
your code looks like php4 code. php4 is not supported since 2008 (http://php.net/eol.php).

Title: php object oriented calculator

Body:
Hello im trying to make an object as learning task which takes a number and calculate it three times and echos every step.

<?

// neues Objekt der Klasse erzeugen
$stringManager = new StringManager();

// output String initialisieren
$meinString = "";
$zahl = "100";
$stringManager->setMeinString($meinString);
$stringManager->setZahl($zahl);

// Schritte ausführen
for ($i=1; $i<=3; $i++) {
  $stringManager->machSchritt($i,$zahl);
}

// String ausgeben
echo $stringManager->getMeinString();

// Klasse StringManager
class StringManager {
  var $meinString;
  var $zahl;

  function StringManager() {
  }

  function machSchritt($welchenSchritt,$zahl) {
    switch ($welchenSchritt) {
      case 1:
        $zahl + 50;
        break;
      case 2:
        $zahl / 2;
        break;
      case 3:
        $zahl * 5;
        break;
      default:
        break;
    }
    $this->append("schritt".$welchenSchritt." fertig...");
    $this->append("Zahl:".$zahl." ");
  }

  function append($what) {
    $this->meinString .= $what;
  }
  //function append($what) {
    //$this->zahl .= $what;
  //}
  function setMeinString($value) {
    $this->meinString = $value;
  }

  function getMeinString() {
    return $this->meinString;
  }

  function setZahl($value) {
    $this->zahl = $value;
  }

  function getZahl() {
    return $this->zahl;
  }
}

?>

My output is: "schritt1 fertig...Zahl:100 schritt2 fertig...Zahl:100 schritt3 fertig...Zahl:100"

But I expect it to be "schritt1 fertig...Zahl:150 schritt2 fertig...Zahl:75 schritt3 fertig...Zahl:375

Please help me find what im doing wrong.

Body:
your problem is between this lines:

    $zahl + 50;
    break;
  case 2:
    $zahl / 2;
    break;
  case 3:
    $zahl * 5;

if you want to increase/manipulate the variable $zahl so you have to use it:

    $zahl += 50;
    break;
  case 2:
    $zahl /= 2;
    break;
  case 3:
    $zahl *= 5;

btw: your code is deprecated.

class StringManager {
  var $meinString;
  var $zahl;

  function StringManager() {
  }
}

should replace with

class StringManager {
  private $meinString;
  private $zahl;

  public function __construct() {
  }
}

update:

ah, now i understand, you need to work with your value.
so use this instead:

    $this->zahl += 50;
    break;
  case 2:
    $this->zahl /= 2;
    break;
  case 3:
    $this->zahl *= 5;

$this->append("Zahl:".$this->zahl." ");

But it would be better, to use your setter (with typecasting) and getter methods.

warning
your code looks like php4 code. php4 is not supported since 2008 (http://php.net/eol.php).


问:
Updating Master / Details in MVC
I am trying to update a Master / Details relationship. At the moment my code only updates the master table but does not add anything to the details page.
I can add records to both tables fine but I want to be able to update the master and add new entries to the details at the same time.
Screenshots show the data being passed to my Controller.

```<code>    [HttpPost]
    public JsonResult saveEdit(OMR_OrderMaster order)
    {
        bool status = false;

        {
            using (PPPEntities dc = new PPPEntities())
            {
                {

                    db.Entry(order).State = EntityState.Modified;
                    db.SaveChanges();
                    status = true;
                }
            }
        }
        return new JsonResult { Data = new { status = status } };
    }
</code>```

At Present no errors are returned but just the Master tabel is being updated

```<code>namespace PPP2.Models
{
using System;
using System.Collections.Generic;

public partial class OMR_OrderMaster
{
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
    public OMR_OrderMaster()
    {
        this.OMR_OrderDetails = new HashSet<OMR_OrderDetails>();
    }

    public int OrderID { get; set; }
    public string OrderNo { get; set; }
    public System.DateTime OrderDate { get; set; }
    public string Description { get; set; }

    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
    public virtual ICollection<OMR_OrderDetails> OMR_OrderDetails { get; set; }
}
</code>```

}

```<code>namespace PPP2.Models
{
using System;
using System.Collections.Generic;

public partial class OMR_OrderDetails
{
    public int OrderDetialsID { get; set; }
    public int OrderID { get; set; }
    public decimal Rate { get; set; }
    public int Quantity { get; set; }
    public int StockID { get; set; }

    public virtual OMR_OrderMaster OMR_OrderMaster { get; set; }
    }
}
</code>```

答:
Using Attach threw an error but changing to add worked in my case
So, thank you for putting me on the right track</p>

```<code>                foreach (var details in order.OMR_OrderDetails)
                dc.OMR_OrderDetails.Add(details);
                dc.Entry(order).State = EntityState.Modified;
                dc.SaveChanges();
                status = true;
</code>```

Title: Updating Master / Details in MVC

Body:
I am trying to update a Master / Details relationship. At the moment my code only updates the master table but does not add anything to the details page.
I can add records to both tables fine but I want to be able to update the master and add new entries to the details at the same time.
Screenshots show the data being passed to my Controller.

    [HttpPost]
    public JsonResult saveEdit(OMR_OrderMaster order)
    {
        bool status = false;

        {
            using (PPPEntities dc = new PPPEntities())
            {
                {

                    db.Entry(order).State = EntityState.Modified;
                    db.SaveChanges();
                    status = true;
                }
            }
        }
        return new JsonResult { Data = new { status = status } };
    }

At Present no errors are returned but just the Master tabel is being updated

namespace PPP2.Models
{
using System;
using System.Collections.Generic;

public partial class OMR_OrderMaster
{
    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors")]
    public OMR_OrderMaster()
    {
        this.OMR_OrderDetails = new HashSet<OMR_OrderDetails>();
    }

    public int OrderID { get; set; }
    public string OrderNo { get; set; }
    public System.DateTime OrderDate { get; set; }
    public string Description { get; set; }

    [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2227:CollectionPropertiesShouldBeReadOnly")]
    public virtual ICollection<OMR_OrderDetails> OMR_OrderDetails { get; set; }
}

}

namespace PPP2.Models
{
using System;
using System.Collections.Generic;

public partial class OMR_OrderDetails
{
    public int OrderDetialsID { get; set; }
    public int OrderID { get; set; }
    public decimal Rate { get; set; }
    public int Quantity { get; set; }
    public int StockID { get; set; }

    public virtual OMR_OrderMaster OMR_OrderMaster { get; set; }
    }
}

Body:
Using Attach threw an error but changing to add worked in my case
So, thank you for putting me on the right track

                foreach (var details in order.OMR_OrderDetails)
                dc.OMR_OrderDetails.Add(details);
                dc.Entry(order).State = EntityState.Modified;
                dc.SaveChanges();
                status = true;