问:
MVC - Domain Service takes charge of filtering or does Repository Layer?
Should I be filtering my IQueryable results from the Domain Service?

For example... My 3 portals (Websites) access the same Domain Service Layer, depending on the type of user it is, I call a specific repository method and return the result,

Current Repository Layer:

```<code>    IQueryable<Products> GetAllProductsForCrazyUserNow(CrazyUser id);
    Products GetAProductForCrazyUserNow(CrazyUser id,product id);

    IQueryable<Products> GetProductsForNiceUserNow(NiceUser id);
    Products GetProductsForNiceUserNow(NiceUser id,product id);
</code>```

Would it be best just to do this in the Repository Layer:

```<code>    IQueryable<Products> GetAllProducts();
    Products GetAProduct(product id);
</code>```

Then within the Domain Service, I simple do the filter i.e.

```<code>var Niceman = IQueryable<Products> GetAllProducts().Where(u=> u.Name == "Nice");
</code>```

NOTE: I have a read only session and session which includes CRUD within the Repository Layer, so please keep that in mind when answering.

Second question: Should I do any filtering at all in the domain service layer? This very layer is the only layer than can amend the Entity i.e. Product.Price == 25.00; This is not delegated to the repository layer.

答:
I normally use the repository layer to do simple CRUD work and have the domain layer perform any business logic or in your case any filtering that is needed before passing that data back to the UI layer.

Separating out the business/filtering logic from the repository layer will help keep things clean. Also, in the future if you move to a different type of data access pattern, then you won't have to change how that code works since it will be separated in your domain layer.

Body:
Should I be filtering my IQueryable results from the Domain Service?

For example... My 3 portals (Websites) access the same Domain Service Layer, depending on the type of user it is, I call a specific repository method and return the result,

Current Repository Layer:

    IQueryable<Products> GetAllProductsForCrazyUserNow(CrazyUser id);
    Products GetAProductForCrazyUserNow(CrazyUser id,product id);

    IQueryable<Products> GetProductsForNiceUserNow(NiceUser id);
    Products GetProductsForNiceUserNow(NiceUser id,product id);

Would it be best just to do this in the Repository Layer:

    IQueryable<Products> GetAllProducts();
    Products GetAProduct(product id);

Then within the Domain Service, I simple do the filter i.e.

var Niceman = IQueryable<Products> GetAllProducts().Where(u=> u.Name == "Nice");

NOTE: I have a read only session and session which includes CRUD within the Repository Layer, so please keep that in mind when answering.

Second question: Should I do any filtering at all in the domain service layer? This very layer is the only layer than can amend the Entity i.e. Product.Price == 25.00; This is not delegated to the repository layer.


来源: stackexchange

问:
Convert JSON to strongly typed objects
I am getting the following json as a response and I would like to convert it into an object.

```<code>WebSQLRows {
  "_array": Array [
    Object {
      "bmi": 24.7,
      "id": 1,
      "imperialgoalweight": 154.3,
      "imperialheight": 70.9,
      "imperialweight": 176.4,
      "metricgoalweight": 70,
      "metricheight": 180,
      "metricweight": 80,
      "standard": "Metric",
    },
    Object {
      "bmi": 24.7,
      "id": 2,
      "imperialgoalweight": 154.3,
      "imperialheight": 70.9,
      "imperialweight": 176.4,
      "metricgoalweight": 70,
      "metricheight": 180,
      "metricweight": 80,
      "standard": "Metric",
    },
    Object {
      "bmi": 26.2,
      "id": 3,
      "imperialgoalweight": 154.3,
      "imperialheight": 70.9,
      "imperialweight": 187.4,
      "metricgoalweight": 70,
      "metricheight": 180,
      "metricweight": 85,
      "standard": "Metric",
    },
  ],
  "length": 3,
}
</code>```

I tried using JSON.parse() and no luck.
Any ideas as to how this can be done?

答:
The text that you have given is probably what you are getting from console.In such a case,just remove the trailing commas.

Otherwise the text needs to be modified by removing the trailing commas as well as the data types(blue colored words)

The following is the valid JSON :

```<code>{
      "_array":  [
         {
          "bmi": 24.7,
          "id": 1,
          "imperialgoalweight": 154.3,
          "imperialheight": 70.9,
          "imperialweight": 176.4,
          "metricgoalweight": 70,
          "metricheight": 180,
          "metricweight": 80,
          "standard": "Metric"
        },
         {
          "bmi": 24.7,
          "id": 2,
          "imperialgoalweight": 154.3,
          "imperialheight": 70.9,
          "imperialweight": 176.4,
          "metricgoalweight": 70,
          "metricheight": 180,
          "metricweight": 80,
          "standard": "Metric"
        },
         {
          "bmi": 26.2,
          "id": 3,
          "imperialgoalweight": 154.3,
          "imperialheight": 70.9,
          "imperialweight": 187.4,
          "metricgoalweight": 70,
          "metricheight": 180,
          "metricweight": 85,
          "standard": "Metric"
        }
      ],
      "length": 3
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: Convert JSON to strongly typed objects

Body:
I am getting the following json as a response and I would like to convert it into an object.

WebSQLRows {
  "_array": Array [
    Object {
      "bmi": 24.7,
      "id": 1,
      "imperialgoalweight": 154.3,
      "imperialheight": 70.9,
      "imperialweight": 176.4,
      "metricgoalweight": 70,
      "metricheight": 180,
      "metricweight": 80,
      "standard": "Metric",
    },
    Object {
      "bmi": 24.7,
      "id": 2,
      "imperialgoalweight": 154.3,
      "imperialheight": 70.9,
      "imperialweight": 176.4,
      "metricgoalweight": 70,
      "metricheight": 180,
      "metricweight": 80,
      "standard": "Metric",
    },
    Object {
      "bmi": 26.2,
      "id": 3,
      "imperialgoalweight": 154.3,
      "imperialheight": 70.9,
      "imperialweight": 187.4,
      "metricgoalweight": 70,
      "metricheight": 180,
      "metricweight": 85,
      "standard": "Metric",
    },
  ],
  "length": 3,
}

I tried using JSON.parse() and no luck.
Any ideas as to how this can be done?

Body:
The text that you have given is probably what you are getting from console.In such a case,just remove the trailing commas.

Otherwise the text needs to be modified by removing the trailing commas as well as the data types(blue colored words)

The following is the valid JSON :

{
      "_array":  [
         {
          "bmi": 24.7,
          "id": 1,
          "imperialgoalweight": 154.3,
          "imperialheight": 70.9,
          "imperialweight": 176.4,
          "metricgoalweight": 70,
          "metricheight": 180,
          "metricweight": 80,
          "standard": "Metric"
        },
         {
          "bmi": 24.7,
          "id": 2,
          "imperialgoalweight": 154.3,
          "imperialheight": 70.9,
          "imperialweight": 176.4,
          "metricgoalweight": 70,
          "metricheight": 180,
          "metricweight": 80,
          "standard": "Metric"
        },
         {
          "bmi": 26.2,
          "id": 3,
          "imperialgoalweight": 154.3,
          "imperialheight": 70.9,
          "imperialweight": 187.4,
          "metricgoalweight": 70,
          "metricheight": 180,
          "metricweight": 85,
          "standard": "Metric"
        }
      ],
      "length": 3
}


问:
How to do when selecting select option toggleClass not force close
I made a button that works to select the number of passengers with the select option. but there was a problem when I selected the number of passengers force close.

How to do when selecting passenger numbers is not force close.

Thanks in advance

I've put his code on > https://jsfiddle.net/devefrontend/vaqdsmjk/1/

$(document).ready(function() {
  $(".btn-passenger").on('click', function(e) {
    $(".passenger-box").toggleClass("s");
    e.stopPropagation();
  });
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.btn-passenger {
  background-color: #eee;
  display: inline-block;
  height: 45px;
  cursor: pointer;
}

.passenger-box.s {
  visibility: visible;
  opacity: 1;
  transition: all .3s ease;
}

.passenger-box {
  padding: 10px 20px;
  background-color: #fff;
  border: 1px solid #eee;
  border-bottom-left-radius: 5px;
  border-bottom-right-radius: 5px;
  margin-top: 7px;
  position: relative;
  z-index: 99;
  opacity: 0;
  visibility: hidden;
}</code>```

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

  0 click button

    Dewasa 12+ Thn
    <select name="adult" id="adult" class="form-control passenger">
      <option selected="selected">1</option>
      <option>2</option>
      <option>3</option>
      <option>4</option>
      <option>5</option>
      <option>6</option>
    </select>
    Anak 2-12 Thn
    <select name="child" id="child" class="form-control passenger">
      <option>0</option>
      <option>1</option>
      <option>2</option>
      <option>3</option>
      <option>4</option>
      <option>5</option>
      <option>6</option>
    </select>
    Bayi
      < 2 Thn
        <select name="infant" id="infant" class="form-control passenger">
          <option>0</option>
          <option>1</option>
          <option>2</option>
          <option>3</option>
          <option>4</option>
          <option>5</option>
          <option>6</option>
        </select>

```

答:
I would suggest making the clickable area smaller, preferably a button to be accessible (clickable div is not accessible to keyboards for example).

See this example: https://jsfiddle.net/negzoqca/

Alternatively you could check if user is clicking the passenger-box or one of its children and if so not toggle the class. Like this:

https://jsfiddle.net/e0yjb5Lw/

Body:
I made a button that works to select the number of passengers with the select option. but there was a problem when I selected the number of passengers force close.

How to do when selecting passenger numbers is not force close.

Thanks in advance

I've put his code on > https://jsfiddle.net/devefrontend/vaqdsmjk/1/

$(document).ready(function() {
  $(".btn-passenger").on('click', function(e) {
    $(".passenger-box").toggleClass("s");
    e.stopPropagation();
  });
});

.btn-passenger {
  background-color: #eee;
  display: inline-block;
  height: 45px;
  cursor: pointer;
}

.passenger-box.s {
  visibility: visible;
  opacity: 1;
  transition: all .3s ease;
}

.passenger-box {
  padding: 10px 20px;
  background-color: #fff;
  border: 1px solid #eee;
  border-bottom-left-radius: 5px;
  border-bottom-right-radius: 5px;
  margin-top: 7px;
  position: relative;
  z-index: 99;
  opacity: 0;
  visibility: hidden;
}

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>

  0 click button

    Dewasa 12+ Thn
    <select name="adult" id="adult" class="form-control passenger">
      <option selected="selected">1</option>
      <option>2</option>
      <option>3</option>
      <option>4</option>
      <option>5</option>
      <option>6</option>
    </select>
    Anak 2-12 Thn
    <select name="child" id="child" class="form-control passenger">
      <option>0</option>
      <option>1</option>
      <option>2</option>
      <option>3</option>
      <option>4</option>
      <option>5</option>
      <option>6</option>
    </select>
    Bayi
      < 2 Thn
        <select name="infant" id="infant" class="form-control passenger">
          <option>0</option>
          <option>1</option>
          <option>2</option>
          <option>3</option>
          <option>4</option>
          <option>5</option>
          <option>6</option>
        </select>


问:
How to add one inner join Instead of 3 inner joins
In here I'm trying to inner join SEARCHED_TAGS table and USER table. Here I use same join in three times. Not only this below I use this query many times. Is it cause to slow down the query & how can I write this query one time instead of 3 times.

Below you can see Query.

```<code>(
 select st.SEARCH_TEXT as SEARCH_TEXT
 from SEARCHED_TAGS st
 inner join USER usr
 on st.SEARCH_BY=usr.USER_ID
 where (st.SEARCH_TEXT like :tagText) and (st.SEARCH_BY = :userId) and (usr.DEP_ID = :userDep)
 order by st.SEARCH_TIME desc
 limit 2
)
UNION
(
 select st.SEARCH_TEXT as SEARCH_TEXT
 from SEARCHED_TAGS st
 inner join USER usr
 on st.SEARCH_BY = usr.USER_ID
 where (st.SEARCH_TEXT like :tagText) and not (st.SEARCH_BY = :userId) and (usr.DEP_ID = :userDep)
 order by st.SEARCH_TIME desc
 limit 2
)
UNION
(
 select st.SEARCH_TEXT as SEARCH_TEXT
 from SEARCHED_TAGS st
 inner join USER usr
 on st.SEARCH_BY= usr.USER_ID
 where (st.SEARCH_TEXT like :tagText) and not (st.SEARCH_BY = :userId) and not (usr.DEP_ID = :userDep)
 order by st.SEARCH_TIME desc
 limit 2
)
</code>```

Can I write like this instead of above.

```<code>inner join USER usr
on st.SEARCH_BY=usr.USER_ID
(
 select st.SEARCH_TEXT as SEARCH_TEXT
 from SEARCHED_TAGS st
 where (st.SEARCH_TEXT like :tagText) and (st.SEARCH_BY = :userId) and (usr.DEP_ID = :userDep)
 order by st.SEARCH_TIME desc
 limit 2
)
UNION
(
 select st.SEARCH_TEXT as SEARCH_TEXT
 from SEARCHED_TAGS st
 where (st.SEARCH_TEXT like :tagText) and not (st.SEARCH_BY = :userId) and (usr.DEP_ID = :userDep)
 order by st.SEARCH_TIME desc
 limit 2
)
UNION
(
 select st.SEARCH_TEXT as SEARCH_TEXT
 from SEARCHED_TAGS st
 where (st.SEARCH_TEXT like :tagText) and not (st.SEARCH_BY = :userId) and not (usr.DEP_ID = :userDep)
 order by st.SEARCH_TIME desc
 limit 2
)
</code>```

Thanks..

答:
Because of the limit statements, this might be the best you can do with ordinary MySQL.  But using session variables we can do slightly better:

```<code>SELECT SEARCH_TEXT
FROM
(
    SELECT SEARCH_TEXT, grp,
        (@num:=if(@group = grp, @num +1, if(@group := grp, 1, 1))) row_number
    FROM
    (
        SELECT
            st.SEARCH_TEXT as SEARCH_TEXT,
            st.SEARCH_TIME,
            CASE WHEN (st.SEARCH_TEXT like :tagText) AND (st.SEARCH_BY = :userId) AND
                      (usr.DEP_ID = :userDep) THEN 1
                 WHEN (st.SEARCH_TEXT like :tagText) AND NOT (st.SEARCH_BY = :userId) AND
                      (usr.DEP_ID = :userDep) THEN 2
                 WHEN (st.SEARCH_TEXT like :tagText) AND NOT (st.SEARCH_BY = :userId) AND NOT
                      (usr.DEP_ID = :userDep) THEN 3
                 ELSE 4 END AS grp
        FROM SEARCHED_TAGS st
        INNER JOIN USER usr
            ON st.SEARCH_BY = usr.USER_ID
    ) t1
    CROSS JOIN (select @num:=0, @group:=null) t2
    ORDER BY grp, t1.SEARCH_TIME DESC
) t
WHERE
    t.row_number <= 2 AND
    t.grp <= 3;
</code>```

This code is untested, mainly because your query is too complex for easy testing, but I can iterate with you if you encounter any problems.

Body:
In here I'm trying to inner join SEARCHED_TAGS table and USER table. Here I use same join in three times. Not only this below I use this query many times. Is it cause to slow down the query & how can I write this query one time instead of 3 times.

Below you can see Query.

(
 select st.SEARCH_TEXT as SEARCH_TEXT
 from SEARCHED_TAGS st
 inner join USER usr
 on st.SEARCH_BY=usr.USER_ID
 where (st.SEARCH_TEXT like :tagText) and (st.SEARCH_BY = :userId) and (usr.DEP_ID = :userDep)
 order by st.SEARCH_TIME desc
 limit 2
)
UNION
(
 select st.SEARCH_TEXT as SEARCH_TEXT
 from SEARCHED_TAGS st
 inner join USER usr
 on st.SEARCH_BY = usr.USER_ID
 where (st.SEARCH_TEXT like :tagText) and not (st.SEARCH_BY = :userId) and (usr.DEP_ID = :userDep)
 order by st.SEARCH_TIME desc
 limit 2
)
UNION
(
 select st.SEARCH_TEXT as SEARCH_TEXT
 from SEARCHED_TAGS st
 inner join USER usr
 on st.SEARCH_BY= usr.USER_ID
 where (st.SEARCH_TEXT like :tagText) and not (st.SEARCH_BY = :userId) and not (usr.DEP_ID = :userDep)
 order by st.SEARCH_TIME desc
 limit 2
)

Can I write like this instead of above.

inner join USER usr
on st.SEARCH_BY=usr.USER_ID
(
 select st.SEARCH_TEXT as SEARCH_TEXT
 from SEARCHED_TAGS st
 where (st.SEARCH_TEXT like :tagText) and (st.SEARCH_BY = :userId) and (usr.DEP_ID = :userDep)
 order by st.SEARCH_TIME desc
 limit 2
)
UNION
(
 select st.SEARCH_TEXT as SEARCH_TEXT
 from SEARCHED_TAGS st
 where (st.SEARCH_TEXT like :tagText) and not (st.SEARCH_BY = :userId) and (usr.DEP_ID = :userDep)
 order by st.SEARCH_TIME desc
 limit 2
)
UNION
(
 select st.SEARCH_TEXT as SEARCH_TEXT
 from SEARCHED_TAGS st
 where (st.SEARCH_TEXT like :tagText) and not (st.SEARCH_BY = :userId) and not (usr.DEP_ID = :userDep)
 order by st.SEARCH_TIME desc
 limit 2
)

Thanks..

Body:
Because of the limit statements, this might be the best you can do with ordinary MySQL.  But using session variables we can do slightly better:

SELECT SEARCH_TEXT
FROM
(
    SELECT SEARCH_TEXT, grp,
        (@num:=if(@group = grp, @num +1, if(@group := grp, 1, 1))) row_number
    FROM
    (
        SELECT
            st.SEARCH_TEXT as SEARCH_TEXT,
            st.SEARCH_TIME,
            CASE WHEN (st.SEARCH_TEXT like :tagText) AND (st.SEARCH_BY = :userId) AND
                      (usr.DEP_ID = :userDep) THEN 1
                 WHEN (st.SEARCH_TEXT like :tagText) AND NOT (st.SEARCH_BY = :userId) AND
                      (usr.DEP_ID = :userDep) THEN 2
                 WHEN (st.SEARCH_TEXT like :tagText) AND NOT (st.SEARCH_BY = :userId) AND NOT
                      (usr.DEP_ID = :userDep) THEN 3
                 ELSE 4 END AS grp
        FROM SEARCHED_TAGS st
        INNER JOIN USER usr
            ON st.SEARCH_BY = usr.USER_ID
    ) t1
    CROSS JOIN (select @num:=0, @group:=null) t2
    ORDER BY grp, t1.SEARCH_TIME DESC
) t
WHERE
    t.row_number <= 2 AND
    t.grp <= 3;

This code is untested, mainly because your query is too complex for easy testing, but I can iterate with you if you encounter any problems.


问:
Can't run app with Instant Run on Android Studio 3.0
I've updated to Android Studio 3.0 and now I cannot run the app with Instant Run enabled.

I get 'Execution failed for task' due to a java.io.FileNotFoundException because it can't find the apk under

../build/intermediates/instant-run-resources/resources-production/

Any idea how to overcome this so that I can run the project with Instant Run?

I'm not sure where to find the missing apk file or how to change the path to look for it in.

答:
Have your settings as below,

Otherwise try to clean and re-install (after uninstalling exsisting apk) application.


问:
SQL Set Question
How can I make the following sql statement part of the "SET" in my query? I want to pull out a list in a column and have my "SET" run against that. That way my "SET" isn't just one variable but rather a list to run against. Make sence? </p>

```<code>DECLARE @Item as char(32)
declare @result varchar(max);
SET @Item = '034100-3JK';
</code>```

<p>I want to use something like the following to have it query against instead of the 034100-3JK: </p>

```<code>select distinct
        a.t_sitm as StartItem
from
        ttibom010101 as a
        INNER JOIN ttiitm001101 as b on a.t_sitm = b.t_item
where
        b.t_ctyp != 'TOP'
        and b.t_ctyp != 'SUB'
</code>```

答: You didn't mention which flavor of SQL you were using, but can you use a cursor or common table expression? </p>

ContentLicense: CC BY-SA 2.5

Title: SQL Set Question

Body:
How can I make the following sql statement part of the "SET" in my query? I want to pull out a list in a column and have my "SET" run against that. That way my "SET" isn't just one variable but rather a list to run against. Make sence?

DECLARE @Item as char(32)
declare @result varchar(max);
SET @Item = '034100-3JK';

I want to use something like the following to have it query against instead of the 034100-3JK:

select distinct
        a.t_sitm as StartItem
from
        ttibom010101 as a
        INNER JOIN ttiitm001101 as b on a.t_sitm = b.t_item
where
        b.t_ctyp != 'TOP'
        and b.t_ctyp != 'SUB'


问:
During activating Tensorflow program, Error 'NoneType' object has no attribute 'group'. How can I solve this?
When I was using Tensorflow to follow the tutorial of Simple Audio Recognition on TensorFlow page, I got a problem in downloading audio data for train.

I have entered the following command:

```<code>C:\Users\user\Document\Tensorflow\tensorflow\examples\speech_commands\train.py
</code>```

and got an error message,

```<code> Downloading speech_commands_v0.01.tar.gz 100.0%
INFO:tensorflow:Successfully downloaded speech_commands_v0.01.tar.gz (1488293908 bytes)
Traceback (most recent call last):
  File "C:\Users\user\Document\Tensorflow\tensorflow\examples\speech_commands\train.py", line 427, in <module>
    tf.app.run(main=main, argv=[sys.argv[0]] + unparsed)
  File "C:\Users\user\AppData\Local\conda\conda\envs\my_root\lib\site-packages\tensorflow\python\platform\app.py", line 133, in run
    _sys.exit(main(argv))
  File "C:\Users\user\Document\Tensorflow\tensorflow\examples\speech_commands\train.py", line 104, in main
    FLAGS.testing_percentage, model_settings)
  File "C:\Users\user\Document\Tensorflow\tensorflow\examples\speech_commands\input_data.py", line 161, in __init__
    testing_percentage)
  File "C:\Users\user\Document\Tensorflow\tensorflow\examples\speech_commands\input_data.py", line 243, in prepare_data_index
    word = re.search('.*/([^/]+)/.*.wav', wav_path).group(1).lower()
AttributeError: 'NoneType' object has no attribute 'group'
</code>```

Should I fix the code on file input_data.py? If it is possible, how can I fix it? It will be helpful if anyone gives me some advice on this problem.

答:
The error suggests that your re.search() call returned None, hence the AttributeError you are getting.

I suggest you give a better look to your regexp to check that is what you desire. Another thing that I noted is that you are also calling group(1). Make sure that is also the group you wish to obtain with that regexp (and not group(0)). Alternatively, the groups() method will return all the subgroups of your match. Hope this helps.

Body:
When I was using Tensorflow to follow the tutorial of Simple Audio Recognition on TensorFlow page, I got a problem in downloading audio data for train.

I have entered the following command:

C:\Users\user\Document\Tensorflow\tensorflow\examples\speech_commands\train.py

and got an error message,

 Downloading speech_commands_v0.01.tar.gz 100.0%
INFO:tensorflow:Successfully downloaded speech_commands_v0.01.tar.gz (1488293908 bytes)
Traceback (most recent call last):
  File "C:\Users\user\Document\Tensorflow\tensorflow\examples\speech_commands\train.py", line 427, in <module>
    tf.app.run(main=main, argv=[sys.argv[0]] + unparsed)
  File "C:\Users\user\AppData\Local\conda\conda\envs\my_root\lib\site-packages\tensorflow\python\platform\app.py", line 133, in run
    _sys.exit(main(argv))
  File "C:\Users\user\Document\Tensorflow\tensorflow\examples\speech_commands\train.py", line 104, in main
    FLAGS.testing_percentage, model_settings)
  File "C:\Users\user\Document\Tensorflow\tensorflow\examples\speech_commands\input_data.py", line 161, in __init__
    testing_percentage)
  File "C:\Users\user\Document\Tensorflow\tensorflow\examples\speech_commands\input_data.py", line 243, in prepare_data_index
    word = re.search('.*/([^/]+)/.*.wav', wav_path).group(1).lower()
AttributeError: 'NoneType' object has no attribute 'group'

Should I fix the code on file input_data.py? If it is possible, how can I fix it? It will be helpful if anyone gives me some advice on this problem.


问:
How to write the user type php code in HTML parameter?
First of all sorry for the title.

This is the code I have written but there is a problem, So decided to come here.

What I want actually that Whatever I type in the value parameter it should be reflected back in the value parameter( for XSS ). But I didn't succeed. Can anyone suggest me something?

```<code><style>body {
    background-color: #000000;
}
</style>
<center><title>  </title>
<h1 style="color:blue;"><u></u></h1><br>

<center><form style="color:red"; action="xss3.php" method="POST"><center>

<b>Advance search:</b>  <input type="text" name="q" id="test" value="<?php echo ($_POST['test']);?>">

<input type="submit" name="search" value="search"><br><br>
</code>```

答:
I hope your php file name is also xss.php (which includes this code).

Assuming that, you need to do a few modifications.

PHP would accept the 'name' attribute in HTML input fields as the variable(associative array index) identifiers of $_POST, $_GET, $_REQUEST arrays.

There for you should change

```<code><?php echo ($_POST['test']);?>
</code>```

to

```<code><?php echo ($_POST['q']);?>
</code>```

There are a few methods to get rid of that error message:

1st Method

And to avoid the error (Undefined Index) at the initial page load, you may use the '@' symbol before the beginning of $_POST to suppresses error messages.

Then it would be: <?php echo (@$_POST['q']);?>

If you use this method, at the end, your code may look like:

```<code><html>

<style>body {
    background-color: #000000;
}
</style>

<body>
<center><title>  </title>
<h1 style="color:blue;"><u></u></h1><br>

<center><form style="color:red"; action="xss.php" method="POST"><center>

<b>Advance search:</b>  <input type="text" name="q" id="test" value="<?php echo (@$_POST['q']);?>">

<input type="submit" name="search" value="search"><br><br>
</body>
</html>
</code>```

2nd Method

Check if the submit button was pressed before displaying the result in the input box. We could use the isset() function to check whether the variable has been set. In this case isset($_POST['submit']) Here you can use two alternatives.

Using the short hand if operator <input type="text" name="q" id="test" value="<?php  echo isset($_POST['search'])?($_POST['q']):'';?>">

If you use this approach, your final code would look like this:

```<code><html>

<style>body {
    background-color: #000000;
}
</style>

<body>
<center><title>  </title>
<h1 style="color:blue;"><u></u></h1><br>

<center><form style="color:red"; action="value.php" method="POST"><center>

<b>Advance search:</b>  <input type="text" name="q" id="test" value="<?php  echo isset($_POST['search'])?($_POST['q']):'';?>">

<input type="submit" name="search" value="search"><br><br>
</body>
</html>
</code>```

Using if statements <?php  if(isset($_POST['search'])){ echo ($_POST['q']); } ?>

And, if you use this approach, your final code would look like this

```<code><html>

<style>body {
    background-color: #000000;
}
</style>

<body>
<center><title>  </title>
<h1 style="color:blue;"><u></u></h1><br>

<center><form style="color:red"; action="value.php" method="POST"><center>

<b>Advance search:</b>  <input type="text" name="q" id="test" value="<?php

 if(isset($_POST['search'])){
echo ($_POST['q']);

}?>">

<input type="submit" name="search" value="search"><br><br>
</body>
</html>
</code>```

Body:
First of all sorry for the title.

This is the code I have written but there is a problem, So decided to come here.

What I want actually that Whatever I type in the value parameter it should be reflected back in the value parameter( for XSS ). But I didn't succeed. Can anyone suggest me something?

<title>  </title>

<form style="color:red"; action="xss3.php" method="POST">

Advance search:  <input type="text" name="q" id="test" value="<?php echo ($_POST['test']);?>">

<input type="submit" name="search" value="search">

Body:
I hope your php file name is also xss.php (which includes this code).

Assuming that, you need to do a few modifications.

PHP would accept the 'name' attribute in HTML input fields as the variable(associative array index) identifiers of $_POST, $_GET, $_REQUEST arrays.

There for you should change

<?php echo ($_POST['test']);?>

to

<?php echo ($_POST['q']);?>

There are a few methods to get rid of that error message:

1st Method

And to avoid the error (Undefined Index) at the initial page load, you may use the '@' symbol before the beginning of $_POST to suppresses error messages.

Then it would be: <?php echo (@$_POST['q']);?>

If you use this method, at the end, your code may look like:

<html>

<style>body {
    background-color: #000000;
}
</style>

<body>
<center><title>  </title>
<h1 style="color:blue;"><u></u></h1><br>

<center><form style="color:red"; action="xss.php" method="POST"><center>

<b>Advance search:</b>  <input type="text" name="q" id="test" value="<?php echo (@$_POST['q']);?>">

<input type="submit" name="search" value="search"><br><br>
</body>
</html>

2nd Method

Check if the submit button was pressed before displaying the result in the input box. We could use the isset() function to check whether the variable has been set. In this case isset($_POST['submit']) Here you can use two alternatives.

Using the short hand if operator <input type="text" name="q" id="test" value="<?php  echo isset($_POST['search'])?($_POST['q']):'';?>">

If you use this approach, your final code would look like this:

<html>

<style>body {
    background-color: #000000;
}
</style>

<body>
<center><title>  </title>
<h1 style="color:blue;"><u></u></h1><br>

<center><form style="color:red"; action="value.php" method="POST"><center>

<b>Advance search:</b>  <input type="text" name="q" id="test" value="<?php  echo isset($_POST['search'])?($_POST['q']):'';?>">

<input type="submit" name="search" value="search"><br><br>
</body>
</html>

Using if statements <?php  if(isset($_POST['search'])){ echo ($_POST['q']); } ?>

And, if you use this approach, your final code would look like this

<html>

<style>body {
    background-color: #000000;
}
</style>

<body>
<center><title>  </title>
<h1 style="color:blue;"><u></u></h1><br>

<center><form style="color:red"; action="value.php" method="POST"><center>

<b>Advance search:</b>  <input type="text" name="q" id="test" value="<?php

 if(isset($_POST['search'])){
echo ($_POST['q']);

}?>">

<input type="submit" name="search" value="search"><br><br>
</body>
</html>


问:
Method reference is ambiguous for Thread.sleep
I've come across a weird problem where a method reference to Thread::sleep is ambiguous but a method with the same signature is not.

```<code>package test;

public class Test
{
    public static void main(String[] args)
    {
        foo(Test::sleep, 1000L); //fine
        foo((FooVoid<Long>)Thread::sleep, 1000L); //fine
        foo(Thread::sleep, 1000L); //error
    }

    public static void sleep(long millis) throws InterruptedException
    {
        Thread.sleep(millis);
    }

    public static <P, R> void foo(Foo<P, R> function, P param) {}

    public static <P> void foo(FooVoid<P> function, P param) {}

    @FunctionalInterface
    public interface Foo<P, R> {
        R call(P param1) throws Exception;
    }

    @FunctionalInterface
    public interface FooVoid<P> {
        void call(P param1) throws Exception;
    }
}
</code>```

I get those 2 errors:

```<code>Error:(9, 17) java: reference to foo is ambiguous
  both method <P,R>foo(test.Test.Foo<P,R>,P) in test.Test and method <P>foo(test.Test.FooVoid<P>,P) in test.Test match

Error:(9, 20) java: incompatible types: cannot infer type-variable(s) P,R
    (argument mismatch; bad return type in method reference
      void cannot be converted to R)
</code>```

The only difference I see is that Thread::sleep is native. Does it change anything? I don't think the overload Thread::sleep(long, int) comes into play here. Why does it happen?

EDIT: Using javac version 1.8.0_111

答:
You can recreate the problem in your own class by adding a method sleep with two arguments to class Test like below:

```<code>public static void sleep(long millis) {
}

public static void sleep(long millis, int nanos) {
}
</code>```

So the problem is really caused by the fact that the method sleep is overloaded.

The JLS indicates that the initial method selection code only looks at the number of type arguments to the functional interface - only in the second phase does it look at the signature of the method inside the functional interface.

JLS 15.13:

It is not possible to specify a particular signature to be matched,
  for example, Arrays::sort(int[]). Instead, the functional interface
  provides argument types that are used as input to the overload
  resolution algorithm (§15.12.2).

(the second-to-last paragraph of this section)

So in the case of Thread::sleep, void sleep(long) potentially matches functional interface FooVoid
, while overload void sleep(long, int) potentially matches functional interface Foo
. That's why you get the "reference to foo is ambiguous" error.

When it tries to go further and see how to match Foo
 with functional method R call(P param1) to the method void sleep(long, int), it finds out that this is not actually possible, and you get another compile error:

```<code>test/Test.java:7: error: incompatible types: cannot infer type-variable(s) P,R
        foo(Thread::sleep, 1000L); // error
           ^
    (argument mismatch; bad return type in method reference
      void cannot be converted to R)
</code>```

Body:
I've come across a weird problem where a method reference to Thread::sleep is ambiguous but a method with the same signature is not.

package test;

public class Test
{
    public static void main(String[] args)
    {
        foo(Test::sleep, 1000L); //fine
        foo((FooVoid<Long>)Thread::sleep, 1000L); //fine
        foo(Thread::sleep, 1000L); //error
    }

    public static void sleep(long millis) throws InterruptedException
    {
        Thread.sleep(millis);
    }

    public static
 void foo(Foo
 function, P param) {}

    public static
 void foo(FooVoid
 function, P param) {}

    @FunctionalInterface
    public interface Foo
 {
        R call(P param1) throws Exception;
    }

    @FunctionalInterface
    public interface FooVoid
 {
        void call(P param1) throws Exception;
    }
}

I get those 2 errors:

Error:(9, 17) java: reference to foo is ambiguous
  both method
foo(test.Test.Foo
,P) in test.Test and method
foo(test.Test.FooVoid
,P) in test.Test match

Error:(9, 20) java: incompatible types: cannot infer type-variable(s) P,R
    (argument mismatch; bad return type in method reference
      void cannot be converted to R)

The only difference I see is that Thread::sleep is native. Does it change anything? I don't think the overload Thread::sleep(long, int) comes into play here. Why does it happen?

EDIT: Using javac version 1.8.0_111

Body:
You can recreate the problem in your own class by adding a method sleep with two arguments to class Test like below:

public static void sleep(long millis) {
}

public static void sleep(long millis, int nanos) {
}

So the problem is really caused by the fact that the method sleep is overloaded.

The JLS indicates that the initial method selection code only looks at the number of type arguments to the functional interface - only in the second phase does it look at the signature of the method inside the functional interface.

JLS 15.13:

It is not possible to specify a particular signature to be matched,
  for example, Arrays::sort(int[]). Instead, the functional interface
  provides argument types that are used as input to the overload
  resolution algorithm (§15.12.2).

(the second-to-last paragraph of this section)

So in the case of Thread::sleep, void sleep(long) potentially matches functional interface FooVoid<P>, while overload void sleep(long, int) potentially matches functional interface Foo<P, R>. That's why you get the "reference to foo is ambiguous" error.

When it tries to go further and see how to match Foo<P, R> with functional method R call(P param1) to the method void sleep(long, int), it finds out that this is not actually possible, and you get another compile error:

test/Test.java:7: error: incompatible types: cannot infer type-variable(s) P,R
        foo(Thread::sleep, 1000L); // error
           ^
    (argument mismatch; bad return type in method reference
      void cannot be converted to R)


问:
is there a more efficient way to count how many vowels in a string?
```<code>def processStrings(userPhrase):
    """ This function will accept the phrase as string and will count every
        instance of vowel then return a dictionary with key:values of each
        vowel and amount of occurrences in string.
    """

    vowelCount = {i:userPhrase.count(i) for i in 'AEIOU'}

    return (vowelCount)
</code>```

<p>I am new to StackOverflow and Programming. I wrote this function as part of small program for class and am now curious to know what the most efficient solution would be. We were told to demonstrate a strong understanding of applicable concepts in developing an efficient solution, as far as I can tell this has to pretty close since it uses a dictionary and the count() is supposed to be good. I am wondering if I missed something like in that it has to iterate over the entire phrase 5 times to get the values but I can't figure out if there is a better solution that would mean less processing time or memory usage say if I used the function for a much larger string and searched more than just vowels or something. </p>

答:
It will likely be more efficient using a Counter, then extracting the values for the vowels, and retuen them:

```<code>from collections import Counter

def count_vowels(phrase):
    """ accepts a string and counts the number of each vowels.
    returns a dictionary key --> values
            of each vowel and their number of occurrences.
    """
    vowels = "aeiou"
    frequencies = Counter(phrase.lower())
    return {vowel: frequencies[vowel] for vowel in vowels}
</code>```

as a one-liner:

(as suggested by @stevenRumbalski in the comments)

```<code>from collections import Counter

def count_vowels(phrase):
    """ accepts a string and counts the number of each vowels.
    returns a dictionary key --> values
            of each vowel and their number of occurrences.
    """
    vowels = "aeiou"
    return Counter(c for c in phrase.lower() if c in vowels)
</code>```

Body:
def processStrings(userPhrase):
    """ This function will accept the phrase as string and will count every
        instance of vowel then return a dictionary with key:values of each
        vowel and amount of occurrences in string.
    """

    vowelCount = {i:userPhrase.count(i) for i in 'AEIOU'}

    return (vowelCount)

I am new to StackOverflow and Programming. I wrote this function as part of small program for class and am now curious to know what the most efficient solution would be. We were told to demonstrate a strong understanding of applicable concepts in developing an efficient solution, as far as I can tell this has to pretty close since it uses a dictionary and the count() is supposed to be good. I am wondering if I missed something like in that it has to iterate over the entire phrase 5 times to get the values but I can't figure out if there is a better solution that would mean less processing time or memory usage say if I used the function for a much larger string and searched more than just vowels or something.

Body:
It will likely be more efficient using a Counter, then extracting the values for the vowels, and retuen them:

from collections import Counter

def count_vowels(phrase):
    """ accepts a string and counts the number of each vowels.
    returns a dictionary key --> values
            of each vowel and their number of occurrences.
    """
    vowels = "aeiou"
    frequencies = Counter(phrase.lower())
    return {vowel: frequencies[vowel] for vowel in vowels}

as a one-liner:

(as suggested by @stevenRumbalski in the comments)

from collections import Counter

def count_vowels(phrase):
    """ accepts a string and counts the number of each vowels.
    returns a dictionary key --> values
            of each vowel and their number of occurrences.
    """
    vowels = "aeiou"
    return Counter(c for c in phrase.lower() if c in vowels)


问:
Multiline input with variable number of string and integer tokens in C
My input file looks like this-

```<code># 4
INS 0 3
DEC 0 0
DEL
INS 1 2
DEC 1 0
DEL
INS 2 1
DEC 2 0
INS 3 3
</code>```

With this whole module having multiple occurences in the input. I want to read the input on a line-by-line basis and then based on first word(delimited by a space), perform a necessary function with the additional values (if present, as in the case of #, INS and DEC
operations).

How do I allow for reading of the possible extra values for the same?

So far, I used fread to read it line by line and then split it, but IMO that's too much work. I tried using scanf("%[^\n]\n", variable) but then  again I need to tokenise it.

Also, when trying to use scanf("%[^\n] %[0-9] %[0-9]\n", var1, var2, var3) specifies the need to use var2 and var3 as character arrays. That reduces the need to tokenise but gives garbage input.

Is there an easier way to do the same?

Ps- I'm using C on Ubuntu 17.10 for the same.

Thanks in advance

答:
Continuing from the comments, using scanf for input for new (and not so new) C programmers is a minefield. scanf does not read and include the trailing '\n' unless you explicitly account for it in your format string. The conversion specifiers handle leading whitespace differently depending on whether you are reading number, character, or string values.

That is one of the primary reasons line oriented input functions such as fgets (or POSIX getline) are recommended when taking user input -- they provide a simple way to validate whether a complete line was read (e.g. get the length and check that the last char is '\n') and consistently handle characters waiting in the input buffer.

Further, using fgets and then parsing the buffer allow separate validation of (1) the read, and (2) the parse of information. You can parse the input with whatever function from string.h fits the bill, with sscanf or simply by walking a pointer (or pair of pointers) down the buffer checking each character and taking whatever action is needed to make use of each part of the line.

A simple example making use of sscanf to parse could be similar to the following. The code expects the filename to read as the first argument, if no argument is given, it will read from stdin by default:

```<code>#include <stdio.h>
#include <string.h>

#define DEL "DEL"                   /* if you need constants, define them */
enum { MAXARG = 3, MAXC = 512 };

int main (int argc, char **argv) {

    int n1, n2;                 /* integer values from line */
    size_t ndx = 0;             /* line index */
    char buf[MAXC] = "",        /* buffer for line */
        cmd[MAXARG+1] = "";     /* buffer for 3-char command */
    FILE *fp = argc > 1 ? fopen (argv[1], "r") : stdin;

    if (!fp) {  /* validate file open for reading */
        fprintf (stderr, "error: file open failed '%s'.\n", argv[1]);
        return 1;
    }

    while (fgets (buf, MAXC, fp)) { /* read each line in file */
        size_t len = 0;             /* buf length */

        if (*buf == '#') {  /* check if first char in line is '#', discard */
            fprintf (stderr, "line[%2zu] - discarding comment line.\n", ndx);
            ndx++;
            continue;
        }

        len = strlen (buf);                 /* get length */
        if (len && buf[len - 1] != '\n') {  /* validate last char '\n' */
            fprintf (stderr, "error: line too long, chars remain unread.\n");
            break;
        }

        /* check for 3 values, then 1 value == "DEL", otherwise throw error */
        if (sscanf (buf, "%3s %d %d", cmd, &n1, &n2) == MAXARG)
            printf ("line[%2zu] (3 vals) : %s %d %d\n", ndx, cmd, n1, n2);
        else if (strncmp (DEL, buf, MAXARG) == 0)
            printf ("line[%2zu] (1 val)  : %s\n", ndx, cmd);
        else
            fprintf (stderr, "error: invalid line: %zu\n", ndx);

        ndx++;
    }

    if (fp != stdin) fclose (fp);   /* close file if not stdin */

    return 0;
}
</code>```

Example Use/Output

Using your data file, the data would be read and parsed as follows. Note the initial label tells whether there was 1 value or 3 values parsed from the line (zero indexed):

```<code>$ ./bin/misclines <dat/misclines.txt
line[ 0] - discarding comment line.
line[ 1] (3 vals) : INS 0 3
line[ 2] (3 vals) : DEC 0 0
line[ 3] (1 val)  : DEL
line[ 4] (3 vals) : INS 1 2
line[ 5] (3 vals) : DEC 1 0
line[ 6] (1 val)  : DEL
line[ 7] (3 vals) : INS 2 1
line[ 8] (3 vals) : DEC 2 0
line[ 9] (3 vals) : INS 3 3
</code>```

Look things over and let me know if you have further questions.

Body:
My input file looks like this-

# 4
INS 0 3
DEC 0 0
DEL
INS 1 2
DEC 1 0
DEL
INS 2 1
DEC 2 0
INS 3 3

With this whole module having multiple occurences in the input. I want to read the input on a line-by-line basis and then based on first word(delimited by a space), perform a necessary function with the additional values (if present, as in the case of #, INS and DEC
operations).

How do I allow for reading of the possible extra values for the same?

So far, I used fread to read it line by line and then split it, but IMO that's too much work. I tried using scanf("%[^\n]\n", variable) but then  again I need to tokenise it.

Also, when trying to use scanf("%[^\n] %[0-9] %[0-9]\n", var1, var2, var3) specifies the need to use var2 and var3 as character arrays. That reduces the need to tokenise but gives garbage input.

Is there an easier way to do the same?

Ps- I'm using C on Ubuntu 17.10 for the same.

Thanks in advance

Body:
Continuing from the comments, using scanf for input for new (and not so new) C programmers is a minefield. scanf does not read and include the trailing '\n' unless you explicitly account for it in your format string. The conversion specifiers handle leading whitespace differently depending on whether you are reading number, character, or string values.

That is one of the primary reasons line oriented input functions such as fgets (or POSIX getline) are recommended when taking user input -- they provide a simple way to validate whether a complete line was read (e.g. get the length and check that the last char is '\n') and consistently handle characters waiting in the input buffer.

Further, using fgets and then parsing the buffer allow separate validation of (1) the read, and (2) the parse of information. You can parse the input with whatever function from string.h fits the bill, with sscanf or simply by walking a pointer (or pair of pointers) down the buffer checking each character and taking whatever action is needed to make use of each part of the line.

A simple example making use of sscanf to parse could be similar to the following. The code expects the filename to read as the first argument, if no argument is given, it will read from stdin by default:

#include <stdio.h>
#include <string.h>

#define DEL "DEL"                   /* if you need constants, define them */
enum { MAXARG = 3, MAXC = 512 };

int main (int argc, char **argv) {

    int n1, n2;                 /* integer values from line */
    size_t ndx = 0;             /* line index */
    char buf[MAXC] = "",        /* buffer for line */
        cmd[MAXARG+1] = "";     /* buffer for 3-char command */
    FILE *fp = argc > 1 ? fopen (argv[1], "r") : stdin;

    if (!fp) {  /* validate file open for reading */
        fprintf (stderr, "error: file open failed '%s'.\n", argv[1]);
        return 1;
    }

    while (fgets (buf, MAXC, fp)) { /* read each line in file */
        size_t len = 0;             /* buf length */

        if (*buf == '#') {  /* check if first char in line is '#', discard */
            fprintf (stderr, "line[%2zu] - discarding comment line.\n", ndx);
            ndx++;
            continue;
        }

        len = strlen (buf);                 /* get length */
        if (len && buf[len - 1] != '\n') {  /* validate last char '\n' */
            fprintf (stderr, "error: line too long, chars remain unread.\n");
            break;
        }

        /* check for 3 values, then 1 value == "DEL", otherwise throw error */
        if (sscanf (buf, "%3s %d %d", cmd, &n1, &n2) == MAXARG)
            printf ("line[%2zu] (3 vals) : %s %d %d\n", ndx, cmd, n1, n2);
        else if (strncmp (DEL, buf, MAXARG) == 0)
            printf ("line[%2zu] (1 val)  : %s\n", ndx, cmd);
        else
            fprintf (stderr, "error: invalid line: %zu\n", ndx);

        ndx++;
    }

    if (fp != stdin) fclose (fp);   /* close file if not stdin */

    return 0;
}

Example Use/Output

Using your data file, the data would be read and parsed as follows. Note the initial label tells whether there was 1 value or 3 values parsed from the line (zero indexed):

$ ./bin/misclines <dat/misclines.txt
line[ 0] - discarding comment line.
line[ 1] (3 vals) : INS 0 3
line[ 2] (3 vals) : DEC 0 0
line[ 3] (1 val)  : DEL
line[ 4] (3 vals) : INS 1 2
line[ 5] (3 vals) : DEC 1 0
line[ 6] (1 val)  : DEL
line[ 7] (3 vals) : INS 2 1
line[ 8] (3 vals) : DEC 2 0
line[ 9] (3 vals) : INS 3 3

Look things over and let me know if you have further questions.


问:
How would you tidy up this controller logic?
I've got some logic in a controller that sets a status of an object if certain conditions are met:

```<code>if params[:concept][:consulted_legal] == 0 && params[:concept][:consulted_marketing] == 1
  @concept.attributes = {:status => 'Awaiting Compliance Approval'}
elsif params[:concept][:consulted_marketing] == 0 && params[:concept][:consulted_legal] == 1
  @concept.attributes = {:status => 'Awaiting Marketing Approval'}
elsif params[:concept][:consulted_marketing] == 0 && params[:concept][:consulted_legal] == 0
  @concept.attributes = {:status => 'Awaiting Marketing & Legal Approval'}
else
  @concept.attributes = {:status => 'Pending Approval'}
end
</code>```

that I share between create and update actions. How would you go about refactoring this nastiness? Looking for best practices.

New to programming and keen to clean up my code.

TIA.

答:
This looks like a business rule to me. As such you might want to wrap it into a function:

```<code>string GetConceptStatus(bool consulted_legal, bool consulted_marketing)
{
    if (consulted_legal && consulted_marketing) {
        return "Pending Approval";
    }
    if (consulted_legal && !consulted_marketing) {
        return "Awaiting Marketing Approval";
    }
    if (!consulted_legal && consulted_marketing) {
        return "Awaiting Legal Approval";
    }
    if (!consulted_legal && !consulted_marketing) {
        return "Awaiting Marketing & Legal Approval";
    }
}
</code>```

This also separates the details of how bools are encoded in your interface from the actual implementation of the business rule.

But the actual structure of the code looks good to me, since it probably better models the business rule.

OwnerDisplayName: The Pied Pipes

Body:
I've got some logic in a controller that sets a status of an object if certain conditions are met:

if params[:concept][:consulted_legal] == 0 && params[:concept][:consulted_marketing] == 1
  @concept.attributes = {:status => 'Awaiting Compliance Approval'}
elsif params[:concept][:consulted_marketing] == 0 && params[:concept][:consulted_legal] == 1
  @concept.attributes = {:status => 'Awaiting Marketing Approval'}
elsif params[:concept][:consulted_marketing] == 0 && params[:concept][:consulted_legal] == 0
  @concept.attributes = {:status => 'Awaiting Marketing & Legal Approval'}
else
  @concept.attributes = {:status => 'Pending Approval'}
end

that I share between create and update actions. How would you go about refactoring this nastiness? Looking for best practices.

New to programming and keen to clean up my code.

TIA.

Body:
This looks like a business rule to me. As such you might want to wrap it into a function:

string GetConceptStatus(bool consulted_legal, bool consulted_marketing)
{
    if (consulted_legal && consulted_marketing) {
        return "Pending Approval";
    }
    if (consulted_legal && !consulted_marketing) {
        return "Awaiting Marketing Approval";
    }
    if (!consulted_legal && consulted_marketing) {
        return "Awaiting Legal Approval";
    }
    if (!consulted_legal && !consulted_marketing) {
        return "Awaiting Marketing & Legal Approval";
    }
}

This also separates the details of how bools are encoded in your interface from the actual implementation of the business rule.

But the actual structure of the code looks good to me, since it probably better models the business rule.

OwnerDisplayName: David Schmitt


问:
Azure Service Bus can't receive JSON body
When debugging this code, the application stops. No error message or exception are shown.

Project X:

```<code>client.OnMessage((message) =>
{
    using (var stream = message.GetBody<Stream>())
    using (var streamReader = new StreamReader(stream, Encoding.UTF8))
    {
        var body = streamReader.ReadToEnd();
    }
 }
</code>```

Below I'm POSTing JSON objects through a REST API.

Project Y:

```<code>public void CreateMessage<T>(T messageToSend, string queueAddress, WebClient webclient)
{
    var apiVersion = "&api-version=2014-01";
    var serializedMessage = JsonConvert.SerializeObject(messageToSend, Formatting.Indented);
    string receivedMessageBody = webclient.UploadString(queueAddress + "/messages" + "?timeout=60&" + apiVersion, "POST", serializedMessage);

}
</code>```

I can see that messages are received in Azure portal, so there is no authentication problem. Also earlier when I passed data with the Azure SDK with the help of BrokeredMessage, I was able to receive JSON objects as expected. However, I need to use the REST API.

As seen in the picture, the MessageID is there, and I'm also able to get properties. But I want to read the content of the body.

Picture of received object

.

Any ideas how I can get the body?

答:
According to your description, I checked this issue and followed Send Message to send my messages to service bus queue.

ForContent-Type to application/atom+xml;type=entry;charset=utf-8, your payload need to be serialized using DataContractSerializer with a binary XmlDictionaryWriter. So you need to construct your payload as follows:

Define your object and send the message:

```<code>[DataContract]
public class DemoMessage
{
    [DataMember]
    public string Title { get; set; }
}

wc.Headers["Content-Type"] = "application/atom+xml;type=entry;charset=utf-8";
MemoryStream ms = new MemoryStream();
DataContractSerializer serializer = new DataContractSerializer(typeof(DemoMessage));
serializer.WriteObject(ms, new DemoMessage() { Title = messageBody });
wc.UploadString(sendAddress, "POST",System.Text.UTF8Encoding.UTF8.GetString(ms.ToArray()));
</code>```

Then you could use the following code to receive the message:

```<code>var message = message.GetBody<DemoMessage>(new DataContractSerializer(typeof(DemoMessage)));
</code>```

For Content-Type to text/plain or not be specified, you could serialize the payload as follows:

```<code>var messageBody = JsonConvert.SerializeObject(new DemoMessage(){ Title = messageBody }, Newtonsoft.Json.Formatting.Indented);
wc.UploadString(sendAddress, "POST", messageBody);
</code>```

For receiving the message, you could use the code below:

```<code>using (var stream = message.GetBody<Stream>())
{
    using (var streamReader = new StreamReader(stream, Encoding.UTF8))
    {
        msg = streamReader.ReadToEnd();
        var obj=JsonConvert.DeserializeObject<DemoMessage>(msg);
    }
}
</code>```

UPDATE:

When debugging this code, the application stops. No error message or exception are shown.

For console application, after configured the client.OnMessage, you need to use Console.ReadKey() or Console.ReadLine() to prevent your application from exiting. Moreover, you could try-catch-throw your processing within client.OnMessage to retrieve the detailed error message for troubleshooting.

UPDATE2:

I just used the following code in my console application with the target framework 4.6.2 and referenced WindowsAzure.ServiceBus.4.1.3.

static void Main(string[] args)
{
    //send the message
    var wc = new WebClient();
    wc.Headers["Authorization"] = createToken("https://brucesb.servicebus.windows.net/order", "RootManageSharedAccessKey", "{your-key}");
    var messageBody = JsonConvert.SerializeObject(new DemoMessage() { Title = "hello world!!!!" }, Newtonsoft.Json.Formatting.Indented);
    wc.UploadString("https://brucesb.servicebus.windows.net/order/messages", "POST", messageBody);

    //receive the message
    QueueClient client = QueueClient.CreateFromConnectionString(connectionString, "order");
    client.OnMessage(message =>
    {
        using (var stream = message.GetBody<Stream>())
        {
            using (var streamReader = new StreamReader(stream, Encoding.UTF8))
            {
                var msg = streamReader.ReadToEnd();
                var obj = JsonConvert.DeserializeObject<DemoMessage>(msg);
                Console.WriteLine(msg);
            }
        }
    });
    Console.WriteLine("Press any key to exit...");
    Console.ReadLine();
}

static string createToken(string resourceUri, string keyName, string key)
{
    var expiry = (long)(DateTime.UtcNow.AddDays(1) - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalSeconds;
    string stringToSign = HttpUtility.UrlEncode(resourceUri) + "\n" + expiry;
    HMACSHA256 hmac = new HMACSHA256(Encoding.UTF8.GetBytes(key));
    var signature = Convert.ToBase64String(hmac.ComputeHash(Encoding.UTF8.GetBytes(stringToSign)));
    var sasToken = String.Format(CultureInfo.InvariantCulture, "SharedAccessSignature sr={0}&sig={1}&se={2}&skn={3}", HttpUtility.UrlEncode(resourceUri), HttpUtility.UrlEncode(signature), expiry, keyName);
    return sasToken;
}
```

Test:

Body:
When debugging this code, the application stops. No error message or exception are shown.

Project X:

client.OnMessage((message) =>
{
    using (var stream = message.GetBody<Stream>())
    using (var streamReader = new StreamReader(stream, Encoding.UTF8))
    {
        var body = streamReader.ReadToEnd();
    }
 }

Below I'm POSTing JSON objects through a REST API.

Project Y:

public void CreateMessage<T>(T messageToSend, string queueAddress, WebClient webclient)
{
    var apiVersion = "&api-version=2014-01";
    var serializedMessage = JsonConvert.SerializeObject(messageToSend, Formatting.Indented);
    string receivedMessageBody = webclient.UploadString(queueAddress + "/messages" + "?timeout=60&" + apiVersion, "POST", serializedMessage);

}

I can see that messages are received in Azure portal, so there is no authentication problem. Also earlier when I passed data with the Azure SDK with the help of BrokeredMessage, I was able to receive JSON objects as expected. However, I need to use the REST API.

As seen in the picture, the MessageID is there, and I'm also able to get properties. But I want to read the content of the body.

Picture of received object

.

Any ideas how I can get the body?

Body:
According to your description, I checked this issue and followed Send Message to send my messages to service bus queue.

ForContent-Type to application/atom+xml;type=entry;charset=utf-8, your payload need to be serialized using DataContractSerializer with a binary XmlDictionaryWriter. So you need to construct your payload as follows:

Define your object and send the message:

[DataContract]
public class DemoMessage
{
    [DataMember]
    public string Title { get; set; }
}

wc.Headers["Content-Type"] = "application/atom+xml;type=entry;charset=utf-8";
MemoryStream ms = new MemoryStream();
DataContractSerializer serializer = new DataContractSerializer(typeof(DemoMessage));
serializer.WriteObject(ms, new DemoMessage() { Title = messageBody });
wc.UploadString(sendAddress, "POST",System.Text.UTF8Encoding.UTF8.GetString(ms.ToArray()));

Then you could use the following code to receive the message:

var message = message.GetBody<DemoMessage>(new DataContractSerializer(typeof(DemoMessage)));

For Content-Type to text/plain or not be specified, you could serialize the payload as follows:

var messageBody = JsonConvert.SerializeObject(new DemoMessage(){ Title = messageBody }, Newtonsoft.Json.Formatting.Indented);
wc.UploadString(sendAddress, "POST", messageBody);

For receiving the message, you could use the code below:

using (var stream = message.GetBody<Stream>())
{
    using (var streamReader = new StreamReader(stream, Encoding.UTF8))
    {
        msg = streamReader.ReadToEnd();
        var obj=JsonConvert.DeserializeObject<DemoMessage>(msg);
    }
}

UPDATE:

When debugging this code, the application stops. No error message or exception are shown.

For console application, after configured the client.OnMessage, you need to use Console.ReadKey() or Console.ReadLine() to prevent your application from exiting. Moreover, you could try-catch-throw your processing within client.OnMessage to retrieve the detailed error message for troubleshooting.

UPDATE2:

I just used the following code in my console application with the target framework 4.6.2 and referenced WindowsAzure.ServiceBus.4.1.3.

static void Main(string[] args)
{
    //send the message
    var wc = new WebClient();
    wc.Headers["Authorization"] = createToken("https://brucesb.servicebus.windows.net/order", "RootManageSharedAccessKey", "{your-key}");
    var messageBody = JsonConvert.SerializeObject(new DemoMessage() { Title = "hello world!!!!" }, Newtonsoft.Json.Formatting.Indented);
    wc.UploadString("https://brucesb.servicebus.windows.net/order/messages", "POST", messageBody);

    //receive the message
    QueueClient client = QueueClient.CreateFromConnectionString(connectionString, "order");
    client.OnMessage(message =>
    {
        using (var stream = message.GetBody<Stream>())
        {
            using (var streamReader = new StreamReader(stream, Encoding.UTF8))
            {
                var msg = streamReader.ReadToEnd();
                var obj = JsonConvert.DeserializeObject<DemoMessage>(msg);
                Console.WriteLine(msg);
            }
        }
    });
    Console.WriteLine("Press any key to exit...");
    Console.ReadLine();
}

static string createToken(string resourceUri, string keyName, string key)
{
    var expiry = (long)(DateTime.UtcNow.AddDays(1) - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalSeconds;
    string stringToSign = HttpUtility.UrlEncode(resourceUri) + "\n" + expiry;
    HMACSHA256 hmac = new HMACSHA256(Encoding.UTF8.GetBytes(key));
    var signature = Convert.ToBase64String(hmac.ComputeHash(Encoding.UTF8.GetBytes(stringToSign)));
    var sasToken = String.Format(CultureInfo.InvariantCulture, "SharedAccessSignature sr={0}&sig={1}&se={2}&skn={3}", HttpUtility.UrlEncode(resourceUri), HttpUtility.UrlEncode(signature), expiry, keyName);
    return sasToken;
}

Test:


问:
Update product price using a hook in WooCommerce
I am trying to update the product regular price using the meta key _regular_price with an integer or string when the product is updated in the wp-admin.

My desired user-flow is:

Open the product edit page

Click the update button

See that the _regular_price is set to 20 after the page has reloaded.

```<code>add_action( 'woocommerce_process_product_meta', 'update_test' );
function update_test( $post_id ) {
    update_post_meta( $post_id, '_regular_price', 20 );
}
</code>```

Please help me find what I'm doing wrong in the above function and let me know of any other ways to accomplish this.

答:
To process woocommerce_process_product_meta, I guess you are missing the parameters. I hope the below code may suit your need.

```<code>add_action( 'woocommerce_process_product_meta',  $wc_meta_box_product_data_save,  $int,  $int );
</code>```

Parameters (3)

$wc_meta_box_product_data_save (string) => 'WC_Meta_Box_Product_Data::save'
The wc meta box product data save.

$int (int) => 10 The int.

$int (int) => 2  The int.

You can find the details in this link.

ContentLicense: CC BY-SA 4.0

Body:
I am trying to update the product regular price using the meta key _regular_price with an integer or string when the product is updated in the wp-admin.

My desired user-flow is:

Open the product edit page

Click the update button

See that the _regular_price is set to 20 after the page has reloaded.

add_action( 'woocommerce_process_product_meta', 'update_test' );
function update_test( $post_id ) {
    update_post_meta( $post_id, '_regular_price', 20 );
}

Please help me find what I'm doing wrong in the above function and let me know of any other ways to accomplish this.

Body:
To process woocommerce_process_product_meta, I guess you are missing the parameters. I hope the below code may suit your need.

add_action( 'woocommerce_process_product_meta',  $wc_meta_box_product_data_save,  $int,  $int );

Parameters (3)

$wc_meta_box_product_data_save (string) => 'WC_Meta_Box_Product_Data::save'
The wc meta box product data save.

$int (int) => 10 The int.

$int (int) => 2  The int.

You can find the details in this link.


问:
By returning a pointer that points to a node, is the rest of the list returned as well? c++
I have a project to do where I have to change SLList to LispList and add a few other functions. My only question is that My prof. has asked us not to create new nodes for a function called rest(), where the rest list is returned without the head.

```<code>Node* rest(){
      Node* nextToHead = head -> next; //this is a pointer to the next node in the list
      return nextToHead;
    }
</code>```

by using the pointer nextToHead, will it point to the rest of the list as well?
If not, it'll be great if you guys can give me tips on how to return the list without the head and without using any other nodes.

答:
When you return a Node pointer, everything the Node exposes can be used and abused. This includes the rest of the list.

The usual solution is to abstract the Node behind an iterator so that the user doesn't even see a Node. All they get is an iterator. The iterator still provides access to the rest of the list, so you have to restrict things even further

```<code>SingleNode rest(){
  return SingleNode (head -> next);
}
</code>```

where SingleNode looks something like

```<code>class SingleNode
{
    Node* node;
public:
    MyDataType& operator*()
    {
        return node->data;
    }
};
</code>```

If you can't do this,

Make the links in Node private to limit access.

Make SLList a friend of Node so only Node and SLList can see the links.

Do not have any accessor functions for the links.

Example:

```<code>struct Node
{
    friend class SLList;
    MyDataType data;
    // other public stuff
private:
    Node * next;
    // other private stuff
};
</code>```

Now the holder of a Node pointer can not see the rest of the list. They can still blow up the list by damaging the Node they have access to, but they have to work at it.

Body:
I have a project to do where I have to change SLList to LispList and add a few other functions. My only question is that My prof. has asked us not to create new nodes for a function called rest(), where the rest list is returned without the head.

Node* rest(){
      Node* nextToHead = head -> next; //this is a pointer to the next node in the list
      return nextToHead;
    }

by using the pointer nextToHead, will it point to the rest of the list as well?
If not, it'll be great if you guys can give me tips on how to return the list without the head and without using any other nodes.

Body:
When you return a Node pointer, everything the Node exposes can be used and abused. This includes the rest of the list.

The usual solution is to abstract the Node behind an iterator so that the user doesn't even see a Node. All they get is an iterator. The iterator still provides access to the rest of the list, so you have to restrict things even further

SingleNode rest(){
  return SingleNode (head -> next);
}

where SingleNode looks something like

class SingleNode
{
    Node* node;
public:
    MyDataType& operator*()
    {
        return node->data;
    }
};

If you can't do this,

Make the links in Node private to limit access.

Make SLList a friend of Node so only Node and SLList can see the links.

Do not have any accessor functions for the links.

Example:

struct Node
{
    friend class SLList;
    MyDataType data;
    // other public stuff
private:
    Node * next;
    // other private stuff
};

Now the holder of a Node pointer can not see the rest of the list. They can still blow up the list by damaging the Node they have access to, but they have to work at it.


问:
Delete Duplicate Lines Ruby
I working on a json file, I think. But Regardless, I'm working with a lot of different hashes and fetching different values and etc. This is

```<code>{"notification_rule"=>
  {"id"=>"0000000",
   "contact_method"=>
    {"id"=>"000000",
     "address"=>"cod.lew@gmail.com",}
{"notification_rule"=>
  {"id"=>"000000"
   "contact_method"=>
      {"id"=>"PO0JGV7",
       "address"=>"cod.lew@gmail.com",}
</code>```

Essential, this is the type of hash I'm currently working with. With my code:
I wanted to stop duplicates of the same thing in the text file. Because whenever I run this code it brings both the address of both these hashes. And I understand why, because its looping over again, but I thought this code that I added would help resolve that issue:

Final UPDATE

```<code>  if jdoc["notification_rule"]["contact_method"]["address"].to_s.include?(".com")
            numbers.print "Employee Name: "
            numbers.puts jdoc["notification_rule"]["contact_method"]["address"].gsub(/@target.com/, '').gsub(/\w+/, &:capitalize)
            file_names = ['Employee_Information.txt']
            file_names.each do |file_name|
                text = File.read(file_name)
                lines = text.split("\n")
                new_contents = lines.uniq.join("\n")
                File.open(file_name, "w") { |file| file.puts new_contents }
            end
        else
            nil
        end
</code>```

答:
This code looks really confused and lacking a specific purpose. Generally Ruby that's this tangled up is on the wrong track, as with Ruby there's usually a simple way of expressing something simple, and testing for duplicated addresses is one of those things that shouldn't be hard.

One of the biggest sources of confusion is the responsibility of a chunk of code. In that example you're not only trying to import data, loop over documents, clean up email addresses, and test for duplicates, but somehow facilitate printing out the results. That's a lot of things going on all at once, and they all have to work perfectly for that chunk of code to be fully operational. There's no way of getting it partially working, and no way of knowing if you're even on the right track.

Always try and break down complex problems into a few simple stages, then chain those stages together as necessary.

Here's how you can define a method to clean up your email addresses:

```<code>def address_scrub(address)
  address.gsub(/\@target.com/, '').gsub(/\w+/, &:capitalize)
end
</code>```

Where that can be adjusted as necessary, and presumably tested to ensure it's working correctly, which you can now do indepenedently of the other code.

As for the rest, it looks like this:

```<code>require 'set'

# Read in duplicated addresses from a file, clean up with chomp, using a Set
# for fast lookups.
duplicates = Set.new(
  File.open("Employee_Information.txt", "r").readlines.map(&:chomp)
)

# Extract addresses from jdoc document array
filtered = jdocs.map do |jdoc|
  # Convert to jdoc/address pair
  [ jdoc, address_scrub(jdoc["notification_rule"]["contact_method"]["address"]) ]
end.reject do |jdoc, address|
  # Remove any that are already in the duplicates list
  duplicates.include?(address)
end.map do |jdoc, _|
  # Return only the document
  jdoc
end
</code>```

Where that processes jdocs, an array of jdoc structures, and removes duplicates in a series of simple steps.

With the chaining approach you can see what's happening before you add on the next "link", so you can work incrementally towards a solution, adjusting as you go. Any mistakes are fairly easy to catch because you're able to, at any time, inspect the intermediate products of those stages.

Title: Delete Duplicate Lines Ruby

Body:
I working on a json file, I think. But Regardless, I'm working with a lot of different hashes and fetching different values and etc. This is

{"notification_rule"=>
  {"id"=>"0000000",
   "contact_method"=>
    {"id"=>"000000",
     "address"=>"cod.lew@gmail.com",}
{"notification_rule"=>
  {"id"=>"000000"
   "contact_method"=>
      {"id"=>"PO0JGV7",
       "address"=>"cod.lew@gmail.com",}

Essential, this is the type of hash I'm currently working with. With my code:
I wanted to stop duplicates of the same thing in the text file. Because whenever I run this code it brings both the address of both these hashes. And I understand why, because its looping over again, but I thought this code that I added would help resolve that issue:

Final UPDATE

  if jdoc["notification_rule"]["contact_method"]["address"].to_s.include?(".com")
            numbers.print "Employee Name: "
            numbers.puts jdoc["notification_rule"]["contact_method"]["address"].gsub(/@target.com/, '').gsub(/\w+/, &:capitalize)
            file_names = ['Employee_Information.txt']
            file_names.each do |file_name|
                text = File.read(file_name)
                lines = text.split("\n")
                new_contents = lines.uniq.join("\n")
                File.open(file_name, "w") { |file| file.puts new_contents }
            end
        else
            nil
        end

Body:
This code looks really confused and lacking a specific purpose. Generally Ruby that's this tangled up is on the wrong track, as with Ruby there's usually a simple way of expressing something simple, and testing for duplicated addresses is one of those things that shouldn't be hard.

One of the biggest sources of confusion is the responsibility of a chunk of code. In that example you're not only trying to import data, loop over documents, clean up email addresses, and test for duplicates, but somehow facilitate printing out the results. That's a lot of things going on all at once, and they all have to work perfectly for that chunk of code to be fully operational. There's no way of getting it partially working, and no way of knowing if you're even on the right track.

Always try and break down complex problems into a few simple stages, then chain those stages together as necessary.

Here's how you can define a method to clean up your email addresses:

def address_scrub(address)
  address.gsub(/\@target.com/, '').gsub(/\w+/, &:capitalize)
end

Where that can be adjusted as necessary, and presumably tested to ensure it's working correctly, which you can now do indepenedently of the other code.

As for the rest, it looks like this:

require 'set'

# Read in duplicated addresses from a file, clean up with chomp, using a Set
# for fast lookups.
duplicates = Set.new(
  File.open("Employee_Information.txt", "r").readlines.map(&:chomp)
)

# Extract addresses from jdoc document array
filtered = jdocs.map do |jdoc|
  # Convert to jdoc/address pair
  [ jdoc, address_scrub(jdoc["notification_rule"]["contact_method"]["address"]) ]
end.reject do |jdoc, address|
  # Remove any that are already in the duplicates list
  duplicates.include?(address)
end.map do |jdoc, _|
  # Return only the document
  jdoc
end

Where that processes jdocs, an array of jdoc structures, and removes duplicates in a series of simple steps.

With the chaining approach you can see what's happening before you add on the next "link", so you can work incrementally towards a solution, adjusting as you go. Any mistakes are fairly easy to catch because you're able to, at any time, inspect the intermediate products of those stages.


问:
Kivy VM Buildozer Command Failed
I recently learned about kivy and tried to make a very simple little app just to test  it. To try it out properly I used the kivy launcher but also felt compelled to try and compile it to an APK for my android phone. So I downloaded virtual box and installed linux mint on it. After installing things like java, cython and all that good stuff I tried to run "buildozer android debug". It keeps returning this bug though and I can't seem to figure out why. Any input is appreciated, thanks!

```<code>Command failed: /usr/bin/python3 -m pythonforandroid.toolchain create --dist_nam
e=vibapplication --bootstrap=sdl2 --requirements=kivy --arch armeabi-v7a --copy-
libs --color=always --storage-dir=/media/sf_python/python projects/kivy_learn/vi
brator/.buildozer/android/platform/build
</code>```

Full log: https://jpst.it/17q2O

答:
Could you try installing Buildozer VM from this link

https://kivy.org/docs/guide/packaging-android-vm.html

also you may follow https://kivy.org/docs/guide/packaging-android.html#buildozer

make sure you run "buildozer init" inside your project folder and also you have main.py file which is your program file and then run "buildozer android debug"

Note: you may also update the buildozer.spec file as per your requirement.

requirement = kivy # this should be by default

Title: Kivy VM Buildozer Command Failed

Body:
I recently learned about kivy and tried to make a very simple little app just to test  it. To try it out properly I used the kivy launcher but also felt compelled to try and compile it to an APK for my android phone. So I downloaded virtual box and installed linux mint on it. After installing things like java, cython and all that good stuff I tried to run "buildozer android debug". It keeps returning this bug though and I can't seem to figure out why. Any input is appreciated, thanks!

Command failed: /usr/bin/python3 -m pythonforandroid.toolchain create --dist_nam
e=vibapplication --bootstrap=sdl2 --requirements=kivy --arch armeabi-v7a --copy-
libs --color=always --storage-dir=/media/sf_python/python projects/kivy_learn/vi
brator/.buildozer/android/platform/build

Full log: https://jpst.it/17q2O


问:
Azure SQL Server BACPAC import failed
whenever i try to import BACPAC on local sql server I am getting below error message:

```<code>TITLE: Microsoft SQL Server Management Studio
------------------------------

Could not import package.
Warning SQL0: The source contains users that rely on an external authentication provider that is not supported by the target. These users will be treated as users without logins.
Warning SQL72012: The object [DB_NAME_Data] exists in the target, but it will not be dropped even though you selected the 'Generate drop statements for objects that are in the target database but that are not in the source' check box.
Warning SQL72012: The object [DB_NAME_Log] exists in the target, but it will not be dropped even though you selected the 'Generate drop statements for objects that are in the target database but that are not in the source' check box.
Error SQL72014: .Net SqlClient Data Provider: Msg 33161, Level 15, State 1, Line 1 Database master keys without password are not supported in this version of SQL Server.
Error SQL72045: Script execution error.  The executed script:
CREATE MASTER KEY;

 (Microsoft.SqlServer.Dac)

------------------------------
BUTTONS:

OK
------------------------------
</code>```

All the previously reported issues on SO are not same as this one. Does anyone faced the same issue before?

答:
Eventually I was able to resolve this issue by following option 2 suggested here

In nutshell,

Save the utility RemoveMasterKeyFrombacpac from here

Run the command .\RemoveMasterKey.ps1  -bacpacPath "C:\BacPacs\fileName.bacpac"

Once above command finishes we get the -patched bacpac which imported seamlessly.

Update

With new MS SQL Server 2016 (13.0.1745.2) and SSMS v17.6 this is not an issue anymore.

Title: Azure SQL Server BACPAC import failed

Body:
whenever i try to import BACPAC on local sql server I am getting below error message:

TITLE: Microsoft SQL Server Management Studio
------------------------------

Could not import package.
Warning SQL0: The source contains users that rely on an external authentication provider that is not supported by the target. These users will be treated as users without logins.
Warning SQL72012: The object [DB_NAME_Data] exists in the target, but it will not be dropped even though you selected the 'Generate drop statements for objects that are in the target database but that are not in the source' check box.
Warning SQL72012: The object [DB_NAME_Log] exists in the target, but it will not be dropped even though you selected the 'Generate drop statements for objects that are in the target database but that are not in the source' check box.
Error SQL72014: .Net SqlClient Data Provider: Msg 33161, Level 15, State 1, Line 1 Database master keys without password are not supported in this version of SQL Server.
Error SQL72045: Script execution error.  The executed script:
CREATE MASTER KEY;

 (Microsoft.SqlServer.Dac)

------------------------------
BUTTONS:

OK
------------------------------

All the previously reported issues on SO are not same as this one. Does anyone faced the same issue before?


问:
Re-enabling Microsoft Word Add-In after Error
We are developing a COM Add-In for Microsoft Word (only local, not for cloud usage). One of our customers had the problem, that each time he started Word, he had to manually activate the Add-In (Word Options > Add-Ins > Go... > tick the checkbox for the corresponding Add-In). I could reproduce this behavior by forcing an error in the Add-In coding which caused Word to crash. When starting Word the next time, I got the following message:

Of course I saw this message several times before. But: back then the consequence of clicking on "Yes" was that the Add-In was disabled. In that case it was sufficient to re-enable it one time (as described above). The next time the Add-In was started, you didn't have to enable it any more.

But now, additionally to disabling the Add-In, there is a registry key created. That key has the name of the Add-In and is located at the following path: HKEY_CURRENT_USER/SOFTWARE/Microsoft/Office/15.0/Word/AddInLoadTimes.

And it seems that this key causes the behavior described at the beginning. Because if I delete the key, start Word, enable the Add-In, close word, set the "LoadBehavior" key in the registry to "3" and then restart word, everything is fine again.

Now my question: is there a user-friendly alternative to enable the Add-In? Since the fewest of our users have administrative privileges, we cannot ask them to change some registry keys in order to fix the problem.

I hope that someone can help me with this.

Best regards

Timo

答:
Not knowing much about your add-in, I can think of 2 possibilities:

Since the registry key is in HKCU (which is normally fairly accessible) why not create a 2nd 'helper add-in' that checks for problems with this key and resets it when required?

Otherwise you could use Inno Setup to create a dummy installer that does this for you?

I think this is possible because your target location is HKEY_CURRENT_USER/SOFTWARE/Microsoft/Office/15.0/Word/AddInLoadTimes (i.e. HKCU) which usually can be modified without admin rights: Changing registry without admin rights


问:
setStatusBarHidden is deprecated in iOS 9.0
I am upgrading my code from iOS 8 to iOS 9. I have a code snippet in my program
[[UIApplication applicationName] setStatusBarHidden:YES];.

I am getting the warning "setStatusBarHidden is deprecated in iOS 9.0, Use -[UIViewController prefersStatusBarHidden". If I just replace 'setStatusBarHidden' with 'prefersStatusBarHidden', I get 'instance method not found'.
Can someone please suggest me how to solve this problem?

答:
prefersStatusBarHidden is available from iOS 7+.

Use this in Your UIViewController class

```<code>   var isHidden = true{
        didSet{
            self.setNeedsStatusBarAppearanceUpdate()
        }
    }
    override var prefersStatusBarHidden: Bool {
        return isHidden
    }
</code>```

If you change the return value for this method, call the
  setNeedsStatusBarAppearanceUpdate() method. To specify that a child
  view controller should control preferred status bar hidden/unhidden
  state, implement the childViewControllerForStatusBarHidden method.

Body:
prefersStatusBarHidden is available from iOS 7+.

Use this in Your UIViewController class

   var isHidden = true{
        didSet{
            self.setNeedsStatusBarAppearanceUpdate()
        }
    }
    override var prefersStatusBarHidden: Bool {
        return isHidden
    }

If you change the return value for this method, call the
  setNeedsStatusBarAppearanceUpdate() method. To specify that a child
  view controller should control preferred status bar hidden/unhidden
  state, implement the childViewControllerForStatusBarHidden method.


问:
iPhone X Launch Screen Storyboard Align UITabBar to Bottom
I am updating my LaunchScreen.storyboard for the iPhone X (using Xcode 9.1) but cannot get the UITabBar to align to the absolute bottom. The Bottom Layout Guide seems to end at the safe area using the suggested constraints. Does anyone know what property or constraint I need to add?

Note that I am deliberately using a UIViewController with a UITabBar instead of a UITabBarController because I do not want any tabs selected by default and this seems to be the only workaround.

答:
If you uncheck "Safe Area Relative Margins" on the tab bar (shown in your screenshot), delete your existing bottom constraint, and then drag the UITabBar into the home indicator area... you should be able to create a new bottom constraint of "0" and it'll stay there.

We just ran into the same problem... and noticed that if you set the XIB to be for any device but the iPhone X it renders a pre-X sized UITabBar for those launch screens, so keep that in mind... leave it on that device setting if you run into the same issue.


问:
Rotate a GameObject slowly on click on it
I have this game object that I am trying to rotate 90 degrees.

How to make it rotate smoothly?

private void OnMouseDown()
{
   gameObject.transform.Rotate(new Vector3(0, 0, -90));
}
```

答:
You can use a Coroutine to slowly animate it.

float rotationAmount = .1f;
float delaySpeed = .1f;
private void OnMouseDown(){
    StartCoroutine(SlowSpin());
}
IEnumerator SlowSpin(){
    float count = 0;
    while(count <= 90){
        gameObject.transform.Rotate(new Vector3(0, 0, rotationAmount));
        count += rotationAmount;
        yield return new WaitForSeconds(delaySpeed);
    }
}
```

Change the variables on lines 1 and 2 to suit your needs. However, don't set delaySpeed too high, otherwise your animation will become choppy.

Body:
You can use a Coroutine to slowly animate it.

float rotationAmount = .1f;
float delaySpeed = .1f;
private void OnMouseDown(){
    StartCoroutine(SlowSpin());
}
IEnumerator SlowSpin(){
    float count = 0;
    while(count <= 90){
        gameObject.transform.Rotate(new Vector3(0, 0, rotationAmount));
        count += rotationAmount;
        yield return new WaitForSeconds(delaySpeed);
    }
}

Change the variables on lines 1 and 2 to suit your needs. However, don't set delaySpeed too high, otherwise your animation will become choppy.


问:
Divide and Difference Between Two TextBoxes
I want to get difference and divided value in two textboxes. Either my javascript or Jquery isn't running. I get problem to get output while calculating the difference in Time and Divided value and finally multiplying with 100.

View:

```<code>        <td>
            <input type="text" id="supply" class="supply form-control" onchange="fill()"/>
            <span class="error">Supply required</span>
        </td>

        <td>
            <input type="text" id="POB" class="POB form-control" onchange="fill()"/>
            <span class="error">POB required</span>
        </td>
        <td>
            <input type="text" id="OCC" class="OCC form-control"/>
            <span class="error">OCC required</span>
        </td>

        <td>
            <input type="text" id="ETD" placeholder="00:00" class="ETD form-control" />
            <span class="error">ETD required</span>
        </td>

        <td>
            <input type="text" id="ATD" placeholder="00:00" class="ATD form-control" onchange="DifferenceTime()" />
            <span class="error">ATD required</span>
        </td>

        <td>
            <input type="text" id="Delay" placeholder="00:00" class="Delay form-control" />
            <span class="error">Delay required</span>
        </td>
</code>```

and inside the Page at bottom i have created a function as:

```<code>function fill() {
            var total = (Number($('#POB').val()) / Number($('#supply').val()))*100;
            $('#OCC').val(total);
        }

function DifferenceTime(){
    var time= $('#ATD').val() -$('#ETD').val();
    $('#Delay').val(time);
    }
</code>```

While calculating difference in time is as:
ATD: 00:20
ETD: 00:10 finally Delay should be 00:10. I need suitable help from all members.

答: You are missing the function brackets of onchange function. You have to rewrite onchange=DifferenceTime(). It will work, then you can check whether the logic is correct or not. Please check this for more.</p>

Body:
I want to get difference and divided value in two textboxes. Either my javascript or Jquery isn't running. I get problem to get output while calculating the difference in Time and Divided value and finally multiplying with 100.

View:

            <input type="text" id="supply" class="supply form-control" onchange="fill()"/>
            Supply required

            <input type="text" id="POB" class="POB form-control" onchange="fill()"/>
            POB required

            <input type="text" id="OCC" class="OCC form-control"/>
            OCC required

            <input type="text" id="ETD" placeholder="00:00" class="ETD form-control" />
            ETD required

            <input type="text" id="ATD" placeholder="00:00" class="ATD form-control" onchange="DifferenceTime()" />
            ATD required

            <input type="text" id="Delay" placeholder="00:00" class="Delay form-control" />
            Delay required

and inside the Page at bottom i have created a function as:

function fill() {
            var total = (Number($('#POB').val()) / Number($('#supply').val()))*100;
            $('#OCC').val(total);
        }

function DifferenceTime(){
    var time= $('#ATD').val() -$('#ETD').val();
    $('#Delay').val(time);
    }

While calculating difference in time is as:
ATD: 00:20
ETD: 00:10 finally Delay should be 00:10. I need suitable help from all members.


问:
how to lose the focus of JtextFeild onClick
how to lose focus of JFormatedTextfeild when click on Calender Window</p>

```<code>private void dateTxtFocusGained(java.awt.event.FocusEvent evt) {
    // TODO add your handling code here:
    PickDate ex=new PickDate();
    // dateTxt.setText(Helper.pickDate.toString());
}

...

private class MyDateListener implements DateListener
{
    public void dateChanged(DateEvent e)
    {
        Calendar c = e.getSelectedDate();
        if (c != null) {
            formatTxt.setText(c.getTime());
            PickDate.this.dispose(); // pickdate is nothing but JFrame in which calender shows
        }
        else {
            System.out.println("No time selected.");
        }
    }
}
</code>```

答:
One hack I have used in the past is to toggle the focusability of the component. In your onClick event:</p>

```<code>//we just want to lose current caret focus
//but still have textfield be focusable
dateTxt.setFocusable(false);
dateTxt.setFocusable(true);
</code>```

Body:
how to lose focus of JFormatedTextfeild when click on Calender Window

private void dateTxtFocusGained(java.awt.event.FocusEvent evt) {
    // TODO add your handling code here:
    PickDate ex=new PickDate();
    // dateTxt.setText(Helper.pickDate.toString());
}

...

private class MyDateListener implements DateListener
{
    public void dateChanged(DateEvent e)
    {
        Calendar c = e.getSelectedDate();
        if (c != null) {
            formatTxt.setText(c.getTime());
            PickDate.this.dispose(); // pickdate is nothing but JFrame in which calender shows
        }
        else {
            System.out.println("No time selected.");
        }
    }
}

Body:
One hack I have used in the past is to toggle the focusability of the component. In your onClick event:

//we just want to lose current caret focus
//but still have textfield be focusable
dateTxt.setFocusable(false);
dateTxt.setFocusable(true);


问:
Changing image color on hover without having to change the image
This question is pretty basic, but I want to be sure there isn't an alternative method than what I currently do. Let's say I have a Facebook icon. As of now, when a user hovers over that image, I display a different image in order to change the color. Is there an alternative CSS method to doing this, so I am not using multiple images?

In the fiddle below, I tried changing the background, but that just covers the entire image.

.social-icon {
    width: 20px;
    height: 20px;
    transition: ease .3s;
    -webkit-transition: ease .3s;
    margin-right: 5px;
    cursor: pointer;
}
#facebook-icon {
    background-image: url(https://s3.us-east-2.amazonaws.com/optimumdesigns/facebook-logo-gray.png);
    background-size: 20px 20px;
}
#facebook-icon:hover {
  background: #FFF;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="social-icon" id="facebook-icon"></div></code>```

jsFiddle

答:
Try this:

```<code>#facebook-icon:hover {
    background-color: blue;
    background-image: url(https://s3.us-east-2.amazonaws.com/optimumdesigns/facebook-logo-gray.png);
}
</code>```

.social-icon {
    width: 20px;
    height: 20px;
    transition: ease .3s;
    -webkit-transition: ease .3s;
    margin-right: 5px;
    cursor: pointer;
}

#facebook-icon {
    background-image: url(https://s3.us-east-2.amazonaws.com/optimumdesigns/facebook-logo-gray.png);
    background-size: 20px 20px;
}

#facebook-icon:hover {
    background-color: blue;
    background-image: url(https://s3.us-east-2.amazonaws.com/optimumdesigns/facebook-logo-gray.png);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="social-icon" id="facebook-icon"></div></code>```

Body:
This question is pretty basic, but I want to be sure there isn't an alternative method than what I currently do. Let's say I have a Facebook icon. As of now, when a user hovers over that image, I display a different image in order to change the color. Is there an alternative CSS method to doing this, so I am not using multiple images?

In the fiddle below, I tried changing the background, but that just covers the entire image.

.social-icon {
    width: 20px;
    height: 20px;
    transition: ease .3s;
    -webkit-transition: ease .3s;
    margin-right: 5px;
    cursor: pointer;
}
#facebook-icon {
    background-image: url(https://s3.us-east-2.amazonaws.com/optimumdesigns/facebook-logo-gray.png);
    background-size: 20px 20px;
}
#facebook-icon:hover {
  background: #FFF;
}

jsFiddle

Body:
Try this:

#facebook-icon:hover {
    background-color: blue;
    background-image: url(https://s3.us-east-2.amazonaws.com/optimumdesigns/facebook-logo-gray.png);
}

.social-icon {
    width: 20px;
    height: 20px;
    transition: ease .3s;
    -webkit-transition: ease .3s;
    margin-right: 5px;
    cursor: pointer;
}

#facebook-icon {
    background-image: url(https://s3.us-east-2.amazonaws.com/optimumdesigns/facebook-logo-gray.png);
    background-size: 20px 20px;
}

#facebook-icon:hover {
    background-color: blue;
    background-image: url(https://s3.us-east-2.amazonaws.com/optimumdesigns/facebook-logo-gray.png);
}

<div class="social-icon" id="facebook-icon"></div>