问:
how to record value via html form into mysql database
I have made a bootstrap contact form but i don't really know how to insert the submitted values into my local database(mysql). Here's my html form:

```<code><!--Contact Section-->
<div id="contact" class="container-fluid bg-grey">
  <h2 class="text-center">CONTACT</h2>
  <div class="row">
    <div class="col-sm-5">
      <p>Contact us and we'll get back to you within 24 hours.</p>
      <p><span class="glyphicon glyphicon-map-marker"></span> Lagos, Nigeria</p>
      <p><span class="glyphicon glyphicon-phone"></span><a href="tel:+2347068613892"> +234 7068613892 </a></p>

    <p><span class="glyphicon glyphicon-envelope"></span><a href="mailto:sparkidea@gmail.com"> Sparkidea@gmail.com </a></p>
    </div>
    <form role="form" id="contactForm" class="contact-form" data-toggle="validator" class="shake">
    <div class="col-sm-7 slideanim" method="post" action="php/mail-core.php">
      <div class="row">
        <div class="col-sm-6 form-group">
            <div class="controls">
                <input class="form-control" id="name" name="name" placeholder="Name" type="text" required required data-error="Please enter your name">
                <div class="help-block with-errors"></div>
            </div>
        </div>
        <div class="col-sm-6 form-group">
            <div class="controls">
                <input class="form-control" id="email" name="email" placeholder="Email" type="email" required required data-error="Please enter your email">
                <div class="help-block with-errors"></div>
            </div>
        </div>
        <div class="col-sm-6 form-group">
            <div class="controls">
                <input type="text" id="msg_subject" class="form-control" placeholder="Subject" required data-error="Please enter your message subject">
                <div class="help-block with-errors"></div>
            </div>
        </div>
        <div class="col-sm-6 form-group">
            <div class="controls">
                <input class="form-control" id="phone" name="phone" placeholder="Phone Number" type="tel" required required data-error="Please enter your Phone Number">
                <div class="help-block with-errors"></div>
            </div>
        </div>
      </div>
        <div class="form-group">
            <div class="controls">
                <textarea class="form-control" id="message" name="message" placeholder="Message" rows="5" required data-error="Write your message"></textarea><br>
                <div class="help-block with-errors"></div>
            </div>
        </div>
        <div class="row">
        <div class="col-sm-12 form-group">
            <button class="btn btn-default pull-right" type="submit" id="submit">Send</button>
            <div id="msgSubmit" class="h3 text-center hidden"></div>
            <div class="clearfix"  style="padding-bottom: 20px;"></div>
        </div>
      </div>
    </div>
    </form>
  </div>
</div>
</code>```

I need help with recording the data inserted into the form above, thanks!

答:
I will use a little form as example but it also works with your form of course.

```<code><form action="post.php" method="POST">
    <input name="login" type="text" />
    <input name="password" type="password" />
    <input type="submit" />
</form>
</code>```

Above there is a form that send its content using the HTTP POST method. It means that you'll be able to get the fields content using the $_POST array in PHP.

post.php

```<code><?php
$login = $_POST['login'];
$password = $_POST['password'];
?>
</code>```

Above there is the post.php file content. When you submit your form, fields content is sent to this file. As you can see, the content of the name attribute is the key in the $_POST array. The input with name = 'login' can be retrieved in $_POST['login']

Body:
I have made a bootstrap contact form but i don't really know how to insert the submitted values into my local database(mysql). Here's my html form:

CONTACT

Contact us and we'll get back to you within 24 hours.

 Lagos, Nigeria

 +234 7068613892

 Sparkidea@gmail.com

    <form role="form" id="contactForm" class="contact-form" data-toggle="validator" class="shake">

                <input class="form-control" id="name" name="name" placeholder="Name" type="text" required required data-error="Please enter your name">

                <input class="form-control" id="email" name="email" placeholder="Email" type="email" required required data-error="Please enter your email">

                <input type="text" id="msg_subject" class="form-control" placeholder="Subject" required data-error="Please enter your message subject">

                <input class="form-control" id="phone" name="phone" placeholder="Phone Number" type="tel" required required data-error="Please enter your Phone Number">

                <textarea class="form-control" id="message" name="message" placeholder="Message" rows="5" required data-error="Write your message"></textarea>

            <button class="btn btn-default pull-right" type="submit" id="submit">Send</button>

    </form>

I need help with recording the data inserted into the form above, thanks!

Body:
I will use a little form as example but it also works with your form of course.

<form action="post.php" method="POST">
    <input name="login" type="text" />
    <input name="password" type="password" />
    <input type="submit" />
</form>

Above there is a form that send its content using the HTTP POST method. It means that you'll be able to get the fields content using the $_POST array in PHP.

post.php

<?php
$login = $_POST['login'];
$password = $_POST['password'];
?>

Above there is the post.php file content. When you submit your form, fields content is sent to this file. As you can see, the content of the name attribute is the key in the $_POST array. The input with name = 'login' can be retrieved in $_POST['login']


来源: stackexchange

问:
Is it reliable to use EventSource to get User's online status?
I have used an EventSource method to get online status of active users on my website.
In this following JavaScript code is inserted in every page

var source = new EventSource("set_online.php");

Thus this code is executing set_online.php file continuously.

On server side i.e. in set_online.php following code executed

```<code>$query = "UPDATE my_db SET last_active = '{$current_time}' WHERE id = {$_SESSION["id"]}";
                $result = mysqli_query($connection, $query);
</code>```

Now I have two concerns about this:

As Database is updating last_active continuously in realtime, will it affect server load?

As connection is open as long as user is on website, will it create vulnerabilities?

答:
Your solution is heavy and unnecessary, a better solution would be to reverse the idea and let the server push user status information to your clients.

You can achieve this by implementing sockets using libraries such as socket.io. It's quite simple to achieve and is a more scalable solution.

Basically, when the page is loaded, a connection will be made between your client and the server and when the server wants to communicate with clients he can simply emit an event such as user-status for example.

Your clients can simply listen to this event and update their views accordingly.

ContentLicense: CC BY-SA 3.0

Body:
I have used an EventSource method to get online status of active users on my website.
In this following JavaScript code is inserted in every page

var source = new EventSource("set_online.php");

Thus this code is executing set_online.php file continuously.

On server side i.e. in set_online.php following code executed

$query = "UPDATE my_db SET last_active = '{$current_time}' WHERE id = {$_SESSION["id"]}";
                $result = mysqli_query($connection, $query);

Now I have two concerns about this:

As Database is updating last_active continuously in realtime, will it affect server load?

As connection is open as long as user is on website, will it create vulnerabilities?


问:
why to import React
I have code which works only after importing React but I'm not using React anywhere I'm using reactDom instead

```<code>import ReactDOM from 'react-dom'
import React, {Component} from 'react'

class App extends Component {
  render () {
    return (
      <div>comp </div>
    )
  }
}

//ReactDOM.render(<App/>, document.getElementById('root'))
ReactDOM.render(<div>sv</div>, document.getElementById('root'))
</code>```

why its require to import React ??

答:
React import is required because the following JSX code:-

```<code>(
   <div>comp </div>
)
</code>```

gets transpiled to

```<code>React.createElement(
  "div",
  null,
  "comp "
);
</code>```

This is the reason you need to import React;
I hope that answers your question.

You can always refer to https://babeljs.io to understand what get's converted to what.

Title: why to import React

Body:
I have code which works only after importing React but I'm not using React anywhere I'm using reactDom instead

import ReactDOM from 'react-dom'
import React, {Component} from 'react'

class App extends Component {
  render () {
    return (

comp

    )
  }
}

//ReactDOM.render(<App/>, document.getElementById('root'))
ReactDOM.render(
sv
, document.getElementById('root'))

why its require to import React ??

Body:
React import is required because the following JSX code:-

(
   <div>comp </div>
)

gets transpiled to

React.createElement(
  "div",
  null,
  "comp "
);

This is the reason you need to import React;
I hope that answers your question.

You can always refer to https://babeljs.io to understand what get's converted to what.


问:
Reading Oracle Explain plan
```<code>explain plan for
    SELECT * FROM schema2.mv_a_data mv
      WHERE mv.routing_code_type_id    = 3
      AND mv.static_data_status_id    IN(5, 8)
      AND mv.acct_currency_ind_id NOT IN
         (SELECT DISTINCT te.acct_currency_ind_id
          FROM schema1.tem_ele te
          WHERE te.lis_tem_id IN
                  (SELECT lis_tem_id
                   FROM schema1.lis_tem
                   WHERE lis_tem.template_type_id = 2
                   AND lis_tem.deleted_flag       = 'N'      )
      AND te.acct_currency_ind_id IS NOT NULL
    )
 ORDER BY mv.treasury_region_code,
          mv.legal_entity_mnemonic,
          mv.currency_code;

 select *
 from TABLE(DBMS_XPLAN.DISPLAY('PLAN_TABLE', null,'ADVANCED'));
</code>```

------------------------------------------------------------------------------------
|  Id  | Operation             | Name      | Rows  | Bytes | Cost (%CPU)| Time     |
------------------------------------------------------------------------------------
|   0 | SELECT STATEMENT       |           |   892 |   318K|    69   (2)| 00:00:01 |
|   1 |  SORT ORDER BY         |           |   892 |   318K|    69   (2)| 00:00:01 |
|*  2 |   HASH JOIN RIGHT ANTI |           |   892 |   318K|    68   (0)| 00:00:01 | `
|   3 |    VIEW                | VW_NSO_1  |  1457 |  8742 |    11  (0) | 00:00:01 |
|*  4 |     HASH JOIN          |           |  1457 | 33511 |    11   (0)| 00:00:01 |
|*  5 |      TABLE ACCESS FULL | lis_tem   |   100 |  1100 |     3   (0)| 00:00:01 |
|*  6 |      TABLE ACCESS FULL | tem_ele   |  3271 | 39252 |     8   (0)| 00:00:01 |
|*  7 |    MAT_VIEW ACCESS FULL| mv_a_data |  2348 |   825K|    57   (0)| 00:00:01 |
```

I am trying to read the given explain plan. After looking at the explain plan and according
    to my understanding, first of all, FTS of LIS_TEM table and TEM_ELE are done and then they are joined using HASH JOIN.

Question 1 - can I change this HASH JOIN to NESTED LOOP?

I am asking just for learning purpose. I know HASH JOIN is good here.
        After HASH JOIN, I guess it is going to ID3 ie VIEW VW_NSO_1 and ID7 MAT_VIEW.

Question 2 - what is this VIEW VW_NSO_1, which clause of the SQL query was responsible to brought it here?

Question 3 - How I will read the rest of the plan?

Question 4 - Why HASH JOIN RIGHT ANTI came in picture?

Please assist me to understand the above explain plan in detail. Thanks and let me know if you need any further details.

答:
The view VW_NSO_1 is your inline view in your query:

```<code>(SELECT DISTINCT te.acct_currency_ind_id
          FROM schema1.tem_ele te
          WHERE te.lis_tem_id IN
                  (SELECT lis_tem_id
                   FROM schema1.lis_tem
                   WHERE lis_tem.template_type_id = 2
                   AND lis_tem.deleted_flag       = 'N'      )
      AND te.acct_currency_ind_id IS NOT NULL
    )
</code>```

The optimiser has converted your "in" clause to a hash join.
It has also converted your "not in" clause to hash join right anti.

All your tables are quite small so full scan is nothing to be concerned about -
the optimiser has probably chosen the best tactic for your data.

Title: Reading Oracle Explain plan

Body:
explain plan for
    SELECT * FROM schema2.mv_a_data mv
      WHERE mv.routing_code_type_id    = 3
      AND mv.static_data_status_id    IN(5, 8)
      AND mv.acct_currency_ind_id NOT IN
         (SELECT DISTINCT te.acct_currency_ind_id
          FROM schema1.tem_ele te
          WHERE te.lis_tem_id IN
                  (SELECT lis_tem_id
                   FROM schema1.lis_tem
                   WHERE lis_tem.template_type_id = 2
                   AND lis_tem.deleted_flag       = 'N'      )
      AND te.acct_currency_ind_id IS NOT NULL
    )
 ORDER BY mv.treasury_region_code,
          mv.legal_entity_mnemonic,
          mv.currency_code;

 select *
 from TABLE(DBMS_XPLAN.DISPLAY('PLAN_TABLE', null,'ADVANCED'));

------------------------------------------------------------------------------------
|  Id  | Operation             | Name      | Rows  | Bytes | Cost (%CPU)| Time     |
------------------------------------------------------------------------------------
|   0 | SELECT STATEMENT       |           |   892 |   318K|    69   (2)| 00:00:01 |
|   1 |  SORT ORDER BY         |           |   892 |   318K|    69   (2)| 00:00:01 |
|*  2 |   HASH JOIN RIGHT ANTI |           |   892 |   318K|    68   (0)| 00:00:01 | `
|   3 |    VIEW                | VW_NSO_1  |  1457 |  8742 |    11  (0) | 00:00:01 |
|*  4 |     HASH JOIN          |           |  1457 | 33511 |    11   (0)| 00:00:01 |
|*  5 |      TABLE ACCESS FULL | lis_tem   |   100 |  1100 |     3   (0)| 00:00:01 |
|*  6 |      TABLE ACCESS FULL | tem_ele   |  3271 | 39252 |     8   (0)| 00:00:01 |
|*  7 |    MAT_VIEW ACCESS FULL| mv_a_data |  2348 |   825K|    57   (0)| 00:00:01 |

I am trying to read the given explain plan. After looking at the explain plan and according
    to my understanding, first of all, FTS of LIS_TEM table and TEM_ELE are done and then they are joined using HASH JOIN.

Question 1 - can I change this HASH JOIN to NESTED LOOP?

I am asking just for learning purpose. I know HASH JOIN is good here.
        After HASH JOIN, I guess it is going to ID3 ie VIEW VW_NSO_1 and ID7 MAT_VIEW.

Question 2 - what is this VIEW VW_NSO_1, which clause of the SQL query was responsible to brought it here?

Question 3 - How I will read the rest of the plan?

Question 4 - Why HASH JOIN RIGHT ANTI came in picture?

Please assist me to understand the above explain plan in detail. Thanks and let me know if you need any further details.

Body:
The view VW_NSO_1 is your inline view in your query:

(SELECT DISTINCT te.acct_currency_ind_id
          FROM schema1.tem_ele te
          WHERE te.lis_tem_id IN
                  (SELECT lis_tem_id
                   FROM schema1.lis_tem
                   WHERE lis_tem.template_type_id = 2
                   AND lis_tem.deleted_flag       = 'N'      )
      AND te.acct_currency_ind_id IS NOT NULL
    )

The optimiser has converted your "in" clause to a hash join.
It has also converted your "not in" clause to hash join right anti.

All your tables are quite small so full scan is nothing to be concerned about -
the optimiser has probably chosen the best tactic for your data.


问:
String array initialization as constructor parameter
In Java, it is completely legal to initialize a String array in the following way:

```<code>String[] s = {"FOO", "BAR"};
</code>```

However, when trying to instantiate a class that takes a String array as a parameter, the following piece of code is NOT allowed:

```<code>Test t = new Test({"test"});
</code>```

But this works again:

```<code>Test t = new Test(new String[] {"test"});
</code>```

Can someone explain why this is?

答: Because Type[] x = { ... } is an initialization syntax for arrays. The { ... } is interpreted in a specific way only in that specific context.

ContentLicense: CC BY-SA 2.5

Body:
In Java, it is completely legal to initialize a String array in the following way:

String[] s = {"FOO", "BAR"};

However, when trying to instantiate a class that takes a String array as a parameter, the following piece of code is NOT allowed:

Test t = new Test({"test"});

But this works again:

Test t = new Test(new String[] {"test"});

Can someone explain why this is?


问:
exporting dataframe into dataframe format to pass as argument into next program
I have certain computations performed on Dataset and I need the result to be stored in external file.

Had it been to CSV, to process it further I'd have to convert again to Dataframe/SFrame, which is again increasing lines of code.

Here's the snippet:

```<code>train_data = graphlab.SFrame(ratings_base)
</code>```

Clearly, it is in SFrame and can be converted to DFrame using

```<code>df_train = train_data.to_dataframe()
</code>```

Now that it is in DFrame, I need it exported to a file without changing it's structure. Since the exported file will be used as Argument to another python code. That code must accept DFrame and not CSV.

I have already check out in place1, place2, place3, place4 and place5

P.S. - I'm still digging for Python serialization, if anyone can simplify

it in the context would be helpful

答:
I'd use HDFS format as it's supported by Pandas and by graphlab.SFrame and beside that HDFS format is very fast.

Alternatively you can export Pandas.DataFrame to Pickle file and read it from another scripts:

```<code>sf.to_dataframe().to_pickle(r'/path/to/pd_frame.pickle')
</code>```

to read it back (from the same or from another script):

```<code>df = pd.read_pickle(r'/path/to/pd_frame.pickle')
</code>```

Body:
I have certain computations performed on Dataset and I need the result to be stored in external file.

Had it been to CSV, to process it further I'd have to convert again to Dataframe/SFrame, which is again increasing lines of code.

Here's the snippet:

train_data = graphlab.SFrame(ratings_base)

Clearly, it is in SFrame and can be converted to DFrame using

df_train = train_data.to_dataframe()

Now that it is in DFrame, I need it exported to a file without changing it's structure. Since the exported file will be used as Argument to another python code. That code must accept DFrame and not CSV.

I have already check out in place1, place2, place3, place4 and place5

P.S. - I'm still digging for Python serialization, if anyone can simplify

it in the context would be helpful

Body:
I'd use HDFS format as it's supported by Pandas and by graphlab.SFrame and beside that HDFS format is very fast.

Alternatively you can export Pandas.DataFrame to Pickle file and read it from another scripts:

sf.to_dataframe().to_pickle(r'/path/to/pd_frame.pickle')

to read it back (from the same or from another script):

df = pd.read_pickle(r'/path/to/pd_frame.pickle')


问:
How to make function with two different parameters taken from the lists?
Well, I wrote this function:

```<code>def hydrostatic_pressure(altitude, density, number_stages, direction):
    i=0
    hydro_pressure=[]
    print(number_stages)
    while i < number_stages:
        if direction[i] == True:    # направление вверх от РО
            hydro_pressure[i]=density*altitude[i]*9.8 # 9.8 - g, константа

        else:
            hydro_pressure[i]=-1*density*altitude[i]*9.8 # вниз от РО
        i +=1
    return hydro_pressure
</code>```

and this is a function call:

```<code>list_hydrostat=hydrostatic_pressure(*scheme[4][5][2], enviroment[2], scheme[4][5][3], *scheme[4][5][1])
</code>```

Where:
*scheme[4][5][2] and *scheme[4][5][1] - list including variable number of elements

I got this error:

```<code>TypeError: hydrostatic_pressure() takes 4 positional arguments but 6 were given
</code>```

So, how to make a correct call?

答: Like Daniel Roseman said, * operator is not required. And also I have mistake in line hydro_pressure[i]=density*altitude[i]*9.8, because hydro_pressure is a empty list without indexes. It is necessary to use generator  hydro_pressure = [i*0 for i in range(0, len(direction))] (direction is a list)

Body:
Well, I wrote this function:

def hydrostatic_pressure(altitude, density, number_stages, direction):
    i=0
    hydro_pressure=[]
    print(number_stages)
    while i < number_stages:
        if direction[i] == True:    # направление вверх от РО
            hydro_pressure[i]=density*altitude[i]*9.8 # 9.8 - g, константа

        else:
            hydro_pressure[i]=-1*density*altitude[i]*9.8 # вниз от РО
        i +=1
    return hydro_pressure

and this is a function call:

list_hydrostat=hydrostatic_pressure(*scheme[4][5][2], enviroment[2], scheme[4][5][3], *scheme[4][5][1])

Where:
*scheme[4][5][2] and *scheme[4][5][1] - list including variable number of elements

I got this error:

TypeError: hydrostatic_pressure() takes 4 positional arguments but 6 were given

So, how to make a correct call?

ContentLicense: CC BY-SA 4.0


问:
CubesViewer Server not always loading cubes
I'm using CubesViewer server on my machine (with linux) and I followed all the instruction on github (https://github.com/jjmontesl/cubesviewer).

I'm using a mysql database to create cubes and they are perfect (using the command "curl", I can see the cubes working and also I can see them using the application) .

The application can work 24/7 but it can't load the cubes after a few hours of usage and I don't know why. The only thing that works is restarting the application but I want to found another solution (easier I hope).

Can someone help me?

答: Thanks to @jjmontes, I added processes: 6 in my environment inside the [server] section of the slicer.ini file and now it's working!


问:
completing a promise without reject/resolve?
I got a custom confirm dialog which waits for user input. I'm wrapping it in a promise.

When the user is choosing the "yes" alternative I resolve the promise.

However, when the user chooses no it's not really an error but more that the next task should not be executed.

How should I handle that scenario with the promise? simply not invoke resolve/reject or is there a better approach?

答:
You could resolve a value and check that value afterwards.</p>

```<code>new Promise((resolve, reject) => {
    const userInput = confirm('Do you want to continue?');
    resolve(userInput);
}).then(input => {
    if(input) {
        // Do something
    } else {
        // Do something else
    }
});
</code>```

Body:
You could resolve a value and check that value afterwards.

new Promise((resolve, reject) => {
    const userInput = confirm('Do you want to continue?');
    resolve(userInput);
}).then(input => {
    if(input) {
        // Do something
    } else {
        // Do something else
    }
});


答:
I typed 192.168.10.4 in UHD:USRP Souurce block.
It isn't correct.
Type addr=192.168.10.4 in the block.
i'm sorry to have caused trouble.</p>

Title: NI USRP-2920 recognized by GNURadio

Body:
I try to operate NI USRP-2920 by GNUradio.
At the first, I typed "uhd_usrp_probe".
Result is below.

[INFO] [UHDlinux; GNU C++ version 4.8.4; Boost_105400; UHD_3.11.0.git-208-g1da86f9c]
[INFO] [USRP2] Opening a USRP2/N-Series device...
[INFO] [USRP2] Current recv frame size: 1472 bytes
[INFO] [USRP2] Current send frame size: 1472 bytes
  _____________________________________________________
 /
|       Device: USRP2 / N-Series Device
|     _____________________________________________________
|    /
|   |       Mboard: N210r4
|   |   hardware: 2577
|   |   product: 30194
|   |   mac-addr: 00:80:2f:19:81:1e
|   |   ip-addr: 192.168.10.4
|   |   subnet: 255.255.255.255
|   |   gateway: 255.255.255.255
|   |   gpsdo: none
|   |   serial: 3077BE9
|   |   FW Version: 12.4
|   |   FPGA Version: 11.1
|   |
|   |   Time sources:  none, external, _external_, mimo
|   |   Clock sources: internal, external, mimo
|   |   Sensors: mimo_locked, ref_locked
|   |     _____________________________________________________
|   |    /
|   |   |       RX DSP: 0
|   |   |
|   |   |   Freq range: -50.000 to 50.000 MHz
|   |     _____________________________________________________
|   |    /
|   |   |       RX DSP: 1
|   |   |
|   |   |   Freq range: -50.000 to 50.000 MHz
|   |     _____________________________________________________
|   |    /
|   |   |       RX Dboard: A
|   |   |   ID: WBX v3, WBX v3 + Simple GDB (0x0057)
|   |   |   Serial: 30733BF
|   |   |     _____________________________________________________
|   |   |    /
|   |   |   |       RX Frontend: 0
|   |   |   |   Name: WBXv3 RX+GDB
|   |   |   |   Antennas: TX/RX, RX2, CAL
|   |   |   |   Sensors: lo_locked
|   |   |   |   Freq range: 68.750 to 2200.000 MHz
|   |   |   |   Gain range PGA0: 0.0 to 31.5 step 0.5 dB
|   |   |   |   Bandwidth range: 40000000.0 to 40000000.0 step 0.0 Hz
|   |   |   |   Connection Type: IQ
|   |   |   |   Uses LO offset: No
|   |   |     _____________________________________________________
|   |   |    /
|   |   |   |       RX Codec: A
|   |   |   |   Name: ads62p44
|   |   |   |   Gain range digital: 0.0 to 6.0 step 0.5 dB
|   |   |   |   Gain range fine: 0.0 to 0.5 step 0.1 dB
|   |     _____________________________________________________
|   |    /
|   |   |       TX DSP: 0
|   |   |
|   |   |   Freq range: -50.000 to 50.000 MHz
|   |     _____________________________________________________
|   |    /
|   |   |       TX Dboard: A
|   |   |   ID: WBX v3 (0x0056)
|   |   |   Serial: 30733BF
|   |   |   ID: WBX + Simple GDB, WBX v3 + Simple GDB, WBX v4 + Simple GDB, WBX-120 + Simple GDB (0x004f)
|   |   |   Serial: F603D5
|   |   |     _____________________________________________________
|   |   |    /
|   |   |   |       TX Frontend: 0
|   |   |   |   Name: WBXv3 TX+GDB
|   |   |   |   Antennas: TX/RX, CAL
|   |   |   |   Sensors: lo_locked
|   |   |   |   Freq range: 68.750 to 2200.000 MHz
|   |   |   |   Gain range PGA0: 0.0 to 31.0 step 1.0 dB
|   |   |   |   Bandwidth range: 40000000.0 to 40000000.0 step 0.0 Hz
|   |   |   |   Connection Type: IQ
|   |   |   |   Uses LO offset: No
|   |   |     _____________________________________________________
|   |   |    /
|   |   |   |       TX Codec: A
|   |   |   |   Name: ad9777
|   |   |   |   Gain Elements: None

In the next, I ran FM radio in GNURadio.
Result is below.

[RuntimeError: LookupError: KeyError: No devices found for ----->
Device Address:
    192.168.10.4:

\[ERROR\] \[UHD\] Device discovery error: unknown key format: 192.168.10.4
\[ERROR\] \[UHD\] Device discovery error: unknown key format: 192.168.10.4
\[ERROR\] \[UHD\] Device discovery error: unknown key format: 192.168.10.4][1]

I can't understand this reason.
Could you tell me any advices?
Thank you.


问:
Staying on no branch after pulling and switching to a branch
I'm trying to switch another branch but I keep staying on a detached head or no branch.

What I tried:

Switch/Checkout:

Getting:

But if I want to commit, I'm still on no branch:

And if I try to pull this branch instead:

I'm getting:

And I'm still on no branch...

How can I actually go back to the portalGraphs branch?

答:
You tried to directly checkout a remote tracked branch. In the git philosophy this is not possible and git checks out a so-called "detached HEAD", i.e., you are not an a branch but the revision will be your HEAD (cf. Why does Git tell me "Not currently on any branch" after I run "git checkout origin/<branch>"?).

When you opened the switch/checkout dialog and you selected the remote branch, the "Create new branch" checkbox was automatically selected. This would create a local branch on the version of the remote branch. See

A quick way to fix this is to go to the switch/checkout dialog and select a local branch, such as master OR select "new branch" on the commit dialog.


问:
Why is FB.UI Share response returning nothing?
I have setup a share popup triggered by Jquery. It works, but I want to use the response value to trigger an AJAX call on success and Facebook only returns an empty array.

Here is the javascript

```

    $("#fb-request").click(function () {
        FB.ui({
            method: 'share',
            name: 'Check out website',
            href: 'URL_TO_SHARE',
        },
        function (response) {
            if (response && !response.error_code) {
              console.log(response); <b>// Returns: []</b>
            }
        });
    });

```

Because of this I can't make the difference between someone who posts and someone who uses the cancel button. Am I missing something here?
Or is there something to setup on the Facebook App?

Thanks,

答:
If the user cancels the share dialog, the response is undefined, so:</p>

```<code>$("#fb-request").click(function () {
    FB.ui({
        method: 'share',
        name: 'Check out website',
        href: 'URL_TO_SHARE',
    },
    function (response) {
        if (response && !response.error_code) {
            if (typeof response != 'undefined'){
                //shered
            }
        }
    });
});
</code>```

Body:
I have setup a share popup triggered by Jquery. It works, but I want to use the response value to trigger an AJAX call on success and Facebook only returns an empty array.

Here is the javascript

    $("#fb-request").click(function () {
        FB.ui({
            method: 'share',
            name: 'Check out website',
            href: 'URL_TO_SHARE',
        },
        function (response) {
            if (response && !response.error_code) {
              console.log(response); // Returns: []
            }
        });
    });

Because of this I can't make the difference between someone who posts and someone who uses the cancel button. Am I missing something here?
Or is there something to setup on the Facebook App?

Thanks,

Body:
If the user cancels the share dialog, the response is undefined, so:

$("#fb-request").click(function () {
    FB.ui({
        method: 'share',
        name: 'Check out website',
        href: 'URL_TO_SHARE',
    },
    function (response) {
        if (response && !response.error_code) {
            if (typeof response != 'undefined'){
                //shered
            }
        }
    });
});


问:
Bolt-CMS keeps logging me out after a period of time
I am using Bolt-CMS in my project and every ten minutes Bolt logs me out from the CMS. Even if I am active and on the root account.

I know I use Bolt version 3.2.13

And that bolt runs on Silex. (with some Symfony components)

And I presume there is a config file for this.

So does anyone know where to find this config file or where I can turn the automatic logout off?

Thanks in advance!

答:
First thing you should do is check the lifetime of your cookie (check the developer toolbar of your browser).

If this does not give a clue, then most likely there is a cron job that deletes your cookie files on the server. This question might be relevant in this scenario.


问:
Dynamic search option in MVC 1.0
I'm looking for a dynamic way to implement search in my MVC 1.0 application.

Let's say that I have a user control containing a textbox, a dropdown and a button. The user will put a query in the textbox, select the column from which to search in the dropdown and then press the search button.

On doing the above activity I want to do this in the model:

```<code>context.MyViewOrTableName.Where(p => (p.ColumnNameFromTheDropdown.Contains(DataFromTheTextbox)));
</code>```

Whether the above scenario is possible in MVC 1.0 and if so then how?
Any help would be appreciated.

Solution:

```<code>context.MyViewOrTableName.Where("" + ColumnNameFromTheDropdown + ".Contains(@0)", DataFromTheTextbox);
</code>```

This happened only after including the namespace System.Linq.Dynamic created by Scott and referred by Omar in the post below.

答:
What you're looking for is a way to build dynamic LINQ queries. You can search for some details about it and the options out there, however, I believe that the Dynamic Linq library that Scott Guthrie wrote is exactly what you're looking for.

It lets you build queries from strings:

```<code>var query =
    db.Customers.
    Where("City = @0 and Orders.Count >= @1", "London", 10).
    OrderBy("CompanyName").
    Select("new(CompanyName as Name, Phone)");
</code>```

Title: Dynamic search option in MVC 1.0

Body:
I'm looking for a dynamic way to implement search in my MVC 1.0 application.

Let's say that I have a user control containing a textbox, a dropdown and a button. The user will put a query in the textbox, select the column from which to search in the dropdown and then press the search button.

On doing the above activity I want to do this in the model:

context.MyViewOrTableName.Where(p => (p.ColumnNameFromTheDropdown.Contains(DataFromTheTextbox)));

Whether the above scenario is possible in MVC 1.0 and if so then how?
Any help would be appreciated.

Solution:

context.MyViewOrTableName.Where("" + ColumnNameFromTheDropdown + ".Contains(@0)", DataFromTheTextbox);

This happened only after including the namespace System.Linq.Dynamic created by Scott and referred by Omar in the post below.

Body:
What you're looking for is a way to build dynamic LINQ queries. You can search for some details about it and the options out there, however, I believe that the Dynamic Linq library that Scott Guthrie wrote is exactly what you're looking for.

It lets you build queries from strings:

var query =
    db.Customers.
    Where("City = @0 and Orders.Count >= @1", "London", 10).
    OrderBy("CompanyName").
    Select("new(CompanyName as Name, Phone)");


问:
How to count every row from select
I want to extract the data from my table and I want to have this result:

```<code>1 Valore
2 Valore
3 Valore
4 Valore
</code>```

So I want to numeration every ROW from 1 to N.

This is my query but not works:

```<code>  SELECT COUNT(DISTINCT dbo.F_ElementStringFromCodeDescription(RR.ID, RR.DisplayName)) AS Count,
         dbo.F_ElementStringFromCodeDescription(RR.ID, RR.DisplayName) AS NAME
    FROM AA_V_PHR_CCD_ResultsObservation R INNER JOIN
         AA_V_PHR_CCD_ResultsObservationXLanguages RR   ON R.ID = RR.ID
   WHERE CodeSystem = '123456789'
GROUP BY dbo.F_ElementStringFromCodeDescription(RR.ID, RR.DisplayName)
</code>```

EDIT

My Database is Tsql

and this is my extract data:

```<code>1 Valore
1 Pippo
1 Pluto
</code>```

Instead of

```<code>1 Valore
2 Pippo
3 Pluto
</code>```

答:
You could do using the rownum function. This would be specific to each DB you are using, but here's an example from oracle:

```<code>Select rownum, <ColumnList> from
       (select <ColumnList> ...)
</code>```

The TSQL documentation says that the equivalent is ROW_NUMBER() function.

For TSQL:

```<code>Select ROW_NUMBER() OVER
   ([PartitionBy] OrderByClause), <ColumnList>...
</code>```

Title: How to count every row from select

Body:
I want to extract the data from my table and I want to have this result:

1 Valore
2 Valore
3 Valore
4 Valore

So I want to numeration every ROW from 1 to N.

This is my query but not works:

  SELECT COUNT(DISTINCT dbo.F_ElementStringFromCodeDescription(RR.ID, RR.DisplayName)) AS Count,
         dbo.F_ElementStringFromCodeDescription(RR.ID, RR.DisplayName) AS NAME
    FROM AA_V_PHR_CCD_ResultsObservation R INNER JOIN
         AA_V_PHR_CCD_ResultsObservationXLanguages RR   ON R.ID = RR.ID
   WHERE CodeSystem = '123456789'
GROUP BY dbo.F_ElementStringFromCodeDescription(RR.ID, RR.DisplayName)

EDIT

My Database is Tsql

and this is my extract data:

1 Valore
1 Pippo
1 Pluto

Instead of

1 Valore
2 Pippo
3 Pluto

Body:
You could do using the rownum function. This would be specific to each DB you are using, but here's an example from oracle:

Select rownum, <ColumnList> from
       (select <ColumnList> ...)

The TSQL documentation says that the equivalent is ROW_NUMBER() function.

For TSQL:

Select ROW_NUMBER() OVER
   ([PartitionBy] OrderByClause), <ColumnList>...


问:
How to storage date interval into MySQL by laravel migration?
I know that:

```<code>Schema::create('xxx', function(Blueprint $table){
        $table->increments('id');
        $table->timestamp('expired_at');
});
</code>```

And I get a MySQL table with a column(expired_at) which storage a time point.

But now I want to storage a time interval(such as, 117 seconds or 3 hours and 43 minutes and so on) into MySQL by laravel migration.

Any suggestion about that task?

答:
As you have mention you want to store 117 seconds or 3 hours and 43 minutes, means you need a column with datatype varchar. So add a new column in table using migration like:

```<code>$table->string('column_name');
</code>```

and then run:

```<code>php artisan migrate
</code>```

or

You can put migrations in more folders and run something like:

```<code>php artisan migrate --path=/app/database/migrations/my_migrations
</code>```

Body:
I know that:

Schema::create('xxx', function(Blueprint $table){
        $table->increments('id');
        $table->timestamp('expired_at');
});

And I get a MySQL table with a column(expired_at) which storage a time point.

But now I want to storage a time interval(such as, 117 seconds or 3 hours and 43 minutes and so on) into MySQL by laravel migration.

Any suggestion about that task?

Body:
As you have mention you want to store 117 seconds or 3 hours and 43 minutes, means you need a column with datatype varchar. So add a new column in table using migration like:

$table->string('column_name');

and then run:

php artisan migrate

or

You can put migrations in more folders and run something like:

php artisan migrate --path=/app/database/migrations/my_migrations


问:
rest_api_init event not fired
I am trying to run custom plugin on wp 4.7.4 . Below is my simple plugin

```<code>add_action( 'rest_api_init', 'register_routes');

function register_routes() {
   register_rest_route( 'taxonomy-manager/v1', '/taxonomies/(P<taxonomy_type>[a-zA-Z]+)', array(
   'methods' => 'GET',
   'callback' => 'get_or_insert'
  ) );
}

function get_or_insert( WP_REST_Request $request ) {

   $parameters = $request->get_params();

   return $parameters;

}
</code>```

When I request wp-json endpoint I see no plugin route there. Plugin was successfully activated. Have I missed something ? Does above plugin (or similar one based on rest_api_init event) works for anybody else ?  Thanks.

答:
Using the latest build I'm not seeing the rest_api_init action being fired. Looks like this code in the plugin.php is always empty and returns, never allowing the rest_api_init action to be fired:</p>

```<code>if ( empty( $GLOBALS['wp']->query_vars['rest_route'] ) ) {
    return;
}
</code>```

Title: rest_api_init event not fired

Body:
I am trying to run custom plugin on wp 4.7.4 . Below is my simple plugin

add_action( 'rest_api_init', 'register_routes');

function register_routes() {
   register_rest_route( 'taxonomy-manager/v1', '/taxonomies/(P<taxonomy_type>[a-zA-Z]+)', array(
   'methods' => 'GET',
   'callback' => 'get_or_insert'
  ) );
}

function get_or_insert( WP_REST_Request $request ) {

   $parameters = $request->get_params();

   return $parameters;

}

When I request wp-json endpoint I see no plugin route there. Plugin was successfully activated. Have I missed something ? Does above plugin (or similar one based on rest_api_init event) works for anybody else ?  Thanks.

Body:
Using the latest build I'm not seeing the rest_api_init action being fired. Looks like this code in the plugin.php is always empty and returns, never allowing the rest_api_init action to be fired:

if ( empty( $GLOBALS['wp']->query_vars['rest_route'] ) ) {
    return;
}


问:
Why compiler don't prevent us, when we try to add duplicate object in Hashset?
As I know HashSet not do not take duplicate object, When I try below code it simply add first one and ignore second one.Why there is no checked Exception for this. How add() is implemented for HashSet?

```<code>public static void main (String[] args) throws java.lang.Exception
{
    HashSet Hs = new HashSet();
    Hs.add("A");
    Hs.add("A");
    System.out.println(Hs);
}
</code>```

OUTPUT- [A]

答:
Checking the duplicate values in the set is the duty of run time but compiler. Compiler does not have any idea on the content of the set while compiling the java code. Hence you won't see any warning, suggestion, etc.

I hope this would answer your question.

Body:
As I know HashSet not do not take duplicate object, When I try below code it simply add first one and ignore second one.Why there is no checked Exception for this. How add() is implemented for HashSet?

public static void main (String[] args) throws java.lang.Exception
{
    HashSet Hs = new HashSet();
    Hs.add("A");
    Hs.add("A");
    System.out.println(Hs);
}

OUTPUT- [A]


问:
Swift protocol inheritance and dynamic object confusion
Trying with here is my setup:

```<code>protocol CommonFeatureProtocol { }
extension CommonFeatureProtocol { }

 protocol SpecificFeature1Protocol : CommonFeatureProtocol {
     func specificFeature1Method()
  }

 protocol SpecificFeature2Protocol : CommonFeatureProtocol {
      func specificFeature2Method()
 }

struct specificFeature1 : SpecificFeature1Protocol { }
struct specificFeature2 : SpecificFeature2Protocol { }
</code>```

Now in one of my other class (UtilFeature), Will it be possible to use feature object and specific feature methods like -

```<code>UtilFeature.feature.specificFeature1Method()
UtilFeature.feature.specificFeature2Method()
</code>```

Something like (in UtilFeature) -

```<code>var feature : CommonFeatureProtocol {
    return specificFeature1() //or specificFeature2()
}
</code>```

答:
Hope I have understood your question correctly

Yes it is possible, consider the following simple example.

```<code>protocol P0 {}
protocol P1 : P0 {}
protocol P2 : P0 {}

class C1 : P1 {}

let p : P0 = C1() //Expects p to be of the type P0
</code>```

Body:
Trying with here is my setup:

protocol CommonFeatureProtocol { }
extension CommonFeatureProtocol { }

 protocol SpecificFeature1Protocol : CommonFeatureProtocol {
     func specificFeature1Method()
  }

 protocol SpecificFeature2Protocol : CommonFeatureProtocol {
      func specificFeature2Method()
 }

struct specificFeature1 : SpecificFeature1Protocol { }
struct specificFeature2 : SpecificFeature2Protocol { }

Now in one of my other class (UtilFeature), Will it be possible to use feature object and specific feature methods like -

UtilFeature.feature.specificFeature1Method()
UtilFeature.feature.specificFeature2Method()

Something like (in UtilFeature) -

var feature : CommonFeatureProtocol {
    return specificFeature1() //or specificFeature2()
}

Body:
Hope I have understood your question correctly

Yes it is possible, consider the following simple example.

protocol P0 {}
protocol P1 : P0 {}
protocol P2 : P0 {}

class C1 : P1 {}

let p : P0 = C1() //Expects p to be of the type P0


问:
What are the best keyboard macros for programming in windows?
I like putting shortcuts of the form "g - google.lnk" in my start menu so google is two keystrokes away. Win, g.

My eight or so most frequent applications go there.

I also make links to my solution files I am always opening "x - Popular Project.lnk"

Are there any better ways to automate opening frequently used applications?

答: I use a lot the "intellisense" snippets in Visual Studio. You can include your own snippets and press double tab when they appear in the list. That's definitely a time saver. </p>

OwnerDisplayName: jeds


问:
How to run a bot created with the help of QnA Maker on the local machine?
(Please note that this FAQ bot is created without any coding with the help of Microsoft QnA Maker and then connecting it to Bot Framework).

I created a FAQ bot on Microsoft Bot Framework with the help of its "no-coding-required" QnA Maker and then registered it on Bot Framework. Now I need to insert Message Endpoint for bot to function. But I am not subscribing to Azure Bot Service or any other hosting service to host the bot as of now. I want to run it on my local Windows machine.

I downloaded Bot Framework Emulator and ran node.js http-server command to its folder, tunneled it with ngrok and put the resultant URL followed by /api/messages (like https://xxxxxxxx.ngrok.io/api/messages) for the message endpoint as well as in Botframework Emulator. But it didn't work. Ngrok gives an error as Bot is remote and tunneling is to my local machine, where software too is needed. But I haven't got the bot software code with me as QnA Maker apparently don't provide it for downloading. So what are the options before me to create a working endpoint for my bot?

Hope my query is clear, if not, please ask me to clarify further. TIA!

答:
How do you want to use your QnA layer?

The QnA Maker page is automatically hosting (for free now but the are looking at the usage) the QnA functionality so you can integrate it in many ways:

using a bot

but also in a classic Asp.Net app

or in many other project types

How?

To use your knowledge base, once you have set it up (and trained), the first step is to publishin https://qnamaker.ai/). You will got this kind of information:

Integration in a bot

You can use the QnA template: https://learn.microsoft.com/en-us/bot-framework/azure/azure-bot-service-template-question-and-answer

It will use a dedicated dialog type called QnAMakerDialog available through NuGet / npm:

For C#, the QnAMaker Dialog is distributed via the
Microsoft.Bot.Builder.CognitiveServices NuGet package.

For Node.js, the QnAMaker Dialog is distributed via the
botbuilder-cognitiveservices npm module.

Here is how you use your parameters from the publish phase: the QnASubscriptionKey and QnAKnowledgebaseId are used in the following sample code:

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Threading;
using Microsoft.Bot.Connector;
using Microsoft.Bot.Builder.Dialogs;
using Microsoft.Bot.Builder.CognitiveServices.QnAMaker;

[Serializable]
public class BasicQnAMakerDialog : QnAMakerDialog
{
    //Parameters to QnAMakerService are:
    //Required: subscriptionKey, knowledgebaseId,
    //Optional: defaultMessage, scoreThreshold[Range 0.0 – 1.0]
    public BasicQnAMakerDialog() : base(new QnAMakerService(new QnAMakerAttribute(Utils.GetAppSetting("QnASubscriptionKey"), Utils.GetAppSetting("QnAKnowledgebaseId"), "No good match in FAQ.", 0.5)))
    {}
}
</code>```

Directly in another projet

As QnA Maker is publishing your QnA knowledge base as a web API, you can directly use it from code with web calls. Here is the link to the API reference: https://qnamaker.ai/Documentation/ApiReference

If you have a look to the methods provided on the API list you will use Generate answer

Body:
How do you want to use your QnA layer?

The QnA Maker page is automatically hosting (for free now but the are looking at the usage) the QnA functionality so you can integrate it in many ways:

using a bot

but also in a classic Asp.Net app

or in many other project types

How?

To use your knowledge base, once you have set it up (and trained), the first step is to publishin https://qnamaker.ai/). You will got this kind of information:

Integration in a bot

You can use the QnA template: https://learn.microsoft.com/en-us/bot-framework/azure/azure-bot-service-template-question-and-answer

It will use a dedicated dialog type called QnAMakerDialog available through NuGet / npm:

For C#, the QnAMaker Dialog is distributed via the
Microsoft.Bot.Builder.CognitiveServices NuGet package.

For Node.js, the QnAMaker Dialog is distributed via the
botbuilder-cognitiveservices npm module.

Here is how you use your parameters from the publish phase: the QnASubscriptionKey and QnAKnowledgebaseId are used in the following sample code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Threading;
using Microsoft.Bot.Connector;
using Microsoft.Bot.Builder.Dialogs;
using Microsoft.Bot.Builder.CognitiveServices.QnAMaker;

[Serializable]
public class BasicQnAMakerDialog : QnAMakerDialog
{
    //Parameters to QnAMakerService are:
    //Required: subscriptionKey, knowledgebaseId,
    //Optional: defaultMessage, scoreThreshold[Range 0.0 – 1.0]
    public BasicQnAMakerDialog() : base(new QnAMakerService(new QnAMakerAttribute(Utils.GetAppSetting("QnASubscriptionKey"), Utils.GetAppSetting("QnAKnowledgebaseId"), "No good match in FAQ.", 0.5)))
    {}
}

Directly in another projet

As QnA Maker is publishing your QnA knowledge base as a web API, you can directly use it from code with web calls. Here is the link to the API reference: https://qnamaker.ai/Documentation/ApiReference

If you have a look to the methods provided on the API list you will use Generate answer


问:
Error Installing React
Whenever I do a npm init then npm install react - I get this error

── UNMET PEER DEPENDENCY react@15.3.0

npm WARN baobab-react@0.1.1 requires a peer of react@>=0.13.0 <1.0.0  but none was installed.

  npm WARN fixed-data-table@0.4.7 requires a
  peer of react@>=0.13.0 <0.15.0 || ^0.14.0-beta3 but none was
  installed.

  npm WARN react-native@0.30.0 requires a peer of
  react@~15.2.0 but none was installed.

  npm WARN react-router@0.13.5
  requires a peer of react@0.13.x||0.14.x but none was installed. npm
  ERR! code 1

This is my node v6.3.0 annd npm 3.10.3 versions.

答:
Inside your project directory, can you please first run the following commands:-</p>

```<code>1) rm -rf node_modules
2) Try installig react again now and other packages which are in your package.json file.
</code>```

Title: Error Installing React

Body:
Inside your project directory, can you please first run the following commands:-

1) rm -rf node_modules
2) Try installig react again now and other packages which are in your package.json file.


问:
How do I avoid a circular reference while serializing Entity Framework class
I have an MVC-3 (RC1) application using Entity Framework 4.

I wish to return a JSON object from a controller action. This object is referenced by other objects, which obviously return the reference.

I thus receive the following circular reference error:

Server Error in '/' Application.

A circular reference was detected
  while serializing an object of type
  'Application.Models.ReferenceObject'.

Description: An unhandled exception
  occurred during the execution of the
  current web request. Please review the
  stack trace for more information about
  the error and where it originated in
  the code.

Exception Details:
  System.InvalidOperationException: A
  circular reference was detected while
  serializing an object of type
  'Application.Models.ReferenceObject'.

NB: Application & ReferenceObject are obviously replacements for the actual namespace / object.

According to Stack Overflow: Circular reference exception when serializing LINQ to SQL classes, this can be overcome using JSON.Net; however I would like to avoid this and instead try to exclude the offending reference properties from the object being serialized.

What do I mean?

I want to do something like this:

```<code>IList<ReferenceObject> list = Repository.GetReferenceObjects();
return Json(list.**<method>**("ObjectsReferencingThis"));
</code>```

where **<method>** is some method that does the opposite to the ObjectQuery(Of T).Include method and ObjectsReferencingThis is the property that is causing the circular reference.

NB: I do not wish to remove these properties or create POCOs as this only affects the Json serialization.

Anyone able to help please?

:)

答:
I had a similar problem when worked on one of my previous project.
Here is what I ended up doing:

```<code>IList<Product> list = Repository.GetProducts();
  var collection = products.Select(product => new
        {
            id = product.Id,
            name = product.Name,
            detailUrl = product.DetailUrl,
            imageLargeUrl = product.ThumbNailUrl,
            tagtitle = product.Name.ToUpper(),
            tagheader = "Words our cherished patrons use to describe this product",
            tagwords = from tag in product.Tags group tag by tag.Name into words select new { name =          words.Key, weight = words.Count() }
        });

 var result = new {id = inquiry.Id, products = collection, };
 return this.Jsonp(result);
</code>```

Here is how the result Json would look like:

```<code>{
"id" : 2,
"products" : [{
    "id" : "3605970008857",
    "name" : "TITLE1",
    "detailUrl" : "http://www.urlhere.com",
    "tagwords" : [{
        "name" : "roses",
        "weight" : 1
    },
    {
        "name" : "cotton",
        "weight" : 1
    },
    {
        "name" : "happy",
        "weight" : 1
    }]
},
{
    "id" : "3605970019891",
    "name" : "TITLE2",
    "detailUrl" : "http://www.urlhere.com",
    "tagwords" : []
}],
</code>```

}

You can also add any other properties from you referenced objects to the result as you wish,to be shown in your Json object :)

Body:
I have an MVC-3 (RC1) application using Entity Framework 4.

I wish to return a JSON object from a controller action. This object is referenced by other objects, which obviously return the reference.

I thus receive the following circular reference error:

Server Error in '/' Application.

A circular reference was detected
  while serializing an object of type
  'Application.Models.ReferenceObject'.

Description: An unhandled exception
  occurred during the execution of the
  current web request. Please review the
  stack trace for more information about
  the error and where it originated in
  the code.

Exception Details:
  System.InvalidOperationException: A
  circular reference was detected while
  serializing an object of type
  'Application.Models.ReferenceObject'.

NB: Application & ReferenceObject are obviously replacements for the actual namespace / object.

According to Stack Overflow: Circular reference exception when serializing LINQ to SQL classes, this can be overcome using JSON.Net; however I would like to avoid this and instead try to exclude the offending reference properties from the object being serialized.

What do I mean?

I want to do something like this:

IList<ReferenceObject> list = Repository.GetReferenceObjects();
return Json(list.**<method>**("ObjectsReferencingThis"));

where **<method>** is some method that does the opposite to the ObjectQuery(Of T).Include method and ObjectsReferencingThis is the property that is causing the circular reference.

NB: I do not wish to remove these properties or create POCOs as this only affects the Json serialization.

Anyone able to help please?

:)

Body:
I had a similar problem when worked on one of my previous project.
Here is what I ended up doing:

IList<Product> list = Repository.GetProducts();
  var collection = products.Select(product => new
        {
            id = product.Id,
            name = product.Name,
            detailUrl = product.DetailUrl,
            imageLargeUrl = product.ThumbNailUrl,
            tagtitle = product.Name.ToUpper(),
            tagheader = "Words our cherished patrons use to describe this product",
            tagwords = from tag in product.Tags group tag by tag.Name into words select new { name =          words.Key, weight = words.Count() }
        });

 var result = new {id = inquiry.Id, products = collection, };
 return this.Jsonp(result);

Here is how the result Json would look like:

{
"id" : 2,
"products" : [{
    "id" : "3605970008857",
    "name" : "TITLE1",
    "detailUrl" : "http://www.urlhere.com",
    "tagwords" : [{
        "name" : "roses",
        "weight" : 1
    },
    {
        "name" : "cotton",
        "weight" : 1
    },
    {
        "name" : "happy",
        "weight" : 1
    }]
},
{
    "id" : "3605970019891",
    "name" : "TITLE2",
    "detailUrl" : "http://www.urlhere.com",
    "tagwords" : []
}],

}

You can also add any other properties from you referenced objects to the result as you wish,to be shown in your Json object :)


问:
React Native: always gradlew clean before run react-native-run-android
If don't run cd android && ./gradlew clean before react-native run-android this fails with some error like:

Failed to create folder: ...

or

Failed to delete folder: ...

so I must run more times again to solve it.

Help me solve it without gradlew clean, please.

Thanks so much.

答: For me, the solution to the problem is to use "watchman" as the file-watcher, as seen here: https://github.com/facebook/react-native/issues/9136#issuecomment-306486102</p>


问:
Django url dispatcher uses strings to specify function, why?
The Django documentation shows examples like this:

```<code>from django.conf.urls import url

from . import views

urlpatterns = [
    url(r'^articles/2003/$', views.special_case_2003),

]
</code>```

However, I have seen some code that looks like this:

```<code>from django.conf.urls import url

urlpatterns = [
    url(r'^articles/2003/$', 'myapp.views.special_case_2003'),

]
</code>```

Where special_case_2003 is the name of a function in myapp/views.py.
What is the difference between these two approaches?

答:
```<code>urlpatterns = [
    url(r'^articles/2003/$', 'myapp.views.special_case_2003'),
]
</code>```

<p>Code like this is out of date. Providing the view as a string like this is deprecated in Django 1.8, and does not work in Django 1.10+. In Django 1.10+, you must use the callable. </p>

Body:
The Django documentation shows examples like this:

from django.conf.urls import url

from . import views

urlpatterns = [
    url(r'^articles/2003/$', views.special_case_2003),

]

However, I have seen some code that looks like this:

from django.conf.urls import url

urlpatterns = [
    url(r'^articles/2003/$', 'myapp.views.special_case_2003'),

]

Where special_case_2003 is the name of a function in myapp/views.py.
What is the difference between these two approaches?

Body:
urlpatterns = [
    url(r'^articles/2003/$', 'myapp.views.special_case_2003'),
]

Code like this is out of date. Providing the view as a string like this is deprecated in Django 1.8, and does not work in Django 1.10+. In Django 1.10+, you must use the callable.


问:
How to open/run YML compose file?
How can I open/run a YML compose file on my computer? I've installed Docker for Windows and Docker tools but couldn't figure out how.</p>

答:
To manage .yml files you have to install and use Docker Compose.

Installation instructions can be found here: https://docs.docker.com/compose/install/

After the installation, go to your docker-compose.yml directory and then execute docker-compose up to create and start services in your docker-compose.yml file.

If you need more information, take a look to Docker Compose docs: https://docs.docker.com/compose

Title: How to open/run YML compose file?


问:
Retrieve an Integer part from a String
I have to use an int value "nid" to work on. But this int value should be an combination of int "did" and String "a"!

```<code>int did = 123456;
String a = "_b";
int nid = Integer.parseInt((did+a).toString());
</code>```

But for this code i get the error message

```<code>java.lang.NumberFormatException: For input string: "123456_b"
</code>```

Is there any way, to convert a combination of int and string to int?

答:
If I understand you correctly, you have a String "123456_b", and you want to retrieve a numeric part of it. Am I right?

In this case, you can use regex - "(d+)[_a-zA-Z]". Let's assume that numeric part ends with underscore character ( _ ). That's why I put it into the regex. I used a group (d+) to catch a numeric part.

```<code>import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main {

    public static void main(String[] args) {
        String str = "1234567_abcde";
        Pattern pattern = Pattern.compile("(\\d+)[_]?[a-zA-Z]");
        Matcher matcher = pattern.matcher(str);
        if (!matcher.find()) {
            System.out.println("Did not find a numeric part.");
            return;
        }

        String numericGroup = matcher.group(1);
        System.out.println(numericGroup);
        int number = Integer.parseInt(numericGroup);
        System.out.println(number);
    }
}
</code>```

Title: Retrieve an Integer part from a String

Body:
I have to use an int value "nid" to work on. But this int value should be an combination of int "did" and String "a"!

int did = 123456;
String a = "_b";
int nid = Integer.parseInt((did+a).toString());

But for this code i get the error message

java.lang.NumberFormatException: For input string: "123456_b"

Is there any way, to convert a combination of int and string to int?

Body:
If I understand you correctly, you have a String "123456_b", and you want to retrieve a numeric part of it. Am I right?

In this case, you can use regex - "(d+)[_a-zA-Z]". Let's assume that numeric part ends with underscore character ( _ ). That's why I put it into the regex. I used a group (d+) to catch a numeric part.

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class Main {

    public static void main(String[] args) {
        String str = "1234567_abcde";
        Pattern pattern = Pattern.compile("(\\d+)[_]?[a-zA-Z]");
        Matcher matcher = pattern.matcher(str);
        if (!matcher.find()) {
            System.out.println("Did not find a numeric part.");
            return;
        }

        String numericGroup = matcher.group(1);
        System.out.println(numericGroup);
        int number = Integer.parseInt(numericGroup);
        System.out.println(number);
    }
}


问:
Protractor if ,else with (expect(condition))
in my script i need to include if and else statement,here is the code

```<code>if((element(by.model('trt_model')).all(by.tagName('option')).get(0).getText()).toEqual('Select Contract'))
{
    element(by.model('trt_model')).get(1).click();
}
else
{
    element(by.model('trt_model')).get(0).click();
}
</code>```

if the expect condition fails , i want the script to execute the else part, but this is not working.
when expect condition fails,the script is not executing the else part

kindly suggest how this can be resolved
Thank you

答:
I have simplified your code and pasted below. You can try this one. Please let me know if you face any error with below code. Hope it will work.</p>

```<code>element(by.model('trt_model')).all(by.tagName('option')).get(0).getText
 ()).then(function(text){
        if(text==='Select Contract')
            element(by.model('trt_model')).get(1).click();
       else
           element(by.model('trt_model')).get(0).click();
});
</code>```

Body:
in my script i need to include if and else statement,here is the code

if((element(by.model('trt_model')).all(by.tagName('option')).get(0).getText()).toEqual('Select Contract'))
{
    element(by.model('trt_model')).get(1).click();
}
else
{
    element(by.model('trt_model')).get(0).click();
}

if the expect condition fails , i want the script to execute the else part, but this is not working.
when expect condition fails,the script is not executing the else part

kindly suggest how this can be resolved
Thank you

Body:
I have simplified your code and pasted below. You can try this one. Please let me know if you face any error with below code. Hope it will work.

element(by.model('trt_model')).all(by.tagName('option')).get(0).getText
 ()).then(function(text){
        if(text==='Select Contract')
            element(by.model('trt_model')).get(1).click();
       else
           element(by.model('trt_model')).get(0).click();
});


问:
ObjC Header-Only Import in Swift: No Such Module error
I've converted an app project from ObjC to Swift. It uses several ObjC frameworks that are managed with Cocoa Pods.

When I try to build it I get an error:

No such module 'Foo'

The Foo file is an ObjC header file that has no .m file. It is used to bind several other classes into one import (in ObjC). here's how the Foo.h would look:

```<code>#import <Foo/FooDefines.h>
#import <Foo/FooToken.h>
#import <Foo/FooAccount.h>
#import <Foo/FooAccountPersistenceInformation.h>
#import <Foo/FooAccountUserInformation.h>
#import <Foo/FooSettings.h>

// Authenticators
#import <Foo/FooAuthenticator.h>
#import <Foo/FooAnonymousAuthenticator.h>
#import <Foo/FooUserPasswordAuthenticator.h>

// UI
#import <Foo/FooViewController.h>
#import <Foo/RLoginDialog.h>
#import <Foo/RLogoutDialog.h>
#import <Foo/RAccountSelectionDialog.h>
#import <Foo/RVerificationDialog.h>
#import <Foo/RBuiltinLogoutActionSheet.h>

// Workflows
#import <Foo/RLoginWorkflow.h>
#import <Foo/RVerificationWorkflow.h>
#import <Foo/RLogoutWorkflow.h>
</code>```

How would I be able to import this successfully in a Swift class to get beyond the compile-time error?

答: Try using #import <Foo/Foo.h> or #import "Foo.h"

Body:
I've converted an app project from ObjC to Swift. It uses several ObjC frameworks that are managed with Cocoa Pods.

When I try to build it I get an error:

No such module 'Foo'

The Foo file is an ObjC header file that has no .m file. It is used to bind several other classes into one import (in ObjC). here's how the Foo.h would look:

#import <Foo/FooDefines.h>
#import <Foo/FooToken.h>
#import <Foo/FooAccount.h>
#import <Foo/FooAccountPersistenceInformation.h>
#import <Foo/FooAccountUserInformation.h>
#import <Foo/FooSettings.h>

// Authenticators
#import <Foo/FooAuthenticator.h>
#import <Foo/FooAnonymousAuthenticator.h>
#import <Foo/FooUserPasswordAuthenticator.h>

// UI
#import <Foo/FooViewController.h>
#import <Foo/RLoginDialog.h>
#import <Foo/RLogoutDialog.h>
#import <Foo/RAccountSelectionDialog.h>
#import <Foo/RVerificationDialog.h>
#import <Foo/RBuiltinLogoutActionSheet.h>

// Workflows
#import <Foo/RLoginWorkflow.h>
#import <Foo/RVerificationWorkflow.h>
#import <Foo/RLogoutWorkflow.h>

How would I be able to import this successfully in a Swift class to get beyond the compile-time error?


问:
Java: How do I get the text of two JLabels when copying JLabel's text with TransferHandler?
How do I get the text of two JLabels when copying JLabel's text with TransferHandler?

Label1111111 How can I keep the text of both JLabels when copied to Label2222222.

For this reason, I will take control of two Jlabel's texts. This shape can only get the text of JLabel, which was first held. Thank you in advance for your help.

```<code>public class deneme2 extends JFrame {

    private static final int COPY = 0;
    private static final int NONE = 0;
    private JPanel contentPane;

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    deneme2 frame = new deneme2();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    public deneme2() {
        JPanel panel= new JPanel();
        MouseListener listener = new DragMouseAdapter();

        JLabel label1 = new JLabel("Label1111111", JLabel.CENTER);
        handlerLabel(label1);
        label1.addMouseListener(listener);
        panel.add(label1);

        JLabel label2 = new JLabel("Label2222222", JLabel.CENTER);
        handlerLabel(label2);
        label2.addMouseListener(listener);
        panel.add(label2);

        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 450, 300);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        contentPane.setLayout(new BorderLayout(0, 0));

        contentPane.add(panel);
        setContentPane(contentPane);
    }

    private void handlerLabel (JLabel lbl)
    {
         lbl.setTransferHandler(new TransferHandler("text") {
                @Override
                protected void exportDone(JComponent source, Transferable data, int action) {
                    if (action == COPY){
                        ((JLabel)lbl.getDropTarget().getDropTargetContext().getComponent()).getText();
                        //((JLabel) source).setText("LabelEmpty");
                        }
                }
            });
    }

    private class DragMouseAdapter extends MouseAdapter
    {
        public void mousePressed(MouseEvent e)
        {
            JComponent comp = (JComponent)e.getSource();
            TransferHandler handler = comp.getTransferHandler();
            handler.exportAsDrag(comp, e, TransferHandler.COPY);
        }
    }
}
</code>```

答:
Maybe in this way. I added inner class MyLabel and console output in your handlerLabel. Ctrl+v this under your main. It will print to console the original String property of each MyLabels.

```<code>    public class MyLabel extends JLabel {
        String original;

        public MyLabel (String text)
        {
            super(text);
            this.original=text;
        }

        public String getOriginal() {
            return original;
        }

        public void setOriginal(String original) {
            this.original = original;
        }

    }
    public deneme2() {
        JPanel panel= new JPanel();
        MouseListener listener = (MouseListener) new DragMouseAdapter();

        MyLabel label1 = new MyLabel("Label1111111");
        handlerLabel(label1);
        label1.addMouseListener(listener);
        panel.add(label1);

        MyLabel label2 = new MyLabel("Label2222222");
        handlerLabel(label2);
        label2.addMouseListener(listener);
        panel.add(label2);

        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 450, 300);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        contentPane.setLayout(new BorderLayout(0, 0));

        contentPane.add(panel);
        setContentPane(contentPane);
    }

        private void handlerLabel(MyLabel lbl) {
        lbl.setTransferHandler(new TransferHandler("text") {
            @Override
            protected void exportDone(JComponent source, Transferable data, int action) {
                if (action == COPY) {
                    System.out.println(((MyLabel) lbl.getDropTarget().getDropTargetContext().getComponent()).getOriginal());
                }
            }
        });
    }
</code>```

Edit: check this out. Ctrl+V this under your main. It will print to console text of source label and text of target label, also the original property. Class MyLabel implements DropTargetListener , which is then registered by new DropTarget(this, this). Then we define what will happen in overriden drop method.

```<code> public class MyLabel extends JLabel implements DropTargetListener {

        String original;

        public MyLabel(String text) {
            super(text);
            this.original = text;

            new DropTarget(this, this);

            this.setTransferHandler(new TransferHandler("text"));

            final MouseListener listener = new MouseAdapter() {
                @Override
                public void mousePressed(final MouseEvent me) {
                    final MyLabel label = (MyLabel) me.getSource();
                    final TransferHandler handler = label.getTransferHandler();
                    handler.exportAsDrag(label, me, TransferHandler.COPY);
                }
            };

            this.addMouseListener(listener);
        }

        public String getOriginal() {
            return original;
        }

        public void setOriginal(String original) {
            this.original = original;
        }

        @Override
        public void dragEnter(DropTargetDragEvent dtde) {

        }

        @Override
        public void dragOver(DropTargetDragEvent dtde) {

        }

        @Override
        public void dropActionChanged(DropTargetDragEvent dtde) {

        }

        @Override
        public void dragExit(DropTargetEvent dte) {

        }

        @Override
        public void drop(DropTargetDropEvent dtde) {
            try {
                final String sourceString = (String) dtde.getTransferable().getTransferData(new DataFlavor("application/x-java-jvm-local-objectref; class=java.lang.String"));
                System.out.println("Source: " + sourceString + " target: " + this.getText());
                this.setText(sourceString);
                System.out.println("Original target: "+this.getOriginal());
            } catch (final UnsupportedFlavorException | IOException | ClassNotFoundException e) {
                e.printStackTrace();
            }
        }

    }

    public deneme2() {
        JPanel panel = new JPanel();
        MyLabel label1 = new MyLabel("Label1111111a");
        panel.add(label1);

        MyLabel label2 = new MyLabel("Label2222222b");
        panel.add(label2);

        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 450, 300);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        contentPane.setLayout(new BorderLayout(0, 0));

        contentPane.add(panel);
        setContentPane(contentPane);
    }
}
</code>```

EDIT2: Following code generates this result see result at the end of this answer:

or

It also prints original property to console. Those could be organised differently (MyLabel, MyLabelTransferable, MyLabelDropTargetListener, MyLabelTransferHandler classes, just to give an idea for future refactoring) but it works in this way too. Consider it a quickfix for your use case.

So main class is this:

```<code> public class Deneme2 extends JFrame {

    private static final int COPY = 0;
    private static final int NONE = 0;

    public static void main(String[] args) {
      Deneme2 mainFrame = new Deneme2();
      SwingUtilities.invokeLater(() -> {//let's get that frame on EDT rollin lambda style:)
          mainFrame.setVisible(true);
      });

    }

    public Deneme2() {
        JPanel panel = new JPanel();
        panel.setLayout(new BorderLayout());
        MyLabel label1 = new MyLabel("Label1111111a");
        panel.add(label1, BorderLayout.WEST);

        MyLabel label2 = new MyLabel("Label2222222b");
        panel.add(label2, BorderLayout.EAST);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setBounds(100, 100, 450, 300);

        panel.setBorder(new EmptyBorder(5, 5, 5, 5));
        this.add(panel);
    }
}
</code>```

Then MyLabel.java :

```<code>    public class MyLabel extends JLabel implements DropTargetListener, Transferable {

    String original;
    protected static final DataFlavor MYLABEL_DATA_FLAVOR = new DataFlavor(DataFlavor.javaJVMLocalObjectMimeType + "; class=\"" + MyLabel.class.getCanonicalName() + "\"",
             "MyLabel label");
    protected static final DataFlavor[] SUPPORTED_FLAVORS = {MYLABEL_DATA_FLAVOR};

    public MyLabel(String text) {
        super(text);
        this.original = text;
        new DropTarget(this, this);
        this.setTransferHandler(new MyLabelTransferHandler()); //here we use our custom TransferHandler
        final MouseListener listener = new MouseAdapter() {
            @Override
            public void mousePressed(final MouseEvent me) {
                final MyLabel label = (MyLabel) me.getSource();
                final TransferHandler handler = label.getTransferHandler();
                handler.exportAsDrag(label, me, TransferHandler.COPY);
            }
        };
        this.addMouseListener(listener);

    }

    public String getOriginal() {
        return original;
    }

    public void setOriginal(String original) {
        this.original = original;
    }

    @Override
    public void dragEnter(DropTargetDragEvent dtde) {
        if (dtde.getTransferable().isDataFlavorSupported(MyLabel.MYLABEL_DATA_FLAVOR)) {
            System.out.println("Drop accept - MyLabel");
            dtde.acceptDrag(DnDConstants.ACTION_COPY_OR_MOVE);
        } else {
            dtde.rejectDrag();
        }
    }

    @Override
    public void dragOver(DropTargetDragEvent dtde) {
        //System.out.println("Drag over");
    }

    @Override
    public void dropActionChanged(DropTargetDragEvent dtde) {
        System.out.println("Action changed");
    }

    @Override
    public void dragExit(DropTargetEvent dte) {
        System.out.println("Exited");

    }

    @Override
    public void drop(DropTargetDropEvent dtde) {
        System.out.println("Drop detected");

        if (dtde.getTransferable().isDataFlavorSupported(MyLabel.MYLABEL_DATA_FLAVOR)) {
            Transferable t = dtde.getTransferable();

            if (t.isDataFlavorSupported(MyLabel.MYLABEL_DATA_FLAVOR)) {
                try {
                    Object transferData = t.getTransferData(MyLabel.MYLABEL_DATA_FLAVOR);

                    if (transferData instanceof MyLabel) {
                        MyLabel mySourceLabel = (MyLabel) transferData;

                        if (!(mySourceLabel.equals(this))) {
                            dtde.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
                            this.setText(mySourceLabel.getText());
                            mySourceLabel.setText("Empty");
                            System.out.println(mySourceLabel.getOriginal() + " " + this.getOriginal());
                        } else {
                            dtde.rejectDrop();
                            System.out.println("Drop rejected - the same MyLabel");
                        }
                    } else {
                        dtde.rejectDrop();
                    }
                } catch (UnsupportedFlavorException | IOException ex) {
                    dtde.rejectDrop();
                }
            } else {
                dtde.rejectDrop();
            }
        }
    }

    @Override
    public DataFlavor[] getTransferDataFlavors() {
        return SUPPORTED_FLAVORS;
    }

    @Override
    public boolean isDataFlavorSupported(DataFlavor flavor) {
        return flavor.equals(MYLABEL_DATA_FLAVOR) || flavor.equals(DataFlavor.stringFlavor);

    }

    @Override
    public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException, IOException {
        if (flavor.equals(MYLABEL_DATA_FLAVOR)) {
            return this;
        } else if (flavor.equals(DataFlavor.stringFlavor)) {
            return this.getText();
        } else {
            throw new UnsupportedFlavorException(flavor);
        }
    }
}
</code>```

And then MyLabelTransferHandler.java :

```<code>public class MyLabelTransferHandler extends TransferHandler {

    @Override
    public boolean canImport(TransferHandler.TransferSupport support) {
        return (support.getComponent() instanceof MyLabel) && support.isDataFlavorSupported(MyLabel.MYLABEL_DATA_FLAVOR);
    }

    @Override
    public boolean importData(JComponent src, Transferable transferable) {
        return src instanceof MyLabel;
    }

    @Override
    public int getSourceActions(JComponent c) {
        return DnDConstants.ACTION_COPY;
    }

    @Override
    protected Transferable createTransferable(JComponent c) {
        Transferable t = (MyLabel)c;
        return t;
    }

    @Override
    protected void exportDone(JComponent source, Transferable data, int action) {
        System.out.println("Export done.");
    }
}
</code>```

After final edit result looks like this:

Little clarification:

```<code>protected static final DataFlavor MYLABEL_DATA_FLAVOR = new DataFlavor(DataFlavor.javaJVMLocalObjectMimeType + "; class=\"" + MyLabel.class.getCanonicalName() + "\"",
             "MyLabel label");
</code>```

in MyLabel. That's important line. This will make getTransferData() return the same instance of MyLabel. If you would do it like:

```<code>protected static final DataFlavor MYLABEL_DATA_FLAVOR = new DataFlavor(MyLabel.class, "MyLabel label");
</code>```

you won't be able to change mySourceLabel text to "Empty" in overridden drop() method, since you would be given a copy of that object.

Also Why shouldn't you extend JFrame and other components? . And you can provide checking for "Empty" text (if getText() returns "Empty", then don't change text in target MyLabel).

Body:
How do I get the text of two JLabels when copying JLabel's text with TransferHandler?

Label1111111 How can I keep the text of both JLabels when copied to Label2222222.

For this reason, I will take control of two Jlabel's texts. This shape can only get the text of JLabel, which was first held. Thank you in advance for your help.

public class deneme2 extends JFrame {

    private static final int COPY = 0;
    private static final int NONE = 0;
    private JPanel contentPane;

    public static void main(String[] args) {
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    deneme2 frame = new deneme2();
                    frame.setVisible(true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    public deneme2() {
        JPanel panel= new JPanel();
        MouseListener listener = new DragMouseAdapter();

        JLabel label1 = new JLabel("Label1111111", JLabel.CENTER);
        handlerLabel(label1);
        label1.addMouseListener(listener);
        panel.add(label1);

        JLabel label2 = new JLabel("Label2222222", JLabel.CENTER);
        handlerLabel(label2);
        label2.addMouseListener(listener);
        panel.add(label2);

        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 450, 300);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        contentPane.setLayout(new BorderLayout(0, 0));

        contentPane.add(panel);
        setContentPane(contentPane);
    }

    private void handlerLabel (JLabel lbl)
    {
         lbl.setTransferHandler(new TransferHandler("text") {
                @Override
                protected void exportDone(JComponent source, Transferable data, int action) {
                    if (action == COPY){
                        ((JLabel)lbl.getDropTarget().getDropTargetContext().getComponent()).getText();
                        //((JLabel) source).setText("LabelEmpty");
                        }
                }
            });
    }

    private class DragMouseAdapter extends MouseAdapter
    {
        public void mousePressed(MouseEvent e)
        {
            JComponent comp = (JComponent)e.getSource();
            TransferHandler handler = comp.getTransferHandler();
            handler.exportAsDrag(comp, e, TransferHandler.COPY);
        }
    }
}

Body:
Maybe in this way. I added inner class MyLabel and console output in your handlerLabel. Ctrl+v this under your main. It will print to console the original String property of each MyLabels.

    public class MyLabel extends JLabel {
        String original;

        public MyLabel (String text)
        {
            super(text);
            this.original=text;
        }

        public String getOriginal() {
            return original;
        }

        public void setOriginal(String original) {
            this.original = original;
        }

    }
    public deneme2() {
        JPanel panel= new JPanel();
        MouseListener listener = (MouseListener) new DragMouseAdapter();

        MyLabel label1 = new MyLabel("Label1111111");
        handlerLabel(label1);
        label1.addMouseListener(listener);
        panel.add(label1);

        MyLabel label2 = new MyLabel("Label2222222");
        handlerLabel(label2);
        label2.addMouseListener(listener);
        panel.add(label2);

        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 450, 300);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        contentPane.setLayout(new BorderLayout(0, 0));

        contentPane.add(panel);
        setContentPane(contentPane);
    }

        private void handlerLabel(MyLabel lbl) {
        lbl.setTransferHandler(new TransferHandler("text") {
            @Override
            protected void exportDone(JComponent source, Transferable data, int action) {
                if (action == COPY) {
                    System.out.println(((MyLabel) lbl.getDropTarget().getDropTargetContext().getComponent()).getOriginal());
                }
            }
        });
    }

Edit: check this out. Ctrl+V this under your main. It will print to console text of source label and text of target label, also the original property. Class MyLabel implements DropTargetListener , which is then registered by new DropTarget(this, this). Then we define what will happen in overriden drop method.

 public class MyLabel extends JLabel implements DropTargetListener {

        String original;

        public MyLabel(String text) {
            super(text);
            this.original = text;

            new DropTarget(this, this);

            this.setTransferHandler(new TransferHandler("text"));

            final MouseListener listener = new MouseAdapter() {
                @Override
                public void mousePressed(final MouseEvent me) {
                    final MyLabel label = (MyLabel) me.getSource();
                    final TransferHandler handler = label.getTransferHandler();
                    handler.exportAsDrag(label, me, TransferHandler.COPY);
                }
            };

            this.addMouseListener(listener);
        }

        public String getOriginal() {
            return original;
        }

        public void setOriginal(String original) {
            this.original = original;
        }

        @Override
        public void dragEnter(DropTargetDragEvent dtde) {

        }

        @Override
        public void dragOver(DropTargetDragEvent dtde) {

        }

        @Override
        public void dropActionChanged(DropTargetDragEvent dtde) {

        }

        @Override
        public void dragExit(DropTargetEvent dte) {

        }

        @Override
        public void drop(DropTargetDropEvent dtde) {
            try {
                final String sourceString = (String) dtde.getTransferable().getTransferData(new DataFlavor("application/x-java-jvm-local-objectref; class=java.lang.String"));
                System.out.println("Source: " + sourceString + " target: " + this.getText());
                this.setText(sourceString);
                System.out.println("Original target: "+this.getOriginal());
            } catch (final UnsupportedFlavorException | IOException | ClassNotFoundException e) {
                e.printStackTrace();
            }
        }

    }

    public deneme2() {
        JPanel panel = new JPanel();
        MyLabel label1 = new MyLabel("Label1111111a");
        panel.add(label1);

        MyLabel label2 = new MyLabel("Label2222222b");
        panel.add(label2);

        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setBounds(100, 100, 450, 300);
        contentPane = new JPanel();
        contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
        contentPane.setLayout(new BorderLayout(0, 0));

        contentPane.add(panel);
        setContentPane(contentPane);
    }
}

EDIT2: Following code generates this result see result at the end of this answer:

or

It also prints original property to console. Those could be organised differently (MyLabel, MyLabelTransferable, MyLabelDropTargetListener, MyLabelTransferHandler classes, just to give an idea for future refactoring) but it works in this way too. Consider it a quickfix for your use case.

So main class is this:

 public class Deneme2 extends JFrame {

    private static final int COPY = 0;
    private static final int NONE = 0;

    public static void main(String[] args) {
      Deneme2 mainFrame = new Deneme2();
      SwingUtilities.invokeLater(() -> {//let's get that frame on EDT rollin lambda style:)
          mainFrame.setVisible(true);
      });

    }

    public Deneme2() {
        JPanel panel = new JPanel();
        panel.setLayout(new BorderLayout());
        MyLabel label1 = new MyLabel("Label1111111a");
        panel.add(label1, BorderLayout.WEST);

        MyLabel label2 = new MyLabel("Label2222222b");
        panel.add(label2, BorderLayout.EAST);
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        this.setBounds(100, 100, 450, 300);

        panel.setBorder(new EmptyBorder(5, 5, 5, 5));
        this.add(panel);
    }
}

Then MyLabel.java :

    public class MyLabel extends JLabel implements DropTargetListener, Transferable {

    String original;
    protected static final DataFlavor MYLABEL_DATA_FLAVOR = new DataFlavor(DataFlavor.javaJVMLocalObjectMimeType + "; class=\"" + MyLabel.class.getCanonicalName() + "\"",
             "MyLabel label");
    protected static final DataFlavor[] SUPPORTED_FLAVORS = {MYLABEL_DATA_FLAVOR};

    public MyLabel(String text) {
        super(text);
        this.original = text;
        new DropTarget(this, this);
        this.setTransferHandler(new MyLabelTransferHandler()); //here we use our custom TransferHandler
        final MouseListener listener = new MouseAdapter() {
            @Override
            public void mousePressed(final MouseEvent me) {
                final MyLabel label = (MyLabel) me.getSource();
                final TransferHandler handler = label.getTransferHandler();
                handler.exportAsDrag(label, me, TransferHandler.COPY);
            }
        };
        this.addMouseListener(listener);

    }

    public String getOriginal() {
        return original;
    }

    public void setOriginal(String original) {
        this.original = original;
    }

    @Override
    public void dragEnter(DropTargetDragEvent dtde) {
        if (dtde.getTransferable().isDataFlavorSupported(MyLabel.MYLABEL_DATA_FLAVOR)) {
            System.out.println("Drop accept - MyLabel");
            dtde.acceptDrag(DnDConstants.ACTION_COPY_OR_MOVE);
        } else {
            dtde.rejectDrag();
        }
    }

    @Override
    public void dragOver(DropTargetDragEvent dtde) {
        //System.out.println("Drag over");
    }

    @Override
    public void dropActionChanged(DropTargetDragEvent dtde) {
        System.out.println("Action changed");
    }

    @Override
    public void dragExit(DropTargetEvent dte) {
        System.out.println("Exited");

    }

    @Override
    public void drop(DropTargetDropEvent dtde) {
        System.out.println("Drop detected");

        if (dtde.getTransferable().isDataFlavorSupported(MyLabel.MYLABEL_DATA_FLAVOR)) {
            Transferable t = dtde.getTransferable();

            if (t.isDataFlavorSupported(MyLabel.MYLABEL_DATA_FLAVOR)) {
                try {
                    Object transferData = t.getTransferData(MyLabel.MYLABEL_DATA_FLAVOR);

                    if (transferData instanceof MyLabel) {
                        MyLabel mySourceLabel = (MyLabel) transferData;

                        if (!(mySourceLabel.equals(this))) {
                            dtde.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE);
                            this.setText(mySourceLabel.getText());
                            mySourceLabel.setText("Empty");
                            System.out.println(mySourceLabel.getOriginal() + " " + this.getOriginal());
                        } else {
                            dtde.rejectDrop();
                            System.out.println("Drop rejected - the same MyLabel");
                        }
                    } else {
                        dtde.rejectDrop();
                    }
                } catch (UnsupportedFlavorException | IOException ex) {
                    dtde.rejectDrop();
                }
            } else {
                dtde.rejectDrop();
            }
        }
    }

    @Override
    public DataFlavor[] getTransferDataFlavors() {
        return SUPPORTED_FLAVORS;
    }

    @Override
    public boolean isDataFlavorSupported(DataFlavor flavor) {
        return flavor.equals(MYLABEL_DATA_FLAVOR) || flavor.equals(DataFlavor.stringFlavor);

    }

    @Override
    public Object getTransferData(DataFlavor flavor) throws UnsupportedFlavorException, IOException {
        if (flavor.equals(MYLABEL_DATA_FLAVOR)) {
            return this;
        } else if (flavor.equals(DataFlavor.stringFlavor)) {
            return this.getText();
        } else {
            throw new UnsupportedFlavorException(flavor);
        }
    }
}

And then MyLabelTransferHandler.java :

public class MyLabelTransferHandler extends TransferHandler {

    @Override
    public boolean canImport(TransferHandler.TransferSupport support) {
        return (support.getComponent() instanceof MyLabel) && support.isDataFlavorSupported(MyLabel.MYLABEL_DATA_FLAVOR);
    }

    @Override
    public boolean importData(JComponent src, Transferable transferable) {
        return src instanceof MyLabel;
    }

    @Override
    public int getSourceActions(JComponent c) {
        return DnDConstants.ACTION_COPY;
    }

    @Override
    protected Transferable createTransferable(JComponent c) {
        Transferable t = (MyLabel)c;
        return t;
    }

    @Override
    protected void exportDone(JComponent source, Transferable data, int action) {
        System.out.println("Export done.");
    }
}

After final edit result looks like this:

Little clarification:

protected static final DataFlavor MYLABEL_DATA_FLAVOR = new DataFlavor(DataFlavor.javaJVMLocalObjectMimeType + "; class=\"" + MyLabel.class.getCanonicalName() + "\"",
             "MyLabel label");

in MyLabel. That's important line. This will make getTransferData() return the same instance of MyLabel. If you would do it like:

protected static final DataFlavor MYLABEL_DATA_FLAVOR = new DataFlavor(MyLabel.class, "MyLabel label");

you won't be able to change mySourceLabel text to "Empty" in overridden drop() method, since you would be given a copy of that object.

Also Why shouldn't you extend JFrame and other components? . And you can provide checking for "Empty" text (if getText() returns "Empty", then don't change text in target MyLabel).


问:
WSO2 Custom Grant Type with customized config properties
I've followed the doc https://docs.wso2.com/display/IS500/Writing+a+Custom+OAuth+2.0+Grant+Type

Now that I created my new Grant Type, I need do make it easy to config to each environment.

How can I add custom properties in a Custom Grant Type?

I need to use those properties to deploy the custom grant_type in distinct environments(production,QA, development, ...) without rebuilding the code.

For example, my Grant Type make a request to a REST Endpoint to validade the credentials, but this endpoint is different for each environment. (rigth now, my custimized grant type have those configuration properties hardcoded)

答:
When you create a project with custom grant_type you can add as many query parameters as you want to your request.

Because of this you can add one custom parameter for your environment and base on this parameter you can add a logic in your custom grant type project to make a separate call to the different REST Endpoints.

In the documentation that you followed a such custom query parameter that I suggest to use is  mobileNumber=0333444

EDIT:

Base on our communication I edit my first response.

You can use  NetworkUtils.getLocalHostname() from org.wso2.carbon.utils jar library which will return HostName property from carbon.xml file.