text:
Q: How to trigger change event after select new added option from select tag using select2 in angularjs? How to trigger change event after select new added option from select tag using select2 in angularjs ?
I have created directive of angular js to apply select2 in <select> tag.  I want to trigger change event after select2 apply on the element. I am using tagging of select2. After adding the new tag in select, I want to trigger change event.  But ng-change event trigger first after that select2:select event trigger. So I am not able to get the value of ng-model after selecting the newly added option.  Please help me to resolve this issue.
I have used jquery 3.2.1, select2 4.0.2, angular js 1.7.8.
I have tried with this below code :
<select custom-select2 id="items" ng-model="items" class="form-control"
        ng-change="onChange(items)">
    <option ng-repeat="item in itemlist" value="{{ item.id }}">
      {{ item.name }}
    </option>
</select>

 let app= angular.module("app",[]);
 app.controller('itemAddController',function($scope, $http){
    $scope.itemlist= {};
    $scope.onChange = (items) => {
      console.log(items)
    }
 });

app.directive('customSelect2', function($timeout) {
    return {
        restrict: 'A',
        require: 'ngModel',
        link: function(scope, element, attr, ngModel) {
            $timeout( function(){
                element.select2({
                    allowClear:true,
                    tags: true,
                    tokenSeparators: [",",";"],
                    createTag: function (params) {
                        let obj = {};
                        let term = $.trim(params.term);
                        if (term === '') {
                            return null;
                        }
                        obj = {
                          id: term,
                          text: term,
                          newTag: true // add additional parameters
                        };
                        return obj;
                    }
                }).on("select2:select", function(e) {
                    if(e.params.data.newTag){
                        scope.itemlist.push(e.params.data.text)
                        ngModel.$setViewValue(e.params.data.text);
                    }
                });
            },200);

        }
    }
});

I want to call function onChange after select2 event trigger.


text:
Q: Enterprise OTA app disappears after install When distributing an iOS app for a client using the "Enterprise Distribution" option, the app downloads and installs but then quickly disappears from the home screen.  After rebooting the iOS device, it reappears.

A: In my situation I actually just reuse the .plist file between builds that is generated if you were to click the "Save for Enterprise Distribution" checkbox when you are about to save the .ipa file. The value I had typed in for the "bundle-identifier" key had an old APPID instead of the one the app is currently distributed under. Correcting this error and reinstalling the app from our website fixed the problem.
Essentially adding a missing .app. to our bundle-identifier allowed the application to install properly and stay on the homes creen without need for reboot.
from:
<key>metadata</key>
        <dict>
            <key>bundle-identifier</key>
            <string>com.mycompany.MyApp</string>

to:
<key>metadata</key>
        <dict>
            <key>bundle-identifier</key>
            <string>com.mycompany.app.MyApp</string>

A: @ThaDon Thanks!  I upvoted you for this post.  I had a similar problem.  I had a plist which I reused from someone else and didn't pay careful enough attention to the value I put in for the bundle-identifier (the previous person used just the app name as the bundle identifier, but I used the recommended reverse domain notation com.. .  It worked fine on iOS 6, but on iOS 5 it downloaded/installed and then disappeared, as you described.  Once I put the exact same bundle identifier I had in my Xcode project, it worked the way I expected it to.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Multiple Notifications, only the first one fires up I am making an attendance tracking system.
So, I need to fire notifications before class begins and after class starts.
Main method is where I am creating notifications for each course form a database.
mainMethod() {
    testAlarmA(s[0], s[2]);
    testAlarmB(s[0], s[2]);
}

I have implemented setAction() method for each intent, and also have different request codes for each pending intent (I have read these in earlier questions on this site)
private void testAlarmA (String code) {
    Log.i("attendance", "class-start");
    AlarmManager alarmManager = (AlarmManager) getContext().getSystemService(Context.ALARM_SERVICE);

    Intent notificationIntent = new Intent("android.media.action.DISPLAY_ATTENDANCE_NOTIFICATION");
    notificationIntent.addCategory("android.intent.category.DEFAULT");
    notificationIntent.putExtra("type", "start");
    notificationIntent.putExtra("courseCode", code);
notificationIntent.setAction(Long.toString(System.currentTimeMillis()));

    Calendar c = Calendar.getInstance();
    c.add(Calendar.MINUTE, 1);

    PendingIntent broadcast = PendingIntent.getBroadcast(getContext(), 111, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);

    alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, c.getTimeInMillis(), (2 * 60 * 1000), broadcast);
}

private void testAlarmB (String code){
    Log.i("attendance", "class-end");
    AlarmManager alarmManager = (AlarmManager) getContext().getSystemService(Context.ALARM_SERVICE);

    Intent notificationIntent = new Intent("android.media.action.DISPLAY_ATTENDANCE_NOTIFICATION");
    notificationIntent.addCategory("android.intent.category.DEFAULT");
    notificationIntent.putExtra("type", "end");
    notificationIntent.putExtra("courseCode", code);
    notificationIntent.setAction(Long.toString(System.currentTimeMillis()));

    Calendar c = Calendar.getInstance();
    c.add(Calendar.MINUTE, 2);

    PendingIntent broadcast = PendingIntent.getBroadcast(getContext(), 222, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);

    alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, c.getTimeInMillis(), (2 * 60 * 1000), broadcast);

}

In by broadcast receiver class, i am extracting extras to know which notification to fire, i.e. class start or end.
But only class start notif is receiver, class end Log Entry is never shown.
@Override
public void onReceive(Context context, Intent intent) {
    Log.i("time", "onReceive");
    mNotificationManager =
            (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
    manager = mNotificationManager;

        if (intent.getExtras().containsKey("type")) {
            Log.i("time", "containsKey");

            String type = intent.getExtras().getString("type");
            if (type.equals("end")) {
                Log.i("time", "end");
                endNotif(context);

            } else if (type.equals("start")) {
                Log.i("time", "start");
                startNotif(context);

            }
     }

}

I have also user unique ID for notification builder.
private void startNotif (Context context) {
    Intent notificationIntent = new Intent();
    notificationIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
    PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);

    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context)
            .setContentTitle("You Have " + courseCode + " at " + roomNo)
            .setContentIntent(pendingIntent)
            .setDefaults(Notification.DEFAULT_VIBRATE)
            .setPriority(Notification.PRIORITY_DEFAULT)
            .setVisibility(Notification.VISIBILITY_PUBLIC)
            .setSmallIcon(R.drawable.ic_library_books_white_24dp)
            .setLights(0xff00ff00, 1000, 1000)
            .setAutoCancel(true);

    mNotificationManager.notify(1, mBuilder.build());
}

My end-class notification will have 3 different action buttons.
private void endNotif (Context context) {
    Intent notificationIntent = new Intent(context, AttendanceActivity.class);
    notificationIntent.putExtra("courseCode", courseCode);
    notificationIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);

    Intent classAttended = new Intent(context, AttendanceNotificationServiceClass.class);
    classAttended.setAction("action");
    classAttended.putExtra("courseCode", courseCode);
    classAttended.putExtra("class", "attended");
    PendingIntent pClassAttended = PendingIntent.getService(context, 11, classAttended, PendingIntent.FLAG_UPDATE_CURRENT);

    Intent classBunked = new Intent(context, AttendanceNotificationServiceClass.class);
    classBunked.setAction("action");
    classBunked.putExtra("courseCode", courseCode);
    classBunked.putExtra("class", "bunked");
    PendingIntent pClassBunked = PendingIntent.getService(context, 22, classBunked, PendingIntent.FLAG_UPDATE_CURRENT);

    Intent classOff = new Intent(context, AttendanceNotificationServiceClass.class);
    classOff.setAction("action");
    classOff.putExtra("courseCode", courseCode);
    classOff.putExtra("class", "off");
    PendingIntent pClassOff = PendingIntent.getService(context, 33, classOff, PendingIntent.FLAG_UPDATE_CURRENT);

    PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);

    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context)
            .setVisibility(Notification.VISIBILITY_PUBLIC)
            .setSmallIcon(R.drawable.ic_library_books_white_24dp)
            .setContentTitle(courseCode + " Just Ended")
            .setContentText("Did you attend " + courseCode + " ?")
            .addAction(R.drawable.ic_thumb_up_white_24dp, "Attended", pClassAttended)
            .addAction(R.drawable.ic_thumb_down_white_24dp, "Bucked", pClassBunked)
            .addAction(R.drawable.ic_clear_white_24dp, "Class Off", pClassOff)
            .setContentIntent(pendingIntent)
            .setDefaults(Notification.DEFAULT_VIBRATE)
            .setPriority(Notification.PRIORITY_HIGH)
            .setLights(0xff00ff00, 1000, 1000)
            .setAutoCancel(true);

    mNotificationManager.notify(0, mBuilder.build());
}

But when i fire up the app, only class-start notification is shown after 1 minute. class-end notif was supposed to show 1 min after class-start notif.
Start notif is shown as it should be, i.e. after every minute.
But end notif is never shown, not even once.
If in the methods testAlarmA() and testAlarmB(), I make changes such that testAlarmB() is made to fire before testAlarmA(), only B/end will be shown. The A/start will never be shown.
My Log
07-14 22:04:49.258 30137-30137/in.ac.iitd.bsw.iitdapp I/time: onReceive
07-14 22:04:49.286 30137-30137/in.ac.iitd.bsw.iitdapp I/time: containsKey
07-14 22:04:49.287 30137-30137/in.ac.iitd.bsw.iitdapp I/time: start
07-14 22:06:29.165 30137-30137/in.ac.iitd.bsw.iitdapp I/time: onReceive
07-14 22:06:29.173 30137-30137/in.ac.iitd.bsw.iitdapp I/time: containsKey
07-14 22:06:29.173 30137-30137/in.ac.iitd.bsw.iitdapp I/time: start
07-14 22:07:59.689 30137-30137/in.ac.iitd.bsw.iitdapp I/time: onReceive
07-14 22:07:59.690 30137-30137/in.ac.iitd.bsw.iitdapp I/time: containsKey
07-14 22:07:59.690 30137-30137/in.ac.iitd.bsw.iitdapp I/time: start
07-14 22:09:52.756 30137-30143/in.ac.iitd.bsw.iitdapp W/art: Suspending all threads took: 5.590ms
07-14 22:10:29.623 30137-30137/in.ac.iitd.bsw.iitdapp I/time: onReceive
07-14 22:10:29.624 30137-30137/in.ac.iitd.bsw.iitdapp I/time: containsKey
07-14 22:10:29.624 30137-30137/in.ac.iitd.bsw.iitdapp I/time: start
07-14 22:11:59.696 30137-30137/in.ac.iitd.bsw.iitdapp I/time: onReceive
07-14 22:11:59.696 30137-30137/in.ac.iitd.bsw.iitdapp I/time: containsKey
07-14 22:11:59.696 30137-30137/in.ac.iitd.bsw.iitdapp I/time: start
07-14 22:13:23.618 30137-30137/in.ac.iitd.bsw.iitdapp I/time: onReceive
07-14 22:13:23.618 30137-30137/in.ac.iitd.bsw.iitdapp I/time: containsKey
07-14 22:13:23.657 30137-30137/in.ac.iitd.bsw.iitdapp I/time: start
07-14 22:15:43.136 30137-30137/in.ac.iitd.bsw.iitdapp I/time: onReceive
07-14 22:15:43.136 30137-30137/in.ac.iitd.bsw.iitdapp I/time: containsKey
07-14 22:15:43.136 30137-30137/in.ac.iitd.bsw.iitdapp I/time: start

A: In testAlarmA and testAlarmB method you are using Intent constructor which is setting action, there is no need of calling setAction again. And in setAction method you are passing Long.toString(System.currentTimeMillis()), which I think you have inserted by mistake, try removing that.
see this intent constructor:
https://developer.android.com/reference/android/content/Intent.html#Intent(java.lang.String)
and setAction method:
https://developer.android.com/reference/android/content/Intent.html#setAction(java.lang.String)

A: Hi When creating pendingIntent object make sure each intent has different notification ID as shown below
PendingIntent deletePendingIntent = PendingIntent.getBroadcast(this.getApplicationContext(), notificationId, deleteIntent, 0);

where notificationId is when open app you need to pass one and after launch you need to have another one


text:
Q: Why does my footer disappear when I remove Border from the Center content I have just started trying to learn to code.
I have tried to replicate the google homepage as part of an online course. This is HTML and CSS, however I have ran into the following issue.
Context: I added the border in css for my own sake, so I can see where and how much space the center is taking.
Here is the code in a snippet:

body,
html {
  background-color: white;
  font-size: 1em;
  width: 100%;
  max-width: 2400px;
  max-height: 100vh;
  margin: 0px;
  font-family: Arial, Helvetica, sans-serif;
  height: 100vh;
  position: fixed;
}

.navigation {
  list-style: none;
  overflow: hidden;
  width: 100%;
  background-color: white;
  height: 8vh;
  display: block;
  text-align: right;
}

.navigation li {
  display: inline-block;
  font-size: .9em;
}

.navigation li a {
  padding: 7px;
  text-decoration: none;
  color: black;
  justify-content: center;
}

.navigation li a:hover {
  cursor: pointer;
  text-decoration: underline;
}

.navimage {
  border-radius: 50%;
  border: 5px solid transparent;
}

#user-image {
  margin-right: 1em;
}

.navimage:hover {
  border-color: #E8E8E8;
  cursor: pointer;
}

.center {
  width: 100%;
  height: 84vh;
  text-align: center;
  border: 1px solid green;
}

.google-logo {
  margin-top: 10em;
  margin-bottom: 1em;
}

.search input {
  margin-top: 1em;
  margin-bottom: 1em;
  border: 2px solid #d3d3d3;
  width: 28%;
  height: 40px;
  border-radius: 30px;
  font-size: 1.4em;
  padding-left: 50px;
  padding-right: 40px;
  color: black;
}

input:hover {
  box-shadow: 3px violet;
}

#magnifier-glass {
  position: absolute;
  margin-top: 36px;
  margin-left: 20px;
}

#microphone {
  position: absolute;
  margin-top: 36px;
  margin-left: -36px;
}

#lucky {
  width: 100%;
}

.btn {
  background-color: #f0f0f0;
  width: 8%;
  height: 40px;
  border-radius: 5px;
  margin: 10px;
  border-color: transparent;
  font-size: 15px;
}

.btn:hover {
  box-shadow: rgba(0, 0, 0, 0.05) 0px 6px 24px 0px, rgba(0, 0, 0, 0.08) 0px 0px 0px 1px;
  cursor: pointer;
}

footer {
  width: 100%;
  height: 8vh;
  justify-content: space-between;
  background-color: #E8E8E8;
  display: flex;
  position: fixed;
  z-index: 1;
  border: 1px solid red;
}

footer ul {
  list-style: none;
}

footer ul li {
  display: inline-block;
  margin: 5px;
  padding-top: 25px;
}

footer ul li a {
  text-decoration: none;
  font-size: 1em;
  color: #686868;
}

footer ul li a:hover {
  text-decoration: underline;
}

.footer-right {
  margin-right: 30px !important;
}

.footer-left {
  margin-left: -15px !important;
}
<!DOCTYPE html>

  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="stylesheet" href="style.css">
  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <link rel="icon" type="image/png" href="images/title-logo.png">
  <title>Google</title>
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">

    <navbar class="navigation">

          Gmail

          Images

    </navbar>

      <input type="text" class="searchGoogle" placeholder="">

      <button class="btn" type="button">Google Search</button>
      <button class="btn" type="button">I'm Feeling Lucky</button>

        About

        Advertising

        Business

        How Search works

        Privacy

        Terms

        Settings

I know the CSS is probably bad as it is too large.
But my main concern is: why does the footer disappear when I remove the border from the center div?
Yes, I tried to remove and modify but I can't figure out what is messing it up (apart from me doing it all wrong).
Thank you for your help.

A: The footer doesn't disappear, it just drops further down so it doesn't appear on the screen and you don't set overflow:auto to body so you can't see it by scrolling.
By the way, it caused by .google-logo's margin. Try deleting it.
Second way, to fix this, see this example. I gave overflow:auto and fixed a bit of CSS for the footer to make it neater by removing position and height.

body, html {
    background-color: white;
    font-size: 1em;
    width: 100%;
    max-width: 2400px;
    max-height: 100vh;
    margin: 0px;
    font-family: Arial, Helvetica, sans-serif;
    height: 100vh;
    position: fixed;
    overflow: auto;
}

.navigation {
    list-style: none;
    overflow: hidden;
    width: 100%;
    background-color: white;
    height: 8vh;
    display: block;
    text-align: right;
}

.navigation li {
    display: inline-block;
    font-size: .9em;

}
.navigation li a {
    padding: 7px;
    text-decoration: none;
    color: black;
    justify-content: center;
}
.navigation li a:hover{
    cursor: pointer;
    text-decoration: underline;
}
.navimage {
    border-radius: 50%;
    border: 5px solid transparent;
}
#user-image{
    margin-right: 1em;
}
.navimage:hover {
    border-color: #E8E8E8;
    cursor: pointer;

}
.center {
    width: 100%;
    height: 84vh;
    text-align: center;

}
.google-logo {
    margin-top: 10em;
    margin-bottom: 1em;
}

.search input {
    margin-top: 1em;
    margin-bottom: 1em;
    border: 2px solid #d3d3d3;
    width: 28%;
    height: 40px;
    border-radius: 30px;
    font-size: 1.4em;
    padding-left: 50px;
    padding-right: 40px;
    color: black;
}

input:hover {
    box-shadow: 3px violet;

}
#magnifier-glass {
    position:absolute;
    margin-top: 36px;
    margin-left: 20px;
}
#microphone {
    position: absolute;
    margin-top: 36px;
    margin-left: -36px;
}

#lucky {
    width: 100%;

}

.btn {
    background-color: #f0f0f0;
    width: 8%;
    height: 40px;
    border-radius: 5px;
    margin: 10px;
    border-color: transparent;
    font-size: 15px;
}

.btn:hover{
    box-shadow: rgba(0, 0, 0, 0.05) 0px 6px 24px 0px, rgba(0, 0, 0, 0.08) 0px 0px 0px 1px;
    cursor: pointer;
}

footer {
    width: 100%;
    height: auto;
    justify-content: space-between;
    background-color: #E8E8E8;
    display: flex;
    z-index: +1;
}

footer ul {
    list-style: none;

}
footer ul li {
    display: inline-block;
    margin: 5px;
    padding-top: 25px;

}
footer ul li a {
    text-decoration: none;
    font-size: 1em;
    color: #686868;
}
footer ul li a:hover{
    text-decoration: underline;
}
.footer-right {
    margin-right: 30px !important;
}
.footer-left {
    margin-left: -15px !important;
}

        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <link rel="stylesheet" href="style.css">
        <meta charset="utf-8" />
     <meta name="viewport" content="width=device-width, initial-scale=1" />
     <link rel="icon" type="image/png" href="images/title-logo.png">
     <title>Google</title>
     <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">

    <navbar  class="navigation">

               Gmail

                Images

    </navbar>

        <input type="text" class="searchGoogle" placeholder="">

        <button class="btn"  type="button">Google Search</button>
        <button class="btn"  type="button">I'm Feeling Lucky</button>

                About

                Advertising

                Business

                How Search works

                Privacy

                Terms

                Settings


text:
Q: Remap Scroll Lock to lock Windows (Win+L) I'm trying to re-purpose some keys that I never use into functions I use all the time.  I discovered AutoHotkey here on SuperUser and figured this would be the way to go, but I'm having difficulties already.
The first thing I wanted to do is to remap the Scroll Lock key so that it locks my computer (like pressing Win+L does).  From what I have gathered in the AutoHotkey help file, this should work
SCROLLLOCK::Send #l

but it doesn't do anything.
If I change the script to read SCROLLLOCK::Send #e then the Scroll Lock key does launch Windows Explorer, as would be expected.  Does anyone know how to lock the computer from AutoHotkey?

Update -
I tried the following code as well, but to no avail:
SCROLLLOCK::Run C:Windows\System32\rundll32.exe user32.dll,LockWorkStation

The command does lock the computer if you just dump it in the run command, but in AutoHotkey it just does a really brief flash of the "waiting" cursor, then nothing.

A: You can lock the computer with AutoHotkey's Run command:
ScrollLock::Run, % "rundll32.exe user32.dll,LockWorkStation"

You have to be careful when passing parameters, so I like to use an expression to encode the entire command properly.


text:
Q: Read textfile and show it in richtextbox. Show one word from Richtextbox in ComboBox then find it in text and replace it with TextBox.text I have opened a .CSV file in RichTextBox.I added every line's first word to CombobBox items. I want to edit this a specific word and then save it back to the File.
This is how i open the file to richTextBox1.
        OpenFileDialog ofd = new OpenFileDialog();
        ofd.Filter = "Csv files (.csv)|*.csv";
        ofd.Title = "Open a file...";
        if (ofd.ShowDialog() == DialogResult.OK)
        {
            StreamReader sr = new StreamReader(ofd.FileName);
            richTextBox1.Text = sr.ReadToEnd();
        }

Now i want a Button that finds my comboBox1.Text in richTextBox and replace it with txtbox.Text.
My button looks like this:
        private void button1_Click(object sender, EventArgs e)
        {
            using (TextReader reader = new StringReader(richTextBox1.Text))
            {
                string str = reader.ReadToEnd();
                string cbtxt = comboBox1.Text;
                string tbtxt = txtbox.Text;
                str = str.Replace(cbtxt, tbtxt);
            }
        }

I would add the method to the end of this button that would save back the text from richTextBox to my .CSV file but this replace method doesnt replace anything in my richTextBox.
My .CSV file (in richTextBox) looks like this:

somestring,somenumber,somespecialcharacters;
  somestring2,somenumber2,somespecialcharacters2;

It has about 50 lines,and my combobox is filled with the first words of every line like: "somestring" "somestring2".
When i click on somestring (then its my combobox.text) then i write "newstring" to my txtbox.text. When i click my button it should find comboBox.text in richtxt and replace it with my txtbox.text.
Any ideas why it doesnt work?

A: You wrote:

but this replace method doesnt replace anything in my richTextBox.

This is because strings in C# are immutable? Whatever you do to strings, the original string is never changed. The result is always in a new string.
See Why .NET String is immutable?
So although your code changes the value of str, the original str that your richtextbox displays is not changed.
string str = reader.ReadToEnd();
string cbtxt = comboBox1.Text;
string tbtxt = txtbox.Text;
str = str.Replace(cbtxt, tbtxt);

str refers to a new string. RichTextBox1.Text still refers to the original string.
Solution: Assign the new string to the rich text box:
this.RichTextBox1.Text = str;

If you want to save the text in a file you'll have to create a FileWriter that will write the new string (not the changed string, strings can't change!).
Depending on how important it is that you don't lose the old file in case of problems, consider using a tmpfile to write, delete the original and move the tmpfile

A: In order to replace or delete something using a stream reader, you will need to delete every line and replace it with a new (temporary) file.
var tempFile = Path.GetTempFileName(); //Creates temporary file
            List<string> linesToKeep = new List<string>(); //Creates list of all the lines you want to keep (everything but your selection)
            using (FileStream fs = new FileStream(path(), FileMode.Open, FileAccess.Read)) //(this opens a new filestream (insert your path to your file there)
            {
                using (StreamReader sr = new StreamReader(fs)) //here is starts reading your file line by line.
                {
                    while (!sr.EndOfStream) //as long it has not finished reading
                    {
                        string currentline = sr.ReadLine().ToString(); //this takes the current line it has been reading
                        string splitline = currentline; //this is a temporary string because you are going to have to split the lines (i think you have 3 so split in "," and then index the first line (your identifier or name)))
                        if (splitline.Split(';')[0] != ID) //split the line and add your personal identifier so it knows what to keep and what to delete.
                        {
                            linesToKeep.Add(currentline); //adds the line to the temporary file list of line that you want to keep
                        }
                    }
                }
            }
            File.WriteAllLines(tempFile, linesToKeep); //writes all the lines you want to keep back into a file
            File.Delete(path()); //deletes the old file
            File.Move(tempFile, path()); //moves temporary file to old location of the old file.

A: On second notice, check out this code:
private void btnLoad_Click(object sender, EventArgs e)
{
    OpenFileDialog ofd = new OpenFileDialog();
    if (ofd.ShowDialog() == DialogResult.OK)
    {
        richTextBox1.LoadFile(ofd.FileName);
    }
}

private void btnSave_Click(object sender, EventArgs e)
{
    OpenFileDialog ofd = new OpenFileDialog();
    if (ofd.ShowDialog() == DialogResult.OK)
    {
        richTextBox1.SaveFile(ofd.FileName);
    }
}

I think this is more in line with what you had in mind?


text:
Q: verb "arguments" to open graph actions I'm trying to define facebook graph actions for my application.
Users can give their opinion about animals, an animal can be either good or bad. I want to publish their votes using timeline and the Open Graph API:

John thinks elephants are good.

or

John thinks snakes are bad.

It it possible to achieve this? can I have a think verb with good/bad as arguments? or can I have two verbs: "to think object is good", "to think object is bad" and somehow configure the app to display the text as I want?

A: This isn't possible, as you have three variables in your action. The object would be the animal and the action would be 'thinks' but there is no room to add the 'good' and 'bad'. Facebook will only let you do something in the form User is {action} {object}, not User is {action} {object} is {good|bad}.

A: You can add custom properties to actions, see [1] and [2].
While you can easily access these properties when building aggregations, I'm not sure if you can get them to display in the simple action message published … (Maybe via translation settings of your app? But I doubt it.)
Maybe you could use the message parameter, and pre-fill it with "I think elephants are good/bad" when publishing the action? (Then you might have to change your action verb to something like "rating" an animal or else for it to make sense.)
[1] https://developers.facebook.com/docs/opengraph/define-actions/#custom
[2] https://developers.facebook.com/docs/opengraph/actions/#instance-property


text:
Q: Where are Kafka consumer properties set in an SCDF context? I am trying to work myself around a CommitFailedException by tinkering with max.poll.interval.ms, session.timeout.ms and heartbeat.interval.ms. I have tried changing these values in the application.properties file, but when the app is deployed in an SCDF context, the values I set here are overridden somewhere else. When running the app locally as a stand-alone Spring Boot app, the property values are set to the same as specified in the application.properties file.
The dataflow-kafka container is based on the image confluentinc/cp-kafka:5.2.1
Where do I tweak Kafka consumer properties in an SCDF context?

A: The max.poll.interval.ms, session.timeout.ms and heartbeat.interval.ms appear to be Kafka's consumer configuration.
If you intend to use and override them in your Spring Cloud Stream consumer, you'd have to spring.cloud.stream.kafka.bindings.input.consumer.configuration.foo=bar notation.
In this example, where foo could be max.poll.interval.ms and bar would be its value: 300000. For more details, see ref. guide.
Once when you have all the desired consumer properties defined in this pattern, you can test the application locally via java -jar. You can then assure when deployed from SCDF; it would run the same way, as well. Nothing should get overridden.


text:
Q: Open/Close multiple div with external content loaded I'm trying to create a portfolio that loads external content when clicking on "read more".
Loading external content works fine and the div animates as it should. I even got the same div to close and open when I click on another "read more" link.
My problem is that when I click on the same "read more" link the div don't close, it just animates and load the external content again.
I hope this makes sense...
My HTML is as follows:

Test title: Webdesign

Filter:

Webdesign

                        Read more →

Test title: Advertisement

Filter:

Advertisement

                        Read more →

And my jQuery is:
$(document).ready(function(){
$(".more").click(function(){
    var href = $(this).attr('href');

    if ($('#portfolio-content').is(':visible')) {
        $('#portfolio-content').css({display:'block'}).animate({height:'1px'}).empty();
    }

    $('#portfolio-content').css({display:'block'}).animate({height:'200px'},function(){
        $('#portfolio-content').html('');
        $("#portfolio-content").load(href);
    });

    return false;
});

$(".more").next().click(function(){
    $("#portfolio-content").fadeOut('normal');
});
});

A: Seems like you're doing more than you need to when #portfolio-content is visible. Maybe try this:
http://jsfiddle.net/isherwood/f8Dfb/3
#portfolio-content {
    display: none;
}

if ($('#portfolio-content').is(':visible')) {
    $('#portfolio-content').slideUp();
}

$('#portfolio-content').css({
    display: 'block', height: '0'
}).animate({
    height: '200px'
}, function () {
...


text:
Q: Continuous seminorms If I have a locally convex vector space $S$ equipped with a countable family $(p_i)_{i \in I}$ of seminorms, is it correct that the topology remains unchanged if I add an extra seminorm $q$ satisfying : $\exists J \subset I$ ($J$ finite) $\exists c>0 | \forall x \in S$ $ q(x) \leq \Sigma_J p_i(x)$ ?

A: We start with the assumption that $S$ is equipped exactly with the topology induced by $(p_i)_{i\in I}$ - the smalled topology on $S$ which makes these seminorms continuous.
Since $q$ is a seminorm, it is continuous if and only if it is continuous at zero.
Take a sequence $x_n\to 0$. Then for all $j$, since $p_j$ are continuous, we have $p_j(x_n)\to p_j(0) = 0$ as $n\to \infty$.
Then,
$$
0\leq q(x_n) \leq \sum_{j\in J}p_j(x_n),
$$
and using the sandwich theorem, we see that $q(x_n) \to 0 = q(0)$.
Consequently, adding $q$ in the original family of seminorms will not alter the topology.


text:
Q: Is there a way to cd back multiple times in bash? I often use cd - to go back to where I was. How can I do this multiple times in bash? Or would zsh or some other tool support this?

A: You can use the pushd builtin in bash to push new working directories onto the directory stack. Use popd to pop directories of the stack in order to return to the previous working directories.

A: In zsh, there's an auto_pushd option. This option makes cd behave like pushd. Then you can just use popd to go back to previous directories.
~ $ setopt auto_pushd
~ $ cd /
/ $ cd /var
/var $ cd /usr
/usr $ dirs
/usr /var / ~
/usr $ popd
/var $ popd
/ $ popd
~ $

In Bash, you can alias cd to pushd.
alias cd=pushd

The one downside of this is that you will lose cd's three flags. From the cd help entry:

-L      force symbolic links to be followed
  -P      use the physical directory structure without following symbolic links
  -e      if the -P option is supplied, and the current working directory
              cannot be determined successfully, exit with a non-zero status

If you ever have to use the actual cd builtin instead of the alias, you can use one of these:

*

*'cd' - Quoting the command makes the shell not resolve the alias and use the
normal cd.

*\cd - Backslashes quote characters. If you quote one character of a word, the
shell treats the whole word as quoted.

*builtin cd - This directly tells the shell to use the builtin instead of the alias.

A: Here's a quick and dirty way to conveniently bookmark directories and jump back to them:
$ a() { alias $1="cd $PWD"; }

Go somewhere and type:
$ a 1

You now have a command called 1 which does cd the directory that is current at this time. Later just type:
$ 1

And presto, back to that directory. I find this very useful.

A: bash
I found a script, available here, that solved this issue for me. With this you can type cd -- to see the last 10 directories that you've used. It'll look something like this:
0  ~/Documents/onedir
1  ~/Music/anotherdir
2  ~/Music/thirddir
3  ~/etc/etc

To go to ~/Music/thirddir just type cd -2
zsh
oh-my-zsh provides some really nice functionality for this (at least I think it's oh-my-zsh that sets this).
Basically, d is aliased to dirs -v | head -10
dirs is a zsh built-in command and shows the last directories you've been to.
Also, 1 is aliased to cd -1 and so on for all numbers to 9.
In practice, it works like this:
$ pwd
/home/me/Documents/gems/java_regex/lib

$ d
0       ~/Documents/gems/java_regex/lib
1       ~/Documents/gems/java_regex
2       ~/Documents/gems
3       ~/Documents
4       ~

$ 2
~/Documents/gems

$ pwd
/home/me/Documents/gems

A: I'm using simple function found on commandlinefu long time ago
 up() { local x='';for i in $(seq ${1:-1});do x="$x../"; done;cd $x; }

(added in my osx .profile works like a charm)

A: Yes. We can make your cd command more powerful. Bash profile allows us to customize it the way we want.
Rather than doing multiple cd to navigate up the directory, we can use alias
For example :
alias ..5="cd ../../../../.."

This will take you 5 directory up the level.


text:
Q: django shell xlrd.open_workbook() Errno 13 I have a set of data that I import from an excel spreadsheet. It is a requirement.
It works fine on other PCs but on this one I get the error message:
File "<console>", line 1, in <module>
  File "C:\Python38\lib\site-packages\xlrd\__init__.py", line 111, in open_workbook
    with open(filename, "rb") as f:
PermissionError: [Errno 13] Permission denied:

I am opening the file the usual way:
import xlrd
xl_workbook = xlrd.open_workbook('spreadsheet' + '.xlsx')

I tried everything

*

*opening another file (no other excel file can be opened)

*reinstalling python (and pip installing the django and xlrd modules)

*restarting the PC

I can assure the file is not open and from the python shell it works fine.
But within the manage.py shell it fails. Can anyone help me?


text:
Q: Typescript: how to use an indexed access type for children of an optional property? Let's say I have a type like:
type Person = {
  firstName: string;
  lastName: string;
  contact: {
    type: string;
    value: string;
  }[];
};

If I want the type of an element of the contact array, I can use an indexed access type like:
type Contact = User['contact'][number];

// same as type Contact = { type: string; value: string };

In essence, "the type at a numeric index of the contacts array", and would also work for a nested object.
However, if that is an optional parameter such as:
type Person = {
  firstName: string;
  lastName: string;
  contact?: {
    type: string;
    value: string;
  }[];
};

This (validly) reports an error of:
Type '{ type: string; value: string; }[] | undefined' has no matching index signature for type 'number'.ts(2537)

How can I "null check" within the type alias to get a nested type?

A: Update
NonNullable<T> will remove undefined and null from its type parameter.
type Contact = NonNullable<User['contact']> // almost the same as the next type, but also excludes `null` from the union.
type Contact = Exclude<User['contact'], undefined>[number];

https://www.typescriptlang.org/docs/handbook/utility-types.html#nonnullabletype
Older answer
You can Exclude types when you need to drill down more.
type Contact = Exclude<User['contact'], undefined>[number];

The docs aren't particularly stable around the subject, but https://www.typescriptlang.org/docs/handbook/utility-types.html is the current link.

A: Wouldn't be easier and more readable to just type contact separately?
type Person = {
  firstName: string;
  lastName: string;
  contact?: PersonContact[];
};

type PersonContact = {
  type: string;
  value: string;
};


text:
Q: iOS - How to set a refresh rate on ads in LeadBolt sdk When my app loads, it shows the same banner ad for the entire session. Is there a method for cycling in new ads, like refreshing the current banner to show the next ad? This is killing my impressions and conversions. As one ad shown the entire session isn't really going to appeal too much to the user. I know that from reading over the documentation that loadAd() has something to do with it but I cant seem to figure out how to actually implement that time interval. Here is my code for whats going on now with leadbolt in the view Im showing the banner in. This is all part of - (void)viewDidLoad, I just left out all the other stuff not relevant to the ads.
    overlay = [[UIWebView alloc] initWithFrame:CGRectZero];
    titleBar = [[UIToolbar alloc] initWithFrame:CGRectZero];
    footerBar = [[UIToolbar alloc] initWithFrame:CGRectZero];
    clickTitleBar = [[UIToolbar alloc] initWithFrame:CGRectZero];
    clickFooterBar = [[UIToolbar alloc] initWithFrame:CGRectZero];
    mask = [[UIView alloc] initWithFrame:CGRectZero];

    [self.view insertSubview:mask atIndex:2];
    [self.view insertSubview:clickTitleBar atIndex:3];
    [self.view insertSubview:clickFooterBar atIndex:4];
    [self.view insertSubview:titleBar atIndex:5];
    [self.view insertSubview:footerBar atIndex:6];
    [self.view insertSubview:overlay atIndex:7];
    overlay.delegate = overlayController;

    //initialize the overlayController
    overlayController  = [[LeadboltOverlay alloc] init];

    [overlayController setSectionid:@"MY AD #"];
    [overlayController setAdWebView:self.overlay];
    [overlayController setCloseBar:self.titleBar];
    [overlayController setFooterBar:self.footerBar];
    [overlayController setClickCloseBar:self.clickTitleBar];
    [overlayController setClickFooterBar:self.clickFooterBar];
    [overlayController setLocationControl:@"0"];
    [overlayController setMask:self.mask];

    ///////This part here?///////
    [overlayController loadAd];
    /////////////////////////////

    overlay.delegate = overlayController;

    self.stsTimer = [NSTimer timerWithTimeInterval:3.0 target:self selector:@selector(checkCompleted) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:self.stsTimer forMode:NSDefaultRunLoopMode];

A: To refresh ads (perhaps every minute or every time there is an event in the UI) you could just set up a HTML banner in a UIWebView and call myWebview reload] each time you want a new ad to be shown.
It's not recommended to [overlayController loadAd] repeatedly as it can cause memory management issues.


text:
Q: C# Encrypt/Decrypt from Java AES/CBC/PKCS5Padding I'm facing an issue trying to Decrypt a string which has been encrypted in Java with the following properties (Java code)
public static Builder getDefaultBuilder(String key, String salt, byte[] iv) {
        return new Builder()
                .setIv(iv)
                .setKey(key)
                .setSalt(salt)
                .setKeyLength(128)
                .setKeyAlgorithm("AES")
                .setCharsetName("UTF8")
                .setIterationCount(1)
                .setDigestAlgorithm("SHA1")
                .setBase64Mode(Base64.DEFAULT)
                .setAlgorithm("AES/CBC/PKCS5Padding")
                .setSecureRandomAlgorithm("SHA1PRNG")
                .setSecretKeyType("PBKDF2WithHmacSHA1");
    }

This is my code so far (C#)
public string DecryptText(string encryptedString)
    {
        using (myRijndael = new RijndaelManaged())
        {
            myRijndael.Key = Convert.FromBase64String(encryptionKey);
            myRijndael.IV = new byte[16];
            myRijndael.Mode = CipherMode.CBC;
            myRijndael.Padding = PaddingMode.PKCS7;

            Byte[] ourEnc = Convert.FromBase64String(encryptedString);
            string ourDec = DecryptStringFromBytes(ourEnc, myRijndael.Key, myRijndael.IV);

            return ourDec;
        }
    }

protected string DecryptStringFromBytes(byte[] cipherText, byte[] Key, byte[] IV)
    {
        // Check arguments.
        if (cipherText == null || cipherText.Length <= 0)
            throw new ArgumentNullException("cipherText");
        if (Key == null || Key.Length <= 0)
            throw new ArgumentNullException("Key");
        if (IV == null || IV.Length <= 0)
            throw new ArgumentNullException("Key");

        // Declare the string used to hold
        // the decrypted text.
        string plaintext = null;

        // Create an RijndaelManaged object
        // with the specified key and IV.
        using (RijndaelManaged rijAlg = new RijndaelManaged())
        {
            rijAlg.Key = Key;
            rijAlg.IV = IV;

            // Create a decrytor to perform the stream transform.
            ICryptoTransform decryptor = rijAlg.CreateDecryptor(rijAlg.Key, rijAlg.IV);

            // Create the streams used for decryption.
            using (MemoryStream msDecrypt = new MemoryStream(cipherText))
            {
                using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
                {
                    using (StreamReader srDecrypt = new StreamReader(csDecrypt))
                    {

                        // Read the decrypted bytes from the decrypting stream
                        // and place them in a string.
                        plaintext = srDecrypt.ReadToEnd();
                    }
                }
            }

        }

        return plaintext;

    }

But when I try to decrypt I get the following  exception "System.Security.Cryptography.CryptographicException: 'Specified key is not a valid size for this algorithm.'
".
The origin of the Java code resides here
https://github.com/simbiose/Encryption/blob/master/Encryption/main/se/simbio/encryption/Encryption.java
This is the Java code when encrypting
public String encrypt(String data) throws UnsupportedEncodingException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidAlgorithmParameterException, InvalidKeyException, InvalidKeySpecException, BadPaddingException, IllegalBlockSizeException {
    if (data == null) return null;
    SecretKey secretKey = getSecretKey(hashTheKey(mBuilder.getKey()));
    byte[] dataBytes = data.getBytes(mBuilder.getCharsetName());
    Cipher cipher = Cipher.getInstance(mBuilder.getAlgorithm());
    cipher.init(Cipher.ENCRYPT_MODE, secretKey, mBuilder.getIvParameterSpec(), mBuilder.getSecureRandom());
    return Base64.encodeToString(cipher.doFinal(dataBytes), mBuilder.getBase64Mode());
}

private SecretKey getSecretKey(char[] key) throws NoSuchAlgorithmException, UnsupportedEncodingException, InvalidKeySpecException {
    SecretKeyFactory factory = SecretKeyFactory.getInstance(mBuilder.getSecretKeyType());
    KeySpec spec = new PBEKeySpec(key, mBuilder.getSalt().getBytes(mBuilder.getCharsetName()), mBuilder.getIterationCount(), mBuilder.getKeyLength());
    SecretKey tmp = factory.generateSecret(spec);
    return new SecretKeySpec(tmp.getEncoded(), mBuilder.getKeyAlgorithm());
}

private char[] hashTheKey(String key) throws UnsupportedEncodingException, NoSuchAlgorithmException {
    MessageDigest messageDigest = MessageDigest.getInstance(mBuilder.getDigestAlgorithm());
    messageDigest.update(key.getBytes(mBuilder.getCharsetName()));
    return Base64.encodeToString(messageDigest.digest(), Base64.NO_PADDING).toCharArray();
}

I've been struggling with this for two day since I haven't really worked a lot with encryption, so any help would be greatly appreciated.
Thanks!
Update:
Whole class
public sealed class MyCryptoClass
{
    protected RijndaelManaged myRijndael;

    private static string encryptionKey = "random";

    // Singleton pattern used here with ensured thread safety
    protected static readonly MyCryptoClass _instance = new MyCryptoClass();
    public static MyCryptoClass Instance
    {
        get { return _instance; }
    }

    public MyCryptoClass()
    {

    }

    public string DecryptText(string encryptedString)
    {
        using (myRijndael = new RijndaelManaged())
        {
            myRijndael.Key = Convert.FromBase64String(encryptionKey);
            myRijndael.IV = new byte[16];
            myRijndael.Mode = CipherMode.CBC;
            myRijndael.Padding = PaddingMode.PKCS7;

            Byte[] ourEnc = Convert.FromBase64String(encryptedString);
            string ourDec = DecryptStringFromBytes(ourEnc, myRijndael.Key, myRijndael.IV);

            return ourDec;
        }
    }

    public string EncryptText(string plainText)
    {
        using (myRijndael = new RijndaelManaged())
        {

            myRijndael.Key = HexStringToByte(encryptionKey);
            myRijndael.IV = HexStringToByte(initialisationVector);
            myRijndael.Mode = CipherMode.CBC;
            myRijndael.Padding = PaddingMode.PKCS7;

            byte[] encrypted = EncryptStringToBytes(plainText, myRijndael.Key, myRijndael.IV);
            string encString = Convert.ToBase64String(encrypted);

            return encString;
        }
    }

    protected byte[] EncryptStringToBytes(string plainText, byte[] Key, byte[] IV)
    {
        // Check arguments.
        if (plainText == null || plainText.Length <= 0)
            throw new ArgumentNullException("plainText");
        if (Key == null || Key.Length <= 0)
            throw new ArgumentNullException("Key");
        if (IV == null || IV.Length <= 0)
            throw new ArgumentNullException("Key");
        byte[] encrypted;
        // Create an RijndaelManaged object
        // with the specified key and IV.
        using (RijndaelManaged rijAlg = new RijndaelManaged())
        {
            rijAlg.Key = Key;
            rijAlg.IV = IV;

            // Create a decrytor to perform the stream transform.
            ICryptoTransform encryptor = rijAlg.CreateEncryptor(rijAlg.Key, rijAlg.IV);

            // Create the streams used for encryption.
            using (MemoryStream msEncrypt = new MemoryStream())
            {
                using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
                {
                    using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
                    {

                        //Write all data to the stream.
                        swEncrypt.Write(plainText);
                    }
                    encrypted = msEncrypt.ToArray();
                }
            }
        }

        // Return the encrypted bytes from the memory stream.
        return encrypted;

    }

    protected string DecryptStringFromBytes(byte[] cipherText, byte[] Key, byte[] IV)
    {
        // Check arguments.
        if (cipherText == null || cipherText.Length <= 0)
            throw new ArgumentNullException("cipherText");
        if (Key == null || Key.Length <= 0)
            throw new ArgumentNullException("Key");
        if (IV == null || IV.Length <= 0)
            throw new ArgumentNullException("Key");

        // Declare the string used to hold
        // the decrypted text.
        string plaintext = null;

        // Create an RijndaelManaged object
        // with the specified key and IV.
        using (RijndaelManaged rijAlg = new RijndaelManaged())
        {
            rijAlg.Key = Key;
            rijAlg.IV = IV;

            // Create a decrytor to perform the stream transform.
            ICryptoTransform decryptor = rijAlg.CreateDecryptor(rijAlg.Key, rijAlg.IV);

            // Create the streams used for decryption.
            using (MemoryStream msDecrypt = new MemoryStream(cipherText))
            {
                using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
                {
                    using (StreamReader srDecrypt = new StreamReader(csDecrypt))
                    {

                        // Read the decrypted bytes from the decrypting stream
                        // and place them in a string.
                        plaintext = srDecrypt.ReadToEnd();
                    }
                }
            }

        }

        return plaintext;

    }

    public static void GenerateKeyAndIV()
    {
        // This code is only here for an example
        RijndaelManaged myRijndaelManaged = new RijndaelManaged();
        myRijndaelManaged.Mode = CipherMode.CBC;
        myRijndaelManaged.Padding = PaddingMode.PKCS7;

        myRijndaelManaged.GenerateIV();
        myRijndaelManaged.GenerateKey();
        string newKey = ByteArrayToHexString(myRijndaelManaged.Key);
        string newinitVector = ByteArrayToHexString(myRijndaelManaged.IV);
    }

    protected static byte[] HexStringToByte(string hexString)
    {
        try
        {
            int bytesCount = (hexString.Length) / 2;
            byte[] bytes = new byte[bytesCount];
            for (int x = 0; x < bytesCount; ++x)
            {
                bytes[x] = Convert.ToByte(hexString.Substring(x * 2, 2), 16);
            }
            return bytes;
        }
        catch
        {
            throw;
        }
    }

    public static string ByteArrayToHexString(byte[] ba)
    {
        StringBuilder hex = new StringBuilder(ba.Length * 2);
        foreach (byte b in ba)
            hex.AppendFormat("{0:x2}", b);
        return hex.ToString();
    }
}

A: *

*Since your MyCryptoClass.encryptionKey corresponds to your Encryption.Builder.mKey you have to generate the secret key on the C#-side i.e. you have to implement on the C# side a counterpart for each Java-method involved in this process. These Java-methods are getSecretKey(char[] key), hashTheKey(String key) and also third.part.android.util.Base64.encodeToString(byte[] input, int flags).

*Possible C#-Counterpart of the Java-method getSecretKey(char[] key):
private static byte[] GetSecretKey()
{
     string hashedKey = GetHashedKey();
     byte[] saltBytes = Encoding.UTF8.GetBytes(salt);                                                // builder.mCharsetName = "UTF8";
     int iterations = 1;                                                                             // builder.mIterationCount = 1
     byte[] secretKey = null;
     using (Rfc2898DeriveBytes rfc2898 = new Rfc2898DeriveBytes(hashedKey, saltBytes, iterations))   // builder.mSecretKeyType = "PBKDF2WithHmacSHA1";
     {
          secretKey = rfc2898.GetBytes(16);                                                          // builder.mKeyLength = 128;
          //Console.WriteLine("Key: " + ByteArrayToHexString(secretKey));
     }
     return secretKey;
 }

This method derives a secret key using PBKDF2WithHmacSHA1 with a key, salt, iterationcount and key length as input. The key (more precisely password) used here is a base64-encoded SHA1-hash from MyCryptoClass.encryptionKey provided by GetHashedKey() (see below).

*Possible C#-Counterpart of the Java-method hashTheKey(String key):
private static string GetHashedKey()
{
     string hashBase64 = String.Empty;
     using (SHA1Managed sha1 = new SHA1Managed())                                  // builder.mDigestAlgorithm = "SHA1";
     {
          byte[] hash = sha1.ComputeHash(Encoding.UTF8.GetBytes(encryptionKey));   // builder.mCharsetName = "UTF8";
          hashBase64 = Base64ThirdPartAndroid(hash, true);
          //Console.WriteLine("Hash (base64): " + hashBase64);
     }
     return hashBase64;
 }

This method derives a SHA1-hash from MyCryptoClass.encryptionKey and base64-encodes that hash. For the base64-encoding the method Base64ThirdPartAndroid(byte[] arr, bool withoutPadding) (see below) is used.

*Possible C#-Counterpart of the Java-method third.part.android.util.Base64.encodeToString(byte[] input, int flags) ( https://github.com/simbiose/Encryption/blob/master/Encryption/main/third/part/android/util/Base64.java):
private static string Base64ThirdPartAndroid(byte[] arr, bool withoutPadding)
{
     string base64String = System.Convert.ToBase64String(arr);
     if (withoutPadding) base64String = base64String.TrimEnd('='); // Remove trailing "="-characters
     base64String += "\n";                                         // Append LF (10)
     //Console.WriteLine("Array as base64 encoded string: " + base64String);
     return base64String;
}

In the Java code third.part.android.util.Base64.encodeToString(byte[] input, int flags) is used with flags = Base64.NO_PADDING which removes the "="-character at the end of the base64-encoded string. Additionally a line feed (LF, \n, ASCII value: 10) is appended. If a Base64-Encoding is used which doesn't remove the "="-characters or without a terminating line feed, the decryption will fail since the hash is the base of the later generated secret key which have to match on the encryption and on the decryption side. To the best of my knowledge there is no Base64-encoding on the C# side with the necessary characteristics. However, if there is such an encoding you can use it of course.

*Add all three C#-counterparts to your MyCryptoClass class.

*Additionally (to the static field encryptionKey) add the static fields initialisationVector, salt and secretKey to your MyCryptoClass-class and assign the following values for testing purposes:
private static string encryptionKey = "A7zb534OPq59gU7q";
private static string salt = "JV5k9GoH";
private static byte[] initialisationVector = Encoding.UTF8.GetBytes("l4iG63jN9Dcg6537");
private static byte[] secretKey = GetSecretKey();

The type of the parameters corresponds to the type in the Java code (encryptionKey and salt are strings, the initialisationVector is a byte-array). The secret key generated by GetSecretKey() is stored in the byte-array secretKey.

*In your C# DecryptText- and EncryptText-method set myRijndael.Key and myRijndael.IV to
myRijndael.Key = secretKey;
myRijndael.IV = initialisationVector;

*Test the modifications as follows:

*

*With your Java encrypt-method encrypt the following plain text:
Test: The quick brown fox jumps over the lazy dog...

using the key/salt/iv above with
mBuilder = Builder.getDefaultBuilder("A7zb534OPq59gU7q","JV5k9GoH","l4iG63jN9Dcg6537".getBytes("UTF-8"));

*The encrypted text is:
mL4ajZtdRgD8CtGSfJGkT24Ebw4SrGUGKQI6bvBw1ziCO/J7SeLiyIw41zumTHMMD9GOYK+kR79CVcpoaHT9TQ==

*Decrypting this using the C# DecryptText-method gives again the plain text. Below are two test cases:
static void Main(string[] args)
{
     // Test 1: Encrypted text from C#
     MyCryptoClass mcc = MyCryptoClass.Instance;
     string encryptedText = mcc.EncryptText("This is a plain text which needs to be encrypted...");
     Console.WriteLine("Encrypted text (base64): " + encryptedText);
     string decryptedText = mcc.DecryptText(encryptedText);
     Console.WriteLine("Decrypted text: " + decryptedText);

     // Test 2: Encrypted text from Java
     string javaEncryptedText = "mL4ajZtdRgD8CtGSfJGkT24Ebw4SrGUGKQI6bvBw1ziCO/J7SeLiyIw41zumTHMMD9GOYK+kR79CVcpoaHT9TQ==";
     Console.WriteLine("Encrypted text from Java (base64): " + javaEncryptedText);
     string javaDecryptedText = mcc.DecryptText(javaEncryptedText);
     Console.WriteLine("Decrypted text from Java: " + javaDecryptedText);
}

A: Following is Full C# class which i were able to work as it is like java class
At the moment i have only checked encryption part
 public sealed class MyCryptoClass
    {
        protected AesManaged myRijndael;

        private static string encryptionKey = "MyKey";
        private static string salt = "Mysalt";
        private static byte[] initialisationVector = new byte[16];
        //private static byte[] initialisationVector = Encoding.UTF8.GetBytes("l4iG63jN9Dcg6537");
        private static byte[] secretKey = GetSecretKey();

        // Singleton pattern used here with ensured thread safety
        protected static readonly MyCryptoClass _instance = new MyCryptoClass();
        public static MyCryptoClass Instance
        {
            get { return _instance; }
        }

        public MyCryptoClass()
        {

        }
        public string DecryptText(string encryptedString)
        {
            using (myRijndael = new AesManaged())
            {
                myRijndael.Key = Convert.FromBase64String(encryptionKey);
                myRijndael.IV = new byte[16];
                myRijndael.Mode = CipherMode.CBC;
                myRijndael.Padding = PaddingMode.PKCS7;

                Byte[] ourEnc = Convert.FromBase64String(encryptedString);
                string ourDec = DecryptStringFromBytes(ourEnc, myRijndael.Key, myRijndael.IV);

                return ourDec;
            }
        }
        public string EncryptText(string plainText)
        {
            using (myRijndael = new AesManaged())
            {

                myRijndael.Key = secretKey;
                myRijndael.IV = initialisationVector;
                myRijndael.Mode = CipherMode.CBC;
                myRijndael.Padding = PaddingMode.PKCS7;

                byte[] encrypted = EncryptStringToBytes(plainText, myRijndael.Key, myRijndael.IV);
                string encString = Convert.ToBase64String(encrypted);

                return encString;
            }
        }
        protected byte[] EncryptStringToBytes(string plainText, byte[] Key, byte[] IV)
        {
            // Check arguments.
            if (plainText == null || plainText.Length <= 0)
                throw new ArgumentNullException("plainText");
            if (Key == null || Key.Length <= 0)
                throw new ArgumentNullException("Key");
            if (IV == null || IV.Length <= 0)
                throw new ArgumentNullException("Key");
            byte[] encrypted;
            // Create an RijndaelManaged object
            // with the specified key and IV.
            using (RijndaelManaged rijAlg = new RijndaelManaged())
            {
                rijAlg.Key = Key;
                rijAlg.IV = IV;

                // Create a decrytor to perform the stream transform.
                ICryptoTransform encryptor = rijAlg.CreateEncryptor(rijAlg.Key, rijAlg.IV);

                // Create the streams used for encryption.
                using (MemoryStream msEncrypt = new MemoryStream())
                {
                    using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
                    {
                        using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
                        {

                            //Write all data to the stream.
                            swEncrypt.Write(plainText);
                        }
                        encrypted = msEncrypt.ToArray();
                    }
                }
            }
            // Return the encrypted bytes from the memory stream.
            return encrypted;

        }
        protected string DecryptStringFromBytes(byte[] cipherText, byte[] Key, byte[] IV)
        {
            // Check arguments.
            if (cipherText == null || cipherText.Length <= 0)
                throw new ArgumentNullException("cipherText");
            if (Key == null || Key.Length <= 0)
                throw new ArgumentNullException("Key");
            if (IV == null || IV.Length <= 0)
                throw new ArgumentNullException("Key");

            // Declare the string used to hold
            // the decrypted text.
            string plaintext = null;

            // Create an RijndaelManaged object
            // with the specified key and IV.
            using (RijndaelManaged rijAlg = new RijndaelManaged())
            {
                rijAlg.Key = Key;
                rijAlg.IV = IV;

                // Create a decrytor to perform the stream transform.
                ICryptoTransform decryptor = rijAlg.CreateDecryptor(rijAlg.Key, rijAlg.IV);

                // Create the streams used for decryption.
                using (MemoryStream msDecrypt = new MemoryStream(cipherText))
                {
                    using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
                    {
                        using (StreamReader srDecrypt = new StreamReader(csDecrypt))
                        {

                            // Read the decrypted bytes from the decrypting stream
                            // and place them in a string.
                            plaintext = srDecrypt.ReadToEnd();
                        }
                    }
                }
            }
            return plaintext;
        }

        public static void GenerateKeyAndIV()
        {
            // This code is only here for an example
            AesManaged myRijndaelManaged = new AesManaged();
            myRijndaelManaged.Mode = CipherMode.CBC;
            myRijndaelManaged.Padding = PaddingMode.PKCS7;

            myRijndaelManaged.GenerateIV();
            myRijndaelManaged.GenerateKey();
            string newKey = ByteArrayToHexString(myRijndaelManaged.Key);
            string newinitVector = ByteArrayToHexString(myRijndaelManaged.IV);
        }

        protected static byte[] HexStringToByte(string hexString)
        {
            try
            {
                int bytesCount = (hexString.Length) / 2;
                byte[] bytes = new byte[bytesCount];
                for (int x = 0; x < bytesCount; ++x)
                {
                    bytes[x] = Convert.ToByte(hexString.Substring(x * 2, 2), 16);
                }
                return bytes;
            }
            catch
            {
                throw;
            }
        }

        public static string ByteArrayToHexString(byte[] ba)
        {
            StringBuilder hex = new StringBuilder(ba.Length * 2);
            foreach (byte b in ba)
                hex.AppendFormat("{0:x2}", b);
            return hex.ToString();
        }

        private static byte[] GetSecretKey()
        {
            string hashedKey = GetHashedKey();
            byte[] saltBytes = Encoding.UTF8.GetBytes(salt); // builder.mCharsetName = "UTF8";
            int iterations = 1; // builder.mIterationCount = 1
            byte[] secretKey = null;
            using (Rfc2898DeriveBytes rfc2898 = new Rfc2898DeriveBytes(hashedKey, saltBytes, iterations)) // builder.mSecretKeyType = "PBKDF2WithHmacSHA1";
            {
                secretKey = rfc2898.GetBytes(16); // builder.mKeyLength = 128;
                //Console.WriteLine("Key: " + ByteArrayToHexString(secretKey));
            }
            return secretKey;
        }

        private static string GetHashedKey()
        {
            string hashBase64 = String.Empty;
            using (SHA1Managed sha1 = new SHA1Managed()) // builder.mDigestAlgorithm = "SHA1";
            {
                byte[] hash = sha1.ComputeHash(Encoding.UTF8.GetBytes(encryptionKey)); // builder.mCharsetName = "UTF8";

                hashBase64 = Base64ThirdPartAndroid(hash, true);
                //hashBase64 = Base64ThirdPartAndroid(hash, true);
                //Console.WriteLine("Hash (base64): " + hashBase64);
            }
            return hashBase64;
        }

        private static string Base64ThirdPartAndroid(byte[] arr, bool withoutPadding)
        {
            string base64String = System.Convert.ToBase64String(arr);
            if (withoutPadding) base64String = base64String.TrimEnd('='); // Remove trailing "="-characters
            base64String += "\n"; // Append LF (10)
            //Console.WriteLine("Array as base64 encoded string: " + base64String);
            return base64String;
        }
    }

A: this method is 100% working for encryption
public static string AESDecrypt(string text, string secretKey)
        {
            try
            {
                SHA1 sha = new SHA1CryptoServiceProvider();
                RijndaelManaged aes = new RijndaelManaged();

                byte[] finalKey = new byte[16]; // Used to generate finalKey
                byte[] byteDataToDecrypt = Convert.FromBase64String(text); // Converting Base64 data to Byte Array
                byte[] byteSecretKey = Encoding.UTF8.GetBytes(secretKey); // Converting secret key in byte array
                byte[] hashSecretKey = sha.ComputeHash(byteSecretKey); // geneating hash in byte array of secret key

                Array.Copy(hashSecretKey, finalKey, 16); // copying fist 16 bytes from hashed secret key to finaly key which to use in algo

                aes.KeySize = 128;
                aes.Padding = PaddingMode.PKCS7;
                aes.Mode = CipherMode.ECB;
                aes.Key = finalKey;

                using (ICryptoTransform decrypt = aes.CreateDecryptor(aes.Key, null)) //Passing IV as NULL because IV is not present in the Java Code
                {
                    byte[] dest = decrypt.TransformFinalBlock(byteDataToDecrypt, 0, byteDataToDecrypt.Length);
                    decrypt.Dispose();
                    return Encoding.UTF8.GetString(dest);
                }
            }
            catch (Exception ex)
            {

                throw ex;
            }

        }


text:
Q: Listing class APIs with parameters and return types I want to list all the APIs of the given jar ( for which I don't have javadoc) in following fashion any help on that?
PackageName, ClassName, API Name, ParamName:type;ParameterName:type,ReturnType

A: Interesting problem. Probably a number of tools to do something similar, though not exactly what you want. Certainly there would be an easy implementation with ASM. As it is, I whipped up one using reflection:
public class C {
    public static void main(String[] args) throws java.io.IOException {
        java.util.jar.JarFile jar = new java.util.jar.JarFile(args[0]);
        java.util.Enumeration<java.util.jar.JarEntry> jarEntries = jar.entries();
        while (jarEntries.hasMoreElements()) {
            java.util.jar.JarEntry jarEntry = jarEntries.nextElement();
            String jarEntryName = jarEntry.getName();
            if (!jarEntryName.endsWith(".class")) {
                continue;
            }
            int jarEntryNameSuffixIndex = jarEntryName.length() - 6;
            String binaryName = jarEntryName.substring(0, jarEntryNameSuffixIndex).replaceAll("/", "\\.");
            Class<?> type = null;
            while (type == null) {
                try {
                    type = ClassLoader.getSystemClassLoader().loadClass(binaryName);
                } catch (ClassNotFoundException e) {
                    int binaryNameQualifiedIndex = binaryName.indexOf(".");
                    if (binaryNameQualifiedIndex == -1) {
                        throw new RuntimeException("couldn't load class for " + jarEntryName);
                    } else {
                        binaryName = binaryName.substring(binaryNameQualifiedIndex + 1);
                    }
                }
            }
            int typeModifiers = type.getModifiers();
            if (!(java.lang.reflect.Modifier.isPublic(typeModifiers) || java.lang.reflect.Modifier.isProtected(typeModi$
                continue;
            }
            String packageName = (type.getPackage() == null) ? "" : type.getPackage().getName();
            String typeName = type.getCanonicalName();
            for (java.lang.reflect.Method method : type.getDeclaredMethods()) {
                if (method.isSynthetic() || method.isBridge()) {
                    continue;
                }
                int methodModifiers = method.getModifiers();
                if (!(java.lang.reflect.Modifier.isPublic(methodModifiers) || java.lang.reflect.Modifier.isProtected(me$
                    continue;
                }
                String methodName = method.getName();
                System.out.print(packageName + ", " + typeName + ", " + methodName + ", ");
                for (Class<?> parameterType : method.getParameterTypes()) {
                    String parameterTypeName = parameterType.getCanonicalName();
                    System.out.print(":" + parameterTypeName + ", ");
                }
                Class<?> returnType = method.getReturnType();
                String returnTypeName = returnType.getCanonicalName();
                System.out.println(returnTypeName);
            }
        }
    }
}

Include the JAR (and its dependencies) in the classpath. This won't print the names of the parameters, since you can't get those via reflection. It also doesn't show type parameters or var-args, though you could get those.

A: You can try classdoc, which attempts to generate a javadoc from compiled files and jar archives.
http://classdoc.sourceforge.net/classdoc10/classdoc.html


text:
Q: scala selenium dsl page object I am using the Selenium dsl and would like to use a Page object. Currently however it seems I have to define the page object inside the test class.  The reason I would want a page object is to share common features between tests so this seems a bit pointless...  Has anyone been using the page object model with Selenium DSL?  What is the idea behind defining the page object in the same class?  How come I get a compiler error if I define the page object outside of the test class.  Am I doing something wrong?
The compiler error I get is:
Expected MySpec.this.type#Page, actual: MyPage

A: You can define the class outside of the test class like this:
class TwitterPage {
  val url = "http://twitter.com"
}

Then, use it inside the test by mixing in the Page trait:
val page = new TwitterPage with Page
go to page
title should be ("Welcome to Twitter")

This compiled and worked just fine for me.


text:
Q: Showing that function for IF statement does not work the same way as IF statement This is a question for a homework problem that I cant figure out:
Question Beginning
Q3. Let's try to write a function that does the same thing as an if statement:
def if_function(condition, true_result, false_result):

    """Return true_result if condition is a true value, and false_result otherwise."""

    if condition:
        return true_result
    else:
        return false_result

This function actually doesn't do the same thing as an if statement in all cases. To prove this fact, write functions c, t, and f such that one of these functions returns the number 1, but the other does not:
def with_if_statement():

    if c():
        return t()
    else:
        return f()

def with_if_function():

    return if_function(c(), t(), f())

Question End
Heres what I figured out:
with_if_statement() does not evaluate f() if c() is true, but with_if_function() evaluates all 3 before checking if c() is true or not.
So, I thought of assigning a global variable in c(), and changing its value in f()
heres my code (which does not work):
def c():

    try:
        global x
    except NameError:
        x=1
    if x==1:
        return True
    else:
        return False

def t():

    if x==1:
        return (1)
    else:
        return (0)

def f():

    global x
    x=2
    if x==1:
        return (1)
    else:
        return (0)

can anyone help me figure out the answer? Thanks..!

A: The global statement shouldn't throw a NameError (and so you won't run x=1 in c()). I would try rewriting your code without using exceptions, they won't be necessary to solve this and are making it more complicated than it needs to be. Using a global variable and having side effects in your functions is certainly the right track.

A: def if_function(condition, true_result, false_result):
    """Return true_result if condition is a true value, and
    false_result otherwise.

    >>> if_function(True, 2, 3)
    2
    >>> if_function(False, 2, 3)
    3
    >>> if_function(3==2, 3+2, 3-2)
    1
    >>> if_function(3>2, 3+2, 3-2)
    5
    """
    if condition:
        return true_result
    else:
        return false_result

def with_if_statement():
    """
    >>> with_if_statement()
    1
    """
    if c():
        return t()
    else:
        return f()

def with_if_function():
    return if_function(c(), t(), f())

The question requires that, write 3 functions: c, t and f such that with_if_statement returns 1 and with_if_function does not return 1 (and it can do anything else)
At the beginning, the problem seems to be ridiculous since, logically, with_if_statement and with_if_function are same. However, if we see these two functions from an interpreter view, they are different.
The function with_if_function uses a call expression, which guarantees that all of its operand subexpressions will be evaluated before if_function is applied to the resulting arguments. Therefore, even if c returns False, the function t will be called. By contrast, with_if_statement will never call t if c returns False (This paragraph from the UCB website).
def c():
    return True

def t():
    return 1

def f():
    '1'.sort() # anything breaks the program is OK


text:
Q: Change React-Native TextInput's placeholder color I'm creating an Android app using React Native in which there's a form. The placeholder doesn't even appear for the textInput fields so I thought of changing the placeholder color but I don't know how to do that. The docs mentioned some way which I don't understand.
Here's the code:
  <TextInput
  secureTextEntry={secureTextEntry}
  style={inputStyle}
  placeholder={placeholder}
  value={value}
  onChangeText={onChangeText}
  />

  inputStyle: {
  color: '#000',
  paddingRight: 5,
  paddingLeft: 5,
  fontSize: 18,
  lineHeight: 23,
  flex: 2,
  }

I also tried:
  <TextInput
  placeholderTextColor="blue"
  style={inputStyle}
  placeholder={placeholder}
  value={value}
  onChangeText={onChangeText}
  />

and
  inputStyle: {
  color: '#000',
  paddingRight: 5,
  paddingLeft: 5,
  fontSize: 18,
  lineHeight: 23,
  flex: 2,
  placeholderTextColor: '#333'
  }

A: Like so:
<TextInput
   placeholder="something"
   placeholderTextColor="#000"
/>

A: Use the placeholderTextColor prop to change the color of the placeholder text.
For example:
<TextInput placeholder="First name..." placeholderTextColor="#FFF" />

You can check the React Native TextInput reference for this and more options on the same.

A: Try using placeholderTextColor property to maintain placeholder color.
secureTextEntry props are generally used for password input.
It's best to follow official document. I think they described everything in a proper way.


text:
Q: Samba - AD cant login from diferent hostname I installed samba with winbind and is currently running properly using the AD to auth clients via the server hostname and ip address.
However i would like the clients to be able to login to the share using a different hostname from my dns, but everytime i try to login it rejects the credentials, here is the output from smb log:
[2016/08/23 10:14:32.650746,  3] ../source3/smbd/smb2_negprot.c:271(smbd_smb2_request_process_negprot)
  Selected protocol SMB2_10
[2016/08/23 10:14:32.990048,  1] ../source3/librpc/crypto/gse.c:497(gse_get_server_auth_token)
  gss_accept_sec_context failed with [Unspecified GSS failure.  Minor code may provide more information: Request ticket server cifs/storage.mydomain.com@MYDOMAIN.COM not found in keytab (ticket kvno 1)]
[2016/08/23 10:14:32.990067,  1] ../auth/gensec/spnego.c:541(gensec_spnego_parse_negTokenInit)
  SPNEGO(gse_krb5) NEG_TOKEN_INIT failed: NT_STATUS_LOGON_FAILURE
[2016/08/23 10:14:32.990128,  2] ../auth/gensec/spnego.c:716(gensec_spnego_server_negTokenTarg)
  SPNEGO login failed: NT_STATUS_LOGON_FAILURE
[2016/08/23 10:14:32.991082,  3] ../source3/smbd/server_exit.c:252(exit_server_common)
  Server exit (NT_STATUS_CONNECTION_RESET)

How can i accomplish this?
Thank you


text:
Q: How to display menu in android using code? I am running my android app on my samsung galaxy s2 phone. The phone has a physical menu button, and if I click it, I get a menu overlap that has 1 option that says by default "Settings". Some phones don't have the physical menu button. I made a button in the app for this purpose, to show the menu.
However I don't know how to show the menu using java code.
Does anyone know how do this?
Thanks.

A: Simply call openOptionsMenu(); and it will programmatically open the options menu.
I suppose you can't do this in onCreate, or other methods similar to this where the options menu has not yet been created.
reference to Android's official documentation.


text:
Q: masterViewController in UISplitViewController not shown I have a tabbarcontroller with 3 tabs that are splitviewcontrollers.
It works fine except when:

*

*in portrait view tap the rootview button to show the master
popover.

*switch to any other tab

*rotate to landscape (the masterview controller of that tab appears)

*switch back to first tab and the detail view controller is in the
right position (320 px from left border) but instead the master view
I have a black screen

I enumerated the splitviewcontroller subviews but the masterview is not there.
If I rotate the device in portrait and back in landscape, the master view appears.
I try to better explain with this picture:

A: It seems to me that the problem might be caused by all of your UISplitViewControllers using the same delegate, probably your AppDelegate. That might cause the behavior you're seeing, since when one UISplitViewController returns false from collapseSecondaryViewController:ontoPrimaryController, they all will return false, giving you the padding on the left to make space for the masterViewController. But your UISplitViewControllers which are not active aren't showing the masterViewController, so you get a blank space, instead of what you expect.


text:
Q: session_start() does not set $_SESSION at all I have the following identical code on my development and production server. It works on the development end, but not on the production side:
<?php
$s = session_start();
mail('me@example.com', 'Site-test', "s=$s; SESSION=".serialize($_SESSION), "MIME...");

Development server shows:
s=1; SESSION=a:4:{s:20:"user_timezone_region";s:13:"Pacific/Samoa";s:4:"lang";s:1:"1";s:12:"sess_user_id";s:3:"225";s:14:"sess_user_type";s:1:"S";}

Production server shows:
s=1; SESSION=a:0:{}

There is something wrong with my PHP settings on the production server which I'm hoping to diagnose. Yes, this is linked to my other two questions recently here and here.
More details:

*

*I have cPanel running on this server

*PHP error_log did NOT report the above to be an error (note that the variable 's' is '1')

*The differences in phpinfo() for the two is mentioned in the first link

A: The session, when first started for a new client, is actually empty. That could mean that on the dev server you see a session of a returning client, while on productive — the session of a first-time client.

A: Why do you test your session in such odd way?
Why not to make such a simple script
<?
session_start();
if (!isset($_SESSION['counter'])) $_SESSION['counter']=0;
echo "Page reloaded ".$_SESSION['counter']++." times.

reload";
?>

if it works, your sessions works perfectly, but there is something wrong with passing identifier.
If not... there ought to be some error message.


text:
Q: Unicode input retrieved via PrimeFaces input components become corrupted When I was still using PrimeFaces v2.2.1, I was able to type unicode input such as Chinese with a PrimeFaces input component such as <p:inputText> and <p:editor>, and retrieve the input in good shape in managed bean method.
However, after I upgraded to PrimeFaces v3.1.1, all those characters become Mojibake or question marks. Only Latin input comes fine, it are the Chinese, Arabic, Hebrew, Cyrillic, etc characters which become malformed.
How is this caused and how can I solve it?

A: Introduction
Normally, JSF/Facelets will set the request parameter character encoding to UTF-8 by default already when the view is created/restored. But if any request parameter is been requested before the view is been created/restored, then it's too late to set the proper character encoding. The request parameters will namely be parsed only once.
PrimeFaces encoding fail
That it failed in PrimeFaces 3.x after upgrading from 2.x is caused by the new isAjaxRequest() override in PrimeFaces' PrimePartialViewContext which checks a request parameter:
@Override
public boolean isAjaxRequest() {
    return getWrapped().isAjaxRequest()
            || FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().containsKey("javax.faces.partial.ajax");
}

By default, the isAjaxRequest() (the one of Mojarra/MyFaces, as the above PrimeFaces code has obtained by getWrapped()) checks the request header as follows which does not affect the request parameter encoding as request parameters won't be parsed when a request header is obtained:
    if (ajaxRequest == null) {
        ajaxRequest = "partial/ajax".equals(ctx.
            getExternalContext().getRequestHeaderMap().get("Faces-Request"));
    }

However, the isAjaxRequest() may be called by any phase listener or system event listener or some application factory before the view is been created/restored. So, when you're using PrimeFaces 3.x, then the request parameters will be parsed before the proper character encoding is been set and hence use the server's default encoding which is usually ISO-8859-1. This will mess up everything.
Solutions
There are several ways to fix it:

*

*Use a servlet filter which sets ServletRequest#setCharacterEncoding() with UTF-8. Setting the response encoding by ServletResponse#setCharacterEncoding() is by the way unnecessary as it won't be affected by this issue.
@WebFilter("/*")
public class CharacterEncodingFilter implements Filter {

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        chain.doFilter(request, response);
    }

    // ...
}

You only need to take into account that HttpServletRequest#setCharacterEncoding() only sets the encoding for POST request parameters, not for GET request parameters. For GET request parameters you'd still need to configure it at server level.
If you happen to use JSF utility library OmniFaces, such a filter is already provided out the box, the CharacterEncodingFilter. Just install it as below in web.xml as first filter entry:
<filter>
    <filter-name>characterEncodingFilter</filter-name>
    <filter-class>org.omnifaces.filter.CharacterEncodingFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>characterEncodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

*Reconfigure the server to use UTF-8 instead of ISO-8859-1 as default encoding. In case of Glassfish, that would be a matter of adding the following entry to <glassfish-web-app> of the /WEB-INF/glassfish-web.xml file:
<parameter-encoding default-charset="UTF-8" />

Tomcat doesn't support it. It has the URIEncoding attribute in <Context> entry, but this applies to GET requests only, not to POST requests.

*Report it as a bug to PrimeFaces. Is there really any legitimate reason to check the HTTP request being an ajax request by checking a request parameter instead of a request header like as you would do for standard JSF and for example jQuery? The PrimeFaces' core.js JavaScript is doing that. It would be better if it has set it as a request header of XMLHttpRequest.

Solutions which do NOT work
Perhaps you'll stumble upon below "solutions" somewhere on the Internet while investigating this problem. Those solutions do won't ever work in this specific case. Explanation follows.

*

*Setting XML prolog:
<?xml version='1.0' encoding='UTF-8' ?>

This only tells the XML parser to use UTF-8 to decode the XML source before building the XML tree around it. The XML parser actually being used by Facelts is SAX during JSF view build time. This part has completely nothing to do with HTTP request/response encoding.

*Setting HTML meta tag:
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>

The HTML meta tag is ignored when the page is served over HTTP via a http(s):// URI. It's only been used when the page is by the client saved as a HTML file on local disk system and then reopened by a file:// URI in browser.

*Setting HTML form accept charset attribute:
<h:form accept-charset="UTF-8">

Modern browsers ignore this. This has only effect in Microsoft Internet Explorer browser. Even then it is doing it wrongly. Never use it. All real webbrowsers will instead use the charset attribute specified in the Content-Type header of the response. Even MSIE will do it the right way as long as you do not specify the accept-charset attribute.

*Setting JVM argument:
-Dfile.encoding=UTF-8

This is only used by the Oracle(!) JVM to read and parse the Java source files.


text:
Q: What does 'x' mark on the icons in package explorer in eclipse mean? I am not able to figure out what it means. I want to make sure if I should delete that package or not.
Also, what does revision number '-1' mean?

A: The "x" means that the folder is Scheduled for deletion.  If you ran svn status you would see this.  Likewise, if you did Team > Commit you would see these items in the dialog and if you committed, it would delete the folders from the repository.
Normally something that is Scheduled for deletion does not exist in the working copy, so you cannot see these indicators.  Obviously something on your end has put the items back.
You might want to run Team > Revert to remove the scheduled deletion.


text:
Q: EAFP coding style in shell script I am learning shell script to facilitate my routine on computer.
In python, there's EAFP style to handle exceptions.
    >>> while True:
    ...     try:
    ...         x = int(input("Please enter a number: "))
    ...         break
    ...     except ValueError:
    ...         print("Oops!  That was no valid number.  Try again...")

Is there such a style in shell script?

A: Traps are a shell scripts error handling functionality

A: It depends on how you interpret EAFP. In the narrow sense, it refers to a use of exception handling that Python is designed for, but that is in some languages impossible, and in most others both uncommon and strongly discouraged. In a broader sense, however, EAFP is common across nearly all programming languages, and especially common in shell scripting.
I assume POSIX shell scripting, with a slight focus on Bash. Python code examples are Python 3.
There's more than one way to ask forgiveness instead of permission...
Python is the programming language most strongly associated with the dichotomy of Look Before You Leap (LBYL) vs. Easier to Ask Forgiveness than Permission (EAFP). In Python, EAFP typically means allowing an exception to be raised and catching it, rather than checking to see if an operation will succeed before attempting it, which would be the LBYL way.
But those are not the only two possibilities; sometimes it is possible to attempt to perform an operation that does not raise an exception when it fails, but check whether or not it failed after trying it, and act differently based on the result. That doesn't use exception handling, so it feels odd, from a Python perspective, to call it EAFP... but really, it has much more in common with EAFP than LBYL. It is this sort of "EAFP" that is very common in shell scripting.
I think it helps to start off with Python examples, not just because those terms are so strongly associated with Python culture, but also because EAFP, LBYL, and exceptionless "EAFP" can all be demonstrated in a clean and simple fashion in Python. Suppose d is of type dict:
# EAFP
try:
    print(d['foo'])
except KeyError:
    print('Not found.')

# LBYL
if 'foo' in d:
    print(d['foo'])
else:
    print('Not found.')

# Exceptionless "EAFP"
v = d.get('foo')
if v is None:
    print('Not found.')
else:
    print(v)

Checking guessing if a shell command will succeed: LBYL
Sometimes we use straightforward LBYL in a shell script. This code, which ships in Debian's and Ubuntu's default .bashrc file, checks if one's home directory contains a regular file called .bash_aliases. If not, no attempt is made to use it. If so, an attempt is made to source it (to run each of its lines as a command in the current shell). Although this is subject to a race condition, the errors that would result in this case are not harmful, so this is a perfectly good design choice here:
if [ -f ~/.bash_aliases ]; then
    . ~/.bash_aliases
fi

Suppose, however, that you wanted to go into a subdirectory and perform an operation you would not want to accidentally do outside it. LBYL, at least in its pure form, is a poor choice. In this example, the operation is recursive deletion starting at multiple subdirectories matched by a glob. (...Which is sort of contrived, in that there are a number of other ways to accomplish it with reasonable safety. If you like, you can imagine that there are more things to do in that directory before and/or after running rm.)
# Don't do it this way!
if [ -d drafts ] && [ -x drafts ]; then  # BAD!
    cd drafts                            # BAD!
    rm -r foo*                           # BAD!
fi                                       # BAD!

Here, I tried to check if changing directory to drafts would succeed. I checked if it existed and is a directory (-d) and if I had execute permissions on it (-x). For a directory on a *nix system, execute permissions are what permit me to change into it. (Usually.)
The problem, besides the considerable complexity of this approach, is that I might have missed something. Even if nothing changes, does this really guarantee that I will be able to go into the directory? Have I checked everything? [I leave this as an exercise for the reader.]
Also, even if I had checked everything and ensured the directory existed and was accessible, well... was. In this case, the race condition actually matters. If something changes, and I cannot go into the directory, and the cd command fails, then I'll be deleting all the precious foo* subdirectories that exist side by side with drafts instead of the rubbish ones contained within it!
Running a shell command and looking to see if it did succeed: EAFP?
You may notice the uncanny similarity between those considerations and some of the reasons for using EAFP in Python: avoiding code that is complex or hard to read and the risk that conditions may have changed between checking and attempting an operation based on the check. Indeed, this is much simpler and more robust than the bad way shown above:
if cd drafts; then
    rm -r foo*
fi

You may see that written this way instead, especially if it is desired that the whole thing have a failing exit status if the condition (cd drafts) fails:
cd drafts && rm -r foo*

This does not use anything even slightly similar to exception handling. But it doesn't look before it leaps. It doesn't check if the drafts directory is present and accessible. It just attempts to change into it. Then, after making the attempt, it checks if this succeeded, and declines to continue on to run the rm command if it did not.
If by EAFP you mean using exception handling, then this is not EAFP. I understand if you balk at the comparison; after all, this approach existed long before exception handling, and is common in languages like C. But it is motivated by some of the same goals, and it is suitable in many of the same situations.
Of course, this is actually the more typical form of asking forgiveness instead of permission in programming. Python is rare in that it is not discouraged--and in fact encouraged--to raise exceptions even in situations that are utterly commonplace.
And what of traps?
I somewhat agree with jas-'s answer. Although they are not really the main way errors (in the sense of a command failing) are handled, traps in shell scripting are somewhat comparable to exception handling in Python.
However, there are a couple of important practical differences between traps in shell scripting and exceptions in Python:

*

*Python programs use exceptions all the time. Most shell scripts used traps rarely, if ever.

*Python exceptions are usually raised from within the current thread of execution (though this is not always so). In contrast, traps are usually triggered asynchronously, and are mainly useful for the purpose of handling asynchronous events like signals sent from a different process or from the system (e.g., SIGINT from when the user presses Ctrl+C), though they are not limited to such cases.

Traps are rarely used for flow control in shell scripts and are not all that common for error handling, either, in cases when there are other options. To run a command and discover if it worked, you check its exit status. As shown above, control structures like if provide a way to do that (and there are others).


text:
Q: No such table error in Sqlite Database swift 4.2 after change from swift 3 I'm trying to retrieve a count of records in a table using SQLite.swift and Swift in a Cocoa macOS application.
All tables can try to get data from SQLite data only two tables is showing
no such table tablename (code:1)

My query for create table is
try db.run(table1.create(ifNotExists: true) {t in
t.column(c1,primaryKey: true)
t.column(c2)
})
try db.run(table2.create(ifNotExists: true) {t in
t.column(c1,primaryKey: true)
t.column(c2)
})

My query to select table count
var count = try db.scalar("SELECT COUNT(*) FROM table1 WHERE userid=?",userid) as! Int64
var count = try db.scalar("SELECT COUNT(*) FROM table2 WHERE userid=?",userid) as! Int64

although the same code ,it is not working for one table.
Anyone knows how to solve?
Thanks Advance.


text:
Q: Pre-set formatting on asp.net pages. I am newish to Asp.net. I have inherited a web application project. When I create a new page it already has some formatting on the top even though I don't use any master page when creating the page. This I can see when I build the page.  I am using ASP.Net 4.0, C# language.
For the life of me I cant figure out as in the underlying code for the file there is no reference to any css or any elements. The code for page.aspx is as follows:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Test.aspx.cs" Inherits="Test" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
</body>
</html>

The code behind is as follows:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Test : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

    }
}

Thanks in advance for any help I can get.

A: Oh Actually when you create a page in Visual studio. He create some by default code file and a project structure.  Just why you show different type of file on solutions.
See on your aspx page header its define cs code file as CodeFile="Test.aspx.cs" and also Inherits test.
 Also .csproj file that contains assembly references
 .projRefs.sln file that contains the current project and all referenced projects

A: I figured it out. There was a theme applied which was adding reference to a stylesheet when compiling the page. I added disable theming tag which removed this reference for the particular page.


text:
Q: cars and Poisson distribution The cars travel on two roads according to the Poisson distribution with frequencies of 3 and 5 per minute, respectively. Calculate the expected length
time after which 100 cars will pass through their intersection.


text:
Q: Generating realistic mock data for a real-world scenario Im a final year math student doing a project for a company. They want to do a cup-and-grid water drop test with a firefighting helicopter. The basic idea is: a grid of 1000cups is setup on an airfield, small groups of 9 cups are placed strategically in the grid to measure variance around sample points, a water-bombing helicopter flies over the grid and drops water, cups are then collected, weighted and data is gathered. The process is then repeated for different speeds, heights etc...
My issue is that there is a chance fire season could come early and helicopters might not be available so im asking for peoples ideas/experiences in this area (im inexperienced), what similar situations have you been in and what solution did you come up with?
What i have so far is this: code the grid of cups in R and then:
step 1. allocate a volume of water to each of them according to a normal distribution. This would be as if an amount of water has been dropped from a height with no other variables involved. I can then graph the density and spread and if i think about how water disperses in real life when dropped it looks reasonable.
step 2. this is where im stuck add the effects of flight speed and flow rate out of the tank so that they influence the spread pattern and density. Generating this data so that its realistic kinda seems like a physics problem.