问:
How to use a different alphabet for Base32 classes?
On python when I do:

```<code>encoded = base64.b32encode("1ACC64E9510C32CE8E34".decode('hex'))
</code>```

I get DLGGJ2KRBQZM5DRU. While on Crypto++:

```<code>std::string decoded2;
std::string first_20="1ACC64E9510C32CE8E34";

StringSource ssv(first_20, true /*pumpAll*/,
    new HexDecoder(
        new StringSink(decoded2)
    ) // HexDecoder
); // StringSource
boost::algorithm::to_lower(decoded2);

StringSource ss( decoded2, true,

    new Base32Encoder(
        new StringSink(hash_sink)
    ) // Base64Decoder
); // StringSource

std::cout<<"encoded raw:"<<hash_sink<<std::endl;
</code>```

I get DMGGJ4MTBS3N7DTW which is wrong.

Is there a way I can encode the string above in c++ and get the same result as python does it ?

答:
I found the perfect solution github

```<code>static const CryptoPP::byte ALPHABET[]          = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"; // Most libraries use RFC4648.

const std::string decode( const std::string& encoded )
{
    std::string decoded;

    static int decoding_array[256];
    CryptoPP::Base32Decoder::InitializeDecodingLookupArray(decoding_array,
                               ALPHABET,
                               32,
                               true); // false = case insensitive

    CryptoPP::Base32Decoder b32decoder;
    CryptoPP::AlgorithmParameters dp = CryptoPP::MakeParameters(
                                       CryptoPP::Name::DecodingLookupArray(),
                                       (const int *)decoding_array,
                                       false);
    b32decoder.IsolatedInitialize(dp);

    b32decoder.Attach( new CryptoPP::StringSink( decoded ) );
    b32decoder.Put( (std::uint8_t*)encoded.c_str(), encoded.size() );
    b32decoder.MessageEnd();

    return decoded;
}
</code>```

I hope the guy who downvoted me can also see this.
I'm very new to crypto++ and cryptography as a whole.

Body:
On python when I do:

encoded = base64.b32encode("1ACC64E9510C32CE8E34".decode('hex'))

I get DLGGJ2KRBQZM5DRU. While on Crypto++:

std::string decoded2;
std::string first_20="1ACC64E9510C32CE8E34";

StringSource ssv(first_20, true /*pumpAll*/,
    new HexDecoder(
        new StringSink(decoded2)
    ) // HexDecoder
); // StringSource
boost::algorithm::to_lower(decoded2);

StringSource ss( decoded2, true,

    new Base32Encoder(
        new StringSink(hash_sink)
    ) // Base64Decoder
); // StringSource

std::cout<<"encoded raw:"<<hash_sink<<std::endl;

I get DMGGJ4MTBS3N7DTW which is wrong.

Is there a way I can encode the string above in c++ and get the same result as python does it ?

Body:
I found the perfect solution github

static const CryptoPP::byte ALPHABET[]          = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"; // Most libraries use RFC4648.

const std::string decode( const std::string& encoded )
{
    std::string decoded;

    static int decoding_array[256];
    CryptoPP::Base32Decoder::InitializeDecodingLookupArray(decoding_array,
                               ALPHABET,
                               32,
                               true); // false = case insensitive

    CryptoPP::Base32Decoder b32decoder;
    CryptoPP::AlgorithmParameters dp = CryptoPP::MakeParameters(
                                       CryptoPP::Name::DecodingLookupArray(),
                                       (const int *)decoding_array,
                                       false);
    b32decoder.IsolatedInitialize(dp);

    b32decoder.Attach( new CryptoPP::StringSink( decoded ) );
    b32decoder.Put( (std::uint8_t*)encoded.c_str(), encoded.size() );
    b32decoder.MessageEnd();

    return decoded;
}

I hope the guy who downvoted me can also see this.
I'm very new to crypto++ and cryptography as a whole.


来源: stackexchange

问:
C# Class with list and non list items
How would I add data to the below class lists. Both the lists are dynamic and the dailyclockings list can be different for each item of the clockings list.
I'm currently able to add data to each list, clockings and dailyclockings but the data in dailyclockings does not pulls through to clockings[1].dailyclockings[1]. I can only see data in clockings[1].name and dailyclockings[1].clockingdate but if I display clockings[1].dailyclocking[1].clockingdate the value is null.

What I'm try to achieve is the following

```<code> Clockings[1].Department = "Testing"
 Clockings[1].Name = "Fred"
 Clockings[1].DailyClockings[1].ClockingDate = "2017/11/01"
 Clockings[1].DailyClockings[1].InClockingTime = "08:00"
 Clockings[1].DailyClockings[1].OutClockingTime = "14:00"
 Clockings[1].DailyClockings[2].ClockingDate = "2017/11/02"
 Clockings[1].DailyClockings[2].InClockingTime = "08:00"
 Clockings[1].DailyClockings[2].OutClockingTime = "14:00"
 Clockings[1].DailyClockings[3].ClockingDate = "2017/11/03"
 Clockings[1].DailyClockings[3].InClockingTime = "08:00"
 Clockings[1].DailyClockings[3].OutClockingTime = "14:00"
 Clockings[1].DailyClockings[4].ClockingDate = "2017/11/06"
 Clockings[1].DailyClockings[4].InClockingTime = "08:00"
 Clockings[1].DailyClockings[4].OutClockingTime = "14:00"

  public class Clockings
    {

        public string Department { get; set; }
        public string UserName { get; set; }
        public string StartTime { get; set; }
        public int NoofDaysClocked { get; set; }

        public List<DailyClocking> DailyClockings { get; set; }

    }

    public class DailyClocking
    {
        public string InClockingTime { get; set; }
        public string OutClockingTime { get; set; }
        public string ClockingDate { get; set; }
        public string DayofTheWeek { get; set; }
        public string MinInEarly { get; set; }
        public string MinOutEarly { get; set; }
    }

 public List<Clockings> clockingTime()
        {
            List<Clockings> f = new List<Clockings>() ;

            Clockings d = new Clockings();

            DailyClocking d1 = new DailyClocking();
            List<DailyClocking> d2 = new List<DailyClocking>();

            float noofusers =1;
            int col = 0;
            int tmpemp = 0;
            int n =0, x = 0;

            var cmd = db.Database.Connection.CreateCommand();

            cmd.CommandType = CommandType.StoredProcedure;
            cmd.CommandText = "[dbo].LateClocking";

            SqlParameter param = new SqlParameter();
            param.ParameterName = "@StartDate";
            param.Value = 20170901;
            cmd.Parameters.Add(param);

            SqlParameter param1 = new SqlParameter();
            param1.ParameterName = "@EndDate";
            param1.Value = 20170930;
            cmd.Parameters.Add(param1);

            SqlParameter param2 = new SqlParameter();
            param2.ParameterName = "@Branch";
            param2.Value = "";
            cmd.Parameters.Add(param2);

            SqlParameter param3 = new SqlParameter();
            param3.ParameterName = "@department";
            param3.Value = "";
            cmd.Parameters.Add(param3);

            SqlParameter param4 = new SqlParameter();
            param4.ParameterName = "@Nme";
            param4.Value = "Fred Smith";
            cmd.Parameters.Add(param4);

            try
            {
                cmd.Connection.Open();
                var reader = cmd.ExecuteReader();

                if (reader.HasRows)
                {

                    while (reader.Read())
                    {
                        if (tmpemp == int.Parse( reader["mst_sq"].ToString() ) )
                        {}
                        else
                        {
                            if (noofusers >1)
                            {
                                f.Add(d);
                            }
                            col = 0;
                            noofusers = noofusers + 1;
                            tmpemp = int.Parse(reader["mst_sq"].ToString());
                            d.UserName = reader["mst_firstname"].ToString() + " " + reader["mst_lastname"].ToString();
                            d.StartTime = reader["starttime"].ToString();
                            d.Department = reader["dept_name"].ToString();
                        }
                        if (reader["dy"].Equals(System.DBNull.Value))
                        {}
                        else
                        {
                            d1.ClockingDate = reader["dy"].ToString().Substring(0, 4) + reader["dy"].ToString().Substring(5, 2) + reader["dy"].ToString().Substring(8, 2);
                            d1.MinInEarly = reader["mnearly"].ToString();
                            d1.MinInEarly = reader["mnlate"].ToString();
                            d1.InClockingTime = reader["tmeclocked"].ToString().Substring(11, 5);
                            d1.OutClockingTime = reader["earlyclocked"].ToString().Substring(11, 5);
                            d2.Add(d1);
                        }
                        col = col + 1;
                        d.NoofDaysClocked = col;

                    }
                    f.Add(new f.DailyClockings( d2));
                    f.Add(d);
                }

            }
            catch (Exception ex)
            {
                // your handling code here

            }

            return (f);
        }
</code>```

答:
Excuse me if I'm wrong, I would comment but my reputation restricts me.

Anyway, in this part here:

```<code>f.Add(new f.DailyClockings( d2));
f.Add(d);
</code>```

It looks as if you take the Clockings list, add the DailyClocking list to the list as an object, and then add the Clockings object to the list afterwards.

Should it perhaps be something like this? :

```<code>d.DailyClockings = d2;
f.Add(d);
</code>```

ContentLicense: CC BY-SA 3.0

Title: C# Class with list and non list items

Body:
How would I add data to the below class lists. Both the lists are dynamic and the dailyclockings list can be different for each item of the clockings list.
I'm currently able to add data to each list, clockings and dailyclockings but the data in dailyclockings does not pulls through to clockings[1].dailyclockings[1]. I can only see data in clockings[1].name and dailyclockings[1].clockingdate but if I display clockings[1].dailyclocking[1].clockingdate the value is null.

What I'm try to achieve is the following

 Clockings[1].Department = "Testing"
 Clockings[1].Name = "Fred"
 Clockings[1].DailyClockings[1].ClockingDate = "2017/11/01"
 Clockings[1].DailyClockings[1].InClockingTime = "08:00"
 Clockings[1].DailyClockings[1].OutClockingTime = "14:00"
 Clockings[1].DailyClockings[2].ClockingDate = "2017/11/02"
 Clockings[1].DailyClockings[2].InClockingTime = "08:00"
 Clockings[1].DailyClockings[2].OutClockingTime = "14:00"
 Clockings[1].DailyClockings[3].ClockingDate = "2017/11/03"
 Clockings[1].DailyClockings[3].InClockingTime = "08:00"
 Clockings[1].DailyClockings[3].OutClockingTime = "14:00"
 Clockings[1].DailyClockings[4].ClockingDate = "2017/11/06"
 Clockings[1].DailyClockings[4].InClockingTime = "08:00"
 Clockings[1].DailyClockings[4].OutClockingTime = "14:00"

  public class Clockings
    {

        public string Department { get; set; }
        public string UserName { get; set; }
        public string StartTime { get; set; }
        public int NoofDaysClocked { get; set; }

        public List<DailyClocking> DailyClockings { get; set; }

    }

    public class DailyClocking
    {
        public string InClockingTime { get; set; }
        public string OutClockingTime { get; set; }
        public string ClockingDate { get; set; }
        public string DayofTheWeek { get; set; }
        public string MinInEarly { get; set; }
        public string MinOutEarly { get; set; }
    }

 public List<Clockings> clockingTime()
        {
            List<Clockings> f = new List<Clockings>() ;

            Clockings d = new Clockings();

            DailyClocking d1 = new DailyClocking();
            List<DailyClocking> d2 = new List<DailyClocking>();

            float noofusers =1;
            int col = 0;
            int tmpemp = 0;
            int n =0, x = 0;

            var cmd = db.Database.Connection.CreateCommand();

            cmd.CommandType = CommandType.StoredProcedure;
            cmd.CommandText = "[dbo].LateClocking";

            SqlParameter param = new SqlParameter();
            param.ParameterName = "@StartDate";
            param.Value = 20170901;
            cmd.Parameters.Add(param);

            SqlParameter param1 = new SqlParameter();
            param1.ParameterName = "@EndDate";
            param1.Value = 20170930;
            cmd.Parameters.Add(param1);

            SqlParameter param2 = new SqlParameter();
            param2.ParameterName = "@Branch";
            param2.Value = "";
            cmd.Parameters.Add(param2);

            SqlParameter param3 = new SqlParameter();
            param3.ParameterName = "@department";
            param3.Value = "";
            cmd.Parameters.Add(param3);

            SqlParameter param4 = new SqlParameter();
            param4.ParameterName = "@Nme";
            param4.Value = "Fred Smith";
            cmd.Parameters.Add(param4);

            try
            {
                cmd.Connection.Open();
                var reader = cmd.ExecuteReader();

                if (reader.HasRows)
                {

                    while (reader.Read())
                    {
                        if (tmpemp == int.Parse( reader["mst_sq"].ToString() ) )
                        {}
                        else
                        {
                            if (noofusers >1)
                            {
                                f.Add(d);
                            }
                            col = 0;
                            noofusers = noofusers + 1;
                            tmpemp = int.Parse(reader["mst_sq"].ToString());
                            d.UserName = reader["mst_firstname"].ToString() + " " + reader["mst_lastname"].ToString();
                            d.StartTime = reader["starttime"].ToString();
                            d.Department = reader["dept_name"].ToString();
                        }
                        if (reader["dy"].Equals(System.DBNull.Value))
                        {}
                        else
                        {
                            d1.ClockingDate = reader["dy"].ToString().Substring(0, 4) + reader["dy"].ToString().Substring(5, 2) + reader["dy"].ToString().Substring(8, 2);
                            d1.MinInEarly = reader["mnearly"].ToString();
                            d1.MinInEarly = reader["mnlate"].ToString();
                            d1.InClockingTime = reader["tmeclocked"].ToString().Substring(11, 5);
                            d1.OutClockingTime = reader["earlyclocked"].ToString().Substring(11, 5);
                            d2.Add(d1);
                        }
                        col = col + 1;
                        d.NoofDaysClocked = col;

                    }
                    f.Add(new f.DailyClockings( d2));
                    f.Add(d);
                }

            }
            catch (Exception ex)
            {
                // your handling code here

            }

            return (f);
        }

Body:
Excuse me if I'm wrong, I would comment but my reputation restricts me.

Anyway, in this part here:

f.Add(new f.DailyClockings( d2));
f.Add(d);

It looks as if you take the Clockings list, add the DailyClocking list to the list as an object, and then add the Clockings object to the list afterwards.

Should it perhaps be something like this? :

d.DailyClockings = d2;
f.Add(d);


问:
Drop down selection is still selectable with "readonly" attribute
I want a read-only "select" element to be not selectable, the same behavior as the readonly input box.

In the code below, you cannot change the value for the input box with the value "abc". However, you can still change the selection in the drop. I can't use "disabled" attribute because I still need to send these values to the server.

```<code><input type="text" readonly="readonly" value="abc">

</input>

<select readonly="readonly">
  <option>Item ABC</option>
  <option>Item XYZ</option>
</select>
</code>```

https://jsfiddle.net/6Lu1jpLx/

答:
Simplist way to resolve this would be to use the below line:

```<code>$("#MySelect").css("pointer-events","none");
</code>```

However, the following worked for me where in my case I wanted my Select to still have the disabled cursor - setting 'pointer-events' to 'none' will no longer show cursor as 'not-allowed'.

JQUERY

```<code>var isReadOnly = $("#MyCheckbox").prop("checked");
var domElements = $("#MyInput, #MySelect");

$(domElements).prop("readonly", isReadOnly);
$(domElements).toggleClass("my-read-only-class", isReadOnly);
$(domElements).find("option").prop("hidden", isReadOnly);
</code>```

CSS

```<code>.my-read-only-class
{
   cursor: not-allowed;
}
</code>```

JSFiddle https://jsfiddle.net/xdddzupm/

Body:
I want a read-only "select" element to be not selectable, the same behavior as the readonly input box.

In the code below, you cannot change the value for the input box with the value "abc". However, you can still change the selection in the drop. I can't use "disabled" attribute because I still need to send these values to the server.

<input type="text" readonly="readonly" value="abc">

</input>

<select readonly="readonly">
  <option>Item ABC</option>
  <option>Item XYZ</option>
</select>

https://jsfiddle.net/6Lu1jpLx/

Body:
Simplist way to resolve this would be to use the below line:

$("#MySelect").css("pointer-events","none");

However, the following worked for me where in my case I wanted my Select to still have the disabled cursor - setting 'pointer-events' to 'none' will no longer show cursor as 'not-allowed'.

JQUERY

var isReadOnly = $("#MyCheckbox").prop("checked");
var domElements = $("#MyInput, #MySelect");

$(domElements).prop("readonly", isReadOnly);
$(domElements).toggleClass("my-read-only-class", isReadOnly);
$(domElements).find("option").prop("hidden", isReadOnly);

CSS

.my-read-only-class
{
   cursor: not-allowed;
}

JSFiddle https://jsfiddle.net/xdddzupm/


问:
How to include External CSS and JS file in Laravel 5.5
I am Using Laravel 5.5, the Form and HTML Helper are removed from this version. I don't know how to include external style sheet and JavaScript files in my header file.

Currently I am using this code:

```<code>{{ HTML::style('css/bootstrap.min.css') }}
</code>```

答:
put your css in public/css and js in public/js and add follow code *.blade.php file

e.g.

```<code><link href="{{ asset('css/app.min.css') }}" media="all" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="{{ asset('js/app.min.js') }}"></script>
</code>```

Body:
I am Using Laravel 5.5, the Form and HTML Helper are removed from this version. I don't know how to include external style sheet and JavaScript files in my header file.

Currently I am using this code:

{{ HTML::style('css/bootstrap.min.css') }}

Body:
put your css in public/css and js in public/js and add follow code *.blade.php file

e.g.

<link href="{{ asset('css/app.min.css') }}" media="all" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="{{ asset('js/app.min.js') }}"></script>


问:
Hibernate mapping multiple class in one configuration file
I have 2 POJO's User and Gift and two tables user and gift. I want to mapping to both User and Gift classes(In database, user and Gift have no relation between them). I use annotation to define User and Gift classes. Below way is wrong, the reason is I only can add one , and the first mapping always works, but the second mapping throws exception.

```<code><hibernate-configuration>
 <session-factory name="hibernateSessionFactory">
  <mapping class="peppergo.GiftShop.Model.User"/>
  <mapping class="peppergo.GiftShop.Model.Administrator"/>
 </session-factory>
</code>```

How can I mapping two classes in one hibernate configuration file.
I don't want to use Spring MVC this time.

答:
You can map any no. of classes or .hbm.xml file in hibernate configuration. There may be some problem with the second entity. Try commenting the first entity configuration and check.

Below is working for me:

```<code>   <mapping resource="resource/AccountTypeCodeMap.hbm.xml" />
   <mapping class="bo.Entity1"/>
   <mapping class="bo.Entity2"/>
</code>```

Body:
I have 2 POJO's User and Gift and two tables user and gift. I want to mapping to both User and Gift classes(In database, user and Gift have no relation between them). I use annotation to define User and Gift classes. Below way is wrong, the reason is I only can add one , and the first mapping always works, but the second mapping throws exception.

<hibernate-configuration>
 <session-factory name="hibernateSessionFactory">
  <mapping class="peppergo.GiftShop.Model.User"/>
  <mapping class="peppergo.GiftShop.Model.Administrator"/>
 </session-factory>

How can I mapping two classes in one hibernate configuration file.
I don't want to use Spring MVC this time.

Body:
You can map any no. of classes or .hbm.xml file in hibernate configuration. There may be some problem with the second entity. Try commenting the first entity configuration and check.

Below is working for me:

   <mapping resource="resource/AccountTypeCodeMap.hbm.xml" />
   <mapping class="bo.Entity1"/>
   <mapping class="bo.Entity2"/>


问:
Docker-compose with Loopback and Mongodb fail to connect mongdb
I have been learning docker lately and I was unable to make a connection between my loopback api and mongodb. The application works fine in local dev environment. With docker-compose my mongodb server runs at localhost:27017 and my react-frontend serves at localhost:3000 and looks fine. Only loopback is unable to connect to mongodb and throws the following errors:

```<code>loopback_1  | Web server listening at: http://localhost:8080
loopback_1  | Browse your REST API at http://localhost:8080/explorer
loopback_1  | Connection fails: MongoError: failed to connect to server
[localhost:27017] on first connect [MongoError: connect ECONNREFUSED
127.0.0.1:27017]
loopback_1  | It will be retried for the next request.
loopback_1  |
loopback_1  | /opt/src/app/node_modules/mongodb/lib/mongo_client.js:421
loopback_1  |           throw err
loopback_1  |           ^
loopback_1  | MongoError: failed to connect to server [localhost:27017]
on first connect [MongoError: connect ECONNREFUSED 127.0.0.1:27017]
loopback_1  |     at Pool.<anonymous>
(/opt/src/app/node_modules/mongodb-core/lib/topologies/server.js:336:35)
</code>```

Here is my Dockerfile for Loopback-API

```<code>FROM node:6

RUN mkdir -p /opt/src/app

WORKDIR  /opt/src/app

COPY package.json /opt/src/app

RUN npm cache clean

RUN npm install

COPY . /opt/src/app

EXPOSE 8080

CMD ["npm", "start"]
</code>```

My docker-compose file looks like this:

```<code>    version: '3.0' # specify docker-compose version

# Define the services/containers to be run
services:
  database: # name of first service
      image: mongo # specify the image to build container from
      ports:
        - "27017:27017" # specify port forwarding

  loopback: # name of second service
      build: myapp_backend # specify the directory of the Dockerfile
      ports:
        - "8080:8080" # specify port mapping
      links:
        - database # link this service to the database service

  react: # name of third service
      build: myapp_frontend # specify the directory of the Dockerfile
      ports:
        - "3000:3000" #specify port mapping
</code>```

And finally datasource file in loopback-api looks like this:

```<code>    {
  "db": {
    "host": "localhost",
    "port": 27017,
    "url": "",
    "database": "test",
    "password": "",
    "name": "mongoDS",
    "user": "",
    "connector": "mongodb"
  }
}
</code>```

答:
Your datasource file should have:

"host": "database"
...

since in docker-compose.yml you link mongo container to loopback as database, so it's not localhost. Remember, you are trying to connect to mongo from loopback docker container. Also you should make sure that mongo is started before loopback, so add depends_on: database to loopback service in docker-compose.yml.

Body:
I have been learning docker lately and I was unable to make a connection between my loopback api and mongodb. The application works fine in local dev environment. With docker-compose my mongodb server runs at localhost:27017 and my react-frontend serves at localhost:3000 and looks fine. Only loopback is unable to connect to mongodb and throws the following errors:

loopback_1  | Web server listening at: http://localhost:8080
loopback_1  | Browse your REST API at http://localhost:8080/explorer
loopback_1  | Connection fails: MongoError: failed to connect to server
[localhost:27017] on first connect [MongoError: connect ECONNREFUSED
127.0.0.1:27017]
loopback_1  | It will be retried for the next request.
loopback_1  |
loopback_1  | /opt/src/app/node_modules/mongodb/lib/mongo_client.js:421
loopback_1  |           throw err
loopback_1  |           ^
loopback_1  | MongoError: failed to connect to server [localhost:27017]
on first connect [MongoError: connect ECONNREFUSED 127.0.0.1:27017]
loopback_1  |     at Pool.<anonymous>
(/opt/src/app/node_modules/mongodb-core/lib/topologies/server.js:336:35)

Here is my Dockerfile for Loopback-API

FROM node:6

RUN mkdir -p /opt/src/app

WORKDIR  /opt/src/app

COPY package.json /opt/src/app

RUN npm cache clean

RUN npm install

COPY . /opt/src/app

EXPOSE 8080

CMD ["npm", "start"]

My docker-compose file looks like this:

    version: '3.0' # specify docker-compose version

# Define the services/containers to be run
services:
  database: # name of first service
      image: mongo # specify the image to build container from
      ports:
        - "27017:27017" # specify port forwarding

  loopback: # name of second service
      build: myapp_backend # specify the directory of the Dockerfile
      ports:
        - "8080:8080" # specify port mapping
      links:
        - database # link this service to the database service

  react: # name of third service
      build: myapp_frontend # specify the directory of the Dockerfile
      ports:
        - "3000:3000" #specify port mapping

And finally datasource file in loopback-api looks like this:

    {
  "db": {
    "host": "localhost",
    "port": 27017,
    "url": "",
    "database": "test",
    "password": "",
    "name": "mongoDS",
    "user": "",
    "connector": "mongodb"
  }
}


问:
Update content to client in near real time: polling vs long polling vs signalr?
We have a website where the user can fill input form and submit his/her contact number to get loan approval. Once the user submits the form, we accept it on the server side and send an immediate response (while we relay this request to some third party API in the background). While we allow the user to browse other sections of the website, we want to show loan approval report based on his number as soon as we get it from the external API.

One way to do this is by:

Polling as user moves to any new page (OR at regular intervals)

Ajax Long polling

Using SignalR. I find it apt to use this here. But I was wondering if this is the right fit for our situation. Also, I was a bit apprehensive in using this considering server resources and performance as I read in signalr "The connection between the client and server is persistent, unlike a classic HTTP connection, which is re-established for each communication."

答:
SignalR would be useful in this scenario.

On your server you can have signalR connected to client with client side script ready to do fancy notifications.
When you get response back from API you can then notify customer (call the client script with connection ID) if they have passed or failed credit check or loan has been approved, pending or take more time.


问:
Why does openCV store a file larger(kB) than the original?
I have code that loads and saves the image in two different ways - first using openCV, the second using PIL.

```<code>import cv2
from PIL import Image

img = cv2.imread("/home/myname/png/image.png")
cv2.imwrite("/home/myname/png/image_save.png", img)

img = Image.open("/home/myname/png/image.png")
img.save("/home/myname/png/image_save_pil.png")
</code>```

The original image is 204.6 kB in size. The result obtained with openCV is 245.0 kB, the result of PIL is 204.6 kB.

Why does the image saved with openCV have a larger size?

答:
You cannot expect two PNGs to have the same size if they were produced by different libraries.

File specifications define the structure of a file so everyone knows where to write information and where to find it. How to encode and how to decode data...

Many things are optional, like metadata, compression rates, ...

It's like raising identical twins in two different families.

You can try to set the same parameters to image writing functions, but even then it is unlikely that you get exact same file size.

Body:
I have code that loads and saves the image in two different ways - first using openCV, the second using PIL.

import cv2
from PIL import Image

img = cv2.imread("/home/myname/png/image.png")
cv2.imwrite("/home/myname/png/image_save.png", img)

img = Image.open("/home/myname/png/image.png")
img.save("/home/myname/png/image_save_pil.png")

The original image is 204.6 kB in size. The result obtained with openCV is 245.0 kB, the result of PIL is 204.6 kB.

Why does the image saved with openCV have a larger size?


问:
Laravel - Vue - Components not updating
I have a fresh installation of laravel 5.4.

I have successfully created a new component and displayed it correctly.

I use npm run watch and my .vue files get compiled correctly.

But now, any changes I make to the .vue files do not get updated.

I purposely made errors to them to see if they compiled but they failed, so I conclude that the watch command successfuly sees changes made to them, on the other hand, nothing updates in the browser (only blade files update).

Any ideas what this could come from ?

PS: I tried php artisan cache:clear but no success.

答:
Silly, the name of the component had a dash in it:

```<code>Vue.component('cardtest-component', require('./components/CardTestComponent.vue'));
</code>```

It was just a typo.

Title: Laravel - Vue - Components not updating

Body:
Silly, the name of the component had a dash in it:

Vue.component('cardtest-component', require('./components/CardTestComponent.vue'));

It was just a typo.


问:
Regular expression to match tags containing certain data
I need help to make a reg exp. to match these:
The goal is to match any html tag that only
 or/and spaces.

```<code><p><br/></p>
<h1><br/></h1>
<p><br/><br/></p>
<span><br/><br/></span>
<b><br/>   <br/>    </b>
<h2><br/>   <br/>    </h2>
</code>```

答:
Try:

```<code>preg_match_all('#<([\S]+)[^>]*>(\s*|(<br\s*/>)*)*</\\1>#i', $html, $m);
</code>```

If you want to strip elements that contain only comments as well as whitespace/
, that's going to be a pain, maybe even impossible, using regex alone.

ContentLicense: CC BY-SA 2.5

Body:
Try:

preg_match_all('#<([\S]+)[^>]*>(\s*|(<br\s*/>)*)*</\\1>#i', $html, $m);

If you want to strip elements that contain only comments as well as whitespace/<br/>, that's going to be a pain, maybe even impossible, using regex alone.


问:
Incrementing ratio button id in for loop
In a for loop i'm rendering radio buttons, but i need to increment the  radio button id to radio1,radio2 and so on. how can i do it ?

Please help.

            <input id="radio1" name="radio" [(ngModel)]="demandValue" [value]="demand.value" type="radio">
            {{demand.name}}
```

答:
    <input id="radio{{i}}" name="radio" [(ngModel)]="demandValue" [value]="demand.value" type="radio">

        {{demand.name}}

```

I added the index in for loop and it fixed the issue

Body:
<span class="radio-radio-wrapper padding-radio" *ngFor="let demand of Demands; let i = index;">
    <input id="radio{{i}}" name="radio" [(ngModel)]="demandValue" [value]="demand.value" type="radio">
    <span class="radioLabel">
        <label class="custom-control-description" for="radio{{i}}">{{demand.name}}</label>
    </span>
</span>

I added the index in for loop and it fixed the issue


问:
Saving large map in GenServer, is this a valid use case?
Could this be a valid use for GenServer:

If the process_id is the user_id and it is unique. Process contains a query result of a big map of data which is generated via DB. Now if 100's of users log in to the system and ask for their data map they all are saved in their own process referenced by the user_id which is unique

So upon asking for the map I will check to see if there is a process with user_id ( which is process id ) and grab it and feed it to back to the user, if not then I create it and put it in a new state

now if user updated his map, at the update, I make sure to update the sate or create a new one.

Thank you for your guidance

答:
If your genserver does nothing else than storing a map and returning it via an API, maybe it's not worth creating a lot of processes.

You can merely use an ets table for this purpose or use the Agent module (key=user id, value=map).


问:
DJANGO_SETTINGS_MODULE envar not getting set
I am currently developing an application in Python 3.6 and Django 1.11, on the production server (Ubuntu 16.04) I am using Apache2.

I am trying to use separated settings for production and development. Instead of a file, I have a settings directory with base setttings, and production and development settings file, which import the base settings and potentially override them. To let Django know which settings to use, I am setting the DJANGO_SETTINGS_MODULE to either prehranske_oznacbe.settings.development or  prehranske_oznacbe.settings.production. This works fine for development. Concerning setting the envvars on the production server, I followed the answers to these two SO:
Access Apache SetEnv variable from Django wsgi.py file, Django + mod_wsgi. Set OS environment variable from Apache's SetEnv.

The problem is, when I try to acces my application, I get a 500 Internal Error. The apache error logs:

```<code>mod_wsgi (pid=404): Target WSGI script '/home/inesmersak/prehranske_oznacbe/prehranske_oznacbe/wsgi.py' cannot be loaded as Python module.
mod_wsgi (pid=404): Exception occurred processing WSGI script '/home/inesmersak/prehranske_oznacbe/prehranske_oznacbe/wsgi.py'.
Traceback (most recent call last):
   File "/home/inesmersak/prehranske_oznacbe/prehranske_oznacbe/wsgi.py", line 25, in <module>
     application = WSGIEnvironment()
   File "/home/inesmersak/prehranske_oznacbe/venv/lib/python3.5/site-packages/django/core/handlers/wsgi.py", line 151, in __init__
     self.load_middleware()
   File "/home/inesmersak/prehranske_oznacbe/venv/lib/python3.5/site-packages/django/core/handlers/base.py", line 48, in load_middleware
     if settings.MIDDLEWARE is None:
   File "/home/inesmersak/prehranske_oznacbe/venv/lib/python3.5/site-packages/django/conf/__init__.py", line 56, in __getattr__
     self._setup(name)
   File "/home/inesmersak/prehranske_oznacbe/venv/lib/python3.5/site-packages/django/conf/__init__.py", line 39, in _setup
     % (desc, ENVIRONMENT_VARIABLE))
django.core.exceptions.ImproperlyConfigured: Requested setting MIDDLEWARE, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.
</code>```

as if the envvar DJANGO_SETTINGS_MODULE is not getting set. My code:

/etc/apache2/sites-available/000-default.conf

```<code><VirtualHost *:80>
    ServerAdmin webmaster@localhost
    DocumentRoot /var/www/html

    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined

    Alias /static /home/inesmersak/prehranske_oznacbe/static
    <Directory /home/inesmersak/prehranske_oznacbe/static>
        Require all granted
    </Directory>

    <Directory /home/inesmersak/prehranske_oznacbe/prehranske_oznacbe>
        <Files wsgi.py>
            Require all granted
        </Files>
    </Directory>

    WSGIDaemonProcess prehranske_oznacbe python-path=/home/inesmersak/prehranske_oznacbe python-home=/home/inesmersak/prehranske_oznacbe/venv
    WSGIProcessGroup prehranske_oznacbe
    WSGIScriptAlias / /home/inesmersak/prehranske_oznacbe/prehranske_oznacbe/wsgi.py

    # Envvars for Django aplication 'Prehranske oznacbe'.
    SetEnv DJANGO_SETTINGS_MODULE prehranske_oznacbe.settings.production
    SetEnv OZNACBE_API_USERNAME (redacted)
    SetEnv OZNACBE_API_PASSWORD (redacted)
    SetEnv OZNACBE_SECRET_KEY (redacted)
</VirtualHost>
</code>```

wsgi.py

```<code>import os
import django
from django.core.handlers.wsgi import WSGIHandler

class WSGIEnvironment(WSGIHandler):
    def __call__(self, environ, start_response):
        os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'prehranske_oznacbe.settings.production')
        os.environ['DJANGO_SETTINGS_MODULE'] = environ['DJANGO_SETTINGS_MODULE']
        os.environ['OZNACBE_SECRET_KEY'] = environ['OZNACBE_SECRET_KEY']
        os.environ['OZNACBE_API_USERNAME'] = environ['OZNACBE_API_USERNAME']
        os.environ['OZNACBE_API_PASSWORD'] = environ['OZNACBE_API_PASSWORD']
        django.setup()
        return super(WSGIEnvironment, self).__call__(environ, start_response)

application = WSGIEnvironment()
</code>```

答:
SetEnv does not set process wide environment variables for a WSGI application, it sets the per request WSGI environ variables passed in the environ dictionary to the WSGI application with the request. That WSGI application entry point is called after Django has been initialised though, so setting os.environ with that at that point is too late. It is also regarded as bad practice to update os.environ on a per request basis. Using a separate WSGI script file is better.

```<code># production.wsgi

import os

os.environ['DJANGO_SETTINGS_MODULE'] = '....'
....

from prehranske_oznacbe.wsgi import application
</code>```

And have WSGIScriptAlias reference production.wsgi file by path.

Body:
I am currently developing an application in Python 3.6 and Django 1.11, on the production server (Ubuntu 16.04) I am using Apache2.

I am trying to use separated settings for production and development. Instead of a file, I have a settings directory with base setttings, and production and development settings file, which import the base settings and potentially override them. To let Django know which settings to use, I am setting the DJANGO_SETTINGS_MODULE to either prehranske_oznacbe.settings.development or  prehranske_oznacbe.settings.production. This works fine for development. Concerning setting the envvars on the production server, I followed the answers to these two SO:
Access Apache SetEnv variable from Django wsgi.py file, Django + mod_wsgi. Set OS environment variable from Apache's SetEnv.

The problem is, when I try to acces my application, I get a 500 Internal Error. The apache error logs:

mod_wsgi (pid=404): Target WSGI script '/home/inesmersak/prehranske_oznacbe/prehranske_oznacbe/wsgi.py' cannot be loaded as Python module.
mod_wsgi (pid=404): Exception occurred processing WSGI script '/home/inesmersak/prehranske_oznacbe/prehranske_oznacbe/wsgi.py'.
Traceback (most recent call last):
   File "/home/inesmersak/prehranske_oznacbe/prehranske_oznacbe/wsgi.py", line 25, in <module>
     application = WSGIEnvironment()
   File "/home/inesmersak/prehranske_oznacbe/venv/lib/python3.5/site-packages/django/core/handlers/wsgi.py", line 151, in __init__
     self.load_middleware()
   File "/home/inesmersak/prehranske_oznacbe/venv/lib/python3.5/site-packages/django/core/handlers/base.py", line 48, in load_middleware
     if settings.MIDDLEWARE is None:
   File "/home/inesmersak/prehranske_oznacbe/venv/lib/python3.5/site-packages/django/conf/__init__.py", line 56, in __getattr__
     self._setup(name)
   File "/home/inesmersak/prehranske_oznacbe/venv/lib/python3.5/site-packages/django/conf/__init__.py", line 39, in _setup
     % (desc, ENVIRONMENT_VARIABLE))
django.core.exceptions.ImproperlyConfigured: Requested setting MIDDLEWARE, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.

as if the envvar DJANGO_SETTINGS_MODULE is not getting set. My code:

/etc/apache2/sites-available/000-default.conf

<VirtualHost *:80>
    ServerAdmin webmaster@localhost
    DocumentRoot /var/www/html

    ErrorLog ${APACHE_LOG_DIR}/error.log
    CustomLog ${APACHE_LOG_DIR}/access.log combined

    Alias /static /home/inesmersak/prehranske_oznacbe/static
    <Directory /home/inesmersak/prehranske_oznacbe/static>
        Require all granted
    </Directory>

    <Directory /home/inesmersak/prehranske_oznacbe/prehranske_oznacbe>
        <Files wsgi.py>
            Require all granted
        </Files>
    </Directory>

    WSGIDaemonProcess prehranske_oznacbe python-path=/home/inesmersak/prehranske_oznacbe python-home=/home/inesmersak/prehranske_oznacbe/venv
    WSGIProcessGroup prehranske_oznacbe
    WSGIScriptAlias / /home/inesmersak/prehranske_oznacbe/prehranske_oznacbe/wsgi.py

    # Envvars for Django aplication 'Prehranske oznacbe'.
    SetEnv DJANGO_SETTINGS_MODULE prehranske_oznacbe.settings.production
    SetEnv OZNACBE_API_USERNAME (redacted)
    SetEnv OZNACBE_API_PASSWORD (redacted)
    SetEnv OZNACBE_SECRET_KEY (redacted)
</VirtualHost>

wsgi.py

import os
import django
from django.core.handlers.wsgi import WSGIHandler

class WSGIEnvironment(WSGIHandler):
    def __call__(self, environ, start_response):
        os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'prehranske_oznacbe.settings.production')
        os.environ['DJANGO_SETTINGS_MODULE'] = environ['DJANGO_SETTINGS_MODULE']
        os.environ['OZNACBE_SECRET_KEY'] = environ['OZNACBE_SECRET_KEY']
        os.environ['OZNACBE_API_USERNAME'] = environ['OZNACBE_API_USERNAME']
        os.environ['OZNACBE_API_PASSWORD'] = environ['OZNACBE_API_PASSWORD']
        django.setup()
        return super(WSGIEnvironment, self).__call__(environ, start_response)

application = WSGIEnvironment()

Body:
SetEnv does not set process wide environment variables for a WSGI application, it sets the per request WSGI environ variables passed in the environ dictionary to the WSGI application with the request. That WSGI application entry point is called after Django has been initialised though, so setting os.environ with that at that point is too late. It is also regarded as bad practice to update os.environ on a per request basis. Using a separate WSGI script file is better.

# production.wsgi

import os

os.environ['DJANGO_SETTINGS_MODULE'] = '....'
....

from prehranske_oznacbe.wsgi import application

And have WSGIScriptAlias reference production.wsgi file by path.


问:
How to select all records with relation and where clause Laravel MySQL
I'm new to Laravel so I have a bit of a problem. I have tables 'Categories' and 'Products' in my DB. In my models I setup the relations like:

Product.php:

```<code>public function category()
{
    return $this->belongsToMany(Category::class);
}
</code>```

Category.php:

```<code>public function products()
{
    return $this->hasMany(Product::class);
}
</code>```

What I need now is that I want to select all of the Categories with their related Products. (User enters in search bar category name and gets list of Categories and when user selects Category I get all of the columns from Categories and ALSO Products related with this Category).

I have tried something like this:

```<code>public function findCategory(Request $request)
{
    return Category::with('products')
        ->where('name', 'like', '%' . $request->category_name . '%')
        ->limit(15)
        ->get();
}
</code>```

ALSO:

```<code>public function findCategory(Request $request)
{
    return Category::where('name', 'like', '%' . $request->category_name . '%')
        ->products()
        ->limit(15)
        ->get();
}
</code>```

But this doesn't seem to work and I ran out of ideas. Does anyone know if there is a way to do this? Any help would be much appreciated :)

答:
it would be something like</p>

```<code>public function findCategory(Request $request)
{

    $term = $request->category_name;

    return Category::with('products')->where(function($q) use($term) {
               $q->where('categories.name','like',"%$term%");
            })->paginate(15); //or use limit(15)

}
</code>```

Body:
I'm new to Laravel so I have a bit of a problem. I have tables 'Categories' and 'Products' in my DB. In my models I setup the relations like:

Product.php:

public function category()
{
    return $this->belongsToMany(Category::class);
}

Category.php:

public function products()
{
    return $this->hasMany(Product::class);
}

What I need now is that I want to select all of the Categories with their related Products. (User enters in search bar category name and gets list of Categories and when user selects Category I get all of the columns from Categories and ALSO Products related with this Category).

I have tried something like this:

public function findCategory(Request $request)
{
    return Category::with('products')
        ->where('name', 'like', '%' . $request->category_name . '%')
        ->limit(15)
        ->get();
}

ALSO:

public function findCategory(Request $request)
{
    return Category::where('name', 'like', '%' . $request->category_name . '%')
        ->products()
        ->limit(15)
        ->get();
}

But this doesn't seem to work and I ran out of ideas. Does anyone know if there is a way to do this? Any help would be much appreciated :)

Body:
it would be something like

public function findCategory(Request $request)
{

    $term = $request->category_name;

    return Category::with('products')->where(function($q) use($term) {
               $q->where('categories.name','like',"%$term%");
            })->paginate(15); //or use limit(15)

}


问:
file transfer through Wifi Direct
I am trying to write an android application that streams images taken from a first device, through the camera, to a second device with WiFi Direct.

I am trying to use this GitHub project, WiFiDIrectDemo, I managed to connect the devices and to send just one file.
When I try to send a second file I don't get any error and, from the logs, everything seems to work, but the second device doesn't get any file.

Is this a known issue? I have tried to look on the internet but I could not find anything that could help me.

I am attaching my File Transfer Service class:

```<code>public class FileTransferService extends IntentService {

Handler mHandler;

public static final int SOCKET_TIMEOUT = 50000; //ms
public static final String ACTION_SEND_FILE = "com.example.android.wifidirect.SEND_FILE";
public static final String EXTRAS_FILE_PATH = "file_url";
public static final String EXTRAS_GROUP_OWNER_ADDRESS = "go_host";
public static final String EXTRAS_GROUP_OWNER_PORT = "go_port";

public static  int PORT = 8888;
public static final String inetaddress = "inetaddress";
public static final int ByteSize = 512;
public static final String Extension = "extension";
public static final String Filelength = "filelength";
public FileTransferService(String name) {
    super(name);
}

public FileTransferService() {
    super("FileTransferService");
}

@Override
public void onCreate() {
    // TODO Auto-generated method stub
    super.onCreate();
    mHandler = new Handler();
}

@Override
protected void onHandleIntent(Intent intent) {

    Context context = getApplicationContext();
    if (intent.getAction().equals(ACTION_SEND_FILE)) {
        String fileUri = intent.getExtras().getString(EXTRAS_FILE_PATH);

        String host = intent.getExtras().getString(EXTRAS_GROUP_OWNER_ADDRESS);

        Socket socket = new Socket();

        InputStream is = null;

        int port = intent.getExtras().getInt(EXTRAS_GROUP_OWNER_PORT);

        String extension = intent.getExtras().getString(Extension);

        String filelength = intent.getExtras().getString(Filelength);

        try {
            if(!socket.isConnected())
            {
                Log.d(WiFiDirectActivity.TAG, "Opening client socket - ");
                socket.bind(null);

                socket.setReuseAddress(true);

                socket.connect((new InetSocketAddress(host, port)),5000); // ..,socket_timeout)
                Log.e("File Transfer Service"," socket connect");

            }

            Log.d(WiFiDirectActivity.TAG, "Client socket - " + socket.isConnected());

            OutputStream stream = socket.getOutputStream();
            Log.e("file transfer" +
                    " service", "get output stream");
            ContentResolver cr = context.getContentResolver();

            Long FileLength = Long.parseLong(filelength);
            WiFiTransferModal transObj = null;
            ObjectOutputStream oos = new ObjectOutputStream(stream);
            if(transObj == null) transObj = new WiFiTransferModal();

            transObj = new WiFiTransferModal(extension,FileLength);
            oos.writeObject(transObj);

            try {
                is = cr.openInputStream(Uri.parse(fileUri));
            } catch (FileNotFoundException e) {
                Log.d(WiFiDirectActivity.TAG, e.toString());
            }
            DeviceDetailFragment.copyFile(is, stream);
            Log.d(WiFiDirectActivity.TAG, "Client: Data written");
            oos.flush();
            oos.close();    //close the ObjectOutputStream after sending data.
        } catch (IOException e) {
            Log.e("file transfer service","unable to connect:  " + e.toString() );
        } finally {
            if (socket != null) {
                if (socket.isConnected()) {
                    try {
                        socket.close();

                    } catch (Exception e) {
                        // Give up
                        e.printStackTrace();
                        Log.e("File transfer service","exception socket.close:  " + e.toString());
                    }
                }
            }
            else Log.e("file transfer service","socket is already null");
        }

    }
}
}
</code>```

EDIT

Receiving code:

```<code> public class FileServerAsyncTask extends AsyncTask<String, String, String> {

    //        private TextView statusText;
    private Context mFilecontext;
    private String Extension, Key;
    private File EncryptedFile;
    private long ReceivedFileLength;
    private int PORT;

    public FileServerAsyncTask(Context context, int port) {
        this.mFilecontext = context;
        handler = new Handler();
        this.PORT = port;

    }

    @Override
    protected String doInBackground(String... params) {
        try {
            Log.e("device detail fragment", "File Async task port-> " + PORT);

            ServerSocket serverSocket = new ServerSocket();
            Log.e("device detail fragment"," new server");

            serverSocket.setReuseAddress(true);
            Log.e("device detail fragment","set reuse address");

            serverSocket.bind(new InetSocketAddress(PORT));
            Log.e("device detail fragment","socket bind");

            Socket client = serverSocket.accept();
            Log.e("device detail fragment "," socket client accept");

            Log.e("Device detail fragment ", "client inet address" + client.getInetAddress());

            WiFiClientIp = client.getInetAddress().getHostAddress();
            Log.e("device detail fragment"," get client ip: " + WiFiClientIp);

            ObjectInputStream ois = new ObjectInputStream(
                    client.getInputStream());
            Log.e("device detail fragment","object input stream + " + ois.toString());

            WiFiTransferModal obj = null;
            String InetAddress;

            try {
                obj = (WiFiTransferModal) ois.readObject();
                Log.e("device detail fragment"," read object");

                if (obj != null) {
                    Log.e("device detail fragment"," obj != null ");
                    InetAddress = obj.getInetAddress();
                    Log.e("device detail fragment"," get inet address: " +
                    InetAddress);
                    if (InetAddress != null
                            && InetAddress
                            .equalsIgnoreCase(FileTransferService.inetaddress)) {

                        SharedPreferencesHandler.setStringValues(mFilecontext,
                                mFilecontext.getString(R.string.pref_WiFiClientIp), WiFiClientIp);

                        //set boolean true which identify that this device will act as server.
                        SharedPreferencesHandler.setStringValues(mFilecontext,
                                mFilecontext.getString(R.string.pref_ServerBoolean), "true");

                        ois.close(); // close the ObjectOutputStream object
                        Log.e("device detail fragment"," output stream close");
                        // after saving
                        serverSocket.close();
                        Log.e("device detail fragment","close");
                        return "Demo";
                    }

                    Log.e("device detail fragment","FileName got from socket on other side->>> "+
                            obj.getFileName());
                }

                final File f = new File(
                        Environment.getExternalStorageDirectory() + "/"
                                + FolderName + "/"
                                + obj.getFileName());
                Log.e("background"," new file f from inputstream");

                File dirs = new File(f.getParent());
                Log.e("device detail fragment"," f get parent()");
                if (!dirs.exists())
                    dirs.mkdirs();
                f.createNewFile();
                Log.e("device detail fragment","create new file");

            /**
             * Receive file length and copy after it
             */
                this.ReceivedFileLength = obj.getFileLength();

                InputStream inputstream = client.getInputStream();
                Log.e("device detail fragment","input stream client get input");
                Message msg = Message.obtain();
                msg.what = 1;
                try
                {
                    // send the images to the image view through handler
                    Bitmap bitmap = BitmapFactory.decodeStream(inputstream);
                    Log.e("device detail fragment", "decode stream");
                    Bundle b = new Bundle();
                    b.putParcelable("bitmap", bitmap);
                    msg.setData(b);
                    Log.e("device detail fragment","message: " + msg.toString());
                    messageHandler.sendMessage(msg);
                }
                catch (Exception e)
                {
                    Log.e("device detail fragment","stream not decoded into bitmap with" +
                    "exception:   " + e.toString());
                }

                copyRecievedFile(inputstream, new FileOutputStream(f),
                        ReceivedFileLength);
                Log.e("device detail fragment","copy input stream into file");
                ois.close(); // close the ObjectOutputStream object after saving
                // file to storage.
                Log.e("device detail fragment","ois close");

                /**
                 *  Set file related data and decrypt file in postExecute.
                 *  */
                this.Extension = obj.getFileName();
                this.EncryptedFile = f;
                final Uri uri = Uri.fromFile(f);
                return f.getAbsolutePath();
            }
            catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
            catch (Exception e) {
                e.printStackTrace();
                Log.e("device detail fragment", e.getMessage());
            }

            return "";
        } catch (IOException e) {
            Log.e("device detail fragment", e.getMessage());
            return null;
        }
    }

    @Override
    protected void onPostExecute(String result) {

        if (result != null) {
            if (!result.equalsIgnoreCase("Demo")) {
                Log.e("On Post Execute","result  +" + result);
            } else if (!TextUtils.isEmpty(result)) {
                /**
                 * To initiate socket again we are initiating async task
                 * in this condition.
                 */
                FileServerAsyncTask FileServerobj = new
                        FileServerAsyncTask(mFilecontext, FileTransferService.PORT);
                if (FileServerobj != null) {
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
                        FileServerobj.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, new String[]{null});
                        Log.e("Post Execute", "FileServerobj.execute on executor");

                    } else
                        {
                            FileServerobj.execute();
                            Log.e("Post Execute", "FileServerobj.execute");
                        }
                }
            }
        }

    }

    @Override
    protected void onPreExecute() {
        if (mProgressDialog == null) {
            mProgressDialog = new ProgressDialog(mFilecontext);
        }
        if(imageView == null){
            imageView = new ImageView(mFilecontext);
        }
    }
}
</code>```

答:
The server will receive a file and then opens it by letting the user choose an app to display the file.  The server asynctask then has finished. So no new file can be received. So i do not believe you if you say that the logs tell that all is normal. Your client socket can not connect to begin with. All is intented behaviour.

```<code>* To initiate socket again we are initiating async task * in this condition..
</code>```

Your code is not coming there.

You have to start an asynctask again to receive the next file.

Title: file transfer through Wifi Direct

Body:
I am trying to write an android application that streams images taken from a first device, through the camera, to a second device with WiFi Direct.

I am trying to use this GitHub project, WiFiDIrectDemo, I managed to connect the devices and to send just one file.
When I try to send a second file I don't get any error and, from the logs, everything seems to work, but the second device doesn't get any file.

Is this a known issue? I have tried to look on the internet but I could not find anything that could help me.

I am attaching my File Transfer Service class:

public class FileTransferService extends IntentService {

Handler mHandler;

public static final int SOCKET_TIMEOUT = 50000; //ms
public static final String ACTION_SEND_FILE = "com.example.android.wifidirect.SEND_FILE";
public static final String EXTRAS_FILE_PATH = "file_url";
public static final String EXTRAS_GROUP_OWNER_ADDRESS = "go_host";
public static final String EXTRAS_GROUP_OWNER_PORT = "go_port";

public static  int PORT = 8888;
public static final String inetaddress = "inetaddress";
public static final int ByteSize = 512;
public static final String Extension = "extension";
public static final String Filelength = "filelength";
public FileTransferService(String name) {
    super(name);
}

public FileTransferService() {
    super("FileTransferService");
}

@Override
public void onCreate() {
    // TODO Auto-generated method stub
    super.onCreate();
    mHandler = new Handler();
}

@Override
protected void onHandleIntent(Intent intent) {

    Context context = getApplicationContext();
    if (intent.getAction().equals(ACTION_SEND_FILE)) {
        String fileUri = intent.getExtras().getString(EXTRAS_FILE_PATH);

        String host = intent.getExtras().getString(EXTRAS_GROUP_OWNER_ADDRESS);

        Socket socket = new Socket();

        InputStream is = null;

        int port = intent.getExtras().getInt(EXTRAS_GROUP_OWNER_PORT);

        String extension = intent.getExtras().getString(Extension);

        String filelength = intent.getExtras().getString(Filelength);

        try {
            if(!socket.isConnected())
            {
                Log.d(WiFiDirectActivity.TAG, "Opening client socket - ");
                socket.bind(null);

                socket.setReuseAddress(true);

                socket.connect((new InetSocketAddress(host, port)),5000); // ..,socket_timeout)
                Log.e("File Transfer Service"," socket connect");

            }

            Log.d(WiFiDirectActivity.TAG, "Client socket - " + socket.isConnected());

            OutputStream stream = socket.getOutputStream();
            Log.e("file transfer" +
                    " service", "get output stream");
            ContentResolver cr = context.getContentResolver();

            Long FileLength = Long.parseLong(filelength);
            WiFiTransferModal transObj = null;
            ObjectOutputStream oos = new ObjectOutputStream(stream);
            if(transObj == null) transObj = new WiFiTransferModal();

            transObj = new WiFiTransferModal(extension,FileLength);
            oos.writeObject(transObj);

            try {
                is = cr.openInputStream(Uri.parse(fileUri));
            } catch (FileNotFoundException e) {
                Log.d(WiFiDirectActivity.TAG, e.toString());
            }
            DeviceDetailFragment.copyFile(is, stream);
            Log.d(WiFiDirectActivity.TAG, "Client: Data written");
            oos.flush();
            oos.close();    //close the ObjectOutputStream after sending data.
        } catch (IOException e) {
            Log.e("file transfer service","unable to connect:  " + e.toString() );
        } finally {
            if (socket != null) {
                if (socket.isConnected()) {
                    try {
                        socket.close();

                    } catch (Exception e) {
                        // Give up
                        e.printStackTrace();
                        Log.e("File transfer service","exception socket.close:  " + e.toString());
                    }
                }
            }
            else Log.e("file transfer service","socket is already null");
        }

    }
}
}

EDIT

Receiving code:

 public class FileServerAsyncTask extends AsyncTask<String, String, String> {

    //        private TextView statusText;
    private Context mFilecontext;
    private String Extension, Key;
    private File EncryptedFile;
    private long ReceivedFileLength;
    private int PORT;

    public FileServerAsyncTask(Context context, int port) {
        this.mFilecontext = context;
        handler = new Handler();
        this.PORT = port;

    }

    @Override
    protected String doInBackground(String... params) {
        try {
            Log.e("device detail fragment", "File Async task port-> " + PORT);

            ServerSocket serverSocket = new ServerSocket();
            Log.e("device detail fragment"," new server");

            serverSocket.setReuseAddress(true);
            Log.e("device detail fragment","set reuse address");

            serverSocket.bind(new InetSocketAddress(PORT));
            Log.e("device detail fragment","socket bind");

            Socket client = serverSocket.accept();
            Log.e("device detail fragment "," socket client accept");

            Log.e("Device detail fragment ", "client inet address" + client.getInetAddress());

            WiFiClientIp = client.getInetAddress().getHostAddress();
            Log.e("device detail fragment"," get client ip: " + WiFiClientIp);

            ObjectInputStream ois = new ObjectInputStream(
                    client.getInputStream());
            Log.e("device detail fragment","object input stream + " + ois.toString());

            WiFiTransferModal obj = null;
            String InetAddress;

            try {
                obj = (WiFiTransferModal) ois.readObject();
                Log.e("device detail fragment"," read object");

                if (obj != null) {
                    Log.e("device detail fragment"," obj != null ");
                    InetAddress = obj.getInetAddress();
                    Log.e("device detail fragment"," get inet address: " +
                    InetAddress);
                    if (InetAddress != null
                            && InetAddress
                            .equalsIgnoreCase(FileTransferService.inetaddress)) {

                        SharedPreferencesHandler.setStringValues(mFilecontext,
                                mFilecontext.getString(R.string.pref_WiFiClientIp), WiFiClientIp);

                        //set boolean true which identify that this device will act as server.
                        SharedPreferencesHandler.setStringValues(mFilecontext,
                                mFilecontext.getString(R.string.pref_ServerBoolean), "true");

                        ois.close(); // close the ObjectOutputStream object
                        Log.e("device detail fragment"," output stream close");
                        // after saving
                        serverSocket.close();
                        Log.e("device detail fragment","close");
                        return "Demo";
                    }

                    Log.e("device detail fragment","FileName got from socket on other side->>> "+
                            obj.getFileName());
                }

                final File f = new File(
                        Environment.getExternalStorageDirectory() + "/"
                                + FolderName + "/"
                                + obj.getFileName());
                Log.e("background"," new file f from inputstream");

                File dirs = new File(f.getParent());
                Log.e("device detail fragment"," f get parent()");
                if (!dirs.exists())
                    dirs.mkdirs();
                f.createNewFile();
                Log.e("device detail fragment","create new file");

            /**
             * Receive file length and copy after it
             */
                this.ReceivedFileLength = obj.getFileLength();

                InputStream inputstream = client.getInputStream();
                Log.e("device detail fragment","input stream client get input");
                Message msg = Message.obtain();
                msg.what = 1;
                try
                {
                    // send the images to the image view through handler
                    Bitmap bitmap = BitmapFactory.decodeStream(inputstream);
                    Log.e("device detail fragment", "decode stream");
                    Bundle b = new Bundle();
                    b.putParcelable("bitmap", bitmap);
                    msg.setData(b);
                    Log.e("device detail fragment","message: " + msg.toString());
                    messageHandler.sendMessage(msg);
                }
                catch (Exception e)
                {
                    Log.e("device detail fragment","stream not decoded into bitmap with" +
                    "exception:   " + e.toString());
                }

                copyRecievedFile(inputstream, new FileOutputStream(f),
                        ReceivedFileLength);
                Log.e("device detail fragment","copy input stream into file");
                ois.close(); // close the ObjectOutputStream object after saving
                // file to storage.
                Log.e("device detail fragment","ois close");

                /**
                 *  Set file related data and decrypt file in postExecute.
                 *  */
                this.Extension = obj.getFileName();
                this.EncryptedFile = f;
                final Uri uri = Uri.fromFile(f);
                return f.getAbsolutePath();
            }
            catch (ClassNotFoundException e) {
                e.printStackTrace();
            }
            catch (Exception e) {
                e.printStackTrace();
                Log.e("device detail fragment", e.getMessage());
            }

            return "";
        } catch (IOException e) {
            Log.e("device detail fragment", e.getMessage());
            return null;
        }
    }

    @Override
    protected void onPostExecute(String result) {

        if (result != null) {
            if (!result.equalsIgnoreCase("Demo")) {
                Log.e("On Post Execute","result  +" + result);
            } else if (!TextUtils.isEmpty(result)) {
                /**
                 * To initiate socket again we are initiating async task
                 * in this condition.
                 */
                FileServerAsyncTask FileServerobj = new
                        FileServerAsyncTask(mFilecontext, FileTransferService.PORT);
                if (FileServerobj != null) {
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
                        FileServerobj.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, new String[]{null});
                        Log.e("Post Execute", "FileServerobj.execute on executor");

                    } else
                        {
                            FileServerobj.execute();
                            Log.e("Post Execute", "FileServerobj.execute");
                        }
                }
            }
        }

    }

    @Override
    protected void onPreExecute() {
        if (mProgressDialog == null) {
            mProgressDialog = new ProgressDialog(mFilecontext);
        }
        if(imageView == null){
            imageView = new ImageView(mFilecontext);
        }
    }
}

Body:
The server will receive a file and then opens it by letting the user choose an app to display the file.  The server asynctask then has finished. So no new file can be received. So i do not believe you if you say that the logs tell that all is normal. Your client socket can not connect to begin with. All is intented behaviour.

* To initiate socket again we are initiating async task * in this condition..

Your code is not coming there.

You have to start an asynctask again to receive the next file.


问:
Calling Stored Procedure in Entity Framework using Aspnet boilerplate
I am using aspnetboilerplate template

i have a student service class. i am getting a student profile List from stored procedure. how can i call a stored procedure in aspnetboilerplate template

```<code>  public class StudentRepository : TabonoRepositoryBase<User, long>
    {
        private readonly IActiveTransactionProvider _transactionProvider;

        public StudentRepository(IDbContextProvider<TabonoDbContext> dbContextProvider, IActiveTransactionProvider transactionProvider)
            : base(dbContextProvider)
        {
            _transactionProvider = transactionProvider;
        }

        //TODO: Make async!
        public async Task<int> GetProfileCompletePercentage(int studentid)
        {
            EnsureConnectionOpen();

            using (var command = CreateCommand("Sp_GetStudentprofilepercentage", CommandType.StoredProcedure, new SqlParameter("StudentId", studentid)))
            {
                using (var dataReader = await command.ExecuteReaderAsync())
                {
                    while (dataReader.Read())
                    {
                        return Convert.ToInt16(dataReader["TotalPer"].ToString());
                    }
                    return 0;
                }
            }
        }

        private DbCommand CreateCommand(string commandText, CommandType commandType, params SqlParameter[] parameters)
        {
            var command = Context.Database.GetDbConnection().CreateCommand();

            command.CommandText = commandText;
            command.CommandType = commandType;
            command.Transaction = GetActiveTransaction();

            foreach (var parameter in parameters)
            {
                command.Parameters.Add(parameter);
            }

            return command;
        }

        private void EnsureConnectionOpen()
        {
            var connection = Context.Database.GetDbConnection();

            if (connection.State != ConnectionState.Open)
            {
                connection.Open();
            }
        }

        private DbTransaction GetActiveTransaction()
        {
            return (DbTransaction)_transactionProvider.GetActiveTransaction(new ActiveTransactionProviderArgs
            {
                {"ContextType", typeof(TabonoDbContext) },
                {"MultiTenancySide", MultiTenancySide }
            });
        }
    }
</code>```

And this is the service class

```<code> public class StudentService : AsyncCrudAppService<StudentCore, StudentDto, int, PagedResultRequestDto, StudentCreateDto, StudentUpdateDto>, IStudentService
    {
        public readonly IRepository<StudentCore> _studentRepository;
        private readonly UserManager _userManager;
        private readonly IStudentService _studentservice;

        public StudentService(IRepository<StudentCore> repository, UserManager um, IStudentService studentservice) : base(repository)
        {
            _studentRepository = repository;
            _userManager = um;
            _studentservice = studentservice;
        }
 public Task GetProfileCompletePercentage(int studentid)
        {
          return  _studentservice.GetProfileCompletePercentage(studentid);
        }
    }
</code>```

答:
Create an interface:

public interface IStudentRepository : IRepository<StudentCore>
{
    Task<int> GetProfileCompletePercentage(int studentid);
}
```

<p>Implement the interface:</p>

<pre class="lang-cs prettyprint-override"><code>public class StudentRepository : TabonoRepositoryBase<StudentCore>, IStudentRepository
{
    // ...
}
</code>```

Inject the interface and call the method:

public class StudentService : ...
{
    private readonly IStudentRepository _studentRepository;

    public StudentService(IStudentRepository repository) : base(repository)
    {
        _studentRepository = repository;
    }

    public Task GetProfileCompletePercentage(int studentid)
    {
        return _studentRepository.GetProfileCompletePercentage(studentid);
    }
}
```

Note: StudentService must not inject IStudentService in constructor → infinite recursion!

For reference: https://www.codeproject.com/Articles/1199648/Using-Stored-Procedure-User-Defined-Function-and-V

Body:
I am using aspnetboilerplate template

i have a student service class. i am getting a student profile List from stored procedure. how can i call a stored procedure in aspnetboilerplate template

  public class StudentRepository : TabonoRepositoryBase<User, long>
    {
        private readonly IActiveTransactionProvider _transactionProvider;

        public StudentRepository(IDbContextProvider<TabonoDbContext> dbContextProvider, IActiveTransactionProvider transactionProvider)
            : base(dbContextProvider)
        {
            _transactionProvider = transactionProvider;
        }

        //TODO: Make async!
        public async Task<int> GetProfileCompletePercentage(int studentid)
        {
            EnsureConnectionOpen();

            using (var command = CreateCommand("Sp_GetStudentprofilepercentage", CommandType.StoredProcedure, new SqlParameter("StudentId", studentid)))
            {
                using (var dataReader = await command.ExecuteReaderAsync())
                {
                    while (dataReader.Read())
                    {
                        return Convert.ToInt16(dataReader["TotalPer"].ToString());
                    }
                    return 0;
                }
            }
        }

        private DbCommand CreateCommand(string commandText, CommandType commandType, params SqlParameter[] parameters)
        {
            var command = Context.Database.GetDbConnection().CreateCommand();

            command.CommandText = commandText;
            command.CommandType = commandType;
            command.Transaction = GetActiveTransaction();

            foreach (var parameter in parameters)
            {
                command.Parameters.Add(parameter);
            }

            return command;
        }

        private void EnsureConnectionOpen()
        {
            var connection = Context.Database.GetDbConnection();

            if (connection.State != ConnectionState.Open)
            {
                connection.Open();
            }
        }

        private DbTransaction GetActiveTransaction()
        {
            return (DbTransaction)_transactionProvider.GetActiveTransaction(new ActiveTransactionProviderArgs
            {
                {"ContextType", typeof(TabonoDbContext) },
                {"MultiTenancySide", MultiTenancySide }
            });
        }
    }

And this is the service class

 public class StudentService : AsyncCrudAppService<StudentCore, StudentDto, int, PagedResultRequestDto, StudentCreateDto, StudentUpdateDto>, IStudentService
    {
        public readonly IRepository<StudentCore> _studentRepository;
        private readonly UserManager _userManager;
        private readonly IStudentService _studentservice;

        public StudentService(IRepository<StudentCore> repository, UserManager um, IStudentService studentservice) : base(repository)
        {
            _studentRepository = repository;
            _userManager = um;
            _studentservice = studentservice;
        }
 public Task GetProfileCompletePercentage(int studentid)
        {
          return  _studentservice.GetProfileCompletePercentage(studentid);
        }
    }

Body:
Create an interface:

public interface IStudentRepository : IRepository<StudentCore>
{
    Task<int> GetProfileCompletePercentage(int studentid);
}

Implement the interface:

public class StudentRepository : TabonoRepositoryBase<StudentCore>, IStudentRepository
{
    // ...
}

Inject the interface and call the method:

public class StudentService : ...
{
    private readonly IStudentRepository _studentRepository;

    public StudentService(IStudentRepository repository) : base(repository)
    {
        _studentRepository = repository;
    }

    public Task GetProfileCompletePercentage(int studentid)
    {
        return _studentRepository.GetProfileCompletePercentage(studentid);
    }
}

Note: StudentService must not inject IStudentService in constructor → infinite recursion!

For reference: https://www.codeproject.com/Articles/1199648/Using-Stored-Procedure-User-Defined-Function-and-V


问:
How can I read input from a file line by line in java?
Ok, I know this is a really rookie question, but I looked around online a lot and am yet unable to find the answer to my question:

How can I read input from a file line by line in java?

Assume a file input that has integers on each line, like:

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

Here's the snippet of code I am trying to work with:

```<code>public static void main(File fromFile) {

  BufferedReader reader = new BufferedReader(new FileReader(fromFile));

  int x, y;

  //initialize
  x = Integer.parseInt(reader.readLine().trim());
  y = Integer.parseInt(reader.readLine().trim());

}
</code>```

Presumably, this would read in the first two lines and store them as integers in x and y.  So going off the example, x=1, y=2.

It is finding a problem with this, and I don't know why.

答:
please check your main method(). It should be like these

```<code>public static void main(String... args) {
}
</code>```

or

```<code>public static void main(String[] args) {
}
</code>```

then read like that :

```<code> BufferedReader reader = new BufferedReader(new FileReader(fromFile));

 String line;
 while( (line = reader.readLine()) != null){
        int i = Integer.parseInt(line);
 }
</code>```

Body:
Ok, I know this is a really rookie question, but I looked around online a lot and am yet unable to find the answer to my question:

How can I read input from a file line by line in java?

Assume a file input that has integers on each line, like:

1
2
3
4
5

Here's the snippet of code I am trying to work with:

public static void main(File fromFile) {

  BufferedReader reader = new BufferedReader(new FileReader(fromFile));

  int x, y;

  //initialize
  x = Integer.parseInt(reader.readLine().trim());
  y = Integer.parseInt(reader.readLine().trim());

}

Presumably, this would read in the first two lines and store them as integers in x and y.  So going off the example, x=1, y=2.

It is finding a problem with this, and I don't know why.

Body:
please check your main method(). It should be like these

public static void main(String... args) {
}

or

public static void main(String[] args) {
}

then read like that :

 BufferedReader reader = new BufferedReader(new FileReader(fromFile));

 String line;
 while( (line = reader.readLine()) != null){
        int i = Integer.parseInt(line);
 }


问:
Doctrine ChoiceType how to change values based on existing data in entity
I have a form in a Symfony 3 CRM for Horse Rider Camps, which has a Doctrine ChoiceType field, with the option of whether to select if an attendee of the Camp is a Non-Rider or not. However, the Camp has a limit to the amount of Non-Riders allowed in the Camp so I need to be able to disable the 'Yes' option of the Non-Rider drop down and, ideally, replace it with a disabled value of "The limit has been reached for this camp" or something similar.

Here is the entry for the field:

```<code>$builder->add('non_rider', ChoiceType::class,
    array(
        'label' => 'Is Non-Rider',
        'required' => true,
        'placeholder' => '-- Please select --',
        'choices' => array(
            'Yes' => 1,
            'No' => 0
        ),
        'label_attr' => array(
            'class' => 'control-label'
        ),
        'attr' => array(
            'class' => 'form-control required'
        )
    ));
</code>```

What I'd like is the choices field to read something like:

```<code>'choices' => array(
     'You have reached the limit' => null,
     'No' => 0
)
</code>```

And somehow disabled the entry. Is this possible?

答:
You can use the event form to do that

Customizing your Form Based on the Underlying Data

Body:
I have a form in a Symfony 3 CRM for Horse Rider Camps, which has a Doctrine ChoiceType field, with the option of whether to select if an attendee of the Camp is a Non-Rider or not. However, the Camp has a limit to the amount of Non-Riders allowed in the Camp so I need to be able to disable the 'Yes' option of the Non-Rider drop down and, ideally, replace it with a disabled value of "The limit has been reached for this camp" or something similar.

Here is the entry for the field:

$builder->add('non_rider', ChoiceType::class,
    array(
        'label' => 'Is Non-Rider',
        'required' => true,
        'placeholder' => '-- Please select --',
        'choices' => array(
            'Yes' => 1,
            'No' => 0
        ),
        'label_attr' => array(
            'class' => 'control-label'
        ),
        'attr' => array(
            'class' => 'form-control required'
        )
    ));

What I'd like is the choices field to read something like:

'choices' => array(
     'You have reached the limit' => null,
     'No' => 0
)

And somehow disabled the entry. Is this possible?


问:
"a bytes-like object is required" but I am using bytes
With Python3 I have re-opened stdout in binary mode. After that when I print("Hello") it tells me that I need to use a bytes-like object. Fair enough, it's in binary mode now.

However when I do this:

```<code>print(b"Some bytes")
</code>```

I still get this error:

```<code>TypeError: a bytes-like object is required, not 'str'
</code>```

What's up with that?

答:
print() always writes str values. It'll convert any arguments to strings first, including bytes objects.

From the print() documentation:

All non-keyword arguments are converted to strings like str() does and written to the stream, separated by sep and followed by end.

You can't use print() on a binary stream, period. Either write directly to the stream (using it's .write() method), or wrap the stream in a TextIOWrapper() object to handle encoding.

These both work:

```<code>import sys

sys.stdout.write(b'Some bytes\n')  # note, manual newline added
</code>```

and

```<code>from io import TextIOWrapper
import sys

print('Some text', file=TextIOWrapper(sys.stdout, encoding='utf8'))
</code>```

Body:
With Python3 I have re-opened stdout in binary mode. After that when I print("Hello") it tells me that I need to use a bytes-like object. Fair enough, it's in binary mode now.

However when I do this:

print(b"Some bytes")

I still get this error:

TypeError: a bytes-like object is required, not 'str'

What's up with that?

Body:
print() always writes str values. It'll convert any arguments to strings first, including bytes objects.

From the print() documentation:

All non-keyword arguments are converted to strings like str() does and written to the stream, separated by sep and followed by end.

You can't use print() on a binary stream, period. Either write directly to the stream (using it's .write() method), or wrap the stream in a TextIOWrapper() object to handle encoding.

These both work:

import sys

sys.stdout.write(b'Some bytes\n')  # note, manual newline added

and

from io import TextIOWrapper
import sys

print('Some text', file=TextIOWrapper(sys.stdout, encoding='utf8'))


问:
Javascript Run Async Code For Each Item Of For Loop With Promises
I have a function that gets's an object passed into it, with key and data that is an array.
I have to call the API to get additional information, which in turn are added back into the object and the whole object is returned.

My first approach was incorrect because I was trying to pass the data out of the .then(), but that was wrong practice.

```<code>function asignChecklistItems(taskArray) {
    // get all the people's tasks passed in
    return new Promise(function(resolve, reject) {

        var promises = []

        // Task Array: {"Person":[tasks,tasks,tasks]}

        for (var person in taskArray) {
            var individualTaskPerson = taskArray[person]
            // get the person's tasks

            for (var individualTask in individualTaskPerson) {

                // here we get each individual task
                var task = individualTaskPerson[individualTask]

                // Check if the checklist is present, the .exists is a bool
                if (task.checklist.exists === true) {
                //Here we push the promise back into the promise array
                // retrieve is the async function
                     promises.push( retrieveCheckListItems(task.checklist.checklistID)
                            .then(checklistItems => {
                                var complete = []
                                var incomplete = []
                                const items = checklistItems["checkItems"];
                                for (var each in items) {
                                    const item = items[each]
                                    if (item["state"] === "complete") {
                                        complete.push(item["name"])
                                    } else {
                                        incomplete.push(item["name"])
                                    }
                                }

                                task.checklist.completeItems.push(complete)
                                task.checklist.incompleteItems.push(incomplete)
                                return taskArray // used to be: resolve(taskArray) See **EDIT**
                            })
                            .catch(err => {
                          logError(err)
                                reject(err)
                            })
             )

                    } else {
              // There's no checklist
            }
                }
            }
        Promise.all(promises).then(function(x){
              // Here when checked, all the items are pushed to the last person inside the array.
              // Eg. {PersonA:[tasks],PersonB:[tasks],PersonC:[tasks]}
              // All of the complete and incomplete items are added to Person C for some reason
              resolve(taskArray)

        })

        })
    }
</code>```

I've tried many approaches, returning the entire promise, trying to return from within the promise (which didn't work because it's not allowed), and trying to run the async code earlier, and moving the for loops into the promise. None of them worked, this is the closest, where it returns it for PersonC.

This was mostly based on other SO questions such as this one, which showed how to use Promise.All.

Is this the preoper way of calling a promise (async function) for each element of a for loop?

EDIT:

Another mistake that was in the code, is that if there is a promise insde a promise, such as the retrieveCheckListItems inside of the asignCheckListItems, it shouldn't resolve itself, but it should return the value. I updated the code to reflect that, based on the working production code.

Apparently another problem I was

答:
You are executing task.checklist.completeItems.push(complete) in the retrieveCheckListItems .then, which means the code is asynchronous.

At the same time, var task is instead being assigned in a for...in loop, which means that by the time your .then is triggered, the for...in iteration will be complete and task will be the last assigned object.

Note that var variables have a function scope, which basically means that your code is equivalent to:

```<code>function asignChecklistItems(taskArray) {
    // get all the people's tasks passed in
    return new Promise(function(resolve, reject) {

        var promises = []
        var individualTaskPerson;
        var task;

        ...
</code>```

Fix it by:

Either changing var task to let task (if you are using ES6). This then creates the variable within each for loop, rather than within the enclosing function.

or

By replacing

```<code>for (var individualTask in individualTaskPerson) {

  // here we get each individual task
  var task = individualTaskPerson[individualTask]
</code>```

with

```<code>Object.keys(individualTaskPerson).forEach(function(individualTask) {
    var task = individualTaskPerson[individualTask];

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

Do the same for the other for...in loops and variables.

Body:
I have a function that gets's an object passed into it, with key and data that is an array.
I have to call the API to get additional information, which in turn are added back into the object and the whole object is returned.

My first approach was incorrect because I was trying to pass the data out of the .then(), but that was wrong practice.

function asignChecklistItems(taskArray) {
    // get all the people's tasks passed in
    return new Promise(function(resolve, reject) {

        var promises = []

        // Task Array: {"Person":[tasks,tasks,tasks]}

        for (var person in taskArray) {
            var individualTaskPerson = taskArray[person]
            // get the person's tasks

            for (var individualTask in individualTaskPerson) {

                // here we get each individual task
                var task = individualTaskPerson[individualTask]

                // Check if the checklist is present, the .exists is a bool
                if (task.checklist.exists === true) {
                //Here we push the promise back into the promise array
                // retrieve is the async function
                     promises.push( retrieveCheckListItems(task.checklist.checklistID)
                            .then(checklistItems => {
                                var complete = []
                                var incomplete = []
                                const items = checklistItems["checkItems"];
                                for (var each in items) {
                                    const item = items[each]
                                    if (item["state"] === "complete") {
                                        complete.push(item["name"])
                                    } else {
                                        incomplete.push(item["name"])
                                    }
                                }

                                task.checklist.completeItems.push(complete)
                                task.checklist.incompleteItems.push(incomplete)
                                return taskArray // used to be: resolve(taskArray) See **EDIT**
                            })
                            .catch(err => {
                          logError(err)
                                reject(err)
                            })
             )

                    } else {
              // There's no checklist
            }
                }
            }
        Promise.all(promises).then(function(x){
              // Here when checked, all the items are pushed to the last person inside the array.
              // Eg. {PersonA:[tasks],PersonB:[tasks],PersonC:[tasks]}
              // All of the complete and incomplete items are added to Person C for some reason
              resolve(taskArray)

        })

        })
    }

I've tried many approaches, returning the entire promise, trying to return from within the promise (which didn't work because it's not allowed), and trying to run the async code earlier, and moving the for loops into the promise. None of them worked, this is the closest, where it returns it for PersonC.

This was mostly based on other SO questions such as this one, which showed how to use Promise.All.

Is this the preoper way of calling a promise (async function) for each element of a for loop?

EDIT:

Another mistake that was in the code, is that if there is a promise insde a promise, such as the retrieveCheckListItems inside of the asignCheckListItems, it shouldn't resolve itself, but it should return the value. I updated the code to reflect that, based on the working production code.

Apparently another problem I was

Body:
You are executing task.checklist.completeItems.push(complete) in the retrieveCheckListItems .then, which means the code is asynchronous.

At the same time, var task is instead being assigned in a for...in loop, which means that by the time your .then is triggered, the for...in iteration will be complete and task will be the last assigned object.

Note that var variables have a function scope, which basically means that your code is equivalent to:

function asignChecklistItems(taskArray) {
    // get all the people's tasks passed in
    return new Promise(function(resolve, reject) {

        var promises = []
        var individualTaskPerson;
        var task;

        ...

Fix it by:

Either changing var task to let task (if you are using ES6). This then creates the variable within each for loop, rather than within the enclosing function.

or

By replacing

for (var individualTask in individualTaskPerson) {

  // here we get each individual task
  var task = individualTaskPerson[individualTask]

with

Object.keys(individualTaskPerson).forEach(function(individualTask) {
    var task = individualTaskPerson[individualTask];

     ...
});

Do the same for the other for...in loops and variables.


答:
The size difference has to do with the ZLIB compression settings.

By default PIL uses the maximum 9 (see here)

By default OpenCV only uses 3 (see here)

Using OpenCV you can set compression to 9 using this code (from this answer)

```<code>cv2.imwrite('image.png', img,  [int(cv2.IMWRITE_PNG_COMPRESSION), 9])
</code>```

Title: Why does openCV store a file larger(kB) than the original?

Body:
I have code that loads and saves the image in two different ways - first using openCV, the second using PIL.

import cv2
from PIL import Image

img = cv2.imread("/home/myname/png/image.png")
cv2.imwrite("/home/myname/png/image_save.png", img)

img = Image.open("/home/myname/png/image.png")
img.save("/home/myname/png/image_save_pil.png")

The original image is 204.6 kB in size. The result obtained with openCV is 245.0 kB, the result of PIL is 204.6 kB.

Why does the image saved with openCV have a larger size?

Body:
The size difference has to do with the ZLIB compression settings.

By default PIL uses the maximum 9 (see here)

By default OpenCV only uses 3 (see here)

Using OpenCV you can set compression to 9 using this code (from this answer)

cv2.imwrite('image.png', img,  [int(cv2.IMWRITE_PNG_COMPRESSION), 9])


问:
jquery disable submit button on form submission
For whatever reason, though this code does refresh the page, no fields get posted...

```<code>$('form').submit(function(){
    $('input[type=submit]', this).attr('disabled', 'disabled');
});
</code>```

Is there a better way of coding this?

答:
Your code is fine. I ran into this same problem but for me the issue was in the php, not javascript. When you disable the button it is no longer sent with the form and my php was relying on the submit button

```<code>if(isset($_POST['submit'])){
   ...
}
</code>```

So the page refreshes but php doesn't execute. I'm now using a different field which has required attribute.

Body:
For whatever reason, though this code does refresh the page, no fields get posted...

$('form').submit(function(){
    $('input[type=submit]', this).attr('disabled', 'disabled');
});

Is there a better way of coding this?

Body:
Your code is fine. I ran into this same problem but for me the issue was in the php, not javascript. When you disable the button it is no longer sent with the form and my php was relying on the submit button

if(isset($_POST['submit'])){
   ...
}

So the page refreshes but php doesn't execute. I'm now using a different field which has required attribute.