text:
Q: Code won't execute in function containing return? I've run into some issues with my scoping, I'm new to javascript so my apologies for my inexperience. The issue i'm having is I don't understand why my console.log within the function groupA(thename) curly braces won't allow code to output. In visual studio's it greys the code out. I think it may be due to the return fetch(`${url}${thename}`), because the code won't grey out when I remove that return. Why does the return function do this?
My goal is to correctly chain each function together so the data pushed into birds_array can be returned via the groupA function. How would I go about correctly formatting these functions to allow this to be possible?
const birds_array = []

let groupAname = "Old World sparrow"
groupA(groupAname);

function groupA(thename) {
    return fetch(`${url}${thename}`)
    .then(response => response.text())
    .then(body => {
        const $ = cheerio.load(body);
        $('.llgymd').each( (index, element) => {
            const $element = $(element);
            const names = $element.text();
            groupA_array[index] = names;
        });

        groupA_loop()
        function groupA_loop(){
        for(j = 0; j < groupA_array.length; j++){
            if(!birds_array.includes(groupA_array[j])){
                birds_array.push(groupA_array[j]);
                }
                // code functions here
                console.log(birds_array);
            }
            // code functions here
            console.log(birds_array);
        }
        // code functions here
        console.log(birds_array);
    });
    // code does not function here
    console.log(birds_array);
}

A: // Create a async function to await any async code. Else u get error.
async function main() {

      let groupAname = "Old World sparrow";
      // Await for the promise to be resolved. // Like pause call
      const birds_array = await groupA(groupAname);
      // Result done, print
      console.log(birds_array)
    }
main()

Sample:

const delayData = (num) => {
  return new Promise((r) => {
    setTimeout(() => {
      r(num);
    }, 1000);
  });
};
async function main() {
  const num = await delayData(1);

  console.log(num); // 1
  const num2 = await delayData(2);

  console.log(num2); // 2
}
main();

// Using then

delayData(1).then(num => {
  console.log(num) // 1
})
delayData(2).then(num => {
  console.log(num) // 2
})


text:
Q: Is it possible to reference an existing ActiveRecord model from the classes generated with Gii? There is an extension for Yii2 I'm using, and it provides a database table and an ActiveRecord model class to work with entities in that table. My other models are generated with Giiant. I want to reference the library model from my generated models, e.g. so relation properties like $myEntity->thatLibraryEntity are generated correctly by Giiant. Is it possible to do so?
I haven't found a way to do so in the documentation, and in the source code the closest thing to what I want is setting the BatchController::$tableNameMap configuration parameter in Giiant, but that seems to only rename the models, and I would like to tell Giiant which existing ActiveRecord to use for entities in a particular table.

A: I worked around it.
The generated models reference class app\models\ThatLibraryEntity for table that_library_entity. I created that class, and made it extend the library ActiveRecord model I wanted to use.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Kill a PM2 Cron Job automatically after 72 hours? I have a PM2 with a Cron Job that run every 5 minutes
pm2 start shoot-msg.sh --name shoot-messages -i 4 --cron "*/5 * * * *"

How can I program the PM2 to quit after 72 hours and kill the cron job ?
Meaning I don't want to do pm2 delete all by myself...

A: Your need is a task scheduler in Ubuntu. Use Crontab to kill the process after 72 hours.

*

*Install crontab
sudo apt install cron

*Set it to run in the background
sudo systemctl enable cron

*Edit the crontab
crontab -e

*Select the editor

*

*/bin/nano        <--- default

*/usr/bin/vim.basic

*/usr/bin/vim.tiny

*/bin/ed

press ENTER to select the default nano.
The editor would show the below,
# Edit this file to introduce tasks to be run by cron.
#
# Each task to run has to be defined through a single line
# indicating with different fields when the task will be run
# and what command to run for the task
#
# To define the time you can provide concrete values for
# minute (m), hour (h), day of month (dom), month (mon),
# and day of week (dow) or use '*' in these fields (for 'any').#
# Notice that tasks will be started based on the cron's system
# daemon's notion of time and timezones.
#
# Output of the crontab jobs (including errors) is sent through
# email to the user the crontab file belongs to (unless redirected).
#
# For example, you can run a backup of all your user accounts
# at 5 a.m every week with:
# 0 5 * * 1 tar -zcf /var/backups/home.tgz /home/
#
# For more information see the manual pages of crontab(5) and cron(8)
#
# m h  dom mon dow   command

*Scroll to the bottom of the editor and add the kill command with cron
0 */72 * * * /bin/node /bin/pm2 delete all
Just replace these values (/bin/node, /bin/pm2) by what is on the /etc/init.d/pm2-init.sh file.

*Save CTRL+O and exit CTRL+X


text:
Q: Associating a number value to a word on a webpage, and then multiplying this by a number on the webpage that follows the word
lawyer (111)

or

doctor (222)

So there are multiple pages containing html similar to the above. I want to assign a specific value to the occurrence of "lawyer" or "lawyer.gif" or whatever and multiply it by 111 IF lawyer is on the page, and then add this to "doctor" multiplied by 222 IF doctor is on the page. There are a lot of different possible "professions" (~50) so the code here is very simplified. One page could have doctor, lawyer, and fireman while another page could have just dentist. This sum should then be displayed on the page or in a popup or whatever really. The 111 and 222 here come from the number in parentheses in the code, and these numbers change on each page.
I planned on doing this with greasemonkey/javascript but only because of my limited experience with this. So I guess my question is first, is this even possible to do at least somewhat simply and if so, could someone at least give me some hints to get me started? Thanks.

A: In general:

*

*To deal with a lot of something, use an array: [blah1, blah2, etc.]

*To associate ad-hoc values to ad-hoc labels, use an object:
[ {blah1: 3.1}, {blah2: 415}, etc.]

*To detect and manipulate things on the page use jQuery.

*To add displays or other elements to the page, also use jQuery.

Putting it all together, here is a complete script that does what your question appears to ask.  You can also see the code in action at jsFiddle.:
// ==UserScript==
// @name     Arbitrary math on arbitrary page values
// @include  http://YOUR_SERVER.COM/YOUR_PATH/*
// @require  http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js
// @grant    GM_addStyle
// ==/UserScript==
/*- The @grant directive is needed to work around a design change
    introduced in GM 1.0.   It restores the sandbox.
*/

var textToValuesArray   = [
    {"doctor": 3}
    , {"lawyer": 5}
    , {"rodeo clown": 7}
    // etc.
];
var targetNodes = $("td.left:has(a)");
var targetText  = targetNodes.text ();
var reportValue = 0;

//-- Loop through the textToValuesArray.
$.each (textToValuesArray, function (index, textToValueObject) {
    var textTerm    = Object.keys (textToValueObject)[0];

    //-- Is the text term in the targeted part of the page?
    var termRegex   = new RegExp(textTerm, 'i'); // Case insensitive
    if (termRegex.test (targetText) ) {
        console.log ("Text '" + textTerm + "' was found!");

        /*-- Given the indicated page structure, targetText will look like:
            "doctor (2)lawyer (4)" etc.
            With the value we want coming one space after the target term
            and in parentheses.

            So, if we split the string on the search term, we get the next
            (number), if any.
        */
        var splitStr    = targetText.split (termRegex);
        if (splitStr  &&  splitStr.length > 1) {
            var multiplierString = splitStr[1].replace (/^\s*\((\d+)\).*$/, "$1");
            if (multiplierString) {
                var multiplierInteger = parseInt (multiplierString, 10);
                if (isNaN (multiplierInteger) ) {
                    console.log ("Multiplier value not found! (2)");
                }
                else {
                    /*-- We found a term and we found its multiplier.
                        Add to the report value.
                    */
                    var termValue   = textToValueObject[textTerm];
                    console.log (
                        "termValue: ", termValue,
                        "   ",
                        "multiplierInteger: ", multiplierInteger
                    );
                    reportValue    += termValue * multiplierInteger
                }
            }
            else {
                console.log ("Multiplier value not found! (1)");
            }
        }
        else {
            console.log ("Split string error!");
        }
    }
} );

console.log ("reportValue: ", reportValue);

$("body").prepend ('
The final value was: ' + reportValue + '
');
$("#gmReport").css ("background", "orange");


text:
Q: google-map-marker in dom-repeat has binding issue i'm trying to make a polymer page with a map, in the map i'm trying to put multiple markers (easy with a dom-repeat), when i click a marker i want to show an infowindow with a component inside that accepts data from outside and displays it in some way. I'm currently having an issue trying to make the dom-repeat of the google-map-marker with binding of the information passed to the component inside the infowindow.
Basically when dom-repeat is executed and the markers created the data is correctly set in the infowindow component, but somewhere between then and when you show the infowindow the data is lost and all that was set is now undefined.
I've tried different things and the conclusions are these:
Binding works if used with a
<slot></slot>

tag, displaying the content directly.
Infowindow component code:
<dom-module id="report-infowindow">
    <template>

        <paper-button><slot></slot></paper-button>

    </template>
    <script>
        /**
         * @customElement
         * @polymer
         */
        class ReportInfoWindow extends Polymer.Element {
            static get is() {
                return 'report-infowindow';
            }

            static get properties() {
                return {
                    mproperty:{
                        type: String,
                        notify: true
                    }
                };
            }
        }

        window.customElements.define(ReportInfoWindow.is, ReportInfoWindow);
    </script>
</dom-module>

Page that calls the component
<dom-module id="map-page">
    <template>
        <style>

            :host {
                display: block;
            }

            google-map {
                width: 100%;
                height: 100%;
            }
        </style>

        <google-map fit-to-markers single-info-window="true" map="{{map}}" api-key="{{key}}">
            <template is="dom-repeat" items="{{markers}}">
                <google-map-marker slot="markers" map="{{map}}" latitude="{{item.lat}}" longitude="{{item.lng}}" draggable="false" icon="{{icon}}">
                    <report-infowindow>{{item.lat}}</report-infowindow>
                </google-map-marker>
            </template>
        </google-map>

    </template>

    <script>
        /**
         * @customElement
         * @polymer
         */
        class MapPage extends Polymer.Element {
            static get is() {
                return 'map-page';
            }

            static get properties() {
                return {
                    key: {
                        type: String,
                        value: "KEY"
                    },

                    icon: {
                        type: String,
                        value: "./src/assets/images/marker_small.png"
                    },

                    markers: {}
                };
            }
        }

        window.customElements.define(MapPage.is, MapPage);
    </script>
</dom-module>

Binding doesn't work if used with a property exposed by the component like this:
Infowindow component:
<dom-module id="report-infowindow">
    <template>

        <paper-button>{{mproperty}}</paper-button>

    </template>
    <script>
        /**
         * @customElement
         * @polymer
         */
        class ReportInfoWindow extends Polymer.Element {
            static get is() {
                return 'report-infowindow';
            }

            static get properties() {
                return {
                    mproperty:{
                        type: String,
                        notify: true
                    }
                };
            }
        }

        window.customElements.define(ReportInfoWindow.is, ReportInfoWindow);
    </script>
</dom-module>

Page calling the component:
<dom-module id="map-page">
    <template>
        <style>

            :host {
                display: block;
            }

            google-map {
                width: 100%;
                height: 100%;
            }
        </style>

        <google-map fit-to-markers single-info-window="true" map="{{map}}" api-key="{{key}}">
            <template is="dom-repeat" items="{{markers}}">
                <google-map-marker slot="markers" map="{{map}}" latitude="{{item.lat}}" longitude="{{item.lng}}" draggable="false" icon="{{icon}}">
                    <report-infowindow mproperty="{{item.lat}}"></report-infowindow>
                </google-map-marker>
            </template>
        </google-map>

    </template>

    <script>
        /**
         * @customElement
         * @polymer
         */
        class MapPage extends Polymer.Element {
            static get is() {
                return 'map-page';
            }

            static get properties() {
                return {
                    key: {
                        type: String,
                        value: "KEY"
                    },

                    icon: {
                        type: String,
                        value: "./src/assets/images/marker_small.png"
                    },

                    markers: {}
                };
            }
        }

        window.customElements.define(MapPage.is, MapPage);
    </script>
</dom-module>

But at the same time the property itself works if set with a static value like
<report-infowindow mproperty="sasa"></report-infowindow>

I don't understand if it's a bug or if it's something i'm doing wrong.

A: You are not doing anything "wrong" - it just doesn't work. This and a host of related issues have been present with the infowindow since inception of the google-map element.  For example, see issue 286, and issue 288 and the long discussion in pull requests that ensued.
The problem is that the google-map-marker copies the infowindow markup into the infowindow which itself is in the context of the document, not your element. Any binding is lost and any ability to style using CSS classes is lost in the copy. This is not going to be fixed unless they drop use of the native infowindow.
I developed a custom element, plastic-map-info, which is a fully composable infowindow for google-map as an alternative. You may want to see if that helps you achieve the result you are looking  for.

A: This is now fixed, but you must declare slot="markers" as an attribute of the google-map-marker component.
<google-map fit-to-markers latitude="44" longitude="44" api-key="your_key">
  <template is="dom-repeat" items="[[data]]">
    <google-map-marker
      slot="markers"
      title="[[item.title]]"
      icon="marker.png"
      latitude="[[item.latitude]]"
      longitude="[[item.longitude]]">
    </google-map-marker>
  </template>
</google-map>


text:
Q: How to name the file created in blob storage from a Powershell Azure Function? Here is the function.json I have. The default for the path property is {rand-guid} which works.
I want name the file, I tried {filename} in the json and in the run.ps1 tried setting $env:filename and $filename, it did not work.
Can this be done?
{
  "bindings": [
    {
      "name": "myTimer",
      "type": "timerTrigger",
      "direction": "in",
      "schedule": "0 * 7 * * *"
    },
    {
      "type": "blob",
      "name": "outputBlob",
      "path": "outcontainer/{filename}",
      "connection": "testfunctionpsta0a5_STORAGE",
      "direction": "out"
    }
  ],
  "disabled": false
}

A: Unfortunately the output binding is not that simple. We need to pass a json object to the output binding to get the values.
Have a look at the examples on https://learn.microsoft.com/en-us/azure/azure-functions/functions-triggers-bindings#advanced-binding-at-runtime-imperative-binding.
// function.json
{
    "name": "$return",
    "type": "blob",
    "direction": "out",
    "path": "output-container/{id}"
}

// C# example: use method return value for output binding
public static string Run(WorkItem input, TraceWriter log)
{
    string json = string.Format("{{ \"id\": \"{0}\" }}", input.Id);
    log.Info($"C# script processed queue message. Item={json}");
    return json;
}

Should be straightforward to do similar in Powershell.

A: Could you pass the name of your file as part of your trigger payload? If yes, this SO thread may help.


text:
Q: Training image classifier - Neural Network I would like to train a conv neural network to detect the presence of hands in images.
The difficulty is that:
1/ the images will contain other objects than the hands, just like a picture of a group of people where the hands are just a small part of the image
2/ hands can have many orientations / shapes etc (whether they are open or not , depending on the angle etc..)
I was thinking of training the convnet on a big set of cropped hand images (+ random images without hands) and then apply the classifier on all the subsquares of my images. Is this a good approach?
Are there other examples of complex 2-class convnets / RNNs I could use for inspiration?
Thank you!

A: This seems more a matter of finding good labeled training data than of choosing a network. A neural network can learn the difference between "pictures of hands" and "pictures which incidentally include hands", but it needs some labeled examples to figure out which category an image belongs to.
You might want to take a look at this: http://www.socher.org/index.php/Main/ParsingNaturalScenesAndNaturalLanguageWithRecursiveNeuralNetworks

A:
I was thinking of training the convnet on a big set of cropped hand
  images (+ random images without hands) and then apply the classifier
  on all the subsquares of my images. Is this a good approach?

Yes, I believe this would be a good approach. However, note that when you say random, you should perhaps sample it from images where "hands are most likely to appear". It really depends on your use case, and you have to tune the data set to fit what you're doing.
How you should build your data set, would be something like this:

*

*Crop images of hands from a big image.

*Sample X number of images from that same image, but not anywhere near the hand/hands.

If however, you should choose to do something like this:

*

*Crop images of hands from a big image.

*Download 1 million images (an exaggeration) that definitely don't have hands. For example, deserts, oceans, skies, caves, mountains, basically lots of scenery. And then use this as your "random images without hands", you might get bad results.

The reason for this, is because there is an underlying distribution already. I assume that most of your images could be pictures of groups of friends, having a party at a house, or perhaps the background images would be buildings. Hence, introducing scenery images, could corrupt this distribution, whilst holding the above assumption.
Therefore, be really careful when using "random images"!

on all the subsquares of my images

As to this part of your question, you are essentially running a sliding window on the entire image. Yes, practically, it would work. But if you're looking for performance, this may not be a good idea. You might want to run some segmentation algorithms, to narrow down the search space.

Are there other examples of complex 2-class convnets / RNNs I could
  use for inspiration?

I'm not sure what you mean by complex 2-class convnets. I'm not familiar with RNNs, so let me focus on convnets. You can basically define the convolutional net yourself. For example, the convolutional layers size, how many layers, what's your max pooling method, how big is your fully connected layer going to be, etc. The last layer, is basically a softmax layer, where the net decides what class it's going to be. If you have 2 classes, your last layer has 2 nodes. If you have 3, then 3. And so on. So it can range from 2, to perhaps even 1000. I've not heard of convnets that have more than 1000 classes, but I could be ill-informed. I hope this helps!


text:
Q: Repeat Alarms on Every Monday in Android using AlarmManager/BroadcastReceiver I want to repeat my task on every Monday at 09:00AM & 05:00 PM. I used following code for that but I am not able to repeat the task.
Activity Code:
public class AndroidScheduledActivity extends Activity {
    /** Called when the activity is first created. */
    int id = 115;
    Intent myIntent;
    PendingIntent pendingIntent;
    AlarmManager alarmManager;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Button buttonStart = (Button)findViewById(R.id.start);

        myIntent = new Intent(getBaseContext(), MyScheduledReceiver.class);
        myIntent.putExtra("id", id);
        pendingIntent = PendingIntent.getBroadcast(getBaseContext(), id, myIntent, 0);

        alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);

        buttonStart.setOnClickListener(new Button.OnClickListener(){
            public void onClick(View arg0) {
                // TODO Auto-generated method stub
                setForMonday();
                finish();
            }});
    }

    public void setForMonday() {
        Calendar calendar = Calendar.getInstance();

        calendar.set(Calendar.DAY_OF_WEEK,2);
        calendar.set(Calendar.HOUR,09);
        calendar.set(Calendar.MINUTE, 00);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        System.out.println("Old is set@ :== " + calendar.getTime());

        long interval = calendar.getTimeInMillis() + 604800000L;
        System.out.println("Next Millis = " + interval);
        alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), interval, pendingIntent);
    }
}

Note: I counted interval based on 86400000 * 7 = 604800000;
Receiver:
public class MyScheduledReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        // TODO Auto-generated method stub

        System.out.println("Receiver");
    }
}

A: Remove interval variable and use the following in place of that.
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),AlarmManager.INTERVAL_DAY * 7, pendingIntent);


text:
Q: percentage - px width in stylus I'm having trouble with an operation using stylus. I thought I read somewhere that we can use calculations between percentage and pixels widths or heights, and stylus does the work to return the right value... However I can't manage to get it to work.
I did some research but didn't find anything related to stylus, I only saw some posts mentioning the function calc()
Here is what I tried: max-width: (50% - 20px)
This returns 30%! looks like it just subtracted 20 from 50! am I missing something?
Thanks

A: If you're going for the native CSS calc it should look something like this:
max-width: calc(50% - 20px);

Note the white space on either side of the operand, it is currently required.


text:
Q: how can I refer to the current object in a With block? I am writing a VBA project for a workbook that has three sheets.  I want to be able to get the last used row number for any one of them.  There will never be any blank rows between used rows on the sheets, so I can use CurrentRegion.  I would like to write a little function that accepts a worksheet as an argument and returns the last used row number. Easy enough.  But I want to be able to use that method inside a With block that refers to a sheet.  How do I do that?  Here's what I hoped would work:
Private Function LastRow(Sheet As Worksheet) As Long
    LastRow = Sheet.cells(1, 1).CurrentRegion.End(xlDown)
End Function

Private Sub UseLastRow()
    With g_PeopleSheet
        msgbox "Last used row: " & LastRow(.)
    End With
End Sub

I am using Excel 2016.


text:
Q: Prove $2^n\cdot n! ≤ (n+1)^n$ by induction. An induction I'm struggling with.

Prove $2^n\cdot n! ≤ (n+1)^n$ by induction.

An idea was to show that $2^n\cdot n! ≤ 1+n^2$ since $1+n^2 ≤ (n+1)^n$ using Bernoulli. However the inequality is just wrong so that approach doesn't work. I had the intuition that $2^n ≤ n!$ but I don't think that yields anything for this problem.
I would really like to get a hint or two. Of course you can post your answer, this is obviously what this platform is for, but I won't read them until I solved the problem myself. It's an induction, can't be that difficult right?

A: Hint: The induction step goes as follows:
$$2^{n+1}(n+1)!=2^nn!2(n+1)\le(n+1)^n2(n+1)=2(n+1)^{n+1}$$
Thus you are left to prove that $2(n+1)^{n+1}\le(n+2)^{n+1}$, which is pretty easy.

A: Base case, $n = 1$: $2 \leq 2$, true.
Assumenow  it holds up to $n\geq 1$. Then,
$$
 2^{n+1}\cdot(n+1)! = 2(n+1)\cdot 2^n\cdot n! \operatorname*{\leq}_{\rm(IH)} 2(n+1)\cdot(n+1)^n = 2(n+1)^{n+1}
$$
so to conclude the induction, it boils down to proving that
$$
2\leq \left(\frac{n+2}{n+1}\right)^{n+1} = \left(1+\frac{1}{n+1}\right)^{n+1} (\operatorname*{\sim}_{n\to\infty} e)
$$

A: $$2(n+1)^{n+1}\leq\sum_{k=0}^{n+1} \binom {n+1}k(n+1)^{n-k+1}= (n+2)^{n+1} .$$


text:
Q: Hyperlink to File from Echo'ed value in a form I am trying to hyperlink to a file saved on my server.
The file gets uploaded using an upload form.
Once Uploaded, a record is created in my document table with the file name.
One another form, I echo all information relating to this particular entry. some of the fields are editable, and others remain read-only.
I am trying to have the field that echo's the fie location be displayed as a link from which you can open the file. All my fields are echoing correctly, but I just can't seem to get this photo field to hyperlink.
What is the best way to do this?
Here is my code for this part of the form:
<input id="photo_input_file" class="form-control1" type="text" placeholder="Photo Verification Missing" value="<a href='http://localhost/scrm/photos/<?php echo $photo_file;?>'>">


text:
Q: using counter to prevent long coding I've been searching for a while to help me with my question, but couldn't find any good tutorials. I started Android recently, so I'm not that good jet. My question is how I can convert my code in a way that I don't have to type everything. I was thinking maybe to use a counter. I want to know if there is a possibility that I only have to set the visibility of the seekbar and the button once. This is my code:
private void numberPlayers() {
    Intent intent = getIntent();
    String str = intent.getStringExtra("rbPlayers");
    if (str.equals("rb2")) {
        sbPlayer3.setVisibility(View.GONE);
        bPlus3.setVisibility(View.GONE);
        sbPlayer4.setVisibility(View.GONE);
        bPlus4.setVisibility(View.GONE);
        sbPlayer5.setVisibility(View.GONE);
        bPlus5.setVisibility(View.GONE);
        sbPlayer6.setVisibility(View.GONE);
        bPlus6.setVisibility(View.GONE);
    } else if (str.equals("rb3")) {
        sbPlayer4.setVisibility(View.GONE);
        bPlus4.setVisibility(View.GONE);
        sbPlayer5.setVisibility(View.GONE);
        bPlus5.setVisibility(View.GONE);
        sbPlayer6.setVisibility(View.GONE);
        bPlus6.setVisibility(View.GONE);
    } else if (str.equals("rb4")) {
        sbPlayer5.setVisibility(View.GONE);
        bPlus5.setVisibility(View.GONE);
        sbPlayer6.setVisibility(View.GONE);
        bPlus6.setVisibility(View.GONE);
    } else if (str.equals("rb5")) {
        sbPlayer6.setVisibility(View.GONE);
        bPlus6.setVisibility(View.GONE);
    }
}

Thank you in advance!

A: This is not really related to Android, but I would suggest the following approach:
Hold all your variables (such as sbPlayer5 or bPlus6) in an array - you can use ArrayList to hold any type of object and have the array grow automatically. So you can access the correct object by a numeric index.
Pass rbPlayers as an Integer instead of String.
Then iterate over your array using the numeric index (for) and call setVisibility inside the loop for all indexes above your maximum.

A: *

*If your layout elements are contained in each other then you can call the method on the parent one and it will call the same method on its children.

*If your objects all inherit from the same base class you can put them in arrays and use a cycle to iterate through them and call the method.


text:
Q: Is there a way to dodge the one-time passwords? I find it quite annoying that every now and then, when I log in to my SWTOR account, Bioware asks me to enter a one-time password sent to my e-mail address. I find that quite annoying.
I doubt there is, but is there a way to skip that question? Like with the Security Key, or just something I haven't seen in the options?

A: Technically, there is - but I don't know if adding a security authenticator to your account will make you any happier.
On the plus side, you'll never be asked for a one-time password again. On the down side, you'll have to use your key generator to get the authentication code whenever you sign on to your account with the browser.
Still, a small price to pay to make sure your account is going to be hard to compromise IMO....

A: Without getting a security key, no there is not.
It will ask for a one-time password every time you log in from a different computer/IP or mobile device, or if you reset your browser data (such as cookies). It is all part of BioWare trying to protect you from hackers.
I do suggest getting the physical security key or the app for your phone. This will help keep your account safe from hackers.


text:
Q: LINQ to Entities does not recognize the method 'System.Object get_Item(System.String)' method In trying to output data to a view I an get the following error.
LINQ to Entities does not recognize the method 'System.Object get_Item(System.String)' method, and this method cannot be translated into a store expression.
Controller code:
public ActionResult Index()
            {
                return View(ReturnResults());
            }

public IQueryable<ShippingRequest> ReturnResults()
        {
            RatesModel db = new RatesModel();

            IQueryable<ShippingRequest> response = db.ShippingRequests;

            var results = response
                .Where(r => r.UserId == (int)Session["UserId"]);

            return results;
        }

View Code:
@model IEnumerable<ShippingRatesApp.Models.ShippingRequest>

@{
    ViewBag.Title = "Get Rates";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

Shipping Rates

@{

    @foreach (var rate in Model)
    {

            @rate.ShipRate

    }

}

I am very new to c# and none of the web searches I have come across have solved my issue. Can someone please help me sort this out? Thanks!

A: It means that it can't translate Session["UserId"] into SQL (it's not smart enough to pull the value out of the collection). I'd recommend storing this in a value before using it:
var currentUserId = (int)Session["UserId"];
var results = response
            .Where(r => r.UserId == currentUserId);


text:
Q: Display nested array/object values into separate elements on click I currently have an object with a few nested arrarys that contain another object and one with just an array.  It is formated as such:
{
    "x": 1409529600000,
    "y": 730,
    "pf": [
        {
            "sd": "this is some text"
        },
        {
            "sd": "here is some stuff"
        }
    ],
    "nf": [
        {
            "sd": "im in the nf array"
        },
        {
            "sd": "me too!"
        }
    ],
    "t": [
        "here is a tip",
        "how about the other tip"
    ]
}

When a user click a link I'd like to display all this data (minus the x: and y:) to elements on the page.  For instance:
from pf:

this is some text

here is some stuff

from nf:

im in the nf array

me too!

from t:

here is a tip

how about the other tip

As you can see its a bit complex.  I need to pull out the values from each nested array/object via pf and nf and also pull out the two items from t's array and them wrap them all in their own elements.
I'm just so lost as to where I even begin.  I know I can loop through and get the values from the two objects, but it seems like a lot of work to pull everything out, bind it to an element, and display.
EDIT:  For easy of a solution I could also have the backend return t: as an object with a key value too.

A: how about using recursivity :
function goThroughObj(obj) {
    var prop;
    for (prop in obj) {
        if (obj.hasOwnProperty(prop)) {
            if (typeof obj[prop] === "object") {
                goThroughObj(obj[prop]);
            } else {
                document
                  .getElementById('showObj')
                  .appendChild(buildData(obj[prop]));
            }
        }
    }
}

Your HTML looks like
<button id="myObj">disp</button>

this is how it works:
first, you listen for a click on your button
(function(){
    document
      .getElementById('myObj')
      .addEventListener("click",  showObjData);
}());

then, on click it will invoke the function showObjData
function showObjData() {
    var key,
        title,
        element = document.getElementById('showObj');

     // clear innerHTML in case user click more than once
     element.innerHTML='';

     for (key in obj) {
         // skip anything that is not an array, ie: x, y
        if (obj[key] instanceof Array) {
            title = '
From ' + key + ' : ';
            element.appendChild(buildData(title));
            // use recursive function
            // to go through each keys/properties
            goThroughObj(obj[key]);
        }
    }
}

last but not least, buildData() creates the HTML element to be displayed
function buildData(content) {
    var data = document.createElement('p');
    data.innerHTML = content;
    return data;
}

here's a jsfiddle for you to play with

A: You need to write logic for looping through array of objects and append the  pair to the DOM. You can use for in loop.
function start(input) {
        for (key in input) {
            var typeObject = "[object Object]",
                typeArray = "[object Array]";
            if (getType(input) == typeObject) {
                if (getType(input[key]) == typeObject || getType(input[key]) == typeArray) {
                    console.log(key + ":");
                    $("#output").append("from "+key+":
");
                    start(input[key]);
                } else{
                    console.log(key + ":", input[key]);
                     $("#output").append("
"+key+":"+input[key]+"
");
                }
            } else if (getType(input) == typeArray) {
                if (getType(input[key]) == typeObject || getType(input[key]) == typeArray) {
                    start(input[key]);
                } else {
                    console.log(input[key]);
                     $("#output").append("
"+input[key]+"
");
                       }
            }
        }
    }
    start(input);

See complete code here: http://jsfiddle.net/4urd4qtt/1/

A: try following this way:

 var arr={
     "x": 1409529600000,
     "y": 730,
     "pf": [
         {
             "sd": "short desc1"
         },
         {
             "sd": "short desc2"
         }
     ],
     "nf": [
         {
             "sd": "short desc1"
         },
         {
             "sd": "short desc2"
         }
     ],
     "t": [
         "tip text1",
         "tip text2"
     ]
 };

 function show(){
  var str="";
  for(a in arr){
   if( a=="x" || a=="y"){continue;}
   str=str+"from "+a+"
";
   str1="";
   for(z in arr[a]){

    if(typeof arr[a][z] === 'object'){
     str1=str1+"
sd:"+arr[a][z].sd+"
";
    //str1=str1+"
"+arr[a][z].toSource()+"
"; //this will displace in object format
    }else{
            str1=str1+"
"+arr[a][z]+"
";
 }

 }
   str=str+str1;
  }
  $("#container2").html(str);// html way of displaying
  console.log(str);// displaying the way written in question
 }

<button id="click" onclick="show()">click</button>

A: Try this:
function escapeRegex(string) {
        return string.replace(/[\[\]""(){}?*+\^$\\.|\-]/g, " ");
    }

$('.yourButtonToClick').click(function(){
    var htmlForT="";
    var htmlForPf="";
    var htmlForNf="";
    var pf= escapeRegex(JSON.stringify(json.pf));
    var nf= escapeRegex(JSON.stringify(json.nf));
    var t= escapeRegex(JSON.stringify(json.t));
    //For t
    var arr = t.split(",");
        for (var i = 0; i < arr.length; ++i) {
            htmlForT+= "
"+arr[i]+"
";
        }
    $(".yourDisplay").append('
for t:
').append(htmlForT);

    //For pf
    var arr1 = pf.split(",");
        for (var i = 0; i < arr1.length; ++i) {
            htmlForPf+= "
"+arr1[i]+"
";
        }
    $(".yourDisplay").append('
for pf:
').append(htmlForPf);
        //For nf
    var arr2 = nf.split(",");
        for (var i = 0; i < arr2.length; ++i) {
            htmlForNf+= "
"+arr2[i]+"
";
        }
    $(".yourDisplay").append('
for nf:
').append(htmlForNf);
        });


text:
Q: How does MultiLanguage search engines Work Today , when searching some videos on youtube i found out that youtube can return relevant results even if you search for videos in languages other than english.
Tried searching about this on google , but all i got was some api's to do this programmatically.Can someone throw some light on the theory behind this.Papers/Links/Explanations,anything  would do.
Thanks

A: When I've done this with elasticsearch, I've simply mapped multiple fields for each document, like:
"text_val": {
  "type": "text",
  "fields": {
    "en": {
      "type": "text",
      "analyzer": "english"
    },
    "it": {
      "type": "text",
      "analyzer": "italian"
    }
  }
}

And then just search both fields for every query. This works well and is good enough for many applications. However I'm sure Google is doing something much more complex, certainly language identification on both the indexed documents and the query. In case you want to do language identification, I've used python langid before and had good results.
The problem you're going to face using elasticsearch for this kind of thing, in my experience, isn't the multi-language part, but that the analyzers for languages other than English don't always work as well as you would like. You may have to write a custom analyzer, with rules to handle lots of special cases, and tuned for your specific dataset.


text:
Q: example of a non differentiable manifold Take the manifold: The graph of $|x|$ on $(-1,1)$, with the induced topology from $\mathbb{R}^2$. This is a topological manifold, which is homeomorphic to $(-1,1)$ by projection. Is it a differentiable manifold? I believe it is, because we can take an atlas with only the projection, and then we will have only one transition map which is the identity, and therefore differentiable. But I'm not sure I get the definition of a differentiable manifold right...
Thanks!

A: You're correct that you can define a smooth structure via the projection map - this should come as no surprise, since the homeomorphic space $(-1,1)$ is obviously a smooth manifold. The reason you're feeling uneasy is that the topological embedding into $\mathbb{R}^2$ is not smooth - there is a corner at the origin.


text:
Q: Не работает кэширование в nginx Использую nginx в качестве прокси-сервера для бэкенда, который в свою очередь сильно зависит от внешнего API, который зачастую отвечает за 100-200 миллисекунд, но иногда там случаются сбои и API может отвечать по 1-2 секунды. Меня это не устраивало и я решил настроить кэширование в nginx таким образом, чтобы он всегда выдавал страницу из кэша, но в фоновом режиме ходил к бэкенду и обновлял содержимое кэша. Но почему-то это не работает.
Слева время ответа nginx, справа - время ответа бэкенда. Следуя логике nginx, время Request Time должно было упасть и стабилизироваться, в то время как Upstream Response Time должно было остаться неизменным - nginx отдаёт просроченную страницу из кэша моментально, а в фоне идёт обновлять кэш для последующих пользователей. Но ситуация не поменялась ни капли и графики по-прежнему идентичны. 13 февраля видно небольшое увеличение времени ответа - это я включил фоновое кэширование и удалил папку /var/cache/nginx.

Моя настройка кэша:
proxy_cache all;
proxy_cache_valid 200 301 302 1h;
proxy_cache_valid 404 500 502 504 30s;
proxy_cache_lock on;
proxy_cache_background_update on;
proxy_cache_use_stale error timeout updating;

Я что-то настроил не так или я просто неправильно интерпретирую графики?


text:
Q: Firebase Bucketname Not Available I'm having a weird problem with Firebase in Android. I'm trying to upload a photo to Firebase Storage and I'm getting the following error:
E/UncaughtException: java.lang.IllegalArgumentException: The supplied bucketname is not available to this project.

At this line of code:
StorageReference mStorageRef = mFirebaseStorage.getReferenceFromUrl("gs://mooseandroid-a9f96.appspot.com");

I'm sure that the bucketname is the same as the one in the console. I even tried with a bucketname that works fine in iOS with Swift. I also changed the rules to public so anyone can read and write to this storage bucket. The realtime database works fine for this project. I'm running out of options right now, don't even know what else I could be trying.
Here's the whole piece of code:
FirebaseStorage mFirebaseStorage = FirebaseStorage.getInstance();
StorageReference mStorageRef = mFirebaseStorage.getReferenceFromUrl("gs://mooseandroid-a9f96.appspot.com");
final StorageReference photoRef = mStorageRef.child("posts_images/mooseImg" + getCurrentDateTime() + ".jpg");
UploadTask uploadTask = photoRef.putBytes(data);
uploadTask.addOnFailureListener(new OnFailureListener() {
    @Override
    public void onFailure(@NonNull Exception exception) {
    // Handle unsuccessful uploads
    }
}).addOnSuccessListener(new OnSuccessListener<UploadTask.TaskSnapshot>() {
    @Override
    public void onSuccess(UploadTask.TaskSnapshot taskSnapshot) {
    // taskSnapshot.getMetadata() contains file metadata such as size, content-type, and download URL.
});

And here's the whole error:
E/UncaughtException: java.lang.IllegalArgumentException: The supplied bucketname is not available to this project.
     at com.google.android.gms.common.internal.zzaa.zzb(Unknown Source)
     at com.google.firebase.storage.FirebaseStorage.zzz(Unknown Source)
     at com.google.firebase.storage.FirebaseStorage.getReferenceFromUrl(Unknown Source)
     at com.moose.android.AddPostActivity.onClick(AddPostActivity.java:163)
     at android.view.View.performClick(View.java:5702)
     at android.widget.TextView.performClick(TextView.java:10888)
     at android.view.View$PerformClick.run(View.java:22541)
     at android.os.Handler.handleCallback(Handler.java:739)
     at android.os.Handler.dispatchMessage(Handler.java:95)
     at android.os.Looper.loop(Looper.java:158)
     at android.app.ActivityThread.main(ActivityThread.java:7229)
     at java.lang.reflect.Method.invoke(Native Method)
     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1230)
     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1120)

A: The documentation for getReferenceFromUrl(String fullUrl) states:

An error is thrown if fullUrl is not associated with the FirebaseApp
  used to initialize this FirebaseStorage

Use this code to see the bucket name in your FirebaseApp:
    FirebaseOptions opts = FirebaseApp.getInstance().getOptions();
    Log.i(TAG, "Bucket = " + opts.getStorageBucket());

I expect it will not be mooseandroid-a9f96.appspot.com and will instead be the storage_bucket value in the project_info section of your google-services.json file:
  "project_info": {
    "project_number": "816275527980",
    "firebase_url": "https://project-8693710910123456789.firebaseio.com",
    "project_id": "project-8693710910123456789",
    "storage_bucket": "project-8693710910123456789.appspot.com"
  },

A: If anyone changes the bucket url afterwards just clean and rebuild the android project, it solved the issue for me.
For cleaning go to Build tab on top nav bar in android studio -> Click Clean Project.
For rebuilding again go to Build tab on top nav bar in android studio -> Click Rebuild Project.


text:
Q: Too many quotation marks in mysql my problem is too many quotation marks.
$come = mysql_query("SELECT * FROM users WHERE email="$_POST['email']" and password="$_POST['password']" ");

Then I tried this but it doesn't work ...
$come = mysql_query("SELECT * FROM users WHERE email="/$_POST['email']/" and password="/$_POST['password']/" ");

Please help me :/

A: Solution to your question:
<?php
$come = mysql_query(sprintf('SELECT * FROM users WHERE email="%s" and password="%s"', $_POST['email'], $_POST['password']));

But you should never use code like this. You have a SQL Injection in your code. Rewrite this using PDO.
<?php

$pdo = new PDO('mysql:host=127.0.0.1;dbname=mydb', 'user', 'password');
$stmt = $pdo->prepare('SELECT * FROM users WHERE email=:email and password=:password');
$stmt->execute(['email' => $_POST['email'], 'password' => $_POST['password']]);
$result = $stmt->fetchAll();

More:
http://php.net/manual/ru/pdo.prepared-statements.php

A: $come = mysql_query("SELECT * FROM users WHERE email='".$_POST['email']."' and password='".$_POST['password']."' ");

Try this it should fix your issue. But mysql is deprecated consider mysqli or pdo.


text:
Q: DEB: "Provides:" field ignored I need to replace a package with a custom one, which gets its own name (foo-origpackage). To allow it to be used as drop-in replacement, I added the Provides: origpackage line to the control file. apt-cache show foo-origpackage lists the "Provides" entry just fine. However, when I  want to install a file depending on origpackage, it fails ("Package origpackage not installed").
Is there some distinction between "real" and virtual packages I'm missing?
EDIT:
To be precise, what I want to replace is xen-utils-common for Squeeze. My tao-xen-utils-common has the following control file:
Source: tao-xen-utils-common
Section: kernel
Priority: optional
Maintainer: Creshal <administration@tao.at>
Build-Depends: debhelper
Standards-Version: 3.8.0
Homepage: http://tao.at

Package: tao-xen-utils-common
Architecture: all
Depends: gawk, lsb-base, udev, xenstore-utils, tao-firewall
Provides: xen-utils-common
Conflicts: xen-utils-common
Replaces: xen-utils-common
Description: Xen administrative tools - common files (modified)
 The userspace tools to manage a system virtualized through the Xen virtual
 machine monitor.
 Modified for use with TAO Firewall.
Installing xen-utils-4.0 fails, however:
foo@bar# apt-cache showpkg tao-xen-utils-common
Package: tao-xen-utils-common
Versions:
4.0.0-1tao1 (/var/lib/apt/lists/repo.tao.at_dists_stable_main_binary-amd64_Packages) (/var/lib/dpkg/status)
 Description Language:
                 File: /var/lib/apt/lists/repo.tao.at_dists_stable_main_binary-amd64_Packages
                  MD5: 7c2503f563fca13b33b4eb3cbcb3c129

Reverse Depends:
  tao-firewall,tao-xen-utils-common
  tao-firewall,tao-xen-utils-common
Dependencies:
4.0.0-1tao1 - gawk (0 (null)) lsb-base (0 (null)) udev (0 (null)) xenstore-utils (0 (null)) tao-firewall (0 (null)) xen-utils-common (0 (null)) xen-utils-common (0 (null))
Provides:
4.0.0-1tao1 - xen-utils-common
Reverse Provides:

foo@bar# apt-get install xen-utils-4.0
Reading package lists... Done
Building dependency tree
Reading state information... Done
The following extra packages will be installed:
  xen-utils-common
Suggested packages:
  xen-docs-4.0
The following packages will be REMOVED:
  tao-xen-utils-common
The following NEW packages will be installed:
  xen-utils-4.0 xen-utils-common
Edit:foo@bar# apt-cache policy xen-utils-4.0
xen-utils-4.0:
  Installed: (none)
  Candidate: 4.0.1-4
  Version table:
     4.0.1-4 0
        500 http://ftp.at.debian.org/debian/ stable/main amd64 Packages
     4.0.1-4 0
        500 http://security.debian.org/ stable/updates/main amd64 Packages

A: I spent quite some time investigating this same issue and I reached the conclusion that the the "Provides" is ignored because xen-utils-4.0 has a versioned "Depends" on xen-utils-common.
Quoting the Debian Policy Manual:

A Provides field may not contain version numbers, and the version number of the concrete package which provides a particular virtual package will not be considered when considering a dependency on or conflict with the virtual package name.

If the Depends were unversioned, the provides would have been satisfied, however a Provides, which is always unversioned, can never satisfy a versioned Depends.
Unfortunately, I do not have a solution apart from what you have already proposed: keeping the same package name and having a higher version number.

A: The section of the Debian Policy Manual quoted in @cavedon's answer is still unchanged, but outdated. Since dpkg 1.17.11 setting a version on a provided package is possible. From the changelog:

*

*Add versioned Provides support:

*

*Add a new dpkg --assert-versioned-provides command.

*Packages can provide a specific version, "virtual (= 1.0)" which will
  be honored, previously it would just be accepted when parsing.

*Non-versioned virtual packages will not satisfy versioned dependencies.

*Versioned virtual packages will satisfy non-versioned dependencies.
  Based on skeletal code by Ben Collins .
  Closes: #7330, #24934, #112131, #134582, #180316

So to solve the original example, in the control file you add a line
Version: *version*
(replacing *version* with the actual version) and replace the line
Provides: xen-utils-common
with
Provides: xen-utils-common (= ${binary:Version})

A: Eventually mitigated the problem by renaming it back to xen-utils-common with a custom version, and making the package requiring the customization conflict higher versions. Thus, updates of xen-utils-common are blocked until I updated both packages.
Kinda works, but I'm open for better solutions.

A: "Provides" is only for virtual packages. If you want to replace a real package, you need to use "Replaces" and probably also "Conflicts" if the package provides the same files.
See Debian Policy, chapter 7.


text:
Q: In a PHP5 class, when does a private constructor get called? Let's say I'm writing a PHP (>= 5.0) class that's meant to be a singleton.  All of the docs I've read say to make the class constructor private so the class can't be directly instantiated.
So if I have something like this:
class SillyDB
{
  private function __construct()
  {

  }

  public static function getConnection()
  {

  }
}

Are there any cases where __construct() is called other than if I'm doing a
new SillyDB()

call inside the class itself?
And why am I allowed to instantiate SillyDB from inside itself at all?

A: __construct() would only be called if you called it from within a method for the class containing the private constructor. So for your Singleton, you might have a method like so:
class DBConnection
{
   private static $Connection = null;

   public static function getConnection()
   {
      if(!isset(self::$Connection))
      {
         self::$Connection = new DBConnection();
      }
      return self::$Connection;
   }

   private function __construct()
   {

   }
}

$dbConnection = DBConnection::getConnection();

The reason you are able/would want to instantiate the class from within itself is so that you can check to make sure that only one instance exists at any given time. This is the whole point of a Singleton, after all. Using a Singleton for a database connection ensures that your application is not making a ton of DB connections at a time.

Edit: Added $, as suggested by @emanuele-del-grande


text:
Q: exim, variable string expansion How can I get the list of local domains from a forward file?
An example of /etc/exim4/forwards:
a@test.com: a@lala.com
# ignore this line
b@test.com: a@example.com
b@hugo.com: hugo@example.com

Here the string expansion (or what ever it's called g) should return test.com : hugo.com.
I assume it can be done with readfile and map, but I can't get it to work.

A: I have something that almost works the way you want it.  What this expansion does is:

*

*Slurp in the file, using ; as the separator.

*Exclude any lines with # in them (i.e. comments).

*It should skip blank lines, but my regex isn't matching, it still includes those blank lines, so I just removed it and left the or{{}{}} block in there.

*Extract the item before the : on each line, and extract the domain from that.

*Mash it all up into the list.

I don't profess this to be exactly what you need, but it shows how the lists can be parsed and grep'd.
CentOS58[root@ivwm41 exim]# more test_list.cf
a@test.com: a@lala.com
# ignore this line
b@test.com: a@example.com
b@hugo.com: hugo@example.com

CentOS58[root@ivwm41 exim]# exim -be '${reduce {<; ${readfile{/etc/exim/test_list.cf}{;}} } {} {${if  or{ {match{$item}{#}} {match{$item}{#}} } {$value} {$value:${sg {${extract{1}{:}{$item}}} {^.*@}{} }}}}}'
:test.com:test.com:hugo.com

If you spread out the expansion logically into its individual parts, it looks like this:
exim -be '${reduce {<; ${readfile{/etc/exim/test_list.cf}{;}} }
             {}
             {${if or{ {match{$item}{#}} {match{$item}{#}} }
                 {$value}
                 {$value:${sg{${extract{1}{:}{$item}}} {^.*@} {}}}}
             }
           }
         '

One thing that still needs to be fixed is that leading : should not be there.  I'm not 100% sure why it is there :-/ and I don't really have the time to delve any further into it.  The logic needs to be massaged a bit to catch whatever condition is causing that leading colon to appear and then the result should be a domain list that you can use as a condition.


text:
Q: Django Queryset - get last related object and filter by it's data I have two Django Models:
class Person(models.Model):
    unique_id = models.CharField()

class PersonData(models.Model):
    person = models.ForeignKey('Person')
    phone = models.CharField()
    email = models.CharField()
    date = models.DateTimeField()

New PersonData objects are added when their information changes, but old ones are kept. And then I want to have a filter, which will filter persons by their data from the latest PersonData object they are related to.
I have the following queryset:
filter_email = "email@example.com"
filter_phone = "964477425"

qs = Person.objects.all()

if filter_email:
    qs = qs.filter(persondata__email__icontains=filter_email)
if filter_phone:
    qs = qs.filter(persondata__phone__icontains=filter_phone)

But that filter searches through every PersonData object associated with Person. Is it possible to restrict this filter to only the latest PersonData object?

A: It is a popular type of query where latest/oldest entry against unique values of one field are desired.
I would like to say that if you think over what other answers suggest deeply, you'll understand they do not serve the purpose.
There is no way to fetch the whole object with desired filter in single django query (Note that it is possible to get one field but not all fields, also it is possible to fetch all fields in raw **sql** queries).
One of the ways I know to tackle this problem is to have a foreign-key in Person to the latest PersonData object, and update it each time new object of PersonData is created.

A: So you could try query to PersonData model:
qs = PersonData.objects.filter()

if filter_email:
    qs = PersonData.objects.filter(email__icontains=filter_email)
if filter_phone:
    qs = PersonData.objects.filter(phone__icontains=filter_phone)

# Cache Person object and pick the last
qs = qs.select_related('person').last()


text:
Q: How to Switch between activities with viewflipper In my android app I am using two activities and I want to make a smooth switch between these activities. I have seen many reference tutorials tells that ViewFlipper can make a smooth switch between views in one activity. So I would like to know if I can use ViewFlipper to switch between activities or Is there any other possible way to do this. At present I am just using button clicks that will start an activity but the switch doesn't look good.
I would be grateful for any suggestions.
Thank You,
Baluk

A: ViewFlipper can only handle views not Activities. If there is a way to wrap an activity in a view then you might be able to emulate it but I fear the navigation stack would get confusing.

A: What you actually want to do is to set a custom or just another type of animation for when the Activity is being called or ended.
The answer is yes. You can do that using the overridePendingTransition() method right after calling one of the startActivity() flavors or on the finish() method.


text:
Q: how to if else on controller for search function? So i have a controller with a basic search function and i want to know when a user click the search button if there is data exist i want it to return the same page with error message, but if data not exist i want return another page. how can i do that? my code as below:
controller:

public function search(Request $request, $companyID, $entityType)
 {
  $data = [];
  $intentTypes = DiraQuestion::select('intent')->where('company_id', $companyID)->groupBy('intent')->get();

  foreach ($intentTypes as $intent)
  {
   $data[$intent->intent] = $intent->intent;
  }

  $q = $request->q;
     $user = DiraQuestion::select('eVal')->where('company_id', $companyID)->where('eType', $entityType)->where('eVal','LIKE','%'.$q.'%')->groupBy('eVal')->get();

     return view('AltHr.Chatbot.addType', compact('data','entityType','companyID'))->withDetails($user)->withQuery($q);
 }

my current view page which shows if exist and if not exist shows form:

@if(isset($details))

       @foreach($details as $user)

{{$user->eVal}} is already included!

                @endforeach

      @if($details->isEmpty())
      <form action="{{action('AltHr\Chatbot\ChatbotController@addQType', [$companyID, $entityType])}}" method="post">
       {{csrf_field()}}

         New Type
         <input type="text" class="form-control" name="entityValue" placeholder="{{$query}}" value="{{$query}}" required readonly/>

           Synonyms:
           <input type="text" class="form-control" name="syn" placeholder="Enter Synonyms" />

*Enter All Synonyms Separating With ','

        <button type="submit" class="btn alt-btn-green alt-btn btn-xs">Save</button>

        test

       @endif
      </form>
      @endif

@endif

route:

Route::post('search/{companyID}/{entityType}','Chatbot\ChatbotController@search');

as you can see currently if data exist, it shows error message on the same page, but if no data it shows a form on the same page itself.. i want it to route to another page when there is no data found.

A: If you want to include another snippet inside of your @if then you can do so like this:
@include('route.to.view')

Which will search for the blade view in that url and insert the html in case when there is $data present


text:
Q: R devtools and packages dependencies in DESCRIPTION Remotes I would like to use a dev version of a package in my own package.
As detailed in devtools vignette, I included the following line of code in the DESCRIPTION file of my package:
Remotes: SciViews/svDialogs
tried also:
Remotes: SciViews/svDialogs@v1.0.2
Unfortunately, that dependency is not installed  prior to the installation of my package. Running, devtools::install_deps() does not install that dependency, but installs any missing dependency in Imports.
On the other hand devtools::install_github("SciViews/svDialogs") works as expected and installs the dev version of the package.
Not sure if I am missing something important. Any ideas?
Thanks

A: Just in case anyone else runs in the some problem...
Solution was provided by @jennybc on the package page.
The dependency need to be listed in the Imports section of the DESCRIPTION too. This is actually stated in the vignette but I somewhat missed.


text:
Q: run an EAS dev-client build on actual device for developing I recently added an NPM package for camera which impacts the Native Modules, so it's not supported by Expo out of the box.  Now I am sending a build to EAS and then running that IPA file on my Simulator locally.  The issue is that the VideoCamera is not supported by the iOS simulator
I am creating a development build which is sent to EAS, as described in my eas.json:
"development": {
      "extends": "staging",
      "developmentClient": true,
      "distribution": "internal", // tried with & without this line
      "ios": {
        "simulator": true
      }
    }

Then I run npx expo start --dev-client so that i can tap into the expo-dev-client can be hooked into my app.  It runs fine on my simulator, but when needing to access the camera for video, we need to use a physical device due to limitation stated above.
How can I run the EAS image on my physical device?  Or how can I run Expo locally, which can still manage the Native Modules impacted by the new NPM lib?


text:
Q: Highcharts refresh tooltip on button click not working with boost modul I use Highcharts to draw my charts with the boost modul. I have multiple data series, with a shared tooltip.The X-axis values are the same for all data series. When I now click on a button, I want to show the shared tooltip. My input is the index of the x-axis point. Here my code, for simplification I use two small data arrays and I want to show the tooltip on index=2:
var chart=$('#container').highcharts({
    boost: {
             useGPUTranslations: true,
             seriesThreshold: 1,
           },
    series: [{
        name: 'Data1',
        data: [24.2, 24.6, 26.7, 28.6, 30.1, 29.0, 27.5, 27.2, 27.4, 28.2, 27.4, 25.6]
    }, {
        name: 'Data2',
        data: [14.1, 16.9, 22.4, 28.6, 32.8, 33.8, 31.0, 29.8, 29.2, 26.0, 20.3, 15.4]
    }],
    tooltip: {
        crosshairs: [true],
        shared: true,
    }
}).highcharts();

$('#showTooltipID').on('click', function() {
chart.tooltip.refresh([chart.series[0].points[2], chart.series[1].points[2]]);
  });

Example with seriesThreshold: 1, http://jsfiddle.net/hu5qatjn/34/ -> not working!
Example with seriesThreshold: 3, http://jsfiddle.net/hu5qatjn/35/ -> working!(boost modul not active)
So what am I doing wrong with the boost modul?

A: While using the boost module the point is not rendered on the initial load to save some performance, that's why your current approach doesn't work - the point object doesn't have enough data/properties to trigger the tooltip. We need to render the point programmatically before will be passed to the tooltip.refresh function.
$('#showTooltipID').on('click', function() {
    const series1 = chart.series[0],
                series2 = chart.series[1],
                point1 = series1.getPoint(series1.points[2]),
                point2 = series2.getPoint(series2.points[2]);

  chart.tooltip.refresh([point1, point2]);
});

Demo: http://jsfiddle.net/BlackLabel/8gos3cx2/


text:
Q: Динамические структуры данных
Задание: 1. Создание списка.
  2. Добавление элемента в список: • в начало списка; • в конец списка; • после элемента с заданным номером; • после элемента с заданным
  ключом.
  3. Вывод содержимого списка на экран.
  4. Удаление элемента из списка: • из начала списка; • из конца списка; • элемента с заданным номером; • элемента с заданным ключом.
  5. Упорядочивание элементов в списке по выбранному признаку.   Почему код не работает?

#include <stdio.h>
    #include <conio.h>
    #include <stdlib.h>
    #define TRUE 1
    struct List
    {
     int x;
     struct List * Next;
    };
    struct List * CreateList(void);
    void DisplayList( struct List* );

    void RemoveTermBegin( struct List** );
    void RemoveTermTag( struct List* );
    void RemoveTermEnd( struct List* );
    void AddTermBegin( struct List** );
    void AddTermEnd(struct List* );
    void AddTermTag(struct List* );
    void FreeList(struct List** );
    int main(void)
{
 struct List* Begin;
 char Key;
 while(TRUE)
 {
 printf( "\nEnter the number- the mode of "
"operations with Lists: "
 "\n 1 - FORMATION OF THE LIST"
 "\n 2 - VIEWING OF CONTENTS OF"
"THE LIST"
 "\n 3 - REMOVE THE ELEMENT FROM "
"THE BEGIN OF LIST"
 "\n 4 - REMOVE THE ELEMENT FROM "
"THE MIDLE OF LIST"
 "\n 5 - REMOVE THE ELEMENT FROM "
"THE END OF LIST"
 "\n 6 - ADD THE ELEMENT IN THE "
"BEGIN OF LIST"
 "\n 7 - ADD THE ELEMENT IN THE "
"END OF LIST"
 "\n 8 - ADD THE ELEMENT AFTER "
"ELEMENT-KEY OF LIST"
 "\n 9 - END OF WORK\n");
 fflush( stdin );
 scanf("%c",&Key);
clrscr();
 switch (Key)
 {
 case '1':
 clrscr();
 Begin = CreateList();
 printf("\n\nPress any key to return in "
"the menu...\n");
 getch();

 clrscr();
 break;
 case '2':
 clrscr();
 DisplayList(Begin);
 printf("\n\nPress any key to return in "
"the menu...\n");
 getch();
 clrscr();
 break;
 case '3':
 clrscr();
 RemoveTermBegin(&Begin);
 printf("\n\nPress any key to return in "
"the menu...\n");
 getch();
 clrscr();
 break;
 case '4':
 clrscr();
 RemoveTermTag(Begin);
 printf("\n\nPress any key to return in "
"the menu...\n");
 getch();
 clrscr();
 break;
 case '5':
 clrscr();
 RemoveTermEnd(Begin);
 printf("\n\nPress any key to return in "
"the menu...\n");
 getch();
 clrscr();
 break;
 case '6':
 clrscr();
 AddTermBegin(&Begin);
 printf("\n\nPress any key to return in "
"the menu...\n");
 getch();

 clrscr();
 break;
 case '7':
 clrscr();
 AddTermEnd(Begin);
 printf("\n\nPress any key to return in "
"the menu...\n");
 getch();
 clrscr();
 break;
 case '8':
 clrscr();
 AddTermTag(Begin);
 printf("\n\nPress any key to return in "
"the menu...\n");
 getch();
 clrscr();
 break;
 case '9':
 FreeList(&Begin);
 DisplayList(Begin);
 printf("\n\nPress any key to "
"exit...\n");
getch();
 return 0;
 default:
 clrscr();
 printf("\nIncorrect input!!! Try "
"again!!!\n");
 printf("\n\nPress any key to return in "
"the menu...\n");
 getch();
 clrscr();
 break;
 }
 }
}
struct List* CreateList(void)
{
 struct List* Begin = NULL, *Previos = NULL,

*Current= NULL;
 char Ok = 'y';
 while (Ok == 'y')
 {
 printf("\nEnter the numbers of List: ");
 Current =
( struct List*)malloc(sizeof(struct List));
 if (Begin==NULL)
Begin = Current;
 else
Previos -> Next = Current;
 Previos = Current;
 scanf("%d",&Current -> x);
 fflush( stdin );
 printf("\nContinue? (Y/N):");
 scanf("%c",&Ok);
 }
 Previos -> Next = NULL;
 return Begin;
}
void DisplayList(struct List* Begin)
{
 struct List* Current = Begin;
if ( Begin == NULL )
 {
 printf("List is empty\n");
 return;
 }
 printf("\nThe List of numbers:\n");
 while (Current)
 {
 printf("%d ",Current -> x);
 Current = Current -> Next;
 }
 printf("\n");
}

void RemoveTermBegin(struct List** Begin)
{
 struct List** Current = Begin;
 *Begin = (*Current) -> Next;
 free(Current);
}
void RemoveTermTag(struct List* Begin)
{
 struct List* Current = Begin, *Previos = Current;
 int NumberTag;
 printf("\nEnter number-key: ");
 scanf("%d",&NumberTag);
 while ( Current )
 {
 if ( Current -> x == NumberTag )
 {
 Previos -> Next = Current -> Next;
 free(Current);
 Current = Previos -> Next;
 }
 else
 {
 Previos = Current;
 Current = Current -> Next;
 }
 }
}
void RemoveTermEnd(struct List* Begin)
{
 struct List* Current = Begin, *Previos;
 while (Current -> Next)
 {
 Previos = Current;
 Current = Current -> Next;
 }
 Previos -> Next = NULL;
 free(Current);
}
95
void AddTermBegin(struct List** Begin)
{
 struct List* Current =
(struct List*)malloc(sizeof(struct List));
 printf("\nEnter number: ");
 scanf("%d",&Current -> x);
 Current -> Next = *Begin;
 *Begin = Current;
}
void AddTermEnd(struct List* Begin)
{
 struct List* Current = Begin, *Previos;
 while (Current)
 {
 Previos = Current;
 Current = Current -> Next;
 }
 Current = (struct List*)malloc(sizeof(struct List));
 Previos -> Next = Current;
 printf("\nEnter the number:\n");
 scanf("%d",&Current -> x);
 Current -> Next = NULL;
}
void AddTermTag(struct List* Begin)
{
 struct List* Current = Begin, *Previos = Current;
 int NumberTag;
 printf("\nEnter number-tag: ");
 scanf("%d",&NumberTag);
 while ( Current )
 {
 if ( Current -> x == NumberTag )
 {
 Previos = Current;
 Current =
(struct List*)malloc(sizeof(struct List));

 Current -> Next = Previos -> Next;
 Previos -> Next = Current;
 printf("\nEnter the number:\n");
 scanf("%d",&Current -> x);
 break;
 }
 else
 {
 Previos = Current;
 Current = Current -> Next;
 }
 }
}
void FreeList(struct List** Begin)
{
 struct List* Current = *Begin;
 while (Current)
 {
 *Begin = (*Begin) -> Next;
 free(Current);
 Current = *Begin;
 }
}

A: Функция clrscr() работает только на компиляторе Borland (Turbo C). Но вы можете использовать функцию system("cls").


text:
Q: Decomposing a particular fraction I am working on Problem I.4.7 in Lang's Complex Analysis. It asks to find the convergence of
\begin{equation}\sum_\limits{n=1}^\infty \frac{z^{n-1}}{(1-z^n)(1-z^{n+1})}.\end{equation} The hint says to multiply and divide each term by $1-z$ and do a partial fraction decomposition to get a telescoping sum. I tried this and got
\begin{equation}\frac{A}{(1-z^n)(1-z)} + \frac{B}{(1-z^{n+1})(1-z)} + \frac{C}{(1-z^n)(1-z^{n+1})} = \frac{z^{n-1}-z^n}{(1-z^n)(1-z^{n+1})(1-z)}.\end{equation}
By inspection, I found that
\begin{equation}
\begin{split}
A&= 0\\
B&=-\frac{1}{z}+1 \\
C&= \frac{1}{z}
\end{split}
\end{equation}
is a solution. This however, does not give me a telescoping sum. The resources I have found only talk about partial fraction decomposition after reducing to irreducible quadratics, which does not seem tenable here. Are there any more general techniques to partial fraction decomposition might help here?
Edit: Here is the decomposition the above obtains, in case it is useful:
\begin{equation}
\frac{z^{n-1}}{(1-z^n)(1-z^{n+1})}=\frac{1}{(1-z^{n+1})(1-z)} - \frac{1}{z(1-z^{n+1})(1-z)} + \frac{1}{z(1-z^{n+1})(1-z^n)}
\end{equation}

A:
The hint says to multiply and divide each term by $1-z$ and do a partial fraction decomposition

Not entirely sure what the hint meant to say, but the following telescopes nicely regardless:
$$
\begin{align}
\frac{z^{n-1}}{(1-z^n)(1-z^{n+1})} &= \frac{z^{n-1}}{(1-z)^2(1+z+\ldots+z^{n-1})(1+z+\ldots+z^{n-1}+z^n)} \\[5px]
 &= \frac{z^{n-1}}{(1-z)^2} \cdot \frac{1}{z^n}\left(\frac{1}{1+z+\ldots+z^{n-1}} - \frac{1}{1+z+\ldots+z^{n-1}+z^n}\right)
\end{align}
$$
Then:
$$
\begin{align}
z(1-z)^2\sum_\limits{n=1}^{N} \frac{z^{n-1}}{(1-z^n)(1-z^{n+1})} &= \sum_\limits{n=1}^{N}  \left(\frac{1}{1+z+\ldots+z^{n-1}} - \frac{1}{1+z+\ldots+z^n}\right) \\[5px]
 &= 1 - \frac{1}{1+z+\ldots+z^N} \\[5px]
 &= 1 - \frac{1-z}{1-z^{N+1}} \\[5px]
 &= \frac{z(1-z^N)}{1-z^{N+1}}
\end{align}
$$

A: You may also ignore the hint and perform the following formal manipulations:
$$ \frac{x^{n-1}}{(1-x^n)(1-x^{n+1})}=\sum_{a,b\geq 0}x^{(a+b+1)n+(b-1)} $$
$$ \sum_{n\geq 1}\sum_{a,b\geq 0}x^{(a+b+1)n+(b-1)}=\sum_{a,b\geq 0}\frac{x^{a+2b}}{1-x^{a+b+1}}=\sum_{m\geq 0}r(m)\,x^m $$
where $r(m)$ is the number of $(a,b,c)\in\mathbb{N}^3$ such that $(c+1)a+(c+2)b+c = m$.
$r(m)$ is clearly less than $(m+1)^3$, hence the radius of convergence of the last power series is at least one, and it cannot be more than one since for any prime $p$ the $p$-th partial sum of the original series has a singularity at $x=\exp\left(\frac{2\pi i}{p}\right)$.


text:
Q: Add GroupDescription dynamically? I'm looking for a way to add GroupDescriptions dynamically, in particular in the viewmodels, I actually add GroupDescription behind code like this:
public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();

        List<Country> items = new List<Country>();
        items.Add(new Country() { Name = "Italy", League = new League { Name = "Serie A" } }); // Added "new League"
        items.Add(new Country() { Name = "Italy", League = new League { Name = "Serie B" } });
        items.Add(new Country() { Name = "England", League = new League { Name = "Premiere League" } });
        items.Add(new Country() { Name = "Spain", League = new League { Name = "Primeira Division" } });
        lvUsers.ItemsSource = items;

        CollectionView view = (CollectionView)CollectionViewSource.GetDefaultView(lvUsers.ItemsSource);
        PropertyGroupDescription groupNations = new PropertyGroupDescription("Name");
        view.GroupDescriptions.Add(groupNations);
        PropertyGroupDescription groupCompetions = new PropertyGroupDescription("League.Name"); // Changed "League" to "League.Name"
        view.GroupDescriptions.Add(groupCompetions); // Fixed the variable name here

        lvUsers.ItemsSource = view;
    }
}

public struct League
{
    public string Name { get; set; }
}

public struct Country
{
    public string Name { get; set; }
    public League League { get; set; } // added getter and setter
}

and this is my xaml:
<Window x:Class="GroupBox_Header.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:GroupBox_Header"
    mc:Ignorable="d"
    Title="MainWindow" Height="350" Width="525">
<Grid Margin="10">
    <ListView Name="lvUsers">
        <ListView.View>
            <GridView>
                <GridViewColumn Header="Home Team" Width="50" DisplayMemberBinding="{Binding HomeTeam}" />
                <GridViewColumn Header="Away Team" Width="50" DisplayMemberBinding="{Binding AwayTeam}" />
            </GridView>
        </ListView.View>

        <ListView.GroupStyle>
            <GroupStyle>
                <GroupStyle.ContainerStyle>
                    <Style TargetType="{x:Type GroupItem}">
                        <Setter Property="Template">
                            <Setter.Value>
                                <ControlTemplate>
                                    <Expander IsExpanded="True">
                                        <Expander.Header>
                                            <StackPanel Orientation="Horizontal">
                                                <TextBlock Text="{Binding Name}" FontWeight="Bold" Foreground="Gray" FontSize="22" VerticalAlignment="Bottom" />
                                                <TextBlock Text="{Binding ItemCount}" FontSize="22" Foreground="Green" FontWeight="Bold" FontStyle="Italic" Margin="10,0,0,0" VerticalAlignment="Bottom" />
                                                <TextBlock Text=" Items" FontSize="22" Foreground="Silver" FontStyle="Italic" VerticalAlignment="Bottom" />
                                            </StackPanel>
                                        </Expander.Header>
                                        <ItemsPresenter />
                                    </Expander>
                                </ControlTemplate>
                            </Setter.Value>
                        </Setter>
                    </Style>
                </GroupStyle.ContainerStyle>
            </GroupStyle>
            <GroupStyle>
                <GroupStyle.ContainerStyle>
                    <Style TargetType="{x:Type GroupItem}">
                        <Setter Property="Template">
                            <Setter.Value>
                                <ControlTemplate>
                                    <Expander IsExpanded="True">
                                        <Expander.Header>
                                            <StackPanel Orientation="Horizontal">
                                                <TextBlock Text="{Binding League}" FontWeight="Bold" Foreground="Gray" FontSize="22" VerticalAlignment="Bottom" />
                                            </StackPanel>
                                        </Expander.Header>
                                        <ItemsPresenter />
                                    </Expander>
                                </ControlTemplate>
                            </Setter.Value>
                        </Setter>
                    </Style>
                </GroupStyle.ContainerStyle>
            </GroupStyle>
        </ListView.GroupStyle>
    </ListView>
</Grid>

what I want to do is Bind in the ListView a collection that have the group description automatically.

A: If I understand your question right, you could either control the GroupDescriptions directly from the ViewModel, from code behind or create a custom ListView which let you bind to an ObservableCollection.
ViewModel
Use CollectionViewSource to get a hold of the CollectionView from the ViewModel. You could argue that this is an anti-pattern, but I think it is okay.
Code behind
Create a dependency property in you code behind that on change will update the group descriptors for the view. Then in you xaml bind that property to you ViewModel.
Custom ListView
Inherit from ListView and create a dependency property that let's you bind to an ObservableCollection.
Either way, you need to control different scenarios like, property
changed and collection changed.


text:
Q: SQL Server 2016 SSIS Conditionally Overwrite Text File Image the following scenario:
1. there are N number of jobs
2. the jobs write data to the same file once a day sequentially
3. task setting indicates whether the file should be overwritten or appended to
what i've tried thus far is using a conditional split in my data flow:

to test it out, the Case 1 & 2 are:

what actually happens is, conditional split tries to work out which data rows to send where, ends up sending all rows to one side and 0 rows to the other and both sides end up opening the file (i think), hence the errors:

i get that i'm misusing the conditional split here, but come one, it's 2017 outside, the must be a way to do this without resorting to Script tasks clearing the files?

A: Your problem - you are misusing Conditional Split; it is designed to manipulate data rows in a data flow and you are trying to manage control flow. Speaking of SSIS, it does not know in advance that you will use only one of Flat File Destinations; it tries to initialize both. By doing so SSIS tries to open the same file from two Destinations and fails with an error.
You can handle the task the SSIS way - manage control flow with tasks. In your case, the destination file should be appended or being overwritten. But the being overwritten can be viewed as being overwritten with zero lines and then being appended. Luckily for you, SSIS overwrites a file event no records are coming from a Data Flow.
So, before your dataflow which should always append data, you create another dataflow which always receives ZERO lines of data (columns in the set can be arbitrary) and Flat File Destination overwriting the file. Then use conditional execution of control flow with precedence constrains to execute this "File Cleanup DataFlow Task". You might also need to set DelayValidation=true on this "File Cleanup DataFlow Task".


text:
Q: HP Proliant 360 G4 hangs on Ethernet Boot Agent My server hangs on Ethernet Boot Agent. I can't access the BIOS.
It used to work fine. I can access the RAID controller, but it stops booting and fails to respond on key inputs once it gets to the Ethernet Boot Agent stage.

A: Have you tried resetting the BIOS? You may need to pull the CMOS battery if you can't get into the BIOS at all.

A: Get the last firmware CD from HP and make certain to upgrade everything if you have not already. This server was retired in March of 2006 so using the latest and greatest Smart Start/Firmware downloads from HP may not work for you.
This is the 8.60 firmware link: http://bizsupport1.austin.hp.com/bizsupport/TechSupport/SoftwareDescription.jsp?lang=en&cc=us&prodTypeId=0&prodSeriesId=397638&swItem=MTX-124beffbed3842cea0b9b3f962&prodNameId=3288140&swEnvOID=2026&swLang=8&taskId=135&mode=4&idx=1
you are not stating which O/S or 32/64 bit so make certain you get the smart start that pertains to your needs. They can be found under the Drivers and software link on the left on this page.
Also, your raid controller may have failed. There are 5 or so different RAID controllers for that machine. The 6i being the base card. If you run the firmware CD/DVD it will honk if it does not see the RAID controller.
Hope this helps


text:
Q: Split number into hundreds tens and units using C# What is the best way to split some given larger number into hundreds, tens and units in C#?
For example: If I enter number 43928 how can I get 40000 + 3000 + 900 + 20 + 8 on the output?

A: Linq implementation:
  String source = "43928";
  // "40000 + 30000 + 900 + 20 + 8"
  String result = String.Join(" + ", source
    .Select((item, index) => item.ToString().PadRight(source.Length - index, '0')));

A: You have to use the % operator. Example:
43928 / 10000 = 4; 43928 % 10000 = 3928; 3928 /1000 = 3; 3928 %1000 = 928, etc...

A: Something like this:
long x = 43928;
long i = 10;

while (x > i / 10)
{
    Console.WriteLine(x % i - x % (i / 10));
    i *= 10;
}

it will give you output
8
20
900
3000
40000

A: var x = "4328";
for (int i = 0; i < x.Length; ++i)
{
    var a = x.Substring(x.Length - i - 1, 1).PadRight(i+1, '0');
    Console.WriteLine(a);
}

if you need numbers use int.Parse(a)

A: The way with the parsing:
var myBigNumber = 43928.ToString();
var asCharachters = myBigNumber.ToArray();
for (var i = 0; i < asCharachters.Length; i++)
{
    var numberOfZeros = asCharachters.Length - i;
    var itemAsString = (asCharachters[i]).ToString().PadRight(numberOfZeros, '0');
    Console.WriteLine( Int32.Parse(itemAsString));
}

Outputs this:
40000
3000
900
20
8


text:
Q: Keep only one MySQL row with specific 2 fields I have a MySQL table with id, username, datetime and entry_id.
I'm logging access to each entry. But I need just one row with same username and entry_id, because I use it just for notifications. How could I programatically delete useless rows? (using PHP and/or SQL)
EDIT:
username is normal string,
ON DUPLICATE KEY wasn't working, because I want to check for duplicity just combination of same username and entry_id. I need just one row, with specific entry_id and username. I want to update just datetime. It's hard to explain :)
So, on each visit is insered new row. I just want datetime to update in every unique username and entry_id combination and not to create always new row.
Thank you for advance!

A: Just check for a previous entry in the database. If there is one, update it, if there is not an entry - insert one.

A: After reading your edit it sounds like you want something like:
SELECT username, entry_id FROM <table name> WHERE username = <username> AND entry_id = <entry_id>;

If you want to update the datetime column for that row:
UPDATE <table>  SET datetime = <yourdatetime> WHERE username = <username> AND entry_id = <entry_id>


text:
Q: Gridview and FrameLayout improperly places images Let's simplify this question.
What I did:

*

*I created a custom Gridview

*I created an adapter view of the framelayout

What I am trying to accomplish is something similar to Shelve view.
Now the result was a proper view of how the background of the gridview looks like with the proper image. However every other image just is a bit off on the height and position. I just seem to get the width right.
What are the possible reasons for the cause of improperly placed images?
How would I set out the proper positioning of a gridview for the adapter?

A: From what I remember of your original version of your question you were drawing custom backgrounds for your grid items in your GridView through dispatchDraw. I think what you're asking is why those backgrounds aren't lining up with your actual child views created by your adapter. If so, I'd have to see some code/layout to be sure, but it's likely that there's padding/margin so that the child views are not laid out exactly evenly. I'm not sure why it's every other image though.
If you're trying to create something like Shelves, you might just want to start by looking at the code there... It's open source after all.


text:
Q: Can we use "then" before the main verb? "... we'll then go."
Each page takes less than a minute to produce, although for colour pages four versions, once each for black, cyan, magenta and yellow are sent. The pages are then processed into photographic negatives and the film is used to produce aluminium printing plates ready for the presses. ROBOTS AT WORK

but I'm always use then between to phrases (when it is mean: next or after that).

Let me finish this job, then we'll go.

My question is: Can we use it before tha man verb?

Let me finish this job, we'll then go.

A:
Let me finish this job, then we'll go.
Let me finish this job, we'll then go.

I think, that "then" can go in either place; although I think most people would tend to put it at the start of the sentence. And I'd write it as two separate sentences, or use a semicolon after "job":

Let me finish this job. Then we'll go.
Let me finish this job; we'll then go.

See the Ngram Viewer.

A: Adverbs of time can be placed at the start of a sentence, after an auxiliary verb/modal, before a main verb or at the end of a sentence:
Soon we must make decision
we must soon make a decision
we must make a decision soon.
With so many choices of location, even small things affect the placement. In the case of your sentence, one of the things that may affect it is the rhythm. For this meaning, the word then must be a strong syllable, and in the first sentence go is also a strong syllable, giving a nice rhythm.

Let me finish this job, then we'll go.

The second sentence also requires go to be a strong syllable, which puts two strong syllables next to each other: we generally avoid this rhythm if possible.

Let me finish this job: we'll then go.

If we add some more information, for example a where clause, go loses its stress, which moves to the where clause, and we find this rhythm much more comfortable.

Let me finish this job: we'll then go and get something to eat.


text:
Q: Changing Class file in InstalledApps directory of WebSphere 5.1 I have application deployed in the server long back. I don't have workspace setup procedure were i am not able to set up the project successfully into my RAD 7 Workspace. But i knew the Class file to be changed. I have changed and replaced in the Installed Apps Folder in Websphere server. But Application not working as expected.The changes are not affected. I modified one of the Jsp file. The changes are affected.
Verified After restarting the server as well.
Can any one help me what would be the problem.
I see there is one option called Export in Admin Console.

A: I am afraid Websphere doesn't work like that.
The class files need to be loaded in memory of the deployment space (even after restart), but the jsp files are static can be loaded at run time.
I would do the following way:
(If I have the jar or the ear file)

*

*Change the extension to zip

*Open it with winzip or winrar

*Locate the folder where your class file is located

*Replace the file by a single drag and drop operation (it will replace automatically)

*Change back the extension

*Redeploy it in Websphere


text:
Q: How can I grep a process in BusyBox using ps I am getting below  error in jenkins pipeline when I try to run ps -ef|grep process command:
ps: unrecognized option: p
BusyBox v1.27.2 (2017-12-12 10:41:50 GMT) multi-call binary.
Usage: ps [-o COL1,COL2=HEADER]
Show list of processes
-o COL1,COL2=HEADER Select columns for displayI have Jenkins version 2.135 and

I have BusyBox v1.27.2
Can some one tell me how can I avoid this error for ps -ef|grep process without installing the alpine image

A: You can use
docker exec -it container_name ps -ef | grep process

or you can do ps -ef | grep process into your container by running docker exec -it container_name /bin/bash


text:
Q: Unary operator in .reduce() function I was reading a medium article and came across this code. It returns the object with the most experienced pilot using .reduce() . I can't wrap my head around the expression (oldest.years || 0) . Why not just use (oldest.years ) ?
var pilots = [
  {
    id: 10,
    name: "Poe Dameron",
    years: 14,
  },
  {
    id: 2,
    name: "Temmin 'Snap' Wexley",
    years: 30,
  },
  {
   id: 41,
   name: "Tallissan Lintra",
   years: 16,
 },
 {
   id: 99,
   name: "Ello Asty",
   years: 22,
 }
   ];

var mostExpPilot = pilots.reduce(function (oldest, pilot) {
  return (oldest.years || 0) > pilot.years ? oldest : pilot;
}, {});

console.log(mostExpPilot);

A: When we look at the documentation of Array.reduce https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce#parameters we can see that this is because the example code has an initialValue of {} which has no years property.
Same would be:
var mostExpPilot = pilots.reduce(function (oldest, pilot) {
  return oldest.years > pilot.years ? oldest : pilot;
}, { years: 0});


text:
Q: Get latest Changeset Number from Path in Build Workflow How can i get the latest changeset number of the current build working path in my build workflow?
I'd like do put the changeset number in the build number and the assembly version file of my projekt.

A: You will have to query tfs api version control for history of your item
http://msdn.microsoft.com/en-us/library/hh981750.aspx
In most basic form:
QueryHistory(
    "ServerPathToYourWorkspace",
    RecursionType.Full,
    1, //number of items returned
)

Not sure this is 1:1 in TFS2012 as in it was in 2010 you can get workspace from BuildDetails.Definition.Workspace.Mappings.
You can get access toVersionControlServer through BuildDetails team project collection calling
GetService<VersionControlServer>();

A: There is a sequence near the end of the standard template (you will probably want to move it up earlier in the template, before the compile) which is call "If Associate Changesets" inside of that is an Associate Changesets and Workitems activity. The result of that, or out argument, is called associatedChangesets which is an List of Changeset objects which you can then use as an InArgument to your own custom task and accomplish what you want. The Changset number is the Property ChangesetID on each of the Changeset objects.


text:
Q: I need help renaming an element in an array I'm doing a java project at school and we were giving the following problem:

rename – changes the name of an existing sheet
public int rename(String currentName, String newName)
rename is passed two sheet names. Renaming should only be performed if the currentName sheet name is in the list and the newName sheet name isn't. Otherwise rename does nothing (i.e. the list is unaffected).
  If the currentName is successfully changed to the newName then the method returns the index position of the sheet renamed. Otherwise it returns -1.

This is what I have so far
public int rename(String currentName, String newName) {
    int i = 0;
    for (i=0; i<SheetsNames.length; i++) {
        if (SheetsNames[i].equals(currentName)) {
            SheetsNames[i] = newName;
                return i;
        }
    }
    return -1;
}

I got the renaming part but I can't get it to not rename it as something with the same name

A: Loop through the SheetNames and store any instances of a currentName's index in a variable called index while also checking if the newName is present in the list. If there is an instance of newName automatically return -1. But if there is no newName in the list then an instance of currentName's index will be stored in the index variable if it is present. If there are none then the function returns -1 anyways because that is what index is initialized as.
public int rename(String currentName, String newName) {
    int index = -1;
    for (int i=0; i<SheetsNames.length; i++) {
        if (SheetsNames[i].equals(newName))
            return -1;
        if (SheetsNames[i].equals(currentName))
            index = i;
    }
    if (index != -1)
        SheetNames[index] = newName;
    return index;
}

A: Here is the solution.
1) Input parameters are validated
2) Looks for string in array and returns the index
public class SheetNames {

    public Integer changeSheetName(String[] sheetNames, String currentName, String newName) {

        if (sheetNames == null || sheetNames.length == 0 || currentName == null || newName == null) {
            throw new IllegalArgumentException("Invalid input");
        }

        Integer replacedIndex = Arrays.asList(sheetNames).indexOf(currentName);
        if (replacedIndex != -1) {
            sheetNames[replacedIndex] = newName;
        }
        System.out.println(Arrays.toString(sheetNames));
        return replacedIndex;
    }
}

Junit Tests:-
public class SheetNamesTest {

    private SheetNames sheetNames;

    @Before
    public void setup() {
        sheetNames = new SheetNames();
    }

    @Test
    public void shouldReplaceSheetName() {
        String[] sheetNamesArr = {"dennis", "john", "dan"};
        Assert.assertEquals(new Integer(1), sheetNames.changeSheetName(sheetNamesArr, "john", "peter"));

        String[] sheetNamesArr2 = {"john", "dan"};
        Assert.assertEquals(new Integer(0), sheetNames.changeSheetName(sheetNamesArr2, "john", "peter"));
    }

    @Test
    public void shouldNotReplaceSheetName() {
        String[] sheetNamesArr = {"dennis", "johnhunt", "dan"};
        Assert.assertEquals(new Integer(-1), sheetNames.changeSheetName(sheetNamesArr, "john", "peter"));
    }

    @Test(expected = IllegalArgumentException.class)
    public void shouldThrowExceptionWhenSheetNameIsNull() {
        sheetNames.changeSheetName(null, "john", "peter");
    }

    @Test(expected = IllegalArgumentException.class)
    public void shouldThrowExceptionWhenSheetNameIsEmpty() {
        String[] sheetNamesArr = {};
        sheetNames.changeSheetName(sheetNamesArr, "john", "peter");
    }

    @Test(expected = IllegalArgumentException.class)
    public void shouldThrowExceptionWhenCurrentNameIsNull() {
        String[] sheetNamesArr = {"dennis", "johnhunt", "dan"};
        sheetNames.changeSheetName(sheetNamesArr, null, "peter");
    }

    @Test(expected = IllegalArgumentException.class)
    public void shouldThrowExceptionWhenNewNameIsNull() {
        String[] sheetNamesArr = {"dennis", "johnhunt", "dan"};
        sheetNames.changeSheetName(sheetNamesArr, "john", null);
    }

}

A: Read the comments in the below code:
public int rename(String currentName, String newName) {
    int currentNameindex = -1; // set the initial position of currentName

    for (int i = 0; i < SheetsNames.length; i++) {
        if (currentNameindex < 0)  // currentName has not been found yet
            if (SheetsNames[i].equals(currentName))
                currentNameindex = i;  // save the position of currentName

        if (SheetsNames[i].equals(newName))  // newName is found in the list
            return -1;
    }

    if (currentNameindex > 0)  // currentName is found in the list
        SheetsNames[currentNameindex] = newName;  // rename the list item

    return currentNameindex;
}

A: Loop through your SheetsNames and check if it contains newName already (if yes, then you dont want to update so return -1)
for(String name: SheetsNames){
   if(name.equals(newName) return -1;
}

Now we are certain the new name is not in the list! Lets check if there is a name same as currentName in there, if yes return its index.
for(int i=0;i<SheetsNames.length;i++){

   if(name.equals(currentName){
     SheetsNames[i] = newName;
     return i;
   }
}
return -1; //its not in SheetsNames, so we return -1