问:
Notifications are being sent out on the wrong time (Java, Android Studio)
In my app the user can choose a time and a date when a notification will be sent out on.
However, the notifcations are not being sent out on the right time. If I choose a notification to be sent out on the same day, it will be sent out on a random time during the next day. and If I choose a notification to be sent out on a day in the future, it will be sent out on a random time during that day. So in summary, it seems to be ignoring the time and sending out notifications based on the date but it can't even get the date right when I choose a notification for the current day.

The code worked fine when the the user only had the ability to choose the time. It broke after I added the ability to choose a date for the notification.

MeeldetuletusActivity.java

```<code>public class MeeldetuletusActivity extends AppCompatActivity implements TimePickerDialog.OnTimeSetListener, DatePickerDialog.OnDateSetListener {
    String timeText;
    TextView textTime;
    Button nupp_vali, nupp_katkesta, nupp_kuupaev, nupp_alarm;
    Calendar c;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_meeldetuletus);

        nupp_vali = findViewById(R.id.button2);
        nupp_katkesta = findViewById(R.id.nupp_katkesta);
        nupp_kuupaev = findViewById(R.id.button);
        nupp_alarm = findViewById(R.id.button3);

        nupp_alarm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startAlarm(c);

            }
        });

        nupp_vali.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                DialogFragment timePicker = new TimePickerFragment();
                timePicker.show(getSupportFragmentManager(), "time picker");

            }
        });

        nupp_kuupaev.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                DialogFragment kuupaevaValija = new KuupaevaFragment();
                kuupaevaValija.show(getSupportFragmentManager(), "date picker");
            }
        });

        nupp_katkesta.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                katkestaAlarm();
                Toast.makeText(MeeldetuletusActivity.this, "Meeldetuletus unustatud", Toast.LENGTH_SHORT).show();

            }
        });

    }

    @Override
    public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
        c = Calendar.getInstance();
        c.set(Calendar.HOUR_OF_DAY, hourOfDay);
        c.set(Calendar.MINUTE, minute);
        c.set(Calendar.SECOND, 0);
    }

    public void onDateSet (DatePicker view, int aasta, int kuu, int paev) {
        c = Calendar.getInstance();
        c.set(Calendar.YEAR, aasta);
        c.set(Calendar.MONTH, kuu);
        c.set(Calendar.DAY_OF_MONTH, paev);
    }

    private void startAlarm(Calendar c) {
        AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        Intent intent = new Intent(this, NotificationPublisher.class);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 1, intent, 0);
        if (c.before(Calendar.getInstance())) {
            c.add(Calendar.DATE, 1);
        }
        Objects.requireNonNull(alarmManager).setExact(AlarmManager.RTC_WAKEUP,
                c.getTimeInMillis(), pendingIntent);
    }

    private void katkestaAlarm() {
        AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        Intent myIntent = new Intent(getApplicationContext(), NotificationPublisher.class);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(
                getApplicationContext(), 1, myIntent,
                PendingIntent.FLAG_UPDATE_CURRENT);

        alarmManager.cancel(pendingIntent);
    }
}
</code>```

KuupaevaFragment.java

```<code>public class KuupaevaFragment extends DialogFragment {
    @NonNull
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        Calendar c = Calendar.getInstance();
        int aasta = c.get(Calendar.YEAR);
        int kuu = c.get(Calendar.MONTH);
        int paev = c.get(Calendar.DAY_OF_MONTH);
        return new DatePickerDialog(getActivity(), (DatePickerDialog.OnDateSetListener) getActivity(),
                aasta, kuu, paev);

    }

}
</code>```

TimePickerFragment.java

```<code>public class TimePickerFragment extends DialogFragment {
    @NonNull
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        Calendar c = Calendar.getInstance();
        int hour = c.get(Calendar.HOUR_OF_DAY);
        int minute = c.get(Calendar.MINUTE);
        return new TimePickerDialog(getActivity(), (TimePickerDialog.OnTimeSetListener) getActivity(),
                hour, minute, DateFormat.is24HourFormat(getActivity()));

    }

}
</code>```

NotificationPublisher.java

```<code>public class NotificationPublisher extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        NotificationHelper notificationHelper = new NotificationHelper(context);
        NotificationCompat.Builder nb = notificationHelper.getChannelNotification();
        notificationHelper.getManager().notify(1, nb.build());
        Notification notification = nb.build();
        notification.defaults |= Notification.DEFAULT_VIBRATE;
        notification.defaults |= Notification.DEFAULT_SOUND;
    }
}
</code>```

NotificationHelper.java

```<code>class NotificationHelper extends ContextWrapper {
    public static final String channelID = "channelID";
    public static final String channelName = "Channel Name";
    private NotificationManager notificationManager;
    public NotificationHelper(Context base) {
        super(base);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            createChannel();
        }
    }
    @TargetApi(Build.VERSION_CODES.O)
    private void createChannel() {
        NotificationChannel channel = new NotificationChannel(channelID, channelName,
                NotificationManager.IMPORTANCE_HIGH);
        getManager().createNotificationChannel(channel);
    }
    public NotificationManager getManager() {
        if (notificationManager == null) {
            notificationManager = (NotificationManager)
                    getSystemService(Context.NOTIFICATION_SERVICE);
        }
        return notificationManager;
    }
    public NotificationCompat.Builder getChannelNotification() {
        return new NotificationCompat.Builder(getApplicationContext(), channelID)
                .setContentTitle("Meeldetuletus")
                .setContentText("Teie valitud aeg on käes")
                .setSmallIcon(R.drawable.ic_baseline_notifications_active_24);
    }
}
</code>```

答:
This is most likely happenning because in Your onTimeSet and onDateSet callback methods You are initializing the c variable - the one that is supposed to represent the date on which the alarm should be fired and thus whenever You are setting a new date or time the c variable loses the previously set data:

@Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
    c = Calendar.getInstance(); // This code is causing the trouble
    c.set(Calendar.HOUR_OF_DAY, hourOfDay);
    c.set(Calendar.MINUTE, minute);
    c.set(Calendar.SECOND, 0);
}

public void onDateSet (DatePicker view, int aasta, int kuu, int paev) {
    c = Calendar.getInstance(); // This code is also causing the trouble
    c.set(Calendar.YEAR, aasta);
    c.set(Calendar.MONTH, kuu);
    c.set(Calendar.DAY_OF_MONTH, paev);
}
```
<p>Now, the straightforward solution would be to initialize the <code>c</code> in Your <code>onCreate</code> lifecycle method <strong>once</strong>:</p>
<pre class="lang-java prettyprint-override"><code>Calendar c;

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_meeldetuletus);

        c = Calendar.getInstance() // Initialize 'c' here!

        ...
}
</code>```

And remove the redundant initialization in the callback methods:

@Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
    c.set(Calendar.HOUR_OF_DAY, hourOfDay);
    c.set(Calendar.MINUTE, minute);
    c.set(Calendar.SECOND, 0);
}

public void onDateSet (DatePicker view, int aasta, int kuu, int paev) {
    c.set(Calendar.YEAR, aasta);
    c.set(Calendar.MONTH, kuu);
    c.set(Calendar.DAY_OF_MONTH, paev);
}
```

Now, whenever Your startAlarm(c) method will be called it will use the data that was set from both onDateSet and onTimeSet or from only one of them - basically, the changes made in those methods won't be overriden by redundantly reinitializing the c variable from those methods themselves.

Body:
In my app the user can choose a time and a date when a notification will be sent out on.
However, the notifcations are not being sent out on the right time. If I choose a notification to be sent out on the same day, it will be sent out on a random time during the next day. and If I choose a notification to be sent out on a day in the future, it will be sent out on a random time during that day. So in summary, it seems to be ignoring the time and sending out notifications based on the date but it can't even get the date right when I choose a notification for the current day.

The code worked fine when the the user only had the ability to choose the time. It broke after I added the ability to choose a date for the notification.

MeeldetuletusActivity.java

public class MeeldetuletusActivity extends AppCompatActivity implements TimePickerDialog.OnTimeSetListener, DatePickerDialog.OnDateSetListener {
    String timeText;
    TextView textTime;
    Button nupp_vali, nupp_katkesta, nupp_kuupaev, nupp_alarm;
    Calendar c;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_meeldetuletus);

        nupp_vali = findViewById(R.id.button2);
        nupp_katkesta = findViewById(R.id.nupp_katkesta);
        nupp_kuupaev = findViewById(R.id.button);
        nupp_alarm = findViewById(R.id.button3);

        nupp_alarm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startAlarm(c);

            }
        });

        nupp_vali.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                DialogFragment timePicker = new TimePickerFragment();
                timePicker.show(getSupportFragmentManager(), "time picker");

            }
        });

        nupp_kuupaev.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                DialogFragment kuupaevaValija = new KuupaevaFragment();
                kuupaevaValija.show(getSupportFragmentManager(), "date picker");
            }
        });

        nupp_katkesta.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                katkestaAlarm();
                Toast.makeText(MeeldetuletusActivity.this, "Meeldetuletus unustatud", Toast.LENGTH_SHORT).show();

            }
        });

    }

    @Override
    public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
        c = Calendar.getInstance();
        c.set(Calendar.HOUR_OF_DAY, hourOfDay);
        c.set(Calendar.MINUTE, minute);
        c.set(Calendar.SECOND, 0);
    }

    public void onDateSet (DatePicker view, int aasta, int kuu, int paev) {
        c = Calendar.getInstance();
        c.set(Calendar.YEAR, aasta);
        c.set(Calendar.MONTH, kuu);
        c.set(Calendar.DAY_OF_MONTH, paev);
    }

    private void startAlarm(Calendar c) {
        AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        Intent intent = new Intent(this, NotificationPublisher.class);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 1, intent, 0);
        if (c.before(Calendar.getInstance())) {
            c.add(Calendar.DATE, 1);
        }
        Objects.requireNonNull(alarmManager).setExact(AlarmManager.RTC_WAKEUP,
                c.getTimeInMillis(), pendingIntent);
    }

    private void katkestaAlarm() {
        AlarmManager alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        Intent myIntent = new Intent(getApplicationContext(), NotificationPublisher.class);
        PendingIntent pendingIntent = PendingIntent.getBroadcast(
                getApplicationContext(), 1, myIntent,
                PendingIntent.FLAG_UPDATE_CURRENT);

        alarmManager.cancel(pendingIntent);
    }
}

KuupaevaFragment.java

public class KuupaevaFragment extends DialogFragment {
    @NonNull
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        Calendar c = Calendar.getInstance();
        int aasta = c.get(Calendar.YEAR);
        int kuu = c.get(Calendar.MONTH);
        int paev = c.get(Calendar.DAY_OF_MONTH);
        return new DatePickerDialog(getActivity(), (DatePickerDialog.OnDateSetListener) getActivity(),
                aasta, kuu, paev);

    }

}

TimePickerFragment.java

public class TimePickerFragment extends DialogFragment {
    @NonNull
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        Calendar c = Calendar.getInstance();
        int hour = c.get(Calendar.HOUR_OF_DAY);
        int minute = c.get(Calendar.MINUTE);
        return new TimePickerDialog(getActivity(), (TimePickerDialog.OnTimeSetListener) getActivity(),
                hour, minute, DateFormat.is24HourFormat(getActivity()));

    }

}

NotificationPublisher.java

public class NotificationPublisher extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        NotificationHelper notificationHelper = new NotificationHelper(context);
        NotificationCompat.Builder nb = notificationHelper.getChannelNotification();
        notificationHelper.getManager().notify(1, nb.build());
        Notification notification = nb.build();
        notification.defaults |= Notification.DEFAULT_VIBRATE;
        notification.defaults |= Notification.DEFAULT_SOUND;
    }
}

NotificationHelper.java

class NotificationHelper extends ContextWrapper {
    public static final String channelID = "channelID";
    public static final String channelName = "Channel Name";
    private NotificationManager notificationManager;
    public NotificationHelper(Context base) {
        super(base);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            createChannel();
        }
    }
    @TargetApi(Build.VERSION_CODES.O)
    private void createChannel() {
        NotificationChannel channel = new NotificationChannel(channelID, channelName,
                NotificationManager.IMPORTANCE_HIGH);
        getManager().createNotificationChannel(channel);
    }
    public NotificationManager getManager() {
        if (notificationManager == null) {
            notificationManager = (NotificationManager)
                    getSystemService(Context.NOTIFICATION_SERVICE);
        }
        return notificationManager;
    }
    public NotificationCompat.Builder getChannelNotification() {
        return new NotificationCompat.Builder(getApplicationContext(), channelID)
                .setContentTitle("Meeldetuletus")
                .setContentText("Teie valitud aeg on käes")
                .setSmallIcon(R.drawable.ic_baseline_notifications_active_24);
    }
}

Body:
This is most likely happenning because in Your onTimeSet and onDateSet callback methods You are initializing the c variable - the one that is supposed to represent the date on which the alarm should be fired and thus whenever You are setting a new date or time the c variable loses the previously set data:

@Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
    c = Calendar.getInstance(); // This code is causing the trouble
    c.set(Calendar.HOUR_OF_DAY, hourOfDay);
    c.set(Calendar.MINUTE, minute);
    c.set(Calendar.SECOND, 0);
}

public void onDateSet (DatePicker view, int aasta, int kuu, int paev) {
    c = Calendar.getInstance(); // This code is also causing the trouble
    c.set(Calendar.YEAR, aasta);
    c.set(Calendar.MONTH, kuu);
    c.set(Calendar.DAY_OF_MONTH, paev);
}

Now, the straightforward solution would be to initialize the c in Your onCreate lifecycle method once:

Calendar c;

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_meeldetuletus);

        c = Calendar.getInstance() // Initialize 'c' here!

        ...
}

And remove the redundant initialization in the callback methods:

@Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
    c.set(Calendar.HOUR_OF_DAY, hourOfDay);
    c.set(Calendar.MINUTE, minute);
    c.set(Calendar.SECOND, 0);
}

public void onDateSet (DatePicker view, int aasta, int kuu, int paev) {
    c.set(Calendar.YEAR, aasta);
    c.set(Calendar.MONTH, kuu);
    c.set(Calendar.DAY_OF_MONTH, paev);
}

Now, whenever Your startAlarm(c) method will be called it will use the data that was set from both onDateSet and onTimeSet or from only one of them - basically, the changes made in those methods won't be overriden by redundantly reinitializing the c variable from those methods themselves.


来源: stackexchange

问:
log4net shows the header and footer to often
I use log4net in a module as a static object of a WCF service.

```<code>public class Service : IService
{
    private static readonly log4net.ILog log = log4net.LogManager.GetLogger(typeof(Service));
</code>```

I also configured header and footer:

```<code>    <layout type="log4net.Layout.PatternLayout">
            <header value="
Session start
" />
            <footer value="Session end
" />
            <conversionPattern value="%date [%5thread] %-5level %c %m%n"/>
    </layout>
</code>```

Sometimes the time between outputs to the log file may be larger than 10 sec.

I see the log output

```<code>2022-02-10 14:30:59,543 [    9] DEBUG ...
2022-02-10 14:30:59,543 [    9] INFO  ...
Session end

Session start
2022-02-10 14:43:01,118 [    7] INFO  ...
</code>```

I can see the the Service object it self is created an disposed. But what about the static member inside my class.

It seams that the static member is disposed in some way and created again.

Can I control this in some way?

答:
The problem was, that I called log4net.Config.XmlConfigurator.Configure(); always when my service object was constrcuted.

I need to do this only once.

```<code>public class Service : IService, IDisposable
{
    private static readonly log4net.ILog log = log4net.LogManager.GetLogger(typeof(Service));
    private static bool logConfigured = false;
...
    public Service()
    {
        if (!logConfigured)
        {
            logConfigured = true;
            log4net.Config.XmlConfigurator.Configure();
        }
    }
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I use log4net in a module as a static object of a WCF service.

public class Service : IService
{
    private static readonly log4net.ILog log = log4net.LogManager.GetLogger(typeof(Service));

I also configured header and footer:

    <layout type="log4net.Layout.PatternLayout">

            <conversionPattern value="%date [%5thread] %-5level %c %m%n"/>
    </layout>

Sometimes the time between outputs to the log file may be larger than 10 sec.

I see the log output

2022-02-10 14:30:59,543 [    9] DEBUG ...
2022-02-10 14:30:59,543 [    9] INFO  ...
Session end

Session start
2022-02-10 14:43:01,118 [    7] INFO  ...

I can see the the Service object it self is created an disposed. But what about the static member inside my class.

It seams that the static member is disposed in some way and created again.

Can I control this in some way?

Body:
The problem was, that I called log4net.Config.XmlConfigurator.Configure(); always when my service object was constrcuted.

I need to do this only once.

public class Service : IService, IDisposable
{
    private static readonly log4net.ILog log = log4net.LogManager.GetLogger(typeof(Service));
    private static bool logConfigured = false;
...
    public Service()
    {
        if (!logConfigured)
        {
            logConfigured = true;
            log4net.Config.XmlConfigurator.Configure();
        }
    }


问:
How to connect nodeJS docker container to mongoDB
I have problems to connect a nodeJS application which is running as a docker container to a mongoDB. Let me explain what I have done so far:

```<code>$ docker ps

CONTAINER ID    IMAGE        COMMAND                  CREATED        STATUS        PORTS        NAMES
3a3732cc1d90    mongo:3.4    "docker-entrypoint..."   3 weeks ago    Up 3 weeks    27017/tcp    mongo_live
</code>```

As you can see, there is already a mongo docker container running.

Now I'm running my nodeJS application docker container (which is a build from meteorJS):

```<code>$ docker run -it 0b422defbd59 /bin/bash
</code>```

In this docker container I want to run the application by running:

```<code>$ node main.js
</code>```

Now I'm getting the error

```<code>Error: MONGO_URL must be set in environment
</code>```

I already tried to set MONGO_URL by setting:

```<code>ENV MONGO_URL mongodb://mongo_live:27017/
</code>```

But this doesn't work:

```<code>MongoError: failed to connect to server [mongo_live:27017] on first connect
</code>```

So my question is how to connect to a DB, which is - as far as I understand - 'outside' of the running container. Alternativly how do I set up a new DB to this container?

答:
I had problem how to connect my server.js to mongodb. And that's how i solved it hope you find it useful.
Tap For My Screenshot</p>

ContentLicense: CC BY-SA 3.0

Body:
I have problems to connect a nodeJS application which is running as a docker container to a mongoDB. Let me explain what I have done so far:

$ docker ps

CONTAINER ID    IMAGE        COMMAND                  CREATED        STATUS        PORTS        NAMES
3a3732cc1d90    mongo:3.4    "docker-entrypoint..."   3 weeks ago    Up 3 weeks    27017/tcp    mongo_live

As you can see, there is already a mongo docker container running.

Now I'm running my nodeJS application docker container (which is a build from meteorJS):

$ docker run -it 0b422defbd59 /bin/bash

In this docker container I want to run the application by running:

$ node main.js

Now I'm getting the error

Error: MONGO_URL must be set in environment

I already tried to set MONGO_URL by setting:

ENV MONGO_URL mongodb://mongo_live:27017/

But this doesn't work:

MongoError: failed to connect to server [mongo_live:27017] on first connect

So my question is how to connect to a DB, which is - as far as I understand - 'outside' of the running container. Alternativly how do I set up a new DB to this container?


问:
flex mobile project: Establish http connection to a specific url
how to establish http connection to a specific url and get data from that url in flex mobile project.

Thanks

答:
The function:

```<code>/* Function to make a generic HTTP Request
 * loc = location e.g. http://www.google.com
 * req = request
 * type = content type
 * complete = function to execute when HTTP req returns with complete
 */
    public function httpReq(loc:String , req:String, type:String, complete:Function):void{
                /* Start the HTTP Request */
                try{
                    requestSender= new URLLoader();
                    requestSender.addEventListener(Event.COMPLETE, complete);
                    requestSender.addEventListener(HTTPStatusEvent.HTTP_RESPONSE_STATUS, printResponse);
                    var urlRequest :URLRequest = new URLRequest(loc);

                    /* Setup HTTP Request */
                    urlRequest.data = req;
                    urlRequest.contentType = type;
                    urlRequest.method = URLRequestMethod.GET;
                    requestSender.load(urlRequest); // Send the request off, when complete jump to completeHandler
                    }
                catch(e:Error){
                        trace(e.message);
                        trace(e.getStackTrace());
                    }
                }
</code>```

Get the response:

```<code>/* HTTP Request complete, back with response */
private function responseHandler(event:Event):void
{
    this.requestSender = URLLoader(event.target); // Set requestSender as response
    this.output.text = this.requestSender.data; // Get its data
    trace("THE DATA IS "+this.requestSender.data);
    this.requestSender.close();
    alert.cancel();
}
</code>```

Example call:

```<code>httpReq("http://www.google.com" , "requestString", "application/x-www-form-urlencoded", responseHandler);
</code>```

Body:
The function:

/* Function to make a generic HTTP Request
 * loc = location e.g. http://www.google.com
 * req = request
 * type = content type
 * complete = function to execute when HTTP req returns with complete
 */
    public function httpReq(loc:String , req:String, type:String, complete:Function):void{
                /* Start the HTTP Request */
                try{
                    requestSender= new URLLoader();
                    requestSender.addEventListener(Event.COMPLETE, complete);
                    requestSender.addEventListener(HTTPStatusEvent.HTTP_RESPONSE_STATUS, printResponse);
                    var urlRequest :URLRequest = new URLRequest(loc);

                    /* Setup HTTP Request */
                    urlRequest.data = req;
                    urlRequest.contentType = type;
                    urlRequest.method = URLRequestMethod.GET;
                    requestSender.load(urlRequest); // Send the request off, when complete jump to completeHandler
                    }
                catch(e:Error){
                        trace(e.message);
                        trace(e.getStackTrace());
                    }
                }

Get the response:

/* HTTP Request complete, back with response */
private function responseHandler(event:Event):void
{
    this.requestSender = URLLoader(event.target); // Set requestSender as response
    this.output.text = this.requestSender.data; // Get its data
    trace("THE DATA IS "+this.requestSender.data);
    this.requestSender.close();
    alert.cancel();
}

Example call:

httpReq("http://www.google.com" , "requestString", "application/x-www-form-urlencoded", responseHandler);


问:
Matching a number against a comma-separated sequence of ranges
I'm writing a bash script which takes a number, and also a comma-separated sequence of values and strings, e.g.: 3,15,4-7,19-20. I want to check whether the number is contained in the set corresponding to the sequence. For simplicity, assume no comma-separated elements intersect, and that the elements are sorted in ascending order.

Is there a simple way to do this in bash other than the brute-force naive way? Some shell utility which does something like that for me, maybe something related to lpr which already knows how to process page range sequences etc.

答:
Is awk cheating?:

```<code>$ echo -n 3,15,4-7,19-20 |
  awk -v val=6 -v RS=, -F- '(NF==1&&$1==val) || (NF==2&&$1<=val&&$2>=val)' -
</code>```

Output:

```<code>4-7
</code>```

Another version:

```<code>$ echo 19 |
awk -v ranges=3,15,4-7,19-20 '
BEGIN {
    split(ranges,a,/,/)
}
{
    for(i in a) {
        n=split(a[i],b,/-/)
        if((n==1 && $1==a[i]) || (n==2 && $1>=b[1] && $1<=b[2]))
            print a[i]
    }
}' -
</code>```

Outputs:

```<code>19-20
</code>```

The latter is better as you can feed it more values from a file etc. Then again the former is shorter. :D

Body:
Is awk cheating?:

$ echo -n 3,15,4-7,19-20 |
  awk -v val=6 -v RS=, -F- '(NF==1&&$1==val) || (NF==2&&$1<=val&&$2>=val)' -

Output:

4-7

Another version:

$ echo 19 |
awk -v ranges=3,15,4-7,19-20 '
BEGIN {
    split(ranges,a,/,/)
}
{
    for(i in a) {
        n=split(a[i],b,/-/)
        if((n==1 && $1==a[i]) || (n==2 && $1>=b[1] && $1<=b[2]))
            print a[i]
    }
}' -

Outputs:

19-20

The latter is better as you can feed it more values from a file etc. Then again the former is shorter. :D


问:
Azure Service Bus Error: Ensure RequiresSession is set to true when creating a Queue, with Databricks
When attempting to retrieve Queue messages from Azure Service via Databricks I get the following error:

Ensure RequiresSession is set to true when creating a Queue or Subscription to enable sessionful behavior

I have set the Message Queue using Azure's Service Bus Explorer, see below

As you can see I have set the sessionId to carlsession6

Therefore, I'm not sure why I'm getting the error message

The code in databricks is as follows:

```<code>session_id = "carlsession6"

connstr = "Endpoint=sb://carlsbus.servicebus.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=myaccesskey"
queue_name = "carlsqueue"

prevTable = None
table = None
rows = []
msgs = []
run = True

batchMsgs = 0

totalMsgs = 0

with ServiceBusClient.from_connection_string(connstr) as client:
    # max_wait_time specifies how long the receiver should wait with no incoming messages before stopping receipt.
    # Default is None; to receive forever.

    while run:

      with client.get_queue_receiver(queue_name, session_id=session_id, max_wait_time=5) as receiver:

          logDebug(D_LEVEL[1], 'GOT QUEUE RECEIVER')
          rows = []
          msgs = []

          i = 0
          for msg in receiver:

            receiver.session.renew_lock()

            logDebug(D_LEVEL[1], 'READ MESSAGE')
            msgs.append(msg)

            msgJSON = json.loads(str(msg))

            if 'table' in msgJSON['control']:
              table = msgJSON['control']['table']

            if prevTable is None:
              prevTable = table

            if prevTable != table or batchMsgs >= MAX_BATCH_SIZE:
              writeData(prevTable, schema, rows, msgs)
              rows = []
              msgs = []
              batchMsgs = 0

            prevTable = table

            i += 1
            batchMsgs += 1

            if (i % 100 == 0):
              logInfo('Processed ' + str(i) + ' messages')

            if 'operation' in msgJSON['control']:
              if msgJSON['control']['operation'] == "stop_message_processor":
                logInfo('RECEIVED stop_message_processor...')
                run = False
                break

            schema, rows = processMsg(msgJSON, rows)

            logDebug(D_LEVEL[1], 'COMPLETED MESSAGE')

            if STOP_AFTER is not None:
              if i >= STOP_AFTER:
                run = False
                break

          if len(rows) > 0:
            writeData(table, schema, rows, msgs)
          elif len(msgs) == 1:
            receiver.complete_message(msg)

      logInfo('PROCESSED ' + str(i) + ' MESSAGES FROM QUEUE')
      totalMsgs += i

    logInfo('TOTAL MESSAGES PROCESSED ' + str(totalMsgs))
</code>```

Any thoughts on how to resolve the error?

答:
Problem resolved with the following code:

New-AzServiceBusQueue -ResourceGroup myresourcegroup -NamespaceName mynamespace
-QueueName myqueue `
-RequiresSession $True

As described at the following link
https://learn.microsoft.com/en-us/azure/service-bus-messaging/enable-message-sessions

Body:
When attempting to retrieve Queue messages from Azure Service via Databricks I get the following error:

Ensure RequiresSession is set to true when creating a Queue or Subscription to enable sessionful behavior

I have set the Message Queue using Azure's Service Bus Explorer, see below

As you can see I have set the sessionId to carlsession6

Therefore, I'm not sure why I'm getting the error message

The code in databricks is as follows:

session_id = "carlsession6"

connstr = "Endpoint=sb://carlsbus.servicebus.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=myaccesskey"
queue_name = "carlsqueue"

prevTable = None
table = None
rows = []
msgs = []
run = True

batchMsgs = 0

totalMsgs = 0

with ServiceBusClient.from_connection_string(connstr) as client:
    # max_wait_time specifies how long the receiver should wait with no incoming messages before stopping receipt.
    # Default is None; to receive forever.

    while run:

      with client.get_queue_receiver(queue_name, session_id=session_id, max_wait_time=5) as receiver:

          logDebug(D_LEVEL[1], 'GOT QUEUE RECEIVER')
          rows = []
          msgs = []

          i = 0
          for msg in receiver:

            receiver.session.renew_lock()

            logDebug(D_LEVEL[1], 'READ MESSAGE')
            msgs.append(msg)

            msgJSON = json.loads(str(msg))

            if 'table' in msgJSON['control']:
              table = msgJSON['control']['table']

            if prevTable is None:
              prevTable = table

            if prevTable != table or batchMsgs >= MAX_BATCH_SIZE:
              writeData(prevTable, schema, rows, msgs)
              rows = []
              msgs = []
              batchMsgs = 0

            prevTable = table

            i += 1
            batchMsgs += 1

            if (i % 100 == 0):
              logInfo('Processed ' + str(i) + ' messages')

            if 'operation' in msgJSON['control']:
              if msgJSON['control']['operation'] == "stop_message_processor":
                logInfo('RECEIVED stop_message_processor...')
                run = False
                break

            schema, rows = processMsg(msgJSON, rows)

            logDebug(D_LEVEL[1], 'COMPLETED MESSAGE')

            if STOP_AFTER is not None:
              if i >= STOP_AFTER:
                run = False
                break

          if len(rows) > 0:
            writeData(table, schema, rows, msgs)
          elif len(msgs) == 1:
            receiver.complete_message(msg)

      logInfo('PROCESSED ' + str(i) + ' MESSAGES FROM QUEUE')
      totalMsgs += i

    logInfo('TOTAL MESSAGES PROCESSED ' + str(totalMsgs))

Any thoughts on how to resolve the error?


问:
How can I change the hash sign in the url of a page to some other value?
WIth this code </p>

```<code>     <script type="text/javascript">
               window.location.hash="Aboutus";
  </script>
</code>```

<p>,I get url#Aboutus..
I want to change this sign to some other value ..How can I procees?</p>

答: To change url without reload - you have to change hash. You a right. But hash is everything after # sign. So you can't change it.

Body:
WIth this code

,I get url#Aboutus..
I want to change this sign to some other value ..How can I procees?


问:
Is there any benefit to writing aria-required="false"?
Is there any benefit to writing aria-required="false" or is it best only to add aria-required="true" as needed and otherwise leave it off?

I have struggled to find any clarification on this in the WCAG docs I have read.

答:
For simplicity, I always leave off the attribute rather than setting it to false even if false is the default value.  Most(*) of the time you're ok either way.  From a javascript perspective, sometimes it's easier to use a conditional (ternary) operator rather than remove the attribute.

disabled = obj.getAttribute('aria-disabled');
obj.setAttribute('aria-disabled', disabled ? "false" : "true");

/* versus */

disabled = obj.getAttribute('aria-disabled');
if (disabled)
  obj.removeAttribute('aria-disabled')
else
  obj.setAttribute('aria-disabled', "true");
```

Sometimes there's a note in the doc to not do this, as with aria-hidden

Note

At the time of this writing, aria-hidden="false" is known to work inconsistently in browsers. As future implementations improve, use caution and test thoroughly before relying on this approach.

(*) There are a few aria- attributes where you do have to set the value specifically to true or false because setting it to false is not the same as not having the attribute, such as aria-expanded, aria-pressed, aria-checked, aria-selected.  For example, not having aria-expanded doesn't have any meaning but having aria-expanded="false" means you have an expandable/collapsable section that is currently collapsed.   Not having aria-checked doesn't have any meaning but having aria-checked="false" means you have a checkbox that is unchecked.

With aria-required, since it's value will typically not change once it's set (unlike the four attributes just mentioned which do typically change based on user interaction), I keep the code simple and just don't have the attribute.

Body:
For simplicity, I always leave off the attribute rather than setting it to false even if false is the default value.  Most(*) of the time you're ok either way.  From a javascript perspective, sometimes it's easier to use a conditional (ternary) operator rather than remove the attribute.

disabled = obj.getAttribute('aria-disabled');
obj.setAttribute('aria-disabled', disabled ? "false" : "true");

/* versus */

disabled = obj.getAttribute('aria-disabled');
if (disabled)
  obj.removeAttribute('aria-disabled')
else
  obj.setAttribute('aria-disabled', "true");

Sometimes there's a note in the doc to not do this, as with aria-hidden

Note

At the time of this writing, aria-hidden="false" is known to work inconsistently in browsers. As future implementations improve, use caution and test thoroughly before relying on this approach.

(*) There are a few aria- attributes where you do have to set the value specifically to true or false because setting it to false is not the same as not having the attribute, such as aria-expanded, aria-pressed, aria-checked, aria-selected.  For example, not having aria-expanded doesn't have any meaning but having aria-expanded="false" means you have an expandable/collapsable section that is currently collapsed.   Not having aria-checked doesn't have any meaning but having aria-checked="false" means you have a checkbox that is unchecked.

With aria-required, since it's value will typically not change once it's set (unlike the four attributes just mentioned which do typically change based on user interaction), I keep the code simple and just don't have the attribute.


问:
Searching through objects inside nested documents provides unexpected output
I am getting unexpected result from Elasticsearch while searching though object property which are inside nested property. I am using elasticsearch-dsl python library for creating document and querying. Is this bug or I am missing something in querying and mapping parts? Below are the elasticsearch json mapping, query, unexpected result and expected result

Mapping:

```<code>{
  "deal_acls": {
    "type": "nested",
    "properties": {
      "created_at": {
        "type": "date"
      },
      "created_by": {
        "properties": {
          "id": {
            "type": "keyword"
          },
          "name": {
            "type": "text",
            "fields": {
              "keyword": {
                "type": "keyword"
              }
            }
          },
          "status": {
            "type": "keyword",
            "normalizer": "lowercase"
          }
        }
      },
      "permission": {
        "properties": {
          "CRM": {
            "properties": {
              "description": {
                "properties": {
                  "created_by": {
                    "type": "keyword",
                    "normalizer": "lowercase"
                  },
                  "object": {
                    "type": "keyword",
                    "normalizer": "lowercase"
                  },
                  "object_id": {
                    "type": "keyword",
                    "normalizer": "lowercase"
                  },
                  "timestamp": {
                    "type": "date"
                  }
                }
              },
              "permission": {
                "properties": {
                  "delete": {
                    "type": "integer"
                  },
                  "edit": {
                    "type": "integer"
                  },
                  "manage": {
                    "type": "long"
                  },
                  "read": {
                    "type": "integer"
                  },
                  "write": {
                    "type": "integer"
                  }
                }
              }
            }
          },
          "deal": {
            "properties": {
              "description": {
                "properties": {
                  "created_by": {
                    "type": "keyword",
                    "normalizer": "lowercase"
                  },
                  "object": {
                    "type": "keyword",
                    "normalizer": "lowercase"
                  },
                  "object_id": {
                    "type": "keyword",
                    "normalizer": "lowercase"
                  },
                  "timestamp": {
                    "type": "date"
                  }
                }
              },
              "permission": {
                "properties": {
                  "delete": {
                    "type": "integer"
                  },
                  "edit": {
                    "type": "integer"
                  },
                  "manage": {
                    "type": "long"
                  },
                  "read": {
                    "type": "integer"
                  },
                  "write": {
                    "type": "integer"
                  }
                }
              }
            }
          },
          "document": {
            "properties": {
              "description": {
                "properties": {
                  "created_by": {
                    "type": "keyword",
                    "normalizer": "lowercase"
                  },
                  "object": {
                    "type": "keyword",
                    "normalizer": "lowercase"
                  },
                  "object_id": {
                    "type": "keyword",
                    "normalizer": "lowercase"
                  },
                  "timestamp": {
                    "type": "date"
                  }
                }
              },
              "permission": {
                "properties": {
                  "delete": {
                    "type": "integer"
                  },
                  "edit": {
                    "type": "integer"
                  },
                  "manage": {
                    "type": "long"
                  },
                  "read": {
                    "type": "integer"
                  },
                  "write": {
                    "type": "integer"
                  }
                }
              }
            }
          },
          "external_deal_team": {
            "properties": {
              "description": {
                "properties": {
                  "created_by": {
                    "type": "keyword",
                    "normalizer": "lowercase"
                  },
                  "object": {
                    "type": "keyword",
                    "normalizer": "lowercase"
                  },
                  "object_id": {
                    "type": "keyword",
                    "normalizer": "lowercase"
                  },
                  "timestamp": {
                    "type": "date"
                  }
                }
              },
              "permission": {
                "properties": {
                  "delete": {
                    "type": "integer"
                  },
                  "edit": {
                    "type": "integer"
                  },
                  "manage": {
                    "type": "long"
                  },
                  "read": {
                    "type": "integer"
                  },
                  "write": {
                    "type": "integer"
                  }
                }
              }
            }
          },
          "internal_deal_team": {
            "properties": {
              "description": {
                "properties": {
                  "created_by": {
                    "type": "keyword",
                    "normalizer": "lowercase"
                  },
                  "object": {
                    "type": "keyword",
                    "normalizer": "lowercase"
                  },
                  "object_id": {
                    "type": "keyword",
                    "normalizer": "lowercase"
                  },
                  "timestamp": {
                    "type": "date"
                  }
                }
              },
              "permission": {
                "properties": {
                  "delete": {
                    "type": "integer"
                  },
                  "edit": {
                    "type": "integer"
                  },
                  "manage": {
                    "type": "long"
                  },
                  "read": {
                    "type": "integer"
                  },
                  "write": {
                    "type": "integer"
                  }
                }
              }
            }
          }
        }
      },
      "status": {
        "type": "keyword",
        "normalizer": "lowercase"
      },
      "updated_at": {
        "type": "date"
      },
      "updated_by": {
        "properties": {
          "id": {
            "type": "keyword"
          },
          "name": {
            "type": "text",
            "fields": {
              "keyword": {
                "type": "keyword"
              }
            }
          },
          "status": {
            "type": "keyword",
            "normalizer": "lowercase"
          }
        }
      },
      "user": {
        "properties": {
          "id": {
            "type": "keyword"
          },
          "name": {
            "type": "text",
            "fields": {
              "keyword": {
                "type": "keyword"
              }
            }
          },
          "status": {
            "type": "keyword",
            "normalizer": "lowercase"
          }
        }
      }
    }
  }
}

</code>```

Query:

```<code>{
  "query": {
    "bool": {
      "must": [
        {
          "nested": {
            "path": "deal_acls",
            "query": {
              "term": {
                "deal_acls.permission.deal.permission.read": 1
              }
            }
          }
        },
        {
          "nested": {
            "path": "deal_acls",
            "query": {
              "terms": {
                "deal_acls.user.id": [
                  "5f7cea05-6562-4bdd-8448-19cfbe11783a"
                ]
              }
            }
          }
        }
      ]
    }
  }
}
</code>```

Unexpected result: Since the deal permission of user with id=5f7cea05-6562-4bdd-8448-19cfbe11783a is 0, it should be returning empty hits.

```<code>{
  "took": 2,
  "timed_out": false,
  "_shards": {
    "total": 1,
    "successful": 1,
    "skipped": 0,
    "failed": 0
  },
  "hits": {
    "total": {
      "value": 1,
      "relation": "eq"
    },
    "max_score": 2,
    "hits": [
      {
        "_index": "dev.crecentric.dealvault.deals",
        "_type": "_doc",
        "_id": "a928838d-3422-41db-b40e-28f5c793f806",
        "_score": 2,
        "_source": {
          "id": "a928838d-3422-41db-b40e-28f5c793f806",
          "deal_acls": [
            {
              "user": {
                "id": "5f7cea05-6562-4bdd-8448-19cfbe11783a",
                "name": "testerrrrs testesssss",
                "status": "active"
              },
              "permission": {
                "deal": {
                  "permission": {
                    "edit": 0,
                    "read": 0,
                    "write": 0,
                    "delete": 0,
                    "manage": 0
                  },
                  "description": {
                    "object": "workspace",
                    "object_id": "fbc840b1-8727-4945-a070-fa1c105f9550",
                    "timestamp": "2022-02-10T05:46:05.140867+00:00",
                    "created_by": "d78411e5-6645-4b95-a98c-db6db8748580"
                  }
                },
                "external_deal_team": {
                  "permission": {
                    "edit": 0,
                    "read": 1,
                    "write": 1,
                    "delete": 0,
                    "manage": 0
                  },
                  "description": {
                    "object": "workspace",
                    "object_id": "fbc840b1-8727-4945-a070-fa1c105f9550",
                    "timestamp": "2022-02-10T05:46:05.140902+00:00",
                    "created_by": "d78411e5-6645-4b95-a98c-db6db8748580"
                  }
                },
                "internal_deal_team": {
                  "permission": {
                    "edit": 0,
                    "read": 1,
                    "write": 1,
                    "delete": 0,
                    "manage": 0
                  },
                  "description": {
                    "object": "workspace",
                    "object_id": "fbc840b1-8727-4945-a070-fa1c105f9550",
                    "timestamp": "2022-02-10T05:46:05.140910+00:00",
                    "created_by": "d78411e5-6645-4b95-a98c-db6db8748580"
                  }
                }
              },
              "status": "active",
              "created_at": "2022-02-10T05:40:15.727598+05:45",
              "updated_at": "2022-02-10T05:46:05.177076+05:45"
            },
            {
              "user": {
                "id": "d78411e5-6645-4b95-a98c-db6db8748580",
                "name": "Ramesh Pradhan",
                "status": "active"
              },
              "permission": {
                "CRM": {
                  "permission": {
                    "edit": 1,
                    "read": 1,
                    "write": 1,
                    "delete": 1,
                    "manage": 1
                  },
                  "description": {
                    "object": "owner",
                    "object_id": "d78411e5-6645-4b95-a98c-db6db8748580",
                    "timestamp": "2022-02-10T05:35:41.453881+00:00",
                    "created_by": "d78411e5-6645-4b95-a98c-db6db8748580"
                  }
                },
                "deal": {
                  "permission": {
                    "edit": 1,
                    "read": 1,
                    "write": 1,
                    "delete": 1,
                    "manage": 1
                  },
                  "description": {
                    "object": "owner",
                    "object_id": "d78411e5-6645-4b95-a98c-db6db8748580",
                    "timestamp": "2022-02-10T05:35:41.453881+00:00",
                    "created_by": "d78411e5-6645-4b95-a98c-db6db8748580"
                  }
                },
                "document": {
                  "permission": {
                    "edit": 1,
                    "read": 1,
                    "write": 1,
                    "delete": 1,
                    "manage": 1
                  },
                  "description": {
                    "object": "owner",
                    "object_id": "d78411e5-6645-4b95-a98c-db6db8748580",
                    "timestamp": "2022-02-10T05:35:41.453881+00:00",
                    "created_by": "d78411e5-6645-4b95-a98c-db6db8748580"
                  }
                },
                "external_deal_team": {
                  "permission": {
                    "edit": 1,
                    "read": 1,
                    "write": 1,
                    "delete": 1,
                    "manage": 1
                  },
                  "description": {
                    "object": "owner",
                    "object_id": "d78411e5-6645-4b95-a98c-db6db8748580",
                    "timestamp": "2022-02-10T05:35:41.453881+00:00",
                    "created_by": "d78411e5-6645-4b95-a98c-db6db8748580"
                  }
                },
                "internal_deal_team": {
                  "permission": {
                    "edit": 1,
                    "read": 1,
                    "write": 1,
                    "delete": 1,
                    "manage": 1
                  },
                  "description": {
                    "object": "owner",
                    "object_id": "d78411e5-6645-4b95-a98c-db6db8748580",
                    "timestamp": "2022-02-10T05:35:41.453881+00:00",
                    "created_by": "d78411e5-6645-4b95-a98c-db6db8748580"
                  }
                }
              },
              "status": "active",
              "created_at": "2022-02-10T05:35:41.453913+05:45",
              "updated_at": "2022-02-10T05:35:41.462956+05:45"
            }
          ]
        }
      }
    ]
  }
}

</code>```

Expected result:

```<code>{
  "took": 2,
  "timed_out": false,
  "_shards": {
    "total": 1,
    "successful": 1,
    "skipped": 0,
    "failed": 0
  },
  "hits": {
    "total": {
      "value": 1,
      "relation": "eq"
    },
    "max_score": 2,
    "hits": []
  }
}
</code>```

答:
You are using two nested queries: so the result is a document which contains "deal_acls.permission.deal.permission.read": 1 and "deal_acls.user.id": ["5f7cea05-6562-4bdd-8448-19cfbe11783a"], but not necessary in the same subobject of the nested field. Try using a terms query inside a single nested query:

```<code>{
"query": {
    "nested": {
        "path": "deal_acls",
        "query": {
            "bool": {
                "must": [
                    { "match": { "deal_acls.user.id": "5f7cea05-6562-4bdd-8448-19cfbe11783a" }},
                    { "match": { "deal_acls.permission.deal.permission.read":  1 }}
                ]
            }
        }
    }
}
</code>```

}

Body:
I am getting unexpected result from Elasticsearch while searching though object property which are inside nested property. I am using elasticsearch-dsl python library for creating document and querying. Is this bug or I am missing something in querying and mapping parts? Below are the elasticsearch json mapping, query, unexpected result and expected result

Mapping:

{
  "deal_acls": {
    "type": "nested",
    "properties": {
      "created_at": {
        "type": "date"
      },
      "created_by": {
        "properties": {
          "id": {
            "type": "keyword"
          },
          "name": {
            "type": "text",
            "fields": {
              "keyword": {
                "type": "keyword"
              }
            }
          },
          "status": {
            "type": "keyword",
            "normalizer": "lowercase"
          }
        }
      },
      "permission": {
        "properties": {
          "CRM": {
            "properties": {
              "description": {
                "properties": {
                  "created_by": {
                    "type": "keyword",
                    "normalizer": "lowercase"
                  },
                  "object": {
                    "type": "keyword",
                    "normalizer": "lowercase"
                  },
                  "object_id": {
                    "type": "keyword",
                    "normalizer": "lowercase"
                  },
                  "timestamp": {
                    "type": "date"
                  }
                }
              },
              "permission": {
                "properties": {
                  "delete": {
                    "type": "integer"
                  },
                  "edit": {
                    "type": "integer"
                  },
                  "manage": {
                    "type": "long"
                  },
                  "read": {
                    "type": "integer"
                  },
                  "write": {
                    "type": "integer"
                  }
                }
              }
            }
          },
          "deal": {
            "properties": {
              "description": {
                "properties": {
                  "created_by": {
                    "type": "keyword",
                    "normalizer": "lowercase"
                  },
                  "object": {
                    "type": "keyword",
                    "normalizer": "lowercase"
                  },
                  "object_id": {
                    "type": "keyword",
                    "normalizer": "lowercase"
                  },
                  "timestamp": {
                    "type": "date"
                  }
                }
              },
              "permission": {
                "properties": {
                  "delete": {
                    "type": "integer"
                  },
                  "edit": {
                    "type": "integer"
                  },
                  "manage": {
                    "type": "long"
                  },
                  "read": {
                    "type": "integer"
                  },
                  "write": {
                    "type": "integer"
                  }
                }
              }
            }
          },
          "document": {
            "properties": {
              "description": {
                "properties": {
                  "created_by": {
                    "type": "keyword",
                    "normalizer": "lowercase"
                  },
                  "object": {
                    "type": "keyword",
                    "normalizer": "lowercase"
                  },
                  "object_id": {
                    "type": "keyword",
                    "normalizer": "lowercase"
                  },
                  "timestamp": {
                    "type": "date"
                  }
                }
              },
              "permission": {
                "properties": {
                  "delete": {
                    "type": "integer"
                  },
                  "edit": {
                    "type": "integer"
                  },
                  "manage": {
                    "type": "long"
                  },
                  "read": {
                    "type": "integer"
                  },
                  "write": {
                    "type": "integer"
                  }
                }
              }
            }
          },
          "external_deal_team": {
            "properties": {
              "description": {
                "properties": {
                  "created_by": {
                    "type": "keyword",
                    "normalizer": "lowercase"
                  },
                  "object": {
                    "type": "keyword",
                    "normalizer": "lowercase"
                  },
                  "object_id": {
                    "type": "keyword",
                    "normalizer": "lowercase"
                  },
                  "timestamp": {
                    "type": "date"
                  }
                }
              },
              "permission": {
                "properties": {
                  "delete": {
                    "type": "integer"
                  },
                  "edit": {
                    "type": "integer"
                  },
                  "manage": {
                    "type": "long"
                  },
                  "read": {
                    "type": "integer"
                  },
                  "write": {
                    "type": "integer"
                  }
                }
              }
            }
          },
          "internal_deal_team": {
            "properties": {
              "description": {
                "properties": {
                  "created_by": {
                    "type": "keyword",
                    "normalizer": "lowercase"
                  },
                  "object": {
                    "type": "keyword",
                    "normalizer": "lowercase"
                  },
                  "object_id": {
                    "type": "keyword",
                    "normalizer": "lowercase"
                  },
                  "timestamp": {
                    "type": "date"
                  }
                }
              },
              "permission": {
                "properties": {
                  "delete": {
                    "type": "integer"
                  },
                  "edit": {
                    "type": "integer"
                  },
                  "manage": {
                    "type": "long"
                  },
                  "read": {
                    "type": "integer"
                  },
                  "write": {
                    "type": "integer"
                  }
                }
              }
            }
          }
        }
      },
      "status": {
        "type": "keyword",
        "normalizer": "lowercase"
      },
      "updated_at": {
        "type": "date"
      },
      "updated_by": {
        "properties": {
          "id": {
            "type": "keyword"
          },
          "name": {
            "type": "text",
            "fields": {
              "keyword": {
                "type": "keyword"
              }
            }
          },
          "status": {
            "type": "keyword",
            "normalizer": "lowercase"
          }
        }
      },
      "user": {
        "properties": {
          "id": {
            "type": "keyword"
          },
          "name": {
            "type": "text",
            "fields": {
              "keyword": {
                "type": "keyword"
              }
            }
          },
          "status": {
            "type": "keyword",
            "normalizer": "lowercase"
          }
        }
      }
    }
  }
}

Query:

{
  "query": {
    "bool": {
      "must": [
        {
          "nested": {
            "path": "deal_acls",
            "query": {
              "term": {
                "deal_acls.permission.deal.permission.read": 1
              }
            }
          }
        },
        {
          "nested": {
            "path": "deal_acls",
            "query": {
              "terms": {
                "deal_acls.user.id": [
                  "5f7cea05-6562-4bdd-8448-19cfbe11783a"
                ]
              }
            }
          }
        }
      ]
    }
  }
}

Unexpected result: Since the deal permission of user with id=5f7cea05-6562-4bdd-8448-19cfbe11783a is 0, it should be returning empty hits.

{
  "took": 2,
  "timed_out": false,
  "_shards": {
    "total": 1,
    "successful": 1,
    "skipped": 0,
    "failed": 0
  },
  "hits": {
    "total": {
      "value": 1,
      "relation": "eq"
    },
    "max_score": 2,
    "hits": [
      {
        "_index": "dev.crecentric.dealvault.deals",
        "_type": "_doc",
        "_id": "a928838d-3422-41db-b40e-28f5c793f806",
        "_score": 2,
        "_source": {
          "id": "a928838d-3422-41db-b40e-28f5c793f806",
          "deal_acls": [
            {
              "user": {
                "id": "5f7cea05-6562-4bdd-8448-19cfbe11783a",
                "name": "testerrrrs testesssss",
                "status": "active"
              },
              "permission": {
                "deal": {
                  "permission": {
                    "edit": 0,
                    "read": 0,
                    "write": 0,
                    "delete": 0,
                    "manage": 0
                  },
                  "description": {
                    "object": "workspace",
                    "object_id": "fbc840b1-8727-4945-a070-fa1c105f9550",
                    "timestamp": "2022-02-10T05:46:05.140867+00:00",
                    "created_by": "d78411e5-6645-4b95-a98c-db6db8748580"
                  }
                },
                "external_deal_team": {
                  "permission": {
                    "edit": 0,
                    "read": 1,
                    "write": 1,
                    "delete": 0,
                    "manage": 0
                  },
                  "description": {
                    "object": "workspace",
                    "object_id": "fbc840b1-8727-4945-a070-fa1c105f9550",
                    "timestamp": "2022-02-10T05:46:05.140902+00:00",
                    "created_by": "d78411e5-6645-4b95-a98c-db6db8748580"
                  }
                },
                "internal_deal_team": {
                  "permission": {
                    "edit": 0,
                    "read": 1,
                    "write": 1,
                    "delete": 0,
                    "manage": 0
                  },
                  "description": {
                    "object": "workspace",
                    "object_id": "fbc840b1-8727-4945-a070-fa1c105f9550",
                    "timestamp": "2022-02-10T05:46:05.140910+00:00",
                    "created_by": "d78411e5-6645-4b95-a98c-db6db8748580"
                  }
                }
              },
              "status": "active",
              "created_at": "2022-02-10T05:40:15.727598+05:45",
              "updated_at": "2022-02-10T05:46:05.177076+05:45"
            },
            {
              "user": {
                "id": "d78411e5-6645-4b95-a98c-db6db8748580",
                "name": "Ramesh Pradhan",
                "status": "active"
              },
              "permission": {
                "CRM": {
                  "permission": {
                    "edit": 1,
                    "read": 1,
                    "write": 1,
                    "delete": 1,
                    "manage": 1
                  },
                  "description": {
                    "object": "owner",
                    "object_id": "d78411e5-6645-4b95-a98c-db6db8748580",
                    "timestamp": "2022-02-10T05:35:41.453881+00:00",
                    "created_by": "d78411e5-6645-4b95-a98c-db6db8748580"
                  }
                },
                "deal": {
                  "permission": {
                    "edit": 1,
                    "read": 1,
                    "write": 1,
                    "delete": 1,
                    "manage": 1
                  },
                  "description": {
                    "object": "owner",
                    "object_id": "d78411e5-6645-4b95-a98c-db6db8748580",
                    "timestamp": "2022-02-10T05:35:41.453881+00:00",
                    "created_by": "d78411e5-6645-4b95-a98c-db6db8748580"
                  }
                },
                "document": {
                  "permission": {
                    "edit": 1,
                    "read": 1,
                    "write": 1,
                    "delete": 1,
                    "manage": 1
                  },
                  "description": {
                    "object": "owner",
                    "object_id": "d78411e5-6645-4b95-a98c-db6db8748580",
                    "timestamp": "2022-02-10T05:35:41.453881+00:00",
                    "created_by": "d78411e5-6645-4b95-a98c-db6db8748580"
                  }
                },
                "external_deal_team": {
                  "permission": {
                    "edit": 1,
                    "read": 1,
                    "write": 1,
                    "delete": 1,
                    "manage": 1
                  },
                  "description": {
                    "object": "owner",
                    "object_id": "d78411e5-6645-4b95-a98c-db6db8748580",
                    "timestamp": "2022-02-10T05:35:41.453881+00:00",
                    "created_by": "d78411e5-6645-4b95-a98c-db6db8748580"
                  }
                },
                "internal_deal_team": {
                  "permission": {
                    "edit": 1,
                    "read": 1,
                    "write": 1,
                    "delete": 1,
                    "manage": 1
                  },
                  "description": {
                    "object": "owner",
                    "object_id": "d78411e5-6645-4b95-a98c-db6db8748580",
                    "timestamp": "2022-02-10T05:35:41.453881+00:00",
                    "created_by": "d78411e5-6645-4b95-a98c-db6db8748580"
                  }
                }
              },
              "status": "active",
              "created_at": "2022-02-10T05:35:41.453913+05:45",
              "updated_at": "2022-02-10T05:35:41.462956+05:45"
            }
          ]
        }
      }
    ]
  }
}

Expected result:

{
  "took": 2,
  "timed_out": false,
  "_shards": {
    "total": 1,
    "successful": 1,
    "skipped": 0,
    "failed": 0
  },
  "hits": {
    "total": {
      "value": 1,
      "relation": "eq"
    },
    "max_score": 2,
    "hits": []
  }
}

Body:
You are using two nested queries: so the result is a document which contains "deal_acls.permission.deal.permission.read": 1 and "deal_acls.user.id": ["5f7cea05-6562-4bdd-8448-19cfbe11783a"], but not necessary in the same subobject of the nested field. Try using a terms query inside a single nested query:

{
"query": {
    "nested": {
        "path": "deal_acls",
        "query": {
            "bool": {
                "must": [
                    { "match": { "deal_acls.user.id": "5f7cea05-6562-4bdd-8448-19cfbe11783a" }},
                    { "match": { "deal_acls.permission.deal.permission.read":  1 }}
                ]
            }
        }
    }
}

}


问:
H2 - Hibernate not inserting Default column values on SQL INSERT
I'm developing a service and currently working on 2 of its entities (Section and GradeLevel)
While I'm still developing, I decided to use H2 and I generate the tables from Java code.

Section.java

```<code>@Entity
@Setter
@Getter
public class Section{

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(unique = true, nullable = false)
    private String name;

    @OneToOne
    private GradeLevel gradeLevel;

    @Column(columnDefinition = "boolean default TRUE")
    private boolean isActive;

    @Column(columnDefinition="TIMESTAMP DEFAULT CURRENT_TIMESTAMP")
    private Timestamp dateCreated;

    private Timestamp dateLastUpdated;
}
</code>```

GradeLevel.java

```<code>@Entity
@Getter
@Setter
public class GradeLevel {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(unique = true, nullable = false)
    private String code; //GL-01, GL-02...

    @Column(unique = true)
    private String description; //Kinder 1, Kinder 2, Grade 1....
    private String category; //Elementary School, Junior Highschool, Senior Highschool

    @Column(columnDefinition = "boolean default TRUE")
    private boolean isActive;

    @Column(columnDefinition = "TIMESTAMP DEFAULT CURRENT_TIMESTAMP")
    private Timestamp dateCreated;

    private Timestamp dateLastUpdated;
}
</code>```

SectionRESTController.java

```<code>@RestController
@RequestMapping(value = "/api/sections")
public class SectionRESTController {

    @Autowired
    private SectionService sectionService;

    @GetMapping(path = "/{sectionId}")
    public Section getSectionById(@PathVariable("sectionId") Long id) {
        return sectionService.getSectionById(id);
    }

    @PostMapping(consumes = "application/json", produces = "application/json")
    public ResponseEntity<Section> createSection(@Valid @RequestBody SectionCreateDTO sectionCreateDTO) {
        Section createdSection = sectionService.createSection(sectionCreateDTO.toSection());
        if (createdSection == null) {
            return ResponseEntity.notFound().build();
        } else {
            URI uri = ServletUriComponentsBuilder.fromCurrentRequest()
                    .path("/{sectionId}")
                    .buildAndExpand(createdSection.getId())
                    .toUri();
            return ResponseEntity.created(uri)
                    .body(createdSection);
        }
    }
}
</code>```

SectionCreateDTO.java

```<code>@Data
public class SectionCreateDTO {
    @NotEmpty(message = "Section name is required.")
    private String name;

    @NotNull(message = "gradelevel id is required.")
    private Long gradeLevelId;

    public Section toSection() {
        Section section = new Section();
        section.setName(name);

        GradeLevel gradeLevel = new GradeLevel();
        gradeLevel.setId(gradeLevelId);

        section.setGradeLevel(gradeLevel);
        return section;
    }
}
</code>```

Problem :
The createSection() controller method is not inserting the DEFAULT column values for Section's  IS_ACTIVE and DATE_CREATED column. I have set both of these 2 columns to have TRUE and CURRENT_TIMESTAMP default values

Sample request in Postman :

POST localhost:8080/api/sections

```<code>{
        "name": "MERCURY",
        "gradeLevelId" : 1
}
</code>```

In H2 Console, Section table shows NULL and FALSE for those fields. Instead of the correct timestamp and TRUE value.

application.properties

```<code>#========================================================================
#H2 Properties
#========================================================================
spring.h2.console.enabled=true
spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
spring.jpa.hibernate.ddl-auto=update
</code>```

I don't know if this problem is only specific to H2 or maybe I am missing something here.

I'd appreciate any comments.

====== EDIT. Below is the Solution =======

The solution that worked for me is this :

```<code>@Column(columnDefinition = "boolean default true")
private Boolean isActive = true;

@CreationTimestamp
@Column(name = "date_created")
private LocalDateTime dateCreated = LocalDateTime.now();

@UpdateTimestamp
@Column(name = "date_last_updated")
private LocalDateTime dateLastUpdated = LocalDateTime.now();
</code>```

Thank you for the suggestion and answers.

答:
Even if you change boolean to Boolean, it is not going to work.

Hibernate always sends all fields including nulls, for example:

INSERT INTO SECTION(..., IS_ACTIVE, ...) VALUES (..., null, ...)

Your DB will insert NULL to IS_ACTIVE, not the default.

If you want the default to be true, set it in Java:
private Boolean isActive = true;

Body:
I'm developing a service and currently working on 2 of its entities (Section and GradeLevel)
While I'm still developing, I decided to use H2 and I generate the tables from Java code.

Section.java

@Entity
@Setter
@Getter
public class Section{

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(unique = true, nullable = false)
    private String name;

    @OneToOne
    private GradeLevel gradeLevel;

    @Column(columnDefinition = "boolean default TRUE")
    private boolean isActive;

    @Column(columnDefinition="TIMESTAMP DEFAULT CURRENT_TIMESTAMP")
    private Timestamp dateCreated;

    private Timestamp dateLastUpdated;
}

GradeLevel.java

@Entity
@Getter
@Setter
public class GradeLevel {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(unique = true, nullable = false)
    private String code; //GL-01, GL-02...

    @Column(unique = true)
    private String description; //Kinder 1, Kinder 2, Grade 1....
    private String category; //Elementary School, Junior Highschool, Senior Highschool

    @Column(columnDefinition = "boolean default TRUE")
    private boolean isActive;

    @Column(columnDefinition = "TIMESTAMP DEFAULT CURRENT_TIMESTAMP")
    private Timestamp dateCreated;

    private Timestamp dateLastUpdated;
}

SectionRESTController.java

@RestController
@RequestMapping(value = "/api/sections")
public class SectionRESTController {

    @Autowired
    private SectionService sectionService;

    @GetMapping(path = "/{sectionId}")
    public Section getSectionById(@PathVariable("sectionId") Long id) {
        return sectionService.getSectionById(id);
    }

    @PostMapping(consumes = "application/json", produces = "application/json")
    public ResponseEntity
 createSection(@Valid @RequestBody SectionCreateDTO sectionCreateDTO) {
        Section createdSection = sectionService.createSection(sectionCreateDTO.toSection());
        if (createdSection == null) {
            return ResponseEntity.notFound().build();
        } else {
            URI uri = ServletUriComponentsBuilder.fromCurrentRequest()
                    .path("/{sectionId}")
                    .buildAndExpand(createdSection.getId())
                    .toUri();
            return ResponseEntity.created(uri)
                    .body(createdSection);
        }
    }
}

SectionCreateDTO.java

@Data
public class SectionCreateDTO {
    @NotEmpty(message = "Section name is required.")
    private String name;

    @NotNull(message = "gradelevel id is required.")
    private Long gradeLevelId;

    public Section toSection() {
        Section section = new Section();
        section.setName(name);

        GradeLevel gradeLevel = new GradeLevel();
        gradeLevel.setId(gradeLevelId);

        section.setGradeLevel(gradeLevel);
        return section;
    }
}

Problem :
The createSection() controller method is not inserting the DEFAULT column values for Section's  IS_ACTIVE and DATE_CREATED column. I have set both of these 2 columns to have TRUE and CURRENT_TIMESTAMP default values

Sample request in Postman :

POST localhost:8080/api/sections

{
        "name": "MERCURY",
        "gradeLevelId" : 1
}

In H2 Console, Section table shows NULL and FALSE for those fields. Instead of the correct timestamp and TRUE value.

application.properties

#========================================================================
#H2 Properties
#========================================================================
spring.h2.console.enabled=true
spring.datasource.url=jdbc:h2:mem:testdb
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
spring.jpa.hibernate.ddl-auto=update

I don't know if this problem is only specific to H2 or maybe I am missing something here.

I'd appreciate any comments.

====== EDIT. Below is the Solution =======

The solution that worked for me is this :

@Column(columnDefinition = "boolean default true")
private Boolean isActive = true;

@CreationTimestamp
@Column(name = "date_created")
private LocalDateTime dateCreated = LocalDateTime.now();

@UpdateTimestamp
@Column(name = "date_last_updated")
private LocalDateTime dateLastUpdated = LocalDateTime.now();

Thank you for the suggestion and answers.


问:
CSS - why doesn't :hover parent hide child elements
I have a navigation bar with images, like so:

```<code><ul>
  <li class="me">
    <span class="cont"><img src="dummy.png" /></span>
  </li>
  <li class="me">
    <span class="cont"><img src="dummy.png" /></span>
  </li>
</ul>
</code>```

On hovering over a list item I want to change the background color to cover the span and image like so:

```<code>.me {background-color: none;}
.me:hover {background-color: rgba(150,150,150,0.5);}
</code>```

Problem is, the image does not get covered... Is this because the background is in fact... a "background" on which child elements are sitting? If so, how could I achieve this effect with plain CSS?

EDIT - solution

this worked with my original HTML structure:

```<code><ul>
  <li>
   <a href="" class="ui-btn">
     <span class="ui-btn-inner"> /* CONTAINS IMAGE AS BACKGROUND */
        <span class="ui-btn-text">text</span>  /* GETS BACKGROUND */
        <span class="ui-icon"></span>
     </span>
   </a>
 </li>
</ul>
</code>```

"Negative logic": If I assign the background to list item, it sits behind all child elements, so I figured I needed to assign the background to an element that is a child of the element containing the img to have it appear above all items. span ui-btn-inner contains the image, so setting the :hover background on span ui-btn-text makes it appear above the image... weird, but works.

答:
Yes, the background is just a background, and is placed behind any child elements.

To achieve what you're looking for, try using the css :after pseudo element to mask the image on hover:

```<code>.me {
    position: relative;
}

.me:hover:after {
    content: "";
    position: absolute;
    top: 0; left: 0;
    width: 100%; height: 100%;
    background: rgba(150,150,150,0.5);
}
</code>```

It's shiny, you get to use the image as a semantic image, and requires no extra HTML markup.

Body:
I have a navigation bar with images, like so:

On hovering over a list item I want to change the background color to cover the span and image like so:

.me {background-color: none;}
.me:hover {background-color: rgba(150,150,150,0.5);}

Problem is, the image does not get covered... Is this because the background is in fact... a "background" on which child elements are sitting? If so, how could I achieve this effect with plain CSS?

EDIT - solution

this worked with my original HTML structure:

      /* CONTAINS IMAGE AS BACKGROUND */
        text  /* GETS BACKGROUND */

"Negative logic": If I assign the background to list item, it sits behind all child elements, so I figured I needed to assign the background to an element that is a child of the element containing the img to have it appear above all items. span ui-btn-inner contains the image, so setting the :hover background on span ui-btn-text makes it appear above the image... weird, but works.

Body:
Yes, the background is just a background, and is placed behind any child elements.

To achieve what you're looking for, try using the css :after pseudo element to mask the image on hover:

.me {
    position: relative;
}

.me:hover:after {
    content: "";
    position: absolute;
    top: 0; left: 0;
    width: 100%; height: 100%;
    background: rgba(150,150,150,0.5);
}

It's shiny, you get to use the image as a semantic image, and requires no extra HTML markup.


问:
Node.js: SyntaxError: Cannot use import statement outside a module
I am getting this error SyntaxError: Cannot use import statement outside a module when trying to import from another javascript file. This is the first time I'm trying something like this. The main file is main.js and the module file is mod.js.

main.js:

```<code>import * as myModule from "mod";
myModule.func();
</code>```

mod.js:

```<code>export function func(){
    console.log("Hello World");
}
</code>```

How can I fix this? Thanks

答:
I had this issue trying to run mocha tests with typescript. This isn't directly related to the answer but may help some.

This article is quite interesting. He's using a trick involving cross-env, that allows him to run tests as commonjs module type. That worked for me.

// package.json
{
  ...
  "scripts": {
    "test": "cross-env TS_NODE_COMPILER_OPTIONS='{ \"module\": \"commonjs\" }' mocha -r ts-node/register -r src/**/*.spec.ts"
  }
}
```

Body:
I am getting this error SyntaxError: Cannot use import statement outside a module when trying to import from another javascript file. This is the first time I'm trying something like this. The main file is main.js and the module file is mod.js.

main.js:

import * as myModule from "mod";
myModule.func();

mod.js:

export function func(){
    console.log("Hello World");
}

How can I fix this? Thanks


问:
how to define function with generic in typescript
I am defined a function api_post_con like this in typescript:

```<code>export const RequestHandler = {
    api_post_con:(url: string,data: any) => {

    }
}
</code>```

now I want the api_post_con function with generic like this function:

```<code>export function api_post<T>(url: string,data: any): Promise<T> {
    return fetch(url,{
        method: 'POST',
        headers: {
            'Content-type': 'application/json',
            'x-access-token': 'xxxxx'
        },
        body: JSON.stringify(data),
    })
        .then(response => {
        if (!response.ok) {
            throw new Error(response.statusText)
        }
        return response.json() as Promise<T>
        })
}
</code>```

how to change the api_post_con function just like api_post function that return generic type? I have tried like this but did not work:

```<code>export const RequestHandler = {
        api_post_con<T>:(url: string,data: any):Promise<T> => {

        }
    }
</code>```

答:
I think what you need is to declare a class, not an object literal:

export class RequestHandler {
    api_post_con<T>(url: string,data: any):Promise<T> {
        return {} as Promise<T>;
    }
}
```

Body:
I am defined a function api_post_con like this in typescript:

export const RequestHandler = {
    api_post_con:(url: string,data: any) => {

    }
}

now I want the api_post_con function with generic like this function:

export function api_post<T>(url: string,data: any): Promise<T> {
    return fetch(url,{
        method: 'POST',
        headers: {
            'Content-type': 'application/json',
            'x-access-token': 'xxxxx'
        },
        body: JSON.stringify(data),
    })
        .then(response => {
        if (!response.ok) {
            throw new Error(response.statusText)
        }
        return response.json() as Promise<T>
        })
}

how to change the api_post_con function just like api_post function that return generic type? I have tried like this but did not work:

export const RequestHandler = {
        api_post_con<T>:(url: string,data: any):Promise<T> => {

        }
    }


问:
Encoding UFT16 Emoji returns invalid bytes
I am trying to encode a Unicode character in dart, but this results in an invalid byte array.

The character:

The bytes: [FF, FE, 3D, D8, 25, DD]

The string is encoded with BOM. After decoding this string I can see that the string is parsed correctly, resulting to see the emoji inside my IDE.

Then I try to encode the String again but that gives me a byte array, I don't understand:

[FF, FE, FD, FF, FD, FF]

I am using the package utf_convert to encode the string:

import 'package:utf_convert/utf_convert.dart' as utf;

List<int> convert(String input) {
  return utf.encodeUtf16le(input, true).cast<int>();
}
```
<p>Is this a bug inside this package, or am I overseeing something here?</p>
<h1>Edit1</h1>
<p>I wrote some simple tests to capture the problem:</p>
<pre class="lang-dart prettyprint-override"><code>void main() {
  var emojiString = '';
  var emojiBytes = <int>[0xFF, 0xFE, 0x3D, 0xD8, 0x25, 0xDD];

  test('Decode Emoji', () {
    var emoji = utf.decodeUtf16le(emojiBytes);

    expect(emoji, emojiString);
  });

  test('Encode Emoji', () {
    var bytes = utf.encodeUtf16le(emojiString, true).cast<int>();

    expect(bytes, emojiBytes);
  });
}
</code>```

The function "Decode Emoji" succeeds, but the second one, "Encode Emoji" fails with the assertion:

Expected: [255, 254, 61, 216, 37, 221] Actual: [255, 254, 253, 255, 253, 255]

答:
So after doing a lot of researching, I think this is a bug within this library. The code found there is a fork of a discontinued package  found here.

The solution I did now, was using some other piece of code, still existing inside the dart library. I found a hint inside this SO post.

Then I implemented a new library on my own, which others facing the same issue can use too. I hosted it on GitHub and pub.dev under MIT license.

Body:
I am trying to encode a Unicode character in dart, but this results in an invalid byte array.

The character:

The bytes: [FF, FE, 3D, D8, 25, DD]

The string is encoded with BOM. After decoding this string I can see that the string is parsed correctly, resulting to see the emoji inside my IDE.

Then I try to encode the String again but that gives me a byte array, I don't understand:

[FF, FE, FD, FF, FD, FF]

I am using the package utf_convert to encode the string:

import 'package:utf_convert/utf_convert.dart' as utf;

List<int> convert(String input) {
  return utf.encodeUtf16le(input, true).cast<int>();
}

Is this a bug inside this package, or am I overseeing something here?

Edit1

I wrote some simple tests to capture the problem:

void main() {
  var emojiString = '';
  var emojiBytes = <int>[0xFF, 0xFE, 0x3D, 0xD8, 0x25, 0xDD];

  test('Decode Emoji', () {
    var emoji = utf.decodeUtf16le(emojiBytes);

    expect(emoji, emojiString);
  });

  test('Encode Emoji', () {
    var bytes = utf.encodeUtf16le(emojiString, true).cast<int>();

    expect(bytes, emojiBytes);
  });
}

The function "Decode Emoji" succeeds, but the second one, "Encode Emoji" fails with the assertion:

Expected: [255, 254, 61, 216, 37, 221] Actual: [255, 254, 253, 255, 253, 255]


问:
adding entries to NSMutableDictionary
I'm having trouble with adding dictionary's to a nsmutabledictionary. Can anyone see what I'm doing wrong?</p>

```<code>@interface viewMap : UIViewController<MKMapViewDelegate> {

     NSMutableDictionary *onclickDic;

}

@property (nonatomic, retain) NSMutableDictionary *onclickDic;
@end

@implementation viewMap
@synthesize onclickDic;

-(MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation {

    NSString *pushLat   = [NSString stringWithFormat:@"%f", [annotation coordinate].latitude];
    NSString *pushLng   = [NSString stringWithFormat:@"%f", [annotation coordinate].longitude];

    NSDictionary *latlngDic = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:pushLat, pushLng, nil] forKeys:[NSArray arrayWithObjects:@"lat", @"lng", nil]];

    NSDictionary *toPush    = [NSDictionary dictionaryWithObject:latlngDic forKey:[NSString stringWithFormat:@"%i", i]];

    NSLog(@"toPush is %@", toPush); // this one is correct and works

    [self.onclickDic addEntriesFromDictionary:toPush];

    NSLog(@"onclickDic is %@", onclickDic); // this one gives (null)
}
@end
</code>```

答:
You do not seem to instantiate self.onclickDic anywhere. Even with @synthesize, this is not done for you. Best place for that is probably init.

The reason the call is not failing, is that it's OK in Objective C to call a function on a nil object. This is commonly used when calling methods of delegates, for example.

Title: adding entries to NSMutableDictionary

Body:
I'm having trouble with adding dictionary's to a nsmutabledictionary. Can anyone see what I'm doing wrong?

@interface viewMap : UIViewController<MKMapViewDelegate> {

     NSMutableDictionary *onclickDic;

}

@property (nonatomic, retain) NSMutableDictionary *onclickDic;
@end

@implementation viewMap
@synthesize onclickDic;

-(MKAnnotationView *)mapView:(MKMapView *)mapView viewForAnnotation:(id <MKAnnotation>)annotation {

    NSString *pushLat   = [NSString stringWithFormat:@"%f", [annotation coordinate].latitude];
    NSString *pushLng   = [NSString stringWithFormat:@"%f", [annotation coordinate].longitude];

    NSDictionary *latlngDic = [NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:pushLat, pushLng, nil] forKeys:[NSArray arrayWithObjects:@"lat", @"lng", nil]];

    NSDictionary *toPush    = [NSDictionary dictionaryWithObject:latlngDic forKey:[NSString stringWithFormat:@"%i", i]];

    NSLog(@"toPush is %@", toPush); // this one is correct and works

    [self.onclickDic addEntriesFromDictionary:toPush];

    NSLog(@"onclickDic is %@", onclickDic); // this one gives (null)
}
@end


问:
HTMLpurifier remove cc email between tags
I'm using HTMLpurifier to sanitize inputs in my PHP application:

I have CC and BCC inputs something like:

Test Admin <test@domain.com>

when I do purify this string, it only keeps: Test Admin (without email between tags)

Please advise!

答:
This probably means you've got an escaping issue somewhere in your pipeline before HTML Purifier - something that's putting E-Mail text into an HTML context without HTML escaping it. HTML you need to purify that looks like this:

EmailTest Admin <test@domain.com>

```
<p>...should really look like this:</p>
<pre class="lang-html prettyprint-override"><code><p><label for "id">Email</label><span id="email">Test Admin <test@domain.com></span></p>
</code>```

If you have no control over the step that's inserting data into the HTML you ultimately want to purify before displaying, you can use this to preprocess your HTML before feeding it to HTML Purifier:

$htmlWithEmail = preg_replace('/<([^<>@]*@[^<>@]*)>/', '<${1}>', $htmlWithEmail);
```

On the other hand - and I mention this because I know only a little bit about your use-case right now - if you're not actually trying to preserve HTML, if the string you're purifying is literally just Test Admin <test@domain.com> with nothing else (unlike the example I crafted above), htmlspecialchars() should be your weapon of choice when outputting into HTML, not HTML Purifier.

HTML Purifier's purpose is not all-purpose data sanitation, it really does exist only for the use-case where you have HTML, you want to preserve it if it's well-behaved, and then output it as HTML. You can find some more info about escaping for context here: https://stackoverflow.com/a/37641037/245790

Body:
This probably means you've got an escaping issue somewhere in your pipeline before HTML Purifier - something that's putting E-Mail text into an HTML context without HTML escaping it. HTML you need to purify that looks like this:

<p><label for "id">Email</label><span id="email">Test Admin <test@domain.com></span></p>

...should really look like this:

<p><label for "id">Email</label><span id="email">Test Admin &lt;test@domain.com&gt;</span></p>

If you have no control over the step that's inserting data into the HTML you ultimately want to purify before displaying, you can use this to preprocess your HTML before feeding it to HTML Purifier:

$htmlWithEmail = preg_replace('/<([^<>@]*@[^<>@]*)>/', '&lt;${1}&gt;', $htmlWithEmail);

On the other hand - and I mention this because I know only a little bit about your use-case right now - if you're not actually trying to preserve HTML, if the string you're purifying is literally just Test Admin <test@domain.com> with nothing else (unlike the example I crafted above), htmlspecialchars() should be your weapon of choice when outputting into HTML, not HTML Purifier.

HTML Purifier's purpose is not all-purpose data sanitation, it really does exist only for the use-case where you have HTML, you want to preserve it if it's well-behaved, and then output it as HTML. You can find some more info about escaping for context here: https://stackoverflow.com/a/37641037/245790


问:
Handling remote (RDP) mouse clicking via Python
I am using pyautogui to automate some mouse clicking in a script that I created.

This script needs to perform one click to log into a program, nothing else (besides other non-clicking stuff). The idea is that the script will run on a remote Win10 PC via a task scheduler every day at, lets say, at 11PM.

My script works perfectly when run on my own PC but I am running into issues with how to handle the remote RDP resolution to correctly identify the mouse position to click. Furthermore, the script will run on a remote PC that might not have "active user" logged in and I am not even sure if this mouse clicking approach will work. How to identify correctly the "resolution" of the remote PC?

Could you help me?

Thanks.

答: Pyautogui can be used to interact with remote system the same way a human can by opening the RDP or VNC window identifying elements inside of it and then directly interacting with them. This works but you're now expecting two systems to be in sufficiently consistent state for the automation to work. This does have the advantage that you don't need to know the resolution of the remote system just what the interactable elements look like when rendered through the RDP client on your system.</p>


问:
How to switch back to Old AWS Management Console
I was trying to switch back to the old management console of AWS. I found this in AWS discussion forum but it seems to be backdated and doesn't work anymore.
I don't see the Switch back to previous version option mentioned there in my dashboard.

My question is how can I switch back to the previous styled web console in AWS?

My current dashboard:

Image mentioned in the forum:

Edit:

Reason why I want to switch back to the previous panel: I was adding some Lifecycle rules to my S3 bucket. The previous console had better instructions and tooltip helps for adding rules.

答:
Go to https://console.aws.amazon.com/

Click "Reset to default layout"