text:
Q: Displaying a image in grid view based on condition I am trying to display
1. Red if the TimeReceived is Null, (or)
2. Amber when Time Received is not null and Time Read is Null (Or)
3. Green When Time read is not null
It throws an error
Input string was not in a correct format.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.FormatException: Input string was not in a correct format.

Source Error:

Line 86:         {
Line 87:             Image img = (Image)e.Row.FindControl("image1");
Line 88:             switch (int.Parse(e.Row.Cells[1].Text))
Line 89:             {
Line 90:                 case 0:

Where I am going wrong, how can I display image based on the condition. I think I haven't done the rowdatabound correctly. Please help.

A: You are probably trying to parse a null or empty string as an int. Change your int.Parse line to:
switch (int.Parse(string.IsNullOrEmpty(e.Row.Cells[1].Text)?"0":e.Row.Cells[1].Text))

UPDATE:  Now that you have pasted the actual image of how the Grid looks, I think Joel Etherton is right, you are trying to parse a Date as an integer. Cell[1] (assuming you don't have any invisible columns to the left) is a Date, not an integer so when you try int.Parse throws the exception because it cannot parse it. Also, according to your conditions, your MyGrid_RowDataBound logic is incorrect. Try changing your implementation to this.
protected void MyGrid_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        Image img = (Image)e.Row.FindControl("image1");
        //condition for red image; Neither TimeReceived and TimeRead are populated
        if(string.IsNullOrEmpty(e.Row.Cells[1].Text) &&
           string.IsNullOrEmpty(e.Row.Cells[2].Text))
        {
            img.ImageUrl = "/images/Red.gif";
            img.Visible = true;
        }
        //condition for amber image; TimeReceived not null and TimeRead is null
        else if (!string.IsNullOrEmpty(e.Row.Cells[1].Text) &&
                 string.IsNullOrEmpty(e.Row.Cells[2].Text))
        {
            img.ImageUrl = "/images/Amber.gif";
            img.Visible = true;
        }
        //condition for green image; TimeReceived not null and TimeRead not null
        else if (!string.IsNullOrEmpty(e.Row.Cells[1].Text) &&
                 !string.IsNullOrEmpty(e.Row.Cells[2].Text))
        {
           img.ImageUrl = "/images/Green.gif";
           img.Visible = true;
        }
        else //default case
        {
            img.Visible = false;
        }
    }
}

A: Here's where I see the problem happening, and frankly this piece of code is a bit of a mess.
switch(int.Parse(string.IsNullOrEmpty(e.Row.Cells[1].Text)?"0":e.Row.Cells[1].Text))

There is way too much going on here to be useful. First, e.Row.Cells[1] looks like it's providing a DateTime, so int.Parse is the absolute wrong thing to use here. Based on your description of what you want I don't see how this is going to achieve that in any way.
Here's my stab at it:
Image img = (Image)e.Row.FindControl("image1");

DateTime received;
DateTime read;

DateTime.TryParse(e.Row.Cells[1].Text, received);   // If exception it will produce DateTime.MinValue
DateTime.TryParse(e.Row.Cells[2].Text, read);

if (received == DateTime.MinValue)
{
    img.ImageUrl = "/images/Red.gif";
}
else if (read == DateTime.MinValue)
{
    img.ImageUrl = "/images/Amber.gif";
}
else
{
    img.ImageUrl = "/images/Green.gif";
}

img.Visible = true;

Use if statements when they are appropriate. What you're attempting to do involves dates, so use dates. Simplify your expressions to make them more readable. You don't have to do everything in a single line. The expression passed to your switch statement is doing way too much all in one shot. I'm not saying it's impossible to pull off, but it generates a lot of grey area as to where any generated errors are coming from.

A: I had difficulty understanding these complicated solutions so I did a little research and here is my solution. I leave it here hoping it help someone
I changed my grid code like this
<asp:GridView ID="gridView" runat="server" AutoGenerateColumns="false" OnRowCommand="RowCommand">
    <Columns>
        <asp:TemplateField HeaderText="Commands">
            <ItemTemplate><asp:ImageButton ID="btnDelete" Visible='<%# ActionPermitted("DELETE") %>' runat="server" ImageUrl="images/bin.png" ToolTip="Delete" CommandName="Delete" CommandArgument='<%# Eval("Id")%>' /></ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="ASPImage">
            <ItemTemplate><asp:Image runat="server" ID="rowImage" ImageUrl='<%# ImageView(((System.Data.DataRowView) Container.DataItem).Row)%>' /></ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="HTMLImage">
            <ItemTemplate><img src='<%# ImageView(((System.Data.DataRowView) Container.DataItem).Row)%>' /></ItemTemplate>
        </asp:TemplateField>
        <asp:TemplateField HeaderText="SetVisible">
            <ItemTemplate>
                <img src="green.gif" style='display:<%# Eval("aColumn") == "Value1"? "inline":"none" %>' />
                <img src="red.gif" style='display:<%# Eval("aColumn") == "Value2"? "none":"inline" %>' />
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>

In my Code behind I have following functions
protected boolean ActionPermitted(string action){
  return (action=="Delete" || user == "admin");
}

protected string ImageView(DataRow row){
    if (row["SomeData"] == DBNull.Value){
        return "red.gif";
    } else if (row["SomeData"] != DBNull.Value && row["SomeOtherData"] == DBNull.Value){
        return "amber.gif";
    } else {
        return "green.gif";
    }
}

Please note that this is actually 4 different solutions.

*

*To change visibility of an asp button based on a value returned from a code behind function (note the single quotes instead of double quotes)

*To pass current DataRow to code behind and return result based on that

*To change properties of an HTML tag (can be used to insert data generated in code behind into columns)

*To show/hide and HTML image (can be any tag)

Last TemplateField is to answer the question.

A: I agree with Icarus but it would be better if you used int.TryParse instead of int.Parse.
Image img = (Image)e.Row.FindControl("image1");
int val = 0;
int.TryParse(e.Row.Cells[1].Text , out val);
        switch (int.Parse(e.Row.Cells[1].Text))
        {
            case 0:
                img.ImageUrl = "/images/Red.gif";
                img.Visible = true;
                break;
            case 1:
                img.ImageUrl = "/images/Amber.gif";
                img.Visible = true;
                break;
            case 2:
                img.ImageUrl = "/images/Green.gif";
                img.Visible = true;
                break;
            default:
                img.Visible = false;
                break;
        }


text:
Q: Update field when record is opened I have a task trigger
public static void CustomObject_Email_rec_date_Upd(list<Task> lst_task){

    list<Custom_Object_c> lst_ELE_Agg_Var = new list<Custom_Object_c>();

          for(Task taskvar:lst_task) {
                  if(taskvar.Whatid !=null)
                  {
                   if(taskvar.Whatid.getSobjectType() == Schema.Custom_Object_c.SObjectType && taskvar.subject.contains('RE:')){

                       DateTime dT = System.now();
                       Date myDate = date.newinstance(dT.year(), dT.month(), dT.day());

                       Custom_Object_c ELE_Agg_Var = new Custom_Object_c();
                           ELE_Agg_Var.id = taskvar.Whatid;
                          // ELE_Agg_Var.Email_Received_Date__c = taskvar.createddate;
                          ELE_Agg_Var.Email_Received_Date__c = myDate;
                          ELE_Agg_Var.Read_Email__c = taskvar.WCT_Is_Read__c;
                          system.debug('+++++++++++=========='+taskvar.WCT_Is_Read__c);
                           lst_ELE_Agg_Var.add(ELE_Agg_Var);
                   }
                  }

                Database.update(lst_ELE_Agg_Var,false);
}
}

Trigger:
 if(trigger.isAfter && trigger.isUpdate){

WCT_Task_Trigger_Handler.Ele_Agrements_Email_rec_date_Upd(Trigger.new);

}

 if(trigger.isAfter && trigger.isInsert){
        WCT_Task_Trigger_Handler.Ele_Agrements_Email_rec_date_Upd(Trigger.new);

    }

I am trying update Email receive date field and Read Email field in custom Object Whenever a task is created or updated.
I have received an email in Activity history and then Email receive date should update and when I open that Read Email field in Custom Object should be updated.
when we open email from Activity history Task trigger will not run? if not when will execute Task trigger to update fields?
Thanks in Advance
This is how we actually update task using this page:
<apex:page standardController="Task" >

 <script src="/soap/ajax/29.0/connection.js"></script>
 <script type="text/javascript">
 if('{!Task.WCT_Is_Read__c}' == 'false'){

    var tsk = new sforce.SObject("Task");
    tsk.Id = '{!Task.Id}';
    tsk.WCT_Is_Read__c = 'true';
    var mobId = '{!Task.What.Id}';
    var result = sforce.connection.update([tsk]);

    var tskRecord =  sforce.connection.query("Select Id,WCT_Is_Read__c from Task where what.id = '{!Task.What.id}' AND recordTypeId = '0121W000000gzDH' AND subject LIKE 'RE:%'");
    //alert('tskRecord'+tskRecord);
    var isMobUpdate;
    var tskRecords = tskRecord.getArray('records');
    var count = 0;
    for(var i = 0; i < tskRecords.length; i++){
        var tskRec = tskRecords[i];

        if(tskRec.WCT_Is_Read__c == 'true'){

            count++;

        }

    }

       if(tskRecords.length == count){
           // alert('Count matched');
            isMobUpdate = 'update';

        }

    if(isMobUpdate == 'update'){

        if("{!Task.WCT_Task_for_object__c}" == 'Pension_Request__c'){

            var mob = new sforce.SObject("Pension_Request__c");

            mob.Id = '{!Task.What.Id}';
            mob.PR_Unread_Email_on_this_Request__c = 'false';

            var mobresult = sforce.connection.update([mob]);
            // alert('result'+mobresult);
        }

    }
    // window.top.location='/'+'{!Task.Id}';
   }

</script>

Can we update any custom object fields using this page? if yes, Can you please tell me how?

A: You're correct, no triggers are fired when you "open" a record.
Triggers are only fired on update, insert and delete events. You'll have to actually update the record in order to fire your trigger to update "read" field on your related object.
If you're sending/receiving emails on case you should enable Email-To-Case as this creates an object called "Email Message". The Email Message has a built in "status" field that will automatically update when an email is read. But this only works for cases.
The only way I can think to achieve what you want using activities is to code a Visualforce page. This would allow you to, onload of the page, flag a "read" value on what ever object you want. Then you could override the "view" action on task/event objects with your page.
References:

*

*Overriding view page

*Apex Detail Tag

*Apex Related List Tag
Update
To access other objects when using the standard controller you'll want to code an apex extension and then query for the objects you want to update.

*

*Extensions
Lightning
I usually think in SF Classic. Thanks to Pranay for pointing out that you could have a bodyless lightning component that handles the init event perform an update on the object. Then simply add the component to your record detail page.

*

*Init Event

*Configure Components for detail pages

redpajama_set_name: RedPajamaStackExchange


text:
Q: how can i created a script with adb shell commands I have been trying to add a wifi network with these commands inside a script:
adb shell wpa_cli -p /data/misc/wifi/sockets/ -i wlan0

# Get to wpa_cli prompt
adb shell wpa_cli -p /data/misc/wifi/sockets/ -i wlan0

# Add new WiFi network
adb shell add_network

adb shell set_network 0 auth_alg OPEN
adb shell set_network 0 key_mgmt WPA-PSK
adb shell set_network 0 ssid "Password"
adb shell set_network 0 proto RSN
adb shell set_network 0 mode 0
adb shell set_network 0 psk "Mynetwork name"

# Connect to it
adb shell select_network 0
adb shell enable_network 0
adb shell reassociate

# Check the status
adb shell status

but after the first command the terminal stays always in adb shell prompt and the other commands are not executed

A: WPACLI="adb shell wpa_cli -p /data/misc/wifi/sockets/ -i wlan0"

# Add new WiFi network
NETWORK=$($WPACLI add_network)

$WPACLI set_network $NETWORK auth_alg OPEN
$WPACLI set_network $NETWORK key_mgmt WPA-PSK
$WPACLI set_network $NETWORK ssid "Password"
$WPACLI set_network $NETWORK proto RSN
$WPACLI set_network $NETWORK mode 0
$WPACLI set_network $NETWORK psk "Mynetwork name"

# Connect to it
$WPACLI select_network $NETWORK
$WPACLI enable_network $NETWORK
$WPACLI reassociate

# Check the status
$WPACLI status


text:
Q: I cannot believe what I have seen today Today, with my best intention, I posted a suggestion to restrict the downvotes (compelling users to justify why they downvote), it got lots of downvotes and reasons: "this has been proposed before lot of times", "it will not work because of this and that", etc. I closed the question (the community does not like it = does not belong here = it should be deleted).
I thought that perhaps I didn't transmit the ideas properly and that's why I tried it again, this time by highlighting my intention of deleting it after reaching -6 (because of not wanting to go against the general feeling). I got various answers and thus wasn't able to delete it. I tried to reply as well as I could; but apparently I wasn't welcome (because people asking something which has been asked before is not welcome) and thus the process was pretty tiring. Here you have the post.
Finally, I stop seeing the point and decided to transmit it via title and content (it is duplicated, I don't like the answers, I want to delete it, why it is still here?): I don't like what I have seen at all. But, apparently, critics are not welcome either and thus someone made my question/title back to what it was before. I re-edited it, but then one of the moderators locked the question and banned me from editing my own question further?! The content you can see there is not what I want to say.
The most ironical part is that some of the arguments against what I proposed were based on the idea that this wasn't too democratic! Apparently, requesting justifications when downvoting is not democratic; but avoiding someone to say what he wants is perfectly fine (if this someone thinks differently and thus is not welcome).
Yesterday (my first day here in Meta) I wrote another post. Despite not having changed this post at all, its ideas seem to be less valid (-2 already) today. How I know that both issues are related; I cannot know, but this is what I think of Meta now (the attitude of a relevant proportion of its users). I am sure that this new question will help me (and anyone else reading it) to get still a better feeling about how are things here.
You can start to downvote now; also, please, feel completely free to change any part of the question which you don't like too much. I will not do any editing, but just to make sure, perhaps you should lock the question right away. This time I will not participate too much; please don't be bothered by this fact at all and just enjoy: upvote each other as much as you can while downvote the question.
UPDATE
Perhaps I have over-reacted a bit, but don't like when actions are taken without my consent. Perhaps I shouldn't have edited my question, but a nice warning would have been enough (rather than modifying what I wrote without my permission). Other than this bit, I am pretty happy to recognise that people here have proven to be tolerant and understanding with a new member who has shown a somehow-aggressive attitude :) I will let the text of my original question, but apologise for the tone and highlight that does not reflect accurately my opinion about Meta.
UPDATE 2
I don't know what to say? How is everything so easily misunderstood here? Anyway... I will not change the update above but don't think that will come back either (not my style).
UPDATE 3 (4 months later update)
I thought that nobody cared about this post since pretty long time ago but today I met someone proving me wrong and that's why I am back. The whole point of this post was showing my disagreement when I wasn't able to do what I wanted with something I wrote (nothing to hide; just realised that wasn't the feeling of the community and thought that better deleting it). When I wrote this post, I was relatively new in SO and wasn't too aware about the overall rules, expectations, etc. (much less about the Meta ones). Now I accept certain things without any problem (although still not everything).
I do agree in that some moderation has to be present; and that, some times, this moderation needs to be executed without any discussion (e.g., spam); but I don't think that censoring certain type of texts should be defended in SO/Meta. For example: I can easily get involved in discussions not related at all with the given question; although, most of the times I do that to help some people to understand the implications of their behaviour, what I think that is good for Meta/SO. I do accept no-discussing censure, but I think that a different approach would be better in these contexts; I would welcome any suggestion from the moderators (e.g,. "ey!, this tone is a bit aggressive here; reword this comments or start a private; etc. If you don't take care of this, we would do it for you").
In summary: the whole point of this update is clarifying what moved me to write this post (and to vandalise my previous one): showing my disagreement with certain SO/Meta rules regarding moderation. My opinion now is a bit different (I guess that I am more used to see this kind of things) and I do think that my vandalising attempt was a bit childish (but I thought in this way also when I wrote this post. Note that I rarely behave childishly, but take freedom-restriction and censure related issues pretty personally; on the other hand, I do take full responsibility for any action and correct any problem ASAP).

A: Try to understand what happened here from the perspective of the rest of Meta. This may sound a bit harsh, but it's meant in earnest.
You need to separate the votes a question receives and the effort others put into it. The generated responses mostly show that people read your post, and understood what you were saying. At this point, they disagreed with you. Since voting is different on Meta, those who strongly disagreed downvoted. Your proposal happens to be one which has been thoroughly discussed many times before.
Now, look at it from the perspective of a Meta user:

*

*a user posted a question which has been asked many times before

*they disagree with your idea (that's not to say everyone does, but it's clearly the majority)

*the OP doesn't seem to have searched for existing threads

*==> downvote

Yes, the actual number of downvotes is often entirely arbitrary, but is an estimator for how people feel. Take the downvotes not as people disliking you, but the content of your post.
Secondly, editing your post to ask for it to be deleted is strictly prohibited. It is considered edit vandalism, and is not appreciated by the community. That, alone, is why your post was rolled back. Flexo locked this post, but whether it was in response to the edits is not my place to say.
So, my advice sums to this: Think about the perspective of a typical Meta user. We have nothing against you; we simply disagree with your request.
If you want it deleted in the future, flag for moderator attention.

A: I would just like to point out something quite relevant:

as you rightly said, it is my content. I can do whatever I want with it.

...that's true, until you publish it on Stack Exchange. In order for Stack Exchange to publish it, you have to give it a license to do so — and the license Stack Exchange requires doesn't let you do takesies backsies. Emphasis mine:

You grant Stack Exchange the perpetual and irrevocable right and license to use, copy, cache, publish, display, distribute, modify, create derivative works and store such Subscriber Content and to allow others to do so in any medium now known or hereinafter developed ("Content License") in order to provide the Services, even if such Subscriber Content has been contributed and subsequently removed by You.

So no, you do not have a right to delete your posts, even if the site occasionally lets you. You waived that right when you clicked on "Post Your Answer" (or "Post Your Question"). Even if you do delete it, it can be undeleted by others.
If you don't like this, this site might not be for you.

A: I am going to go through your post and try to give my standpoint on the concerns you have mentioned:

I closed the question (the community does not like it = does not belong here = it should be deleted

Just because a question (or an answer) is not liked by the community, doesn't mean it doesn't belong and it also doesn't mean it should be deleted. There are many "unpopular" questions or answers that need to stay on the site for their historical significance. You can take a look at some of them by searching for questions and sorting by votes in reverse or the same for answers. I would say that this opinion is primary seen on meta sites. If a suggestion is made (and suggested in a clear coherent manner), and the community doesn't like the suggestion (for whatever reasons), that suggestion should be kept in order to have somewhere to link to when someone in the future makes the same or a similar suggestion. As long as the answers on that (rejected) suggestion convey why the community is opposed there is no reason to start a new discussion and reiterate all the ideas from another discussion.

...apparently I wasn't welcome (because people asking something which has been asked before is not welcome)

It's nothing personal here. It has nothing to do with you as a user but rather the content of that specific post. Duplicates are duplicates and redundant duplicates are redundant. ;) This is why there is a special close reason for duplicates and why an entire system of linking duplicates exists. I feel that here would be a great place to link to the well-known blog post: Dr. Strangedupe: Or, How I Learned to Stop Worrying And Love Duplication.

...apparently, critics are not welcome...

Have you seen the downvote button? ;) Ok -this one was a little joke :P Onward!

Apparently, requesting justifications when downvoting is not democratic

Is is democratic to force people to publicize who/how/what they voted for, and why? Furthermore while the Stack Exchange network might feel like a democracy (of sorts), the actual truth is quite the different.

About meta - Meta is a weird place. You have to have quite a thick skin to get by because people are simply not afraid to tell you exactly what they think of your suggestions. In a place like this, you have to be open to the fact that people might not agree with you.

A final note about the content you contribute to the site and this is the same no matter which Stack Exchange site you are on: Everything you post (or see) with regard to content is automatically assigned the Creative Commons Licence. It basically means that people are free to do what ever they want with the content as long as attribution is supplied back to the original author. People can and will edit your posts. Sometimes, you might not agree with their opinions and changes - this can very quickly turn into an edit war and the lock that the moderator placed was to prevent this exact situation.
The correct way to handle a situation like this one is to leave a comment for the editor (you can reference any editor as you would to any other user, using @comment replies). Find out what that user meant by their edits, see if you can find a middle ground on what edits should stay and what edits should be reversed.

A: It was already explained to you why you are not allowed to delete the question (because it already has received upvoted answers), and why deleting a question just because people disagree with you doesn't make sense. Bart's and Yannis's comments are particularly succinct and powerful in making this point:

Because this is a Q&A. You propose something, and then other users get to express their views in answers. That's how this site works. There is no point in continuously making proposals and then deleting them if the votes are not to your liking.
  –Bart

There's nothing logical about deleting this question. The downvotes are there to show every future reader that the community strongly disagree with the premise of your question. That's a useful datapoint, and it doesn't say anything about the quality of the discussion or you, personally.
  –Yannis

So then you tried to beat the system by vandalizing your own question, removing all the content and replacing it with "delete me"-style nonsense. We don't allow that from the original poster any more than we would allow it from some random spammer. So someone rolled that back.
I cannot imagine why that offended you so greatly. He wasn't putting words into your mouth or anything. He didn't even make substantive edits to the content of your question. He just put back exactly what you had originally written.
But even if he had made edits to the content of your post, like improving the grammar or fixing the formatting, that would have been OK, too. Like the moderator who locked your question said, this site (like all Stack Exchange sites) is collaboratively edited. Anyone can make or suggest edits to improve posts. That is in the FAQ.
The moderator stepped in and locked the question because there was an edit war going on. You had tried to vandalize your question, someone had rolled it back and complained, etc. It didn't look like that process was going to stop. So in order to ensure that you listened, the moderator put the question back to its original, non-vandalized state and locked it. That way, if you want to contest that, you would have to do what you've done: ask a new question to discuss it.
Aside from all of that, I have a hard time understanding why it shocks you that people are relatively unlikely to approve of brand new revolutionary ideas that go completely against the fabric and foundation of the entire system we have set up here. Obviously we [mostly] like the current system, or we wouldn't have put so much time and energy into creating, defending, and improving it. Therefore, we don't want to make fundamental changes to it that we think violate its spirit or essence. We also get fatigued by reading the same suggestions over and over from people about things we've already discussed to death. We wonder why those people don't just go back and read those previous discussions first, before making their own arguments and trying to pass them off as completely novel. They don't seem that way to us.
But even if we're completely wrong and your revolutionary ideas are right, it should still not surprise you that we do not react positively. History is littered with examples of this. If people could have downvoted Che Guevara, they would have. Sometimes, it takes enduring a bit of opposition to effect real change. If you believe strongly in your arguments, you should stick by them. It's not like downvotes really mean anything anyway. (Other than disagreement, which has already been adequately explained to you.)


text:
Q: Printing sum of digits greater than average For an assignment, I have to write a code in C that prints the digits from a number that are greater than its average.
I already wrote some code, but when I insert a single number or a number with the same digits (like 555), it does not give me an answer. It  should give, in the case of 555 --> 5 (and 8 -> 8, 77 -> etc.)
The code I wrote is:
(I've commented at every step I take.)
#include <stdio.h>
#include <stdlib.h>

int main (int argc, char *v[])  {
    /* imput: 1 number between 1 and 2.000.000.000 */
    int n;          /*  stores the value                            */
    int ext, ext2;  /*  stores a copy of the number                 */
    int rem;        /*  stores the remainders                       */
    int tot;        /*  stores the total of the digits              */
    int avg;        /*  stores the average of the digits            */
    int i;          /*  counts the amount of digits                 */
    int big;        /*  stores the biggest and second biggest value */

    scanf("%d", &n);

    /* seperate digits and add them */
    ext=n;
    ext2=n;
    tot=0;
    big=0;
    avg=0;
    i=0;

    while(ext!=0 && n<2000000000 && n>=1){
        rem=ext%10;
        tot=tot+rem;
        ext=ext/10;
        i++;
    };

    /* average value */
    avg=tot/i;

    /* find and print higher numbers */
    while (ext2>0){
        rem = ext2 % 10;
        if (rem > avg){
            big += rem;
        };
        ext2 = ext2 / 10;
    }

    if(n<100 && n>9){
        printf("%d\n", big);
    } else if(big==avg){
        printf("%d\n", 0);
    } else if(big>=avg){
        printf("%d\n", big);
    };

    return 0;
}

Hope someone can help me!

A: You forgot to initialize variable i with 0. I've corrected your code and it gives expected outcome. And the answer is 0 for a single number because the average of one number is always the number itself so the number is never greater than the average.
#include <stdio.h>
#include <stdlib.h>

int main ()
{
    /* imput: 1 number between 1 and 2.000.000.000 */
    int n;          /*  stores the value                            */
    int ext, ext2;  /*  stores a copy of the number                 */
    int rem, rem2;  /*  stores the remainders                       */
    long tot;       /*  stores the total of the digits              */
    int avg;        /*  stores the average of the digits            */
    int i;          /*  counts the amount of digits                 */
    int big, big2;  /*  stores the biggest and second biggest value */
    int sum;        /*  stores sum of digits greater than average   */
    scanf("%d", &n);

    /* seperate digits and add them */
    ext=n;
    ext2=n;
    tot=0;
    big=0;
    big2=0;
    avg=0;
    i=0;
    sum=0;

    while(ext!=0 && n<2000000000 && n>=1)
    {
        rem=ext%10;
        tot=tot+rem;
        ext=ext/10;
        i++;
    };

    /* average value */
    avg=tot/i;

    /* find and print higher numbers */

    while(ext2>0)
    {
        rem2=ext2%10;
        if(rem2>avg)
        {
            sum+=rem2;
        };
        ext2=ext2/10;
    };

    printf("sum of digits greater than average: %d",sum);

    return 0;
}

A: In addition to failing to initialize i = 0; prior to i++;, your biggest problem is you are confusing yourself with the large number of unnecessary and nondescript variable names. ext, ext2, tot, big, big2, avg, rem, rem2 is just variable salad.
While you will need ext2 to hold a copy of the variable you reduce by % (modulo) to find tot and avg, there is no need for rem2 or big2 (you can simply reuse rem) and you only need one big (presuming that is your variable holding the sum of digits greater than avg)
Further, your loop to find big (and using big2) is wildly more confusing than it need be. You don't care if rem2 is greater than big2 and then setting big2 = rem2; what you care about is whether the digit is larger than avg. (that's it) All you need is:
    /* find and print higher numbers */
    while (ext2>0){
        rem = ext2 % 10;
        if (rem > avg){
            big += rem;
        };
        ext2 = ext2 / 10;
    }

Now big holds the sum of digits larger than averages.
Reusing variables and using descriptive variable names will go a long way to keeping your logic straight and prevent unnecessary variable sprawl. There is a normal rule-of-thumb to keep in mind when writing functions (it is good to keep in mind always), but if you are writing a function and you find yourself using more than 4-variables, you may need to refactor your program. (it's not a hard rule, but the crux of it is to prevent exactly the variable salad you fell into)
Why long tot;? At the very most 1+9+9+9+9+9+9+9+9+9 = 82. The use of int like you use for the rest of your variables is fine. (given your constraint that 1≤n<2000000000)
Lastly, while you can take the input numerically as you have and use modulo to extract each digit, it would be far simpler just to read the input as a string and then simply iterate over each character subtracting '0' to get the numeric value (as suggested in the comments by Weather Vane)
Edit Tidying Up Variables
From our continued discussion, I've decided to drop a quick edit that tidies the rest of the code up a bit and reduces the number of variables, as well as initializing the variables when they are declared. You could do something similar to:
#include <stdio.h>

int main (void)  {

    int n,          /*  stores the value                                */
        tmp,        /*  stores a copy of the number                     */
        rem,        /*  stores the remainders                           */
        tot = 0,    /*  stores the total of the digits                  */
        avg = 0,    /*  stores the average of the digits                */
        digits = 0, /*  counts the number of digits                     */
        big = 0;    /*  stores the sum of digits larger than avg        */

    /* imput: 1 number (1 <= n && n <= 2.000.000.000    */
    if (scanf("%d", &n) != 1) { /* read/validate number */
        fputs ("error: invalid integer input.\n", stderr);
        return 1;
    }
    if (n < 1 || 2000000000 < n) {  /* validate n in allowable range */
        fputs ("error: input outside allowable value.\n", stderr);
        return 1;
    }

    tmp = n;
    while (tmp) {           /* sum digits for average */
        rem = tmp % 10;
        tot += rem;
        tmp /= 10;
        digits++;
    }
    avg = tot / digits;     /* calculate average */

    tmp = n;
    while (tmp) {           /* sum numbers higher than avg */
        rem = tmp % 10;
        if (rem > avg)
            big += rem;
        tmp /= 10;
    }

    printf ("sum of digits greater than avg : %d\n", big);
}

Nothing fancy, but 989 -> 18, and 777 -> 0 and 778 -> 8. Look things over and let me know if you have further questions.


text:
Q: Stepping into the source of a dll being called through reflection I am trying to call a .dll's method via reflection, but am getting a TargetInvocationException.  The scenario works like this: I have a dll called Labor.dll. It holds several files, among them Demand.cs and Role.cs.  I can successfully step into functions defined in Demand.cs, but whenever I attempt to step into a function that was defined in Role.cs, I get a TargetInvocationException.  I should not, however, that this error occurs inside the Role.cs method, so .Net can find the method and execute from it, it just won't show me what it is doing.
How do I step into the methods that are defined in Role.cs, or what would prevent me from viewing that code?
Extra information:

*

*Labor.dll is being loaded and called through reflection.

*When I use reflector on Labor.dll I can view the methods defined in Role.cs

*The method in Role.cs is throwing an error when it executes code I believe should not be executing, which is why I am more focused on stepping into the code than preventing the TargetInvocationException

A: After fiddling with this code for a while, I believe I found the cause of the error.
It appears that when you're using reflection .net will attempt to validate method signatures before those methods are executed (it appears to occur when you load the method that houses the invalid method call).  Therefore, I could not step into Role.cs because .net would attempt to validate an invalid method signature defined in the method I was calling.  By commenting out that invalid method call and recompiling the dll, I was able to successfully step into the Role.cs code.
Bottom line is this:
AFAIK, You can not have an invalid method signature within a .dll that you call via reflection.  When the code that uses the invalid method is loaded, .net will find the error and throw an exception, even if that code will never be executed (in an if statement that never returns true).


text:
Q: How do I swap CTRL and CAPS LOCK on Carbon Emacs on OSX without doing it OS-wide? I've recently started learning emacs since I was unhappy with Textmate and as a starting point read the "Effective Emacs" article by Steve Yegge. I was very keen on his CTRL -> CAPS LOCK swap, but I don't want to do it OS-wide, I want this swap to only occur in emacs every time I run it.
I was wondering if there's a way to do this in the .emacs file instead of going into system-properties and swapping it for the whole OS. I'm using Mac OS X Leopard.

A: This is, unfortunately, not possible to do in your .emacs file.


text:
Q: Clonezilla and multiple Activation for Office 2010 We have a large desktop deployment (approximately 2000 PCs) coming and I'm in charge in structuring the best possible manner to have the PCs installed and staged before them out to multiple geographical sites. We have already purchased group license for both Windows 7 and Office 2010. The method of deployment is clonezilla multicast from a clonezilla SE. The problem here is Windows 7 seems be installed and imaged successfully but unfortunately Office 2010 needs to be reactivated by each and every PC.
Is there at all a way/method that I could employ to have it activated by at least the first time a PC boots up?

A: In your Microsoft license portal, you should have an option to use KMS keys. KMS is the Microsoft Key Management Service, and is the proper method of activating/licensing systems deployed in the manner you're planning.
Here's a tutorial on setting up a KMS host server.


text:
Q: Add Data From One Table To Another Table I have a tableview with genre: rock, rap, dance, country, pop, etc.
Lets say I have another tableView where I can make a custom list with a bunch of these genres.
Say in the mainView, I can add lists, like Dinner, Gym, Studying etc.  Then within each of these lists (when you click its cell it will push to a subtableview for that list).  I want to choose items from the separate genres to add to this subview.  Examplple, Dinner list might include country and classical music, and gym list might have rock and rap etc.
I have everything set up so far except the code that lets me add genres to the custom sub groups.  So I can make groups such as Dinner but I need to still make code that lets me fill this group with genres from the other tableView.
I think I need to have a modal view pop up when I click the add button.  THis model view will have the genre table and when I click a cell, the modal view will dismiss and it will add whatever I clicked as a cell in the group.

A: Use the same genre array that backs the genre tables as the data source for the modal table.
In the modal table didSelectRowWIthIndexPath, get the genre string from that array.
Now you have lots of choices for how to get the genre item back to your detail table view controller.
You could post a notification, you could use a KeyValue Observer, you could pass a reference to the detail VC to the modal and then the modal can set an exposed attribute on the detail VC, etc.
Then the detail vc would add that genre value to whatever array is back it's data, and then you call reloadData on the detail VC table.
Your modal VC would have to do something like [navigationController popViewController:animated] to dismiss itself.


text:
Q: Can't get checked status in iCheck-helper checkbox I use Bootstrap theme in my MVC 4 web application. There is a checkbox in my application.
My Razor code below.

                @Html.CheckBoxFor(model => model.NeedsRepacking)Needs Repacking

but there is no check box render in the web browser. Please see the rendered code.

<input data-val="true" data-val-required="The NeedsRepacking field is required." id="NeedsRepacking" name="NeedsRepacking" type="checkbox" value="true" style="position: absolute; opacity: 0;">
<input name="NeedsRepacking" type="hidden" value="false">Needs Repacking

When I checked the checkbox div class is changed to icheckbox_minimal-blue checked .

<input data-val="true" data-val-required="The NeedsRepacking field is required." id="NeedsRepacking" name="NeedsRepacking" type="checkbox" value="true" style="position: absolute; opacity: 0;">
<input name="NeedsRepacking" type="hidden" value="false">Needs Repacking

But I can't get the checked status of the checkbox.

A: Here's a copy/paste/modify from a project that I am working on and had the same issue with the iCheck library. This solution is not 100% tested so you will need to modify it to your code:

N.B. this code can and should be re-factored as well as optimized.


text:
Q: Is there a way of checking if a user defined class is initialized or not? Consider the class below
    class test;
    class sample
    {
        sample() { }
        ~sample(){}
        void SomeMethod();
        private:
        test t;
    };

sample::SomeMethod(test &t1)
{

  if(t.isuninitialized())
  {
    t = t1;
  }
  else
  {
    // Check if t and t1 member values are the same
  }
}

main()
{
  sample s;
  test t1(a);
  s.someMethod(t1);
}

Is there a way to check if object t is initialized or not? In case of pointers it would suffice to check if the object is NULL. However, in this case, where t is not a pointer can such a check be done, or do I need to write a method that checks if the member variable values are initialized to default value

A: Yes, in fact the compiler can check this for you: if the code compiles, the compiler was able to generate code which calls the default constructor of test, which in turn takes care of creating the object - so the object exists, and is initialized to some (possibly unknown, depending on how the test default constructor is implemented) state.


text: Q: Unit Testing With Magento 2 Where should i start working with extension development using test driven approach, with Magento 2. I do not see any resources and tutorials from where I get idea. I believe I have a fair amount of idea of unit tests in php, but doing it in magento seems very much complex. From, Where should i start working with it.


text:
Q: pyspark.sql.functions.lit() not nullable conversion As I create a new column with F.lit(1), while calling printSchema() I get
column_name: integer (nullable = false)

as lit function docs is quite scarce, do you think there is any simple mapping that can be done to turn it into nullable = true?

A: Okay, in this scenario (only some specific column mapping, nothing in bulk) it seems like
df.schema['column_name'].nullable = True
does the trick. Nevertheless df.printSchema() isn't updated, although df.schema is.


text:
Q: Forward all requests to one index.php file, for non-existing files, but *including* the index.php itself So I have this quite typical "single point of entry" config in the .htaccess file:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php?url=$1 [QSA,L]

And it works fine. Now - I also what that behavior on the request to the index.php file itself. So I do this:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
#file must not exist:
RewriteCond %{REQUEST_FILENAME} !-f [or]

# *unless* this is the index.php *itself*, then I also
#want to pass it to itself.
RewriteCond %{REQUEST_FILENAME} index.php

RewriteRule ^(.*)$ index.php?url=$1 [QSA,L]

So we have kind of exception here - go on when file doesn't exist but also when it exists but it's the 'index.php'.
And it works, but unfortunately it also works for files deeper in the structure. What I want is to catch only the 'index.php' being on the same level as the .htaccess itself.
Update:
Maybe I should clarify. I want to create a very generic, out of the box single point of entry for php, like this one:
https://github.com/kpion/point1
It "works", but I feel I should do it a bit differently. I already asked a similar question ( The utlimate way to make a single entry point (front controller) working with the most common web server setups ) but was considered as "too long" so this is my second approach :)
Please bear in mind, that I can't use ^/index.php - in the condition, because the 'request uri doesn't really need to start with it. This htaccess can be deeper as well, i.e. deeper in the document root. This is actually quite common, when I have many small projects in /var/www/html and I don't want to create a vhost for everything. So the "root" is /var/www/html and now:
Example:
The project is located in
/var/www/html/point/point1
The .htaccess is inside it. It forwards all requests to non-existing files to the index.php. With my few additional lines, it also forwards itself to the index.php.
Note: %{REQUEST_URI} in this case, when we open /var/www/html/point/point1 is equal to "/point/point1/index.php"
It is not /index.php
It works fine, when I call http://localhost/point/point1/.local/noExistinFile or http://localhost:82/point/point1/ (this will point to index.php, which will be matched by my last RewriteCond).
But, when I have a file located in /var/www/html/point/point1/.local/index.php and I call http://localhost2/point/point1/.local/index.php - I don't want this to pass the conditions and I don't want it to be forwarded to index.php.
So I need something relative to the .htaccess location.

A: This should work:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
#file must not exist:
RewriteCond %{REQUEST_FILENAME} !-f [or]
#or is /index.php
RewriteCond %{REQUEST_URI} ^/index.php$
RewriteRule ^(.*)$ index.php?url=$1 [NC,L,QSA]

A: Ah, I forgot I asked this question. For anyone interested: I found out the solution is quite simple:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php?url=$1 [QSA,L]

# lets forward the index.php itself as well, to be later consistent in how we handle things:
RewriteRule ^(index.php)$ index.php?url=index.php [QSA,L]

The last line does the job, because:

*

*The RewriteCond above obviously does not apply (by default they only work for the "RewriteRule" directly below). So the -f (must not exist) doesn't apply, which is cool.

*Now the key part: the tested string in the RewriteRule is a file/dir relative to the directory .htaccess is in. So, if the .htaccess file is inside /var/www/html/point/point1 and we request:
http://whateverHostWeSetPointingToThisDir/index.php then the string being tested in RewriteRule is exactly "index.php". And when we request
http://localhost/point/point1/blah/index.php then, assuming the ...point1 points to our 'point1' dir, what is tested is exactly "blah/index.php".
This is why RewriteRule ^(index.php)$ matches the 'index.php' file being in the same directory as the .htaccess itself. Regardless the host name, or the parent directory name, or anything.
By the way: if we request http://whateverHostWeSetPointingToThisDir then this will work as well if we have set DirectoryIndex index.php but that's not really related.


text:
Q: Single MySQL Query on multiple databases I am working with the following set-up:
Consider two MySQL databases: abcand xyz, each with their own table:abc.table_in_abc and xyz.table_in_xyz. I need to run a simple MySQL query that select elements from the table_in_abc with a JOIN relationship to table_in_xyz.
In Workbench, the following query works fine:
SELECT AB.* , XY.*
FROM `abc`.`table_in_abc` AB
LEFT JOIN `xyz`.`table_in_xyz` XY ON AB.`ID` = XY`ID`

I am trying to achieve the same things in VBA. I am able to run a MySQL query on a single database (see example below) but unable to do so when the query involves multiple databases.
Example of simple VBA query on single database:
Set conn = New ADODB.Connection
conn.Open "DRIVER={MySQL ODBC 5.3 Unicode Driver}" _
& ";SERVER=" & server_name _
& ";DATABASE=" & database_name _
& ";UID=" & user_id _
& ";PWD=" & password _
& ";OPTION=3" '

Set rs1 = New ADODB.Recordset
sqlstr = "SELECT * FROM `abc`.`table_in_abc` WHERE `ID`=" & ID & ";"
rs1.Open sqlstr, conn, adOpenStatic
With Worksheets("Main").Cells(a, 1)
.ClearContents
.CopyFromRecordset rs1
End With
rs1.Close
Set rs1 = Nothing

A: I found a way to solve my above problem by simply setting two connections to the two different databases (working on the same MySQL instance).
My code looks like that :
Set conn = New ADODB.Connection
conn.Open "DRIVER={MySQL ODBC 5.3 Unicode Driver}" _
& ";SERVER=" & server_name _
& ";DATABASE=" & database_name _
& ";UID=" & user_id _
& ";PWD=" & password _
& ";OPTION=3" '

Set conn2 = New ADODB.Connection
conn2.Open "DRIVER={MySQL ODBC 5.3 Unicode Driver}" _
& ";SERVER=" & server_name _
& ";DATABASE=" & database_name2 _
& ";UID=" & user_id2 _
& ";PWD=" & password2 _
& ";OPTION=3" '

' SELECT Query with LEFT JOIN on the two different databases
Set rs1 = New ADODB.Recordset
sqlstr = "SELECT AB.* , XY.* FROM `abc`.`table_in_abc` AB LEFT JOIN `xyz`.`table_in_xyz` XY ON AB.`ID` = XY`ID`"
rs1.Open sqlstr, conn, adOpenStatic
With Worksheets("main").Cells(1, 1)
.ClearContents
.CopyFromRecordset rs1
End With
rs1.Close
Set rs1 = Nothing


text:
Q: FreeGlut (Similar to OpenGL) is taking picture of my desktop instead of drawing shapes Genpfault helped me tremendously is getting my code to compile. The code below is a reduced version of what I'm currently working with. However, Glut is not letting me draw shapes. The only thing that happens when I run the executable after compiling is that I see a screenshot of my desktop.
How can I remedy this so that I can actually draw colorful triangles and polygons on a black screen? Screenshot of what the program looks like when it runs
#include <iostream>
#include <GL/freeglut.h>

namespace GameBoxes
{
    template<class T>
    class Box
    {
        public:
            void display( void );
    };
} //GameBoxes

namespace GameBoxes
{
    template <class T>
    void Box<T>::display( void )
    {
        glClearColor( 0.0, 0.0, 0.0, 0.0 );       // black background
        glClear( GL_COLOR_BUFFER_BIT );
        glColor3f( 0.2, 0.2, 0.2 );
        glBegin( GL_TRIANGLES );
        glVertex2f( -0.5, -0.5 );
        glVertex2f(  0.5, -0.5 );
        glVertex2f(  0.0,  0.5 );
        glutSwapBuffers();
    }
} // GameBoxes

int main( int argc, char **argv )
{
    glutInit( &argc, argv );

    int windowPos1 = 0, windowPos2 = 0, windowSize1 = 400, windowSize2 = 400;
    glutInitDisplayMode( GLUT_DOUBLE | GLUT_RGB | GLUT_DEPTH );
    glutInitWindowPosition( windowPos1, windowPos2 );
    glutInitWindowSize( windowSize1, windowSize2 );
    glutCreateWindow( "square" );

    GameBoxes::Box<double> square;

    glutSetWindowData( &square );
    glutDisplayFunc( []()
    {
        auto instance = static_cast< GameBoxes::Box<double>* >(    glutGetWindowData() );
        instance->display();
    } );
    glutMainLoop();

    return 0;
};

A: You missed to finish the glBegin/glEnd sequence with glEnd
template <class T>
void Box<T>::display( void )
{
    glClearColor( 0.0, 0.0, 0.0, 0.0 );       // black background
    glClear( GL_COLOR_BUFFER_BIT );
    glColor3f( 0.2, 0.2, 0.2 );
    glBegin( GL_TRIANGLES );
    glVertex2f( -0.5, -0.5 );
    glVertex2f(  0.5, -0.5 );
    glVertex2f(  0.0,  0.5 );
    glEnd();  // <-------------- add glEnd
    glutSwapBuffers();
}

Note, that drawing by glBegin/glEnd sequences is deprecated since decades.
Read about Fixed Function Pipeline and see Vertex Specification and Shader for a state of the art way of rendering.


text:
Q: Windows RADIUS Server: Sync between RADIUS servers? We will be setting up a tertiary RADIUS server at a remote site.  Up until now, changes to the RADIUS database has been done manually, since it was only 2 servers.  With a third one coming online I wanted to see if there is some way to sync the changes between RADIUS servers using Windows Server 2008 R2.

A: Why not use an active directory back end? If you do this, you will only have to update the appropriate groups once instead of on all servers? This is very easy to configure in NPS.

A: I just came across your question.  I have been working with nps in windows 2008/2008r23 alot recently.  If you haven't found a good solution for this problem I might have one.
Decide on which of your servers is going to be your master.  Make your chances on this server.  Using powershell you can export the configuration for nps including shared secrets to a config file.  It will not include sql database accounting setup.  You can save it on a shared location between your servers.  Then on the slave server (your servers that you want to apply your changes to) you can run the powershell import.  You can script the export and import on your servers.
Export Config from powershell prompt on master server
netsh nps export filename = "C:\config.xml"  exportPSK = YES
Import Config from powershell prompt on slave server
netsh nps import filename = "C:\config.xml"
You can script this and also substitute any shared storage you have between the servers. With powershell you can copy the file over to your remote servers with
copy-item C:\Config.xml \server\share\Config.xml
Potentially you could take these pieces and with a little more powershell and have a script that you run whenever you make a change that will push out the change to all of your nps servers.

A: When I was looking for a solution for this problem, I found this article by Microsoft:
Manage Multiple NPS Servers by Using the NPS MMC Snap-in
If anybody has the same issue, I hope this link will help.


text: Q: Computing a projection of a $p$-adic plane curve Given a prime $p$ and a polynomial equation $f(x,y)=0$ with rational coefficients, I would like to obtain a precise description of the set of all numbers $y\in\mathbb Q_p$ such that the equation has a solution $x\in\mathbb Q_p$. Are there currently implemented methods for doing this?


text:
Q: Select only checkboxes that are checked in a column I have an html table that has 5 columns. 2 columns are checkboxes (entry and high) and the other 3 are data. I have 2 buttons, one is called entry and the other high. When a user clicks on the high button, I'm trying to check the column (high) only and get all that is checked, take those values and average them.
The same with entry, when the entry button is clicked, check only the checkboxes in column (entry) and take those values and average them.
So far I have a function to check both columns but not sure how to separately check and separate the columns to each button function only. I have tried the below, but the GetHigh function doesn't work.
Any points in the right direction would be appreciated!
Table
<input type="checkbox" class="entry" id="entry" value="{{$sup->entry}}" name="rows[]">
<input type="checkbox" class="high" id="high" value="{{$sup->high}}" name="rows[]">
{{$sup->entry}}
{{$sup->high}}
{{$sup->days}}

Buttons

                                     Entry Average

                                     High Average

Javascript
function GetEntry() {
                             //Create an Array.
                             var selected = new Array();

                             //Reference the Table.
                             var supTable = document.getElementById("supTable");

                             //Reference all the CheckBoxes in Table. I WANT ONLY THE ENTRY COLUMN
                             var entry = supTable.getElementsByTagName("INPUT");

                             // Loop and push the checked CheckBox value in Array.
                             for (var i = 0; i < entry.length; i++) {
                                 if (entry[i].checked) {
                                     selected.push(entry[i].value);

                                 }

                             }
                             // alert("Average: " + calculate(selected));
                             $(".text-message").text("Average: " + calculate(selected)).show();

                         }

function GetHigh() {
                             //Create an Array.
                             var selected = new Array();

                             //Reference the Table.
                             var supTable = document.getElementById("supTable");

                             //Reference all the CheckBoxes in Table. I WANT ONLY THE ENTRY COLUMN
                             var entry = supTable.getElementsByName("High");

                             // Loop and push the checked CheckBox value in Array.
                             for (var i = 0; i < high.length; i++) {
                                 if (high[i].checked) {
                                     selected.push(high[i].value);

                                 }

                             }
                             // alert("Average: " + calculate(selected));
                             $(".text-message").text("Average: " + calculate(selected)).show();

                         }

A: You can use a css selector to get the cells of your table
const getCheckboxes = columnIndex =>document.querySelectorAll(`tbody td:nth-child(${columnIndex}) input:checked`);

Or add a common class and select by the class to the checkboxes
const getCheckboxes = className =>document.querySelectorAll(`tbody .${className}:checked`);

Basic example:

const getCheckedCheckboxesClassName = className => document.querySelectorAll(`tbody .${className}:checked`);

const getCheckedCheckboxesByIndex = columnIndex =>document.querySelectorAll(`tbody td:nth-child(${columnIndex}) input:checked`);

const sumValues = cbs => [...cbs].reduce((total, cb) => total + +cb.value, 0);

const getTotal = (group) => {
  const cbs = getCheckedCheckboxesClassName(group);
  const value = sumValues(cbs);
  console.log(value);
}

const getTotalIndex = (index) => {
  const cbs = getCheckedCheckboxesByIndex(index);
  const value = sumValues(cbs);
  console.log(value);
}
<button type="button" onclick="getTotal('low'); getTotalIndex(1)">low</button>
<button type="button" onclick="getTotal('high'); getTotalIndex(2)">high</button>

      <input class="low" type="checkbox" value="1" />
      <input class="high" type="checkbox" value="10" />

      <input class="low" type="checkbox" value="2" />
      <input class="high" type="checkbox" value="20" />

      <input class="low" type="checkbox" value="3" />
      <input class="high" type="checkbox" value="30" />

      <input class="low" type="checkbox" value="4" />
      <input class="high" type="checkbox" value="40" />

      <input class="low" type="checkbox" value="5" />
      <input class="high" type="checkbox" value="50" />

A: getElementsByName is used to select HTML where their name="" attribute matches what you've entered, in this case 'High'. But your HTML in the example shows a different name.
You want to use querySelectorAll('high') to get all of the elements that have class="high" set.


text:
Q: Querying Contacts with Partial Data I've been trying to replicate some of the OEM dialer app behaviors regarding contact matching without much luck.  Basically, I'd like to populate a list of potential contact matches as the user types numbers into the dialer that match the typed entry against the phone number and the name, as most phones do.  For instance, typing 323 into the dialer would match contacts that have 323 anywhere in the NUMBER, such as (323)123-4567 as well as contacts with DISPLAY_NAME of Dad or Daffy, etc.
I know that ContactsContract.PhoneLookup.CONTENT_FILTER_URI is supposed to be used to match phone numbers while ignoring formatting (so querying that uri against 5551234567 would return a contact whose number was stored as (555)123-4567).  The problem is that I cannot get this to work with partial numbers, so that querying against 5551 would include the same result, even if I add selection args with a LIKE clause and wildcards.  If I use any of the other URIs, the selection arg with LIKE will return partial results, but the formatting screws things up so that 5551 would not match, only 555)1 does.  Can anybody explain how I might get a partial number match while ignoring formatting from a single query?  Other attempts to use multiple queries have proved to be too slow and not offer the experience I see on most phones (I have noticed that the stock dialer in the Android source does not do the contact matching, only search, so no help there).
Secondly, for the name part of things, I have a working solution, although I'm not sure it is the best strategy.  I had hoped to use ContactsContract.Contacts.CONTENT_FILTER_URI, as the docs say this is how you should filter results for as-you-type suggestions, but again that would only work for an alpha search of a single partial name, while I need to translate 323 to search against partial matches for all combinations of the associated keypad letters (dad, dae, daf, ead, eae, eaf, fad, etc).  I have instead used ContactsContract.CommonDataKinds.Phone.CONTENT_URI with selection args using LIKE to match against all possibilities, and then subsequent requests narrow the field based on contact IDs returned from the previous request.  Is there a way to leverage ContactsContract.Contacts.CONTENT_FILTER_URI for this type of numeric pattern matching?  I haven't tried breaking it down to multiple requests, but based on the latency I experienced trying something similar for partial number matching described above, I suspect it would not work very well.
Any advice is much appreciated!
Thanks,
Scott

A: I've been struggling with this for 2 days now and I finally got a solution that works as desired by myself and Scott.
You need to use this URI
ContactsContract.CommonDataKinds.Phone.CONTENT_FILTER_URI and append URI path which is the partial string (name or number).
Uri uri = Uri.withAppendedPath(ContactsContract.CommonDataKinds.Phone.CONTENT_FILTER_URI, Uri.encode(partial));
Cursor cursor = context.getContentResolver().query(uri, null, null, null, null);

Hope this helps!

A: This technique works for me, to parse partial number, by using:
//encode the phone number and build the filter URI
Uri contactUri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, Uri.encode(number.substring(len-9)));

String selection = PhoneLookup.NUMBER + " LIKE %" + number.substring(len-9) + "%";

Cursor cursor = context.getContentResolver().query(contactUri, projection, selection, null, null);

Complete Example:
private void getContactDetails(String number) {
    // define the columns you want the query to return
    String[] projection = new String[] {
        PhoneLookup.DISPLAY_NAME,
        PhoneLookup._ID,
        PhoneLookup.LOOKUP_KEY};
    int len = number.length();
    // encode the phone number and build the filter URI
    Uri contactUri = Uri.withAppendedPath(PhoneLookup.CONTENT_FILTER_URI, Uri.encode(number.substring(len-9)));

    String selection = PhoneLookup.NUMBER + " LIKE %" + number.substring(len-9) + "%";

    Cursor cursor = context.getContentResolver().query(contactUri, projection, selection, null, null);

    if(cursor != null) {
        if (cursor.moveToFirst()) {
            String name = cursor.getString(cursor.getColumnIndex(PhoneLookup.DISPLAY_NAME));
            String lookUpKey = cursor.getString(cursor.getColumnIndex(PhoneLookup.LOOKUP_KEY));
        }
        cursor.close();
    }
}

It parses and matches last 10 digits of number, hope it will help !!!


text:
Q: What are the Ultimate Scream Card in FIFA 19
Halloween is coming! Many sites offer the Ultimate Scarem Cards, I can't understand the feature of that cards. So, who can explain the features of this card for me? Thank you!

A: The FAQ here states:
"Ultimate Scream is back in FIFA 19 Ultimate Team, and a squad of 21 shapeshifting beasts has been let loose in FUT. These beasts have been released in the form of special player items that will have a boost throughout the FUT season to two of their six stat categories. These Ultimate Scream players are unlike any other in FIFA 19 Ultimate Team; not only will each player have two of their six attributes boosted at all times, but the stats that get boosted will change throughout the season.
When these boosts will occur, how often they occur, and which two of the six attributes are shifted each time is a complete mystery."
I suggest you read through the rest of the FAQs in the link above for more information.


text:
Q: Switching between two accounts using IOS6 settings I've been trying for the past two days to connect to multiple accounts for my app, without success.
I've read that there was potentially a problem with Facebook SDK not clearing the cached token correctly. I am using version 3.1.1.
Here is how it goes.
From fresh install:

*

*Connect to account 1.

*Launch game and login successfully. Everything is fine.

*Close the game

*Goto settings and change to account 2.

*Launch game, login failed.

I Am receiving that error code from openActiveSessionWithReadPermissions : FBSessionStateClosedLoginFailed
And even if I press the OK button when Facebook is asking for my permission to access my info, the granted variable that comes back says NO.
The research I did brought me multiple solutions that failed, unfortunately.
I tried resynchronizing with this function:
- (void)fbResync
{
    ACAccountStore *accountStore;
    ACAccountType *accountTypeFB;
    if ((accountStore = [[ACAccountStore alloc] init]) && (accountTypeFB = [accountStore     accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierFacebook] ) )
    {

    NSArray *fbAccounts = [accountStore accountsWithAccountType:accountTypeFB];
    id account;
    if (fbAccounts && [fbAccounts count] > 0 && (account = [fbAccounts objectAtIndex:0]))
    {

        [accountStore renewCredentialsForAccount:account completion:^(ACAccountCredentialRenewResult renewResult, NSError *error)
        {
            //we don't actually need to inspect renewResult or error.
            if (error){

            }
        }];
    }
}

fbAccounts always return me an empty array. So I cannot really resynchronize.
I also tried to clear facebook token in my  status switch
case FBSessionStateClosed:
case FBSessionStateClosedLoginFailed:
{
     [FBSession.activeSession close];
     [FBSession.activeSession closeAndClearTokenInformation];
     // Clear out the Facebook instance

     [self.facebook logout];
     self.facebook.accessToken = nil;
     self.facebook.expirationDate = nil

}break;

No matter what I do, It seems that I cannot completely get rid of my facebook token.
The only way I found was to reset the settings of the IPAD which is not a solution.
Does anybody have more options I could try?
Thanks!
Tickets I'm aware of :

*

*Facebook authorization fails on iOS6 when switching FB account on device

*Facebook SDK 3.1 - Error validating access token


text:
Q: Função para rearranjar valores em um grupo de 5 campos de um formulário, usando jQuery Eu tenho 5 campos de um formulário e gostaria de, através de uma função, rearranjar os valores dos mesmos fazendo com que os primeiros campos sejam preenchidos e os últimos vazios, de acordo com os valores existentes na ordem crescente.
Por exemplo:
HTML:
<input id="campo1" type="text" />

<input id="campo2" type="text" value="uva" />

<input id="campo3" type="text" />

<input id="campo4" type="text" value="laranja" />

<input id="campo5" type="text" />

Ao chamar a função, ficaria assim:
<input id="campo1" type="text" value="uva" />

<input id="campo2" type="text" value="laranja" />

<input id="campo3" type="text" />

<input id="campo4" type="text" />

<input id="campo5" type="text" />

Atualizando: A ordem dos valores devem obedecer o id dos campos na ordem crescente (campo1, campo2...).

A: Podes fazer isso assim:
var inputs = Array.from(document.querySelectorAll('#campox input'));
var valores = inputs.filter(el => el.value.trim());
inputs.forEach((el, i) => el.value = valores[i] && valores[i].value || '');

jsFiddle: https://jsfiddle.net/x3ormw3y/2/
Basicamente os passos são:

*

*coloca os inputs todos numa array

*filtra os elementos vazios

*percorre os inputs de novo usando os valores da nova array só com os inputs preenchidos

Em JavaScript ES5 poderia ser
var inputs = [].slice.call(document.querySelectorAll('#campox input'));
var valores = inputs.filter(function(el){
    return el.value.trim();
});
inputs.forEach(function(el, i){
    el.value = valores[i] && valores[i].value || '';
});


text:
Q: git-ftp: Is not a git command I am trying to install git-ftp under my windows 8.1 install in my git version 2.17.0.windows.1
I did the following:
cd /c/"Program Files"/Git
git clone https://github.com/git-ftp/git-ftp git-ftp.git
cd git-ftp.git && chmod +x git-ftp
cp /c/"Program Files"/Git/git-ftp.git/git-ftp /c/"Program Files"/Git/bin/git-ftp

However, when restarting on a fresh git console as admin, I get the following:
$ git ftp
git: 'ftp' is not a git command. See 'git --help'.

The most similar command is
        fetch

The official installation instructions also cp the git-ftp file to the folder C:\Program Files (x86)\Git\bin.
Any suggestions what I am doing wrong?
I appreciate your replies!
UPDATE
After executing I found my execution path:
$ git --exec-path
C:\Program Files\Git\mingw64/libexec/git-core

I copied the file:
cp /c/"Program Files"/Git/git-ftp.git/git-ftp /c/"Program Files"/Git/bin/git-ftp

The file is now located:

However, I still get the above error that git: 'ftp' is not a git command..

A: I was facing same problem after these install instructions.
Solution: I've copied file git-ftp from c:\Program Files\Git\bin\ to the folder c:\Program Files\Git\mingw64\libexec\git-core\ and command gif ftp push -s was finally successful.
Thank you all for you hints above! Mike


text:
Q: Почему «Первый запрос к API» users.get возвращает city.id, но не city.title? В настройках iFrame-приложения для ВКонтакте в качестве Первого запроса к API я указал:
method=users.get&user_ids={viewer_id}&fields=sex,city,photo_big&format=JSON&v=5.52

В официальной документации users.get точно такой же запрос возвращает:
response: [{
    id: 597xxxxx,
    first_name: 'Alexander',
    last_name: 'Farber',
    city: {
        id: 1945522,
        title: 'Bochum'
    },
    photo_50: 'http://cs5344.vk....1265/e_9ae5906d.jpg',
    verified: 0
}]

А вот в мой PHP-скрипт (он же "Адрес IFrame" в настройках) приходят следующие данные по HTTP GET:
[api_result] => {"response":[{
    "uid":597xxxxx,
    "first_name":"Alexander",
    "last_name":"Farber",
    "sex":2,
    "city":1945522,
    "photo_big":"http:\/\/cs5344.vk.me\/u59751265\/a_047c17e7.jpg"
}]}

То есть приходят только данные city.id (1945522), в то время как мне нужен city.title (Bochum).
Конечно, можно произвести второй вызов к API и получить через database.getCitiesById (или старую функцию getCities) нужное название города... но почему оно не приходит сразу?


text:
Q: How to add user to QBRTCSession if it is already established I have audio chat session (QBRTCSession) object with 3 QBUUsers in it. I need possibility to add another QBUUser in that call session. Can I do this without creating new session and calling to all users again?
Currently I create session in QBRTCClient this way
NSArray *opponentsIDs = @[@2145, @2144, @2143];
QBRTCSession* session =
[QBRTCClient.instance createNewSessionWithOpponents:opponentsIDs
withConferenceType:conferenceType];

A: As for now you should recreate session.
This feature is planned for future releases.


text:
Q: Monomorphisms and epimorphisms in Ab I have a rather simple question though I couldn't find the answer here. Do monomorphisms (epimorphisms) have left (right) inverses in the category of abelian groups? How can we prove this fact knowing that the kernel (cokernel) must be trivial in this case? Will be also glad just for the link with the proof.

A: $f:\Bbb Z\to\Bbb Z$ given by $f(a)=2a$ has no left inverse.
The projection $\pi:\Bbb Z\to \Bbb Z/2\Bbb Z$ has no right inverse.


text:
Q: How to clear all memory used in WebAssembly How would one simply clear up all of the memory used by a WebAssembly instance. But still allow for the WASM binary to be run again.
Essentially, I have a WASM operation that uses a lot of memory, and if memory runs out (too much memory has been allocated and the system cannot give anymore), I simple want to reset the program; by clearing all of the memory used, but also allow for the program to be run again... Is there a way to do this via the WebAssembly JavaScript API, as my searches online have yielded no results. Would one just delete the shared array buffer, and reallocate that to the same variable - I do not know?
Any help would be much appreciated. Many thanks.


text:
Q: Allow duplicate names in google sheets data validation I'm requiring duplicate names within a sheet to be read by data validation.
Currently at the minute, if a duplicate first name appears, it won't appear within the drop down menu even if the last name and other data is different, if it views the first column to be a duplicate it won't be an option to select.
Example:
John Smith  01/01/2000 - 22/02/2022
John Doe    05/05/2005 - 15/01/2021
John Robert 18/08/1970 - 12/11/2021

It will only read the top one as the second and third "First name" is a duplicate.

Here is the link to the test sheet to view what's set up currently - CLICK ME
Please note the link allows editors for the next hour then it'll be marked as view only
Any and all help is highly appreciated.

A: Created a work-around solution
Created an entirely new column and created a join function Google Join Functions =A2:A&" "&B2:B was the exact formula made (as seen on the spreadsheet) I then proceeded to change the data validation on the first page (Pretty side) to follow that new data column created instead of the original column it was finding, so it now finds a full name eliminating any duplicates (even if there is a duplicate first name) as it seeks for a whole name instead.
I then moved that entire column to the first (A) column and marked it as "Hide" so you don't see that text as it's irrelevant for what I need, then the rest of the "Pretty side" sheet follows the VLOOKUP function currently in place.
The only problem I see having down the future is having the exact same first and last name and a D.O.B being the only difference. Until that happens this will suffice.


text:
Q: How to force data filtering based on a parent ID, following an additional lookup on an API key in Loopback4/Typescript I am a bit of a noob to Typescript and loopback(lb4) and I am at a sticking point, where I am pulling my hair a little and I am hopeful that the community may be able to assist. I am trying to complete a lookup for an record ID based on a API key that is against the database record, so I can then use this record as a foreign key for deriving another set of results from another database table. I am working with a preexisting database
Error showing as the below.

loopback:connector:mssql Result: null
  {"recordsets":[[]],"recordset":[],"output":{},"rowsAffected":[0]}
  +302ms /Users/bloop/Desktop/AngularTestFolder/ZaharaReporting/zaharareporting/dist/controllers/tenancy.controller.js:27
              return object.tenancyid.valueOf;
                            ^

TypeError: Cannot read property 'tenancyid' of null
I have tried a number of things and suspect that it is a lack of understanding some of the fundamentals of typescript or loopback4, so my apologies if this is the case, I am just finding myself going over the same ideas on how to get around it, so I feel in need of someone to point out why and how I am being stupid please.
I am trying to get the endpoint /api/{apikey}/GetSpecificBusinessunit' to work.
but I am getting `FindTenancyID.IdOnly' coming back as undefined
import {
  repository,
} from '@loopback/repository';
import {
  param,
  get,
} from '@loopback/rest';
import { Tenancy, Businessunit } from '../models';
import { TenancyRepository, BusinessunitRepository } from '../repositories';

class TenancyHelper {
  constructor(@repository(TenancyRepository)
  public tenancyRepository: TenancyRepository) { }

  // Query filter tenancy to get Id only
  async idOnly(api: String) {
    return await this.tenancyRepository.findOne(
      { where: { apikey: api }, fields: { tenancyid: true }, limit: 1 },
      function (err: any, object: Tenancy) {
        //console.log("TenancyId was " + object.tenancyid);
        return object.tenancyid.valueOf;
      }).catch(a => console.log(a));
  }
}

export class TenancyController {
  constructor(
    @repository(TenancyRepository)
    public tenancyRepository: TenancyRepository,
    @repository(BusinessunitRepository)
    public businessunitRepository: BusinessunitRepository,
  ) { }

  @get('/api/{apikey}/GetSpecificBusinessunit', {
    responses: {
      '200': {
        description: 'Get BusinessUnit by API Key',
        content: { 'application/json': { schema: { 'x-ts-type': Businessunit } } },
      },
    },
  })
  async GetBusinessunit(
    @param.path.string('apikey') Apikey: String,
    FindTenancyId = new TenancyHelper(this.tenancyRepository),

  ): Promise<Businessunit[]> {
    return new Promise<Number>(function (resolve, reject) {
      Number(FindTenancyId.idOnly(Apikey));
    })
      .then(a => {
        console.log("This was the excecuted: " + a);
        return this.businessunitRepository.find(
          { where: { tenancyid: a } })
      })
  }

I expect a JSON object with a return of all business units with this tenancy API key defined in the path to be returned.

A: Just an answer to my own question incase someone looks to try a similar outcome.
I wasn't using promises correctly(And possibly may not still), but this functions correctly for me.
@get('/api/{apikey}/GetBusinessunits', {
    responses: {
      '200': {
        description: 'Get BusinessUnits for API Key',
        content: { 'application/json': { schema: { 'x-ts-type': Businessunit } } },
      },
    },
  })
  async GetBusinessunit(
    @param.path.string('apikey') Apikey: String
  ): Promise<Businessunit[]> {
    return await this.tenancyRepository.findOne(
      { where: { apikey: Apikey }, fields: { tenancyid: true }, limit: 1 }
    ).then((a) => {
      let id = -1;
      if (a !== null) {
        id = Number(a!.tenancyid);
      }
      return this.businessunitRepository.find(
        { where: { tenancyid: id } })
    })
  }

A:
I wasn't using promises correctly(And possibly may not still), but this functions correctly for me

In LoopBack 4, we avoid .then() and .catch() APIs in favor of await and regular try/catch blocks.
export class TenancyController {
  //...
  async GetBusinessunit(
    @param.path.string('apikey') Apikey: String
  ): Promise<Businessunit[]> {
    const a = await this.tenancyRepository.findOne(
      { where: { apikey: Apikey }, fields: { tenancyid: true }, limit: 1 }
    );

    let id = -1;
    if (a !== null) {
      id = Number(a!.tenancyid);
    }
    return this.businessunitRepository.find(
      { where: { tenancyid: id } })
    });
  }
}


text:
Q: Effective way of using SQL statements in Protractor Tests I am writing a protractor test that tries to validate the UI against the DB values. I am first trying a simple test
This is how my step definition looks like:-
Given(/^I run a random select query$/, function(){
    let sql2 = "Select * from table Where ID  = 8888";
       return this.db.getConnection(dbConfig).then(function(connection) {
                return connection.execute(sql2).then(function(result, err){
                    return console.log(result.rows.toString());
           });
          });

       });

The above test works fine
1) this.db refers to oracleDb import and it's part of my custom Constructor in world.js
2) DBconfigs are included as a file in my config.js
Could someone please advise as to how I can abstract the hardcoded sqls out of  the step def and make them separate so as to maintain them effectively;  call or generate them when I have to for a certain step. Basically, any example or idea of managing SQLs, db tables and connections to diff environments in a more effective manner

A: This is not an answer but an approach,  probably need more one time efforts but it has worked out really well for me. if you can build a RESTfull APIs around DB quires and call the APIs whenever needed.


text:
Q: How to get value or name of enum from SQLAlchemy result query? I want to build an API for my project and return everything as JSON using Flask and SQLAlchemy. Unfortunately, SQLAlchemy did not return the query as JSON Seriazeble, so I'm using data classes to solve that problem. The code working and it returns JSON as I wanted. The problem occurs when I try to implement enum column like gender, because the enum column returns an enum object, so it's not JSON Seriazeble again. This is the code:
ActivityLevel.py
class GenderEnum(Enum):

    p = 0
    l = 1

@dataclass
class ActivityLevel(db.Model):
    __tablename__ = "activity_level"

    id: int
    name: str
    gender: GenderEnum
    activity_score: float
    date_created: str

    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(100), nullable=False)
    gender = db.Column(db.Enum(GenderEnum), nullable=False)
    activity_score = db.Column(
        db.Float(precision=3, decimal_return_scale=2), nullable=False
    )
    date_created = db.Column(db.DateTime, default=datetime.utcnow)

ActivityLevelController.py

from flask import jsonify
from flask_restful import Resource
from models.ActivityLevel import ActivityLevel

class ActivityLevelController(Resource):
    def get(self):
        try:
            activity = ActivityLevel().query.all()
            result = {
                "activity": activity
            }

            print(activity)

            return jsonify(result)

        except Exception as e:
            print(e)
            return jsonify({"message": "Error again"})

And this is the result of print(activity)

[
ActivityLevel(id=1, name='asdfasdf', gender=<GenderEnum.p: 0>, activity_score=12.0, date_created=datetime.datetime(2022, 8, 12, 10, 54, 58)),
ActivityLevel(id=2, name='qwerqwer', gender=<GenderEnum.l: 1>, activity_score=13.0, date_created=datetime.datetime(2022, 8, 12, 10, 54, 58))
]

As you can see, gender did not return l or p, and it return <GenderEnum.l: 1>. Which is correct as the documentation says https://docs.python.org/3/library/enum.html, when i call GenderEnum.l it will result just like the response.
What I want to ask is something like this:

*

*Is there a way to override the return value of GenderEnum.l to the value or name by doing something in GenderEnum class?

*Is there a way I can get the value or name of GenderEnum when I query the data from the database?

*Or a way to make the query call the gender value or name as the default instead the enum object?

Thank you very much.

A:

*

*Is there a way to override the return value of GenderEnum.l to the value or name by doing something in GenderEnum class?

That's not really what Enums are meant to do, but you can access the name and value of your enum via the name and value attributes. In fact, SQLAlchemy will store the name of the Enum in the database in most cases.

*Is there a way I can get the value or name of GenderEnum when I query the data from the database?

You define your model with an gender as an enum, so when loading, that is what you will get.

*Or a way to make the query call the gender value or name as the default instead the enum object?

Same answer as above, you define gender as an enum, so SQLAlchemy gives it to you.
But to fix your problem, I can only recommend you look into dependency inversion.
Have a model which corresponds to your logic and allows you to solve the problem, then this model can be mapped to an entity, which allows you to store the model in whatever persistance layer, and finally a converter/serialiser for your model to load from/dump to your API.
This way, your model is not tied to where you store it or how you recieve it.
Slightly simplified example from your code:
# model.py
from dataclasses import dataclass, field
from enum import Enum, auto

class GenderEnum(Enum):
    p = auto()
    l = auto()

@dataclass
class ActivityLevel:
    id: int = field(init=False)  # NOTE add `repr=False` if trying to display instances
    name: str
    gender: GenderEnum

# orm.py
from sqlalchemy import Column, Enum, ForeignKey, Integer, String, Table
from sqlalchemy.orm import registry

from .model import ActivityLevel

mapper_registry = registry()

activity_level = Table(
    "activity_level",
    mapper_registry.metadata,
    Column("id", Integer, primary_key=True),
    Column("name", String(100), nullable=False),
    Column("gender", Enum(GenderEnum), nullable=False),
)

def start_mapper():
    mapper_registry.map_imperatively(ActivityLevel, activity_level)

# serialiser.py
from json import JSONDecoder, JSONEncoder

from .model import ActivityLevel, GenderEnum

class ActivityLevelJSONEncoder(JSONEncoder):
    def default(self, o):
        try:  # NOTE duck typing and asking for forgiveness not permission
            return {
                "name": o.name,
                "gender": o.gender.name,
            }
        except AttributeError:
            return super().default(self, o)

class ActivityLevelJSONDecoder(JSONDecoder):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, object_hook=self._object_hook, **kwargs)

    @staticmethod
    def _object_hook(d: dict) -> ActivityLevel:
        return ActivityLevel(
            name=d["name"],
            gender=GenderEnum[d["gender"]],
        )

Then in during application startup, start the mappers, and whenever needed json.dumps your ActivityLevel instances with the kwarg cls=ActivityLevelJSONEncoder.

A: This is what I found to temporarily fix my problem. I found this post and answer and follow the answer of @Vlad Bezden that uses the f-string method to override the return value of enum object when I call it like this GenderEnum.l from this <GenderEnum.l: 1> to just the value like 0 or 1. This is what I change in the enum class
class GenderEnum(int, Enum):

    p = 0
    l = 1

I add additional int. From what I noticed in the query behavior, the query just essentially calls enum object like this GenderEnum.l so that's why I got the response like that, just like what ljmc's says in the comment of his/her answer. That code initially overrides the response to the value of the enum object. If you want to return the name of the enum object, I'm terribly sorry, I can't seem to find a way to accomplish that.
After that it change the result to this
{
    "activity": [
        {
            "date_created": "Fri, 12 Aug 2022 17:22:03 GMT",
            "gender": 0,
            "id": 1,
            "name": "asdf",
            "activity_score": 12.0
        },
    ],
}

It works and I can return it as JSON. In contrast to that, I really not recommended this way to solve this problem, cause I find a hard way to do some relationship calls like join, and I really recommend anyone to follow Ijmc's answer to solving this problem, that's why I gonna accept Ijmc's answer as the correct one.
Thank you very much for helping me Ijmc for giving me insight, so I can come up with this little solution.

In any case of you guys wondering example how to do a join so i can return it as json, link to this post


text:
Q: How to use std::list to implement LRU Using a list and a hash-map, we can implement LRU in Java.
How would you implement an LRU cache in Java?
In C++, does std::list allow us to implement this?
For each element in cache, we need to know its position in the list.
However, after removing a position, does list ensure that the positions (list::iterator) after this one will not be changed?

A: Yes, you can implement LRU using std::list and std::map.
std::list iterators referencing retained elements are unaffected by insertions and erasures of other elements. See this answer: Iterator invalidation rules
The same is true for std::map. See this answer: Does insertion to STL map invalidate other existing iterator?


text:
Q: Empty SESSION Table in Keycloak H2 Database I'm using Keycloak 15.0.2 with the default H2 database. I have logged in several users and can get active session in the Keycloak session tab, but in DB, I cannot see any entries in all tables related to sessions like USER_SESSION and CLIENT_SESSION.
Does anyone have any suggestion that how can I get these entries?
Thanks in advance.

A: Keycloak does not store sessions in the database, except for offline sessions. Sessions are stored in-memory in Infinispan caches.
You can use the REST API to access sessions.


text:
Q: UIPanGestureRecogniser not working properly I've got this function to handle the dragging of a view:+
func handlePan(recognizer:UIPanGestureRecognizer) {
    let translation = recognizer.translationInView(self.view)

    let newCenter = CGPointMake(self.view.bounds.size.width / 2,
        recognizer.view!.center.y + translation.y)

    print("the translation x:\(translation.x) & y:\(newCenter.y)")

    if (newCenter.y >= 397 && newCenter.y <= 632) {
        recognizer.view!.center = newCenter

        recognizer.setTranslation(CGPointZero, inView: self.view)
    }

}

The positions are right.
However, the view that I need to move often blocks while I'm dragging, so I need to stop and start dragging it again.
How can I solve this?
EDIT: My code looks like this now, but I still got the problem:
func handlePan(recognizer:UIPanGestureRecognizer) {
    let translation = recognizer.translationInView(self.view)

        switch recognizer.state {
            case .Ended:fallthrough
            case .Changed:

                let newCenter = CGPointMake(self.view.bounds.size.width / 2,
                    recognizer.view!.center.y + translation.y)

                print("the translation x:\(translation.x) & y:\(newCenter.y)")

                if (newCenter.y >= 397 && newCenter.y <= 632) {
                    recognizer.view!.center = newCenter
                    recognizer.setTranslation(CGPointZero, inView: self.view)}

            default : break }

}

A: Since I don't know the other parts of your code, this is a section assuming what yours might and should look like:
class ViewController: UIViewController {

// Gesture function
func panAround(recognizer: UIPanGestureRecognizer) {
    switch recognizer.state {
    ...
    case .Changed:
        let translation = recognizer.translationInView(yourView)
        let newCenter = CGPointMake(self.view.bounds.size.width / 2,
                recognizer.view!.center.y + translation.y)

        print("the translation x:\(translation.x) & y:\(newCenter.y)")

        if (newCenter.y >= 397 && newCenter.y <= 632) {
            recognizer.view!.center = newCenter

            // Updating the UI whenever there is a "small change"
            updateUI()

            recognizer.setTranslation(CGPointZero, inView: self.view)
        }
    ...
    }
}

private func updateUI() {
    yourView.setNeedsDisplay()
}

NOTE: The code above WILL NOT work directly by copy and pasting, I am merely pointing out where you can make adjustments.


text:
Q: How would I tile a section of a texture in screen space? Do forgive me if this has been asked before, I've been looking for the answer to this all day and all I'm coming up with is help with tile based 2D games. x~x
I'm trying to create a skinnable GUI in Direct3D 9, using an XML file that has positions for each element and an option to stretch or tile them. Stretching's a simple enough procedure, but I've been unable to figure out a way to tile a small section of a texture. Traditionally to tile a texture I would just set the UV coordinates to > 1.0, but the source texture coordinates are only going to be a small subset of the whole texture, such as 0.4 to 0.5.
I have a feeling I missed something really obvious, but how would I go about simply tiling instead of stretching? My best guess is it has something to do with having more than one set of texture coordinates, but from there, I'm not sure where to go.
The project currently uses the fixed function pipeline, so I would prefer an answer using that if possible, but I would not turn down an answer that uses a shader if that's the only way.

A: I understand you want to tile only a subset of the texture, right? Then things get complicated.
Assume we want to tile u-coord between u1 and u2 values, u1 < u2.
Then we need a function f(u), so that
f(0.0) = u1
f(0.5) = (u1+u2)/2
f(0.9999) = u2
f(1.0) = u1
f(1.5) = (u1+u2)/2
f(1.9999) = u2
f(2.0) = u1
and so on...

An appropriate function is f(u) = frac(u) * (u2-u1) + u1
The same goes for v-coord, f(v) = frac(v) * (v2-v1) + v1
Notice that it's tiling without mirroring. If you need mirroring, then the function should be a triangular-wave function, which is t(x) = arcsin(sin(pi*(x-0.5)))/pi+0.5 and f(u) = t(u) * (u2-u1) + u1. Using trigonometric functions can be expensive though.
I don't know if it's possible with fixed pipeline, but you can do it easily in pixel shader (HLSL code):
// float2 tex_coord -> (u,v) from vertex shader, in [0,n] range,
//                     n - number of repetitions
// float2 tex1, tex2 -> constants, subrange of [0,1] coords that will be tiled

// no mirroring
float4 color = tex2D(sampler, frac(tex_coord) * (tex2-tex1) + tex1);

or
// mirroring, t(x) = arcsin(sin(pi*(x-0.5)))/pi+0.5
float4 color = tex2D(sampler, t(tex_coord) * (tex2-tex1) + tex1);

EDIT:
a better way to compute triangular-wave function: t1(x) = abs(2(0.5x-floor(0.5x+0.5))) or t2(x) = abs(2(frac(0.5x+0.5))-1) (not exactly the same as t1 but correct for non-negative numbers).


text:
Q: Use authentication for more than one model in cakephp 3 I am trying to have a web page with two kinds of logins, one for "users" and another one for "handlers". Both kind of models are very different from each other and, therefore, I can't make the login by giving them different roles.
What I want is to have two sepparate views where each kind of person can access the web and maintain their session open while they are logged in, but I don't know how to handle this in my AppController (when loading the Auth component).
I have tried using alliases and reconfiguring my Auth component in the controller where the second component should be used, but none of these options have worked in my case.


text:
Q: $f: \mathbb{N} \to \mathbb{N}$, Find $f$ with Mathematical Induction of the value of $f(x)-f(x-1).$
$ f:\mathbb{N}\to\mathbb{N}. \\ \ \\\text{i)} \ \ \ \ f(x-1)f(x+1)=\big(f(x)\big)^2 \text{ for } \forall x \in \mathbb{N} \text{ s.t. } \frac x 2 \in \mathbb{N}. \\ \text{ii)} \; \; f(x-1)+f(x+1)=2f(x) \text{ for } \forall x \in \mathbb{N} \text{ s.t. } \frac x 2 \not\in \mathbb{N}. \\ \text{iii)} \ f(2)=2f(1) \\ \ \\ \text{Find } f \text{ with Mathematical Induction of the value of } f(x)-f(x-1).$

Here is my solution, which is quite long and hard to read. I'm posting my solution, but I'm waiting for another clear solution for this.
\begin{align}
\ \\
\ \\
\text{Claim: } & f(x)-f(x-1) = \bigg[ \frac {x+1} 2 \bigg]f(1). \ \text{($[x]$: greatest integer function.)} \\
\ \\
x=2; \ & f(2)-f(1)=2f(1)-f(1)=f(1)=\bigg[ \frac 3 2 \bigg]f(1). \\
\ \\
\text{Assume) } & \text{The Claim is valid until } x=k. \\
\ \\
x=k+1; \ & \Bigg( \text{WTS) } f(k+1)-f(k)=\bigg[ \frac {k+2} 2 \bigg]f(1). \Bigg) \\
\text{(i)} \ \frac k 2 \not\in \mathbb{N}: \ & \bigg[ \frac {k+1} 2 \bigg] = \bigg[ \frac {k+2} 2 \bigg]. \\
& f(k-1)+f(k+1)=2f(k). \\
\therefore \ & f(k+1) =(f(k)-f(k-1))+f(k) \\
& = \bigg[ \frac {k+1} 2 \bigg]f(1)+f(k) \\
& = \bigg[ \frac {k+2} 2 \bigg]f(1)+f(k). \\
\ \\
(ii) \ \frac k 2 \in \mathbb{N}: \ &\bigg[ \frac {k+1} 2 \bigg] = \bigg[ \frac {k+2}{2} \bigg]-1. \\
& f(k-1)f(k+1)=f(k)^2. \\
\therefore \ & f(k+1)\Bigg( f(k)-\bigg[ \frac {k+1} 2 \bigg]f(1)\Bigg)=f(k)^2. \\
\Rightarrow\ & f(k)\Big(f(k+1)-f(k)\Big)=\bigg[ \frac {k+1} 2 \bigg] f(1)f(k+1). \\
\Rightarrow \ & f(k+1)-f(k)=\bigg[ \frac {k+1} 2 \bigg] f(1) \frac {f(k+1)}{f(k)} \\
& = \bigg[ \frac {k+1} 2 \bigg] f(1)\Bigg( 1 + \frac {\big[ \frac {k+1} 2 \big]f(1)} {f(k-1)} \Bigg) \\
& = \Bigg( \bigg[ \frac {k+1} {2} \bigg]+\frac {\big[ \frac {k+1} 2 \big]^2f(1)} {f(k-1)} \Bigg) f(1) \\
& = \Bigg( \bigg[ \frac {k+2} 2 \bigg]-1+\frac {\Big( \big[ \frac {k+2} 2 \big]^2-2\big[ \frac {k+2} 2 \big]+1 \Big) f(1)} {f(k-1)} \Bigg) f(1) \\
& = \Bigg( \bigg[ \frac {k+2} 2 \bigg] + \frac {\frac {k^2-4k+4} 4 -k-2+1} {f(k-1)} - 1 \Bigg)f(1) \\
& = \Bigg( \Bigg[ \frac {k+2} 2 \Bigg]+\frac {k^2f(1)} {4f(k-1)}-1 \Bigg) f(1). \\
\ \\
&\begin{matrix}
& f(k-1)-\color{Red}{f(k-2)} & = & \Bigg[ \dfrac k 2 \Bigg]f(1) \\
& \color{Red}{f(k-2)}-\color{Blue}{f(k-3)} & = & \bigg[ \dfrac {k-1} 2 \bigg]f(1) \\
& \color{Blue}{f(k-3)}-\color{Red}{f(k-4)} & = & \bigg[ \dfrac {k-2} 2 \bigg]f(1) \\
& \vdots & \vdots & \vdots \\
{\huge +} & \color{Red}{f(2)}-f(1) & = & \bigg[ \dfrac 3 2 \bigg]f(1).   \\
{\Huge-} & {\Huge ----} & {\Huge --} & {\Huge ---} \\
& f(k-1)-f(1) & = &\Bigg(\displaystyle \sum_{i=3}^k \bigg[ \dfrac k 2 \bigg] \Bigg) f(1)
\end{matrix} \\
\therefore \ & f(k-1)=f(1)+\Bigg( \displaystyle \sum_{i=2}^{\frac k 2} \bigg[ \frac {2i-1} 2 \bigg] + \bigg[ \frac {2i} 2 \bigg] \Bigg) f(1) \\
& = f(1)+\Bigg( \displaystyle \sum_{i=2}^{\frac k 2} (i-1)+i \Bigg) f(1) \\
& = \Bigg( \displaystyle \sum_{i=1}^{\frac k 2} 2i-1 \Bigg)f(1) \\
& = \Bigg( \bigg( \frac k 2 \bigg) \bigg( \frac k 2 + 1 \bigg)-\frac k 2 \Bigg)f(1) \\
& = \frac {k^2f(1)} 4. \\
\therefore \ & 4f(k-1)=k^2f(1). \label{(1)} \tag{1}\\
\ \\
\therefore \ & f(k+1)-f(k)=\Bigg( \bigg[ \frac {k+2} 2 \bigg] + \frac {k^2f(1)} {4f(k-1)} - 1 \Bigg)f(1) \\
& = \bigg[ \frac {k+2} 2 \bigg]f(1). \\
\ \\
\therefore \ & \text{Claim proved.} \\
\ \\
f(x) & = f(x-1)+\bigg[ \frac {x+1} 2 \bigg]f(1) \\
& = f(x-2)+ \Bigg( \bigg[ \frac x 2 \bigg] + \bigg[ \frac {x+1} 2 \bigg] \Bigg) f(1) \\
& \ \ \vdots \\
& = f(1) + \Bigg(\displaystyle \sum_{k=3}^{x+1} \bigg[ \frac k 2 \bigg] \Bigg) f(1) \\
& = f(1)\sum_{k=1}^{x+1} \bigg[ \frac k 2 \bigg]. \Bigg( \because \bigg[ \frac 1 2 \bigg] = 0, \bigg[ \frac 2 2 \bigg] = 1. \Bigg) \\
\therefore \ & f(x)=c\sum_{k=1}^{x+1} \bigg[ \frac k 2 \bigg]. \\
\text{By $\color{#4995CF}{(\ref{(1)})}$, }& f(x)=\frac {(x+1)^2} 4 f(1) \text{ if $x$ is odd.} \\
\text{if $x$ is even: } & f(x)=f(x-1)+\bigg[ \frac {x+1} 2 \bigg]f(1) \\
& = \frac {x^2} {4} f(1) + \frac x 2 f(1) \\
&=\bigg( \frac x 2 \bigg) \bigg( \frac x 2 +1 \bigg) f(1). \\
\ \\
\therefore \ & f(x)=
\begin{cases}
\bigg( \dfrac {x+1} {2} \bigg)^2c & \text{if $x$ is odd.} \\
\bigg(\dfrac x 2 \bigg) \bigg( \dfrac x 2 +1 \bigg)c & \text{if $x$ is even.}
\end{cases}
\end{align}