text:
Q: Are sexual innuendo jokes acceptable in answers? A recent answer was posted with a joke tagged on at the end. I wouldn't normally mind and might even find it funny most of the time, but the joke in question is an overtly sexual double entendre, which I don't think is appropriate for a Q&A site "for professional and enthusiast programmers" (to quote About).
I proposed an edit to remove it, which was accepted, then reversed by the answerer. I'm not sure what to do here.
Is using such jokes acceptable? If not, how should I respond when I find them in questions or answers?
Please note this is not and was never intended to be a question about whether one is permitted to have a sense of humour on Stack Overflow, or about jokes in general. This is just a question of whether sexual innuendo jokes belong in questions and answers.

A: Stack Overflow is many different things to many different people.  I get the impression that there is a segment of users that want SO to be an interactive reference book (no humor, no opinions).
Others like myself feel that Stack Overflow is an interactive community of users trying to help each other.  The quality of help can vary but as long as the intent is to help, it is acceptable.  Feel free to point me to an FAQ - I know they exist - I am just saying this is how I feel and I am certain there are others who feel the same way.
I won't attempt to say who is right/wrong rather I think it is important to recognize that not everyone feels the same way as you.  Personally, I find that the idea of removing the human element (humor, newbie questions, opinion threads) is offensive on its own accord.  The act of removing someone's mild-mannered joke because it doesn't meet your personal vision of what is appropriate bothers me greatly.
It's a community site, there are a variety of people out there with different backgrounds, and they are only trying to help folks.  Unless the comment is intended to disparage someone else (i.e. name calling, threatening, etc.) then I say leave it.
Please don't take this as an attack on you as an individual - I just want to be sure that the opposing viewpoint is represented.

A: If someone puts what they feel is an innocent joke in a post, presumably they've done so because they want people  to laugh, not feel offended, and wouldn't mind the joke being removed if it were discovered to be potentially offensive.
If changes to a post raise an argument over its content, or who has the strongest right to decide what it contains, it's time to involve a moderator. Don't get into a rollback war with anyone even when you have the best intentions. Flag the post as 'other', let the moderators know what you find objectionable and why, then move on.
Humor that is clean, clear cut and evident without context that only a specific area might have can be okay, I don't think we can come up with blanket guidelines on what is and isn't acceptable when it comes to simple jokes. What I can say is, if a joke is likely to offend certain groups of people, or is just more than our steely, business like smiles can take, then it probably needs to come out.
In short, don't go to great lengths to edit out harmless fun, unless you feel that it's very likely to put off a professional in your field. And, obviously, don't get into edit wars - let the mods take care of it if you see an argument brewing.

A: One of the great aspects of SO is that you have participants from all over the world, and hence from all time zones. So when your brain is fried after a long day and nothing works for you, someone on SO has just had their morning coffee and is graciously putting their fresh brainpower to work for you if you post your problem in reasonably comprehensible terms - after you make sure it hasn't been asked before, of course.
The flip side is that we need to create some neutral ground for this exchange of knowledge, and humor is one of the first obstacles people encounter when trying to create an international professional environment.
In the no-nonsense Q/A framework that SO is trying to create, humour is not a part of the mission. So given the usefulness of SO and the importance of the mission, use of humour will have to be kept to a very limited level. Along with cultural references, politics and religious views, which are equally if not more toxic to a place like SO.
'Tis a pity, because I like to get a glimpse of other cultures and their humour. But this is the Internet, so if I miss something and think it is important enough, I can just join another site that covers it.  Much better than arguing with people from other cultures about their possibly limited world views, an exercise which btw. mostly serves to cement my own.


text:
Q: Update HTML input value in other control event ASP.NET Input value is updated properly when in page load:
protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        txtSupplierType.Value = "Local";
    }
}

but when we try to update it from other control events like:
ASPX Page
 <asp:DropDownList runat="server" ID="ddlProduct" name="form-control" class="form-control select-chosen" OnSelectedIndexChanged="ddlProduct_SelectedIndexChanged" AutoPostBack="true"> </asp:DropDownList>

SelectedIndexChanged Event
 protected void ddlProduct_SelectedIndexChanged(object sender, EventArgs e)
    {
        txtSupplierType.Value = "Global";
    }

it won't update and many other html controls with runat="server" do not work as in page load:
<input type="text" id="txtSupplierType" runat="server" name="example-text-input" class="form-control" />

A: Here is complete code that will work according to your requirement.
<asp:UpdatePanel ID="PnlUsrDetails" runat="server">
                <ContentTemplate>
                    <asp:DropDownList runat="server" ID="ddlProduct"                                                                             name="form-control"
                        class="form-control select-chosen"
                        OnSelectedIndexChanged="ddlProduct_SelectedIndexChanged"
                        AutoPostBack="true"> </asp:DropDownList>

                    <input type="text" id="txtSupplierType" runat="server"
                         name="example-text-input" class="form-control" />
                </ContentTemplate>
            </asp:UpdatePanel>

this code works because this is how update panel works. it will start async postback whenever your control in update panel changes the state. and by default update mode property of update panel is set to "Automatically". so only the code in content template of update panel will be sent to server and come back with updated information.
and you better provide whole code so other users can understand the code and help you much better way.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Does data manipulation query affect performance of databases within a server i would like to know if i use data manipulation queries (such as insert ,delete,select)
with a database does it affect the operations of another database within the same
server.Is there performance issue within databases within the same server.


text:
Q: How to save a type of a pointer c++ Function1 can be called with any type T which will be converted to (void*) to be able to add to the list but with this I lose the original pointer type (I need t store tham in one linkedlist because I cannot create one for every possible type). So somehow I need to save the type of the pointer as well. I know that it cant be done using c++. Can anyone suggest an alternative solution?
class MyClass
{

    template<class T>
    void function1(T* arg1)
    {
        myList.add((void*)arg);
    }

    void function2()
    {
        for(int i = 0; i < myList.size(); i++)
        {
            myList.get(i);
            //restore the original pointer type
        }
    }

    STLinkedlist<void*> myList;
}

A: The usual way to handle these kinds of problems is  by using a public interface, in C++ this is done through inheritance. This can be a drag, especially in constrained situations, where a full class/interface hierarchy would provide too much code/runtime overhead.
In comes Boost.Variant, which allows you to use the same object to store different types. If you need even more freedom, use Boost.Any. For a comparison, see e.g. here.
At the end of the day (or better: rather sooner than later), I'd try to do things differently so you don't have this problem. It may well be worth it in the end.

A: If you lost the type info by going void* it is just gone. You can not just restore it.
So you either must store extra information along with the pointer, then use branching code to cast it back, or rather drive design to avoid the loss.
Your case is pretty suspicious that you do not what you really want.
A more usual case is that you want a polymorphic collection. That doesn't store any kind of pointers but those belonging to the same hierarchy. Collection has Base* pointers, and you can use the objects through Base's interface, all calling the proper virtual function without programmer's  interaction.  And if you really need to cast to the original type you can do it via dynamic_cast safely.  Or add some type info support in the base interface.

A:
Function1 can be called with any type T which will be converted to (void*) to be able to add to the list but with this I lose the original pointer type (I need t store tham in one linkedlist because I cannot create one for every possible type).

You're having the XY problem. The solution is not to decay your pointers to void* and store type information.
You simply can create a type for every possible type - you create a template type. You need to define an abstract interface for your "type for every object", then define a template class implementing this interface, that is particularized by type. Finally, you create your custom-type instance on your type of pointer received and store them by base class pointer (where the base class is your interface definition).
All that said, you (normally) shouldn't need to implement this at all, because the functionality is already implemented in boost::any or boost::variant (you will have to choose one of them).

A: General
Take into consideration, that if you want to store different objects inside a std::vector<void *>, mostly likely your application has a bad design. In this case, I'd think, whether it is really necessary to do it (or how can it be done in another way), rather than searching for the solution, how to do it.
However, there are no fully evil things in C++ (nor in any other language), so if you are absolutely certain, that this is the only solution, here are three possible ways to solve your problem.
Option 1
If you store only pointers to simple types, store the original type along with the pointer by an enum value or simply a string.
enum DataType
{
    intType,
    floatType,
    doubleType
};

std::vector<std::pair<void *, DataType>> myData;

Option 2
If you store mixed data (classes and simple types), wrap your data in some kind of class.
class BaseData
{
public:
    virtual ~BaseData() { }
};

class IntData : public BaseData
{
public:
    int myData;
};

std::vector<BaseData *> myData;

Later, you'll be able to check the type of your data using dynamic_cast.
Option 3
If you store only classes, store them simply as a pointer to their base class and dynamic_cast your way out.

A: You could use boost::any to store any type in your list instead of use void*. It's not exactly what you want but I don't think you can restore the type in run time (as Kerrek said, it's not Java).
class MyClass
{

   template<class T>
   void function1(T arg1)
   {
      myList.add(arg);
   }

   template<class T>
   T get(int i)
   {
      return boost::any_cast<T>(myList.get(i));
   }

   STLinkedlist<boost::any> myList;
};


text:
Q: iPhone SDK: Checking the ID number for each object in a UITableView and change the badge number accordingly I'm tryin to use some code to create a badge number for the iPhone App Icon.
I can successfully do this, however the code I am using (below) is pretty bad and could easily be done better, however I do not have the logic knowledge to be able to do this.
This is what it's doing...

*

*Get's the 'ID' of a user from the first message in a UITableView. It then checks this against the stored ID (from the first object when it was last loaded) and makes the badge number 1.

*Then checks the second ID in a message to see if that is the same as the stored. If not it will make the badge number 2.

*etc etc..

What I want it to do is automatically check the IDs and add '1' to the badge number until the first post with the correct ID is found however, I'm not too sure on the coding.
Any help would be great!
Thanks
(The code is below:)
        NSDictionary* tweetValues = [[NSDictionary alloc] init];
    tweetValues = [tweets objectAtIndex:1];
    NSString *newStatusID = [[tweetValues objectForKey:@"id"] stringValue];
    NSString *oldStatusID = [[NSUserDefaults standardUserDefaults] stringForKey:@"latestID"];
    [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
    if([newStatusID isEqualToString:oldStatusID]){
        [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
    } else {
        tweetValues = [tweets objectAtIndex:2];
        newStatusID = [[tweetValues objectForKey:@"id"] stringValue];

        if ([newStatusID isEqualToString:oldStatusID]){
            [UIApplication sharedApplication].applicationIconBadgeNumber = 1;
        }else{

            tweetValues = [tweets objectAtIndex:3];
            newStatusID = [[tweetValues objectForKey:@"id"] stringValue];

            if ([newStatusID isEqualToString:oldStatusID]){
                [UIApplication sharedApplication].applicationIconBadgeNumber = 2;
            }else{
                [UIApplication sharedApplication].applicationIconBadgeNumber = 3;
            }
        }

    }

A: I'm not exactly sure what you are trying to, but looking at your code I think you need to use a for loop.
Also the first line of your code is leaks. I'm not sure what you are trying to do. As far as I can see you don't have to create an empty dictionary here.
The line where you retrieve your tweetValues (tweetValues = [tweets objectAtIndex:1];) is also strange. You are retrieving the object at index 1. Since arrays are zero-indexed you are retrieving the second object in the array. If you wanted to retrieve the first you need to call: [tweets objectAtIndex:0];
If I had to refactor your code I would probably do something like:
[UIApplication sharedApplication].applicationIconBadgeNumber = 0;

NSString *oldStatusID = [[NSUserDefaults standardUserDefaults] stringForKey:@"latestID"];
for (NSDictionary *tweetValues in tweets) { // Iterate over all the tweetValues in tweets (assume tweets exist?)

    NSString *newStatusID = [[tweetValues objectForKey:@"id"] stringValue];

    if ([oldStatusID isEqualToString:newStatusID]) {

        [UIApplication sharedApplication].applicationIconBadgeNumber++; // Increase the badge number by 1
    }
}

I hope I correctly interpreted your code. If not, some more context might be useful.

A: I ended up doing the follow which seems to be working:
    NSDate *dateRefreshed = [[NSUserDefaults standardUserDefaults] objectForKey:@"dateRefreshed"];

    [[NSUserDefaults standardUserDefaults] setObject:[NSDate date] forKey:@"dateRefreshed"];
    [[NSUserDefaults standardUserDefaults] synchronize];

    [UIApplication sharedApplication].applicationIconBadgeNumber = 0;

    for (NSDictionary *tweetValues in tweets) { // Iterate over all the tweetValues in tweets (assume tweets exist?)

        NSDate *dates = [tweetValues objectForKey:@"created_at"];

        NSTimeInterval sincePostDate = [[NSDate date] timeIntervalSinceDate: dates];
        NSTimeInterval sinceNow = [[NSDate date] timeIntervalSinceDate: dateRefreshed];
        int timeDiff = sincePostDate;
        int timeSinceNow = sinceNow;

        if (timeDiff <= timeSinceNow){

             [UIApplication sharedApplication].applicationIconBadgeNumber++; // Increase the badge number by 1
        }

    }

If anyone has any better ideas, please feel free to post the code :)


text:
Q: Azure - Service Health alert fired but alert emails not received I created a Service Health alert to fire whenever Azure Data Factory was experiencing any issue from their side.
I have been creating alerts for other services of Azure but somehow only the one for Service Health is not working, even though the history log said that the alert was "fired" the last few days. I ran the test with "Service Health" sample type and it was also not working, even though for other sample types it did send me the test alert email.
My setup for the action group and the alert rule is really simple: send email notification whenever Service Health was showing issue with Data Factory. Here is the json code for the action group setup
{
"$schema": "https://schema.management.azure.com/schemas/2019-04-01/deploymentTemplate.json#",
"contentVersion": "1.0.0.0",
"parameters": {
    "actionGroups_Adf_alert_actiongroup_name": {
        "defaultValue": "Adf-alert-actiongroup",
        "type": "String"
    }
},
"variables": {},
"resources": [
    {
        "type": "microsoft.insights/actionGroups",
        "apiVersion": "2022-06-01",
        "name": "[parameters('actionGroups_Adf_alert_actiongroup_name')]",
        "location": "GermanyWestCentral",
        "properties": {
            "groupShortName": "Adf-alert-ac",
            "enabled": true,
            "emailReceivers": [
                {
                    "name": "TeamName_-EmailAction-",
                    "emailAddress": "TeamName@mycompany.com",
                    "useCommonAlertSchema": false
                },
                {
                    "name": "MyName_-EmailAction-",
                    "emailAddress": "MyName@mycompany.com",
                    "useCommonAlertSchema": false
                }
            ],
            "smsReceivers": [],
            "webhookReceivers": [],
            "eventHubReceivers": [],
            "itsmReceivers": [],
            "azureAppPushReceivers": [],
            "automationRunbookReceivers": [],
            "voiceReceivers": [],
            "logicAppReceivers": [],
            "azureFunctionReceivers": [],
            "armRoleReceivers": []
        }
    }
]

Any suggestion for what might have gone wrong in my setup? Many thanks!

A: I found out that "Enable the common alert schema" has to be turned on for the alert to work. Very simple but quite easy to overlook.


text:
Q: why do properties in visual studio reference themselves with macro For example:

As far as i know what is happening here is that jcapimin.c's AdditionalIncludeDirectories metadata property is being set so that it can be referenced later with the %(AdditionalIncludeDirectories) macro in the compilers command line and wherever else you want.
So what I don't understand is why when something down the line retrieves this information using the %(AdditionalIncludeDirectories) macro the information retrieved needs to have %(AdditionalIncludeDirectories) stuck on the end of it

A: Values of variables (properties, items, metadata, ...) are not automatically inherited in MsBuild, but instead new declarations of the same name override the previous value. So if the %(AdditionalIncludeDirectories) is not appended the new value of AdditionalIncludeDirectories would be just the ....\jpeg;....\jpeg\simd part and the compiler wouldn't be able to find standard library headers etc.
The property pages like you show are just a user interface on top of msbuild, which is easy to check if you open the project file in a text editor so here's a fictive sample of what happens in MsBuild:
<!--Somewhere in the msbuild files with compiler options-->
<ItemGroup>
  <AdditionalIncludeDirectories Include="$(VCInstallPath)\include"/>
</ItemGroup>

The code in the above file is eventually included in your project file, and now you want to add directories to the compiler's include search path. Suppose you'd write
<ItemGroup>
  <AdditionalIncludeDirectories Include="..\jpeg"/>
</ItemGroup>

then the new value of AdditionalIncludeDirectories is just ..\jpeg. Which is why we use
<ItemGroup>
  <AdditionalIncludeDirectories Include="..\jpeg;%(AdditionalIncludeDirectories)"/>
</ItemGroup>

instead so the value is expanded to ..\jpeg;$(VCInstallPath)\include.
Unrelated remark: usually you shouldn't be declaring include directories per file like that; suppose there's a second file which also needs that jpeg include path, you'd have to repeat yourself and write the same thing again. Repeating yourself in programming is nearly always wrong. Declaring the include path on the project level would be a good start. If you also don't want to repeat the same path across projects, look into using property sheets.


text:
Q: How to looping grid in PHP enter image description here
<?php foreach($posts as $post) : ?>

<?php echo $post['title']; ?>

        Posted on: <?php echo $post['created_at']; ?> in <?php echo $post['name']; ?>

<?php endforeach; ?>

the problem i have is every time the looping is the same result
as shown below :
enter image description here
My question can any one help me come with a PHP loop at works better than mine and does not leave any syntax errors with any given image count?

A: I have modified your code it looks like a lot but that's because I had to create an array to simulate the data you receive.
//create an array that contains the column sizes we want in order
<?php $gridLayoutConfig = array("col-md-12", "col-md-8", "col-md-4", "col-md-3", "col-md-3", "col-md-3"); ?>
//here I am simulating data since I dont have your data
<?php $posts = array(
array("title" => "Mean Streets", "name" => "Meaner Streets", "created_at" => "0000"),
array("title" => "Mean Streets 2", "name" => "Meaner Streets 2" , "created_at" => "0000"),
array("title" => "Mean Streets 3", "name" => "Meaner Streets 3", "created_at" => "0000"),
array("title" => "Mean Streets 4", "name" => "Meaner Streets 4", "created_at" => "0000"),
array("title" => "Mean Streets 5", "name" => "Meaner Streets 5", "created_at" => "0000"),
array("title" => "Mean Streets 6", "name" => "Meaner Streets 6", "created_at" => "0000")
);  ?>
<?php $i = 0; ?>
//create container row outside the foreach
<?php echo "
"; ?>
<?php foreach($posts as $post) : ?>
//set divs class to whatever count is currently (0 = "col-md-12", 1 = "col-md-8")
//divide count by how many entries in our gridLayoutConfig  by whatever $i that means when we reach the last array entry $i % count($gridLayoutConfig) roll back around to equal 0 starting the layout again.
<?php echo '
' ?>

<?php echo $post['title']; ?>

        Posted on: <?php echo $post['created_at']; ?> in
        <?php echo $post['name']; ?>

<?php $i++; ?>

<?php endforeach; ?>
<?php echo "
"; ?>

Also added a PHPFiddle to better demonstrate open the link press F9 to run then check the inspector and you will see each div has the correct class it will not display properly in the fiddle as there is no bootstrap included but should work fine in your own page.
http://phpfiddle.org/main/code/aei9-tw86
You see in the php fiddle when we reach "Mean Streets 7" the $gridLayoutConfig starts from the beginning ($gridLayoutConfig[0]) again and will repeat the pattern.


text:
Q: How to specify priority in makefile I have a makefile and several targets there. I want to clean directory first, then build directories and then run compilation of tasks1..4. Sometimes building directories starts after compilation and this makes compilation impossible.
Makefile in general looks like:
release: clean
release: build
release: task1 task2
release: task3 task4

Clean and build must be finished before tasks1..4 start running. In other words how to specify priority in makefile tasks. Now seems all 4 lines from the makefile start altogether in one moment.

A: I'm assuming you're using -j; without parallel builds enabled make will never start any rules together: it always runs them one at a time in the order the prerequisites are listed.
The only way to specify order is via prerequisites.  So, this would look like:
release: task1 task2 task3 task4
task1 task2 task3 task4: build
build: clean

However, this last step is a very bad idea: you don't want your build target to depend on clean in general, otherwise it will always be run.  You can either ask people to run clean by hand, but probably the most common way to deal with release targets like this is with make recursion:
release:
        $(MAKE) clean
        $(MAKE) build
        $(MAKE) task1 task2 task3 task4


text:
Q: Cannot make a static reference to the non-static method getConfig() from the type JavaPlugin I am trying to create a Minecraft plugin with a command that will set the world name into config.yml. Except I keep getting "Cannot make a static reference to the non-static method getConfig() from the type JavaPlugin" when I attempt to set the config. I have already searched around for several way to fix this but I have not understood have to implement other situations into mine.
Here is my code:
Main.java:
package me.Liam22840.MurderRun;

import org.bukkit.plugin.java.JavaPlugin;

import me.Liam22840.MurderRun.commands.HelpCommand;
import me.Liam22840.MurderRun.commands.SetmapCommand;

public class Main extends JavaPlugin {

@Override
public void onEnable(){
    loadConfig();
    new HelpCommand(this);
    new SetmapCommand(this);
}

public void loadConfig(){
    getConfig().options().copyDefaults(true);
    saveConfig();
    }
}

SetmapCommand.java:
package me.Liam22840.MurderRun.commands;

import org.bukkit.Location;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;

import Utils.Utils;
import me.Liam22840.MurderRun.Main;
import me.Liam22840.MurderRun.getConfig;

public class SetmapCommand implements CommandExecutor{
   private int count;
   public SetmapCommand(Main plugin){
       plugin.getCommand("Setmap").setExecutor(this);

}

@Override
public boolean onCommand(CommandSender sender, Command cmd, String label, String[] args) {
    if (!(sender instanceof Player)){
        sender.sendMessage("Only players can execute this command!");
        return true;
    }
    Player p = (Player) sender;
    Location b_loc = p.getLocation();
    if(p.hasPermission("MurderRun.Setworld")){
        Main.getConfig().set("Maps." + p.getName() + count + ".World", b_loc.getWorld().getName());
        Main.saveConfig();
        p.sendMessage(Utils.chat("&4Map Set"));
        return true;
    } else{
        p.sendMessage("You do not have the required permissions to execute this command!");
    }
    return false;

    }

}

A: You can't directly call the Main class, because it is not static. To call it, you should do this in your Setmap class and the constructor:
private Main plugin;

public SetmapCommand(Main plugin){
   this.plugin = plugin;
   plugin.getCommand("Setmap").setExecutor(this);
}

After you did this, you can use in your Setmap class:
plugin.saveConfig();


text:
Q: Using t-test to get pValue for observed state in two vectors I am planning to use this on network data.
My network has two kinds of edges.
I have written a function which returns the indegree for these two edge types separately for you to see what it looks like:
    Node    G_obs   R_obs
1   N1      3       2
2   N2      1       0
3   N3      9       0
4   N4      1       4
5   N5      1       0
...

and I wrote another function which samples the network edges. Here is what it looks like after this:
    Node    G_obs   R_obs
1   N1      4       1
2   N2      1       0
3   N3      3       6
4   N4      3       2
5   N5      1       0
...

Note that the G_obs+R_obs, aka the indegree of the node stays the same.
I'd like to know the pValue for each node to have the originally observed indegree-split between G_obs and R_obs.
EDIT:
Sorry - this seemed to be a little too unclear.
I don't want the row-wise probability of the observed distribution.
I want the probability of the observed G_obs, R_obs split for each node, where sample(G_obs) + sample(R_obs) still have the same sum for node as before.
I should consult an English native speaker for better wording next time.. Hope I described the problem more clearly now :(
EDIT 2
observation:
    Node    G_obs   R_obs
1   N1      3       2
2   N2      1       0
3   N3      9       0
4   N4      1       4
5   N5      1       0

as you can see, N1 has 5 in-edges. 3 of them are green (G_obs), 2 of them are red (R_obs)
for the 5 Nodes shown, we have 15 green edges in total and 6 red edges in total.
Now we 'sample' all green and all red edges, aka re-distribute them in their assigned column - but at the same time, N1 still has 5 edges. (See example sampling above, where
    Node    G_obs   R_obs
1   N1      4       1
...

I already have a function which provides the 'sampling' correctly (placeholder for this: mySample(graph) ) and need a function which takes mySample, uses it e.g. 1000 times, and calculates how likely the orginal oberservation was for each node.
Any help appreciated
Thank you

A: It sounds like you are after a binomial probability (the probability that randomly dividing the edges between the two types will yield the same distribution as originally observed).
You can compute these probabilities using the dbinom() function:
transform(
  df,
  prob_same = dbinom(G_obs, G_obs + R_obs, prob = .5)
)

data
df <- read.table(
  text = "
   Node    G_obs   R_obs
N1      3       2
N2      1       0
N3      9       0
N4      1       4
N5      1       0
  ",
  header = TRUE
)


text:
Q: getting facebook page fans? Is there any way to get a list of fans page ids from my page?
i know that using Graph API  its bug may be another way.
http://bugs.developers.facebook.net/show_bug.cgi?id=12880
Also its posible to get facebook session cookies?  (datr; lu; locale; L=2; act; c_user; sct; xs; presence; e; wd;)--i see this from firebug.

A: Try using the fql query.
Select uid from page_fan where page_id = *
refer to http://developers.facebook.com/docs/reference/fql/page_fan/


text:
Q: If $3$ couples are randomly seated, what is they probability that at least $1$ couple sits together? My attempt:
$$A = \text{couple 1 sits together}$$
$$B = \text{couple 2 sits together}$$
$$C = \text{couple 3 sits together}$$
Solving for
$$P(A \cup B \cup C) = P(A)+P(B)+P(C)-P(A \cap B)-P(A \cap C)-P(B \cap C)+P(A \cap B \cap C)$$
$$P(A)=P(B)=P(C) \quad\text{and}\quad P(A \cap B)=P(A \cap C)=P(B \cap C)\text{, so}$$
$$P(A \cup B \cup C) = 3P(A)-3P(A \cap B)+P(A \cap B \cap C)$$
\begin{align*}
P(A) = \frac{5!}{6!}\quad&\text{if 1 couple acts as a unit}\\
P(A \cap B) = \frac{4!}{6!}\quad&\text{if 2 couples act as single units}\\
P(A \cap B \cap C) = \frac{3!}{6!}\quad&\text{if all couples act as single units}
\end{align*}

A: You have the right idea, but you have not taken into account the internal arrangements of the couples that sit together.  A couple can sit together in $2!$ ways.  Hence, you should have
\begin{align*}
\Pr(A) & = \frac{5!2!}{6!}\\
\Pr(A \cap B) & = \frac{4!2!^2}{6!}\\
\Pr(A \cap B \cap C) & = \frac{3!2!^3}{6!}
\end{align*}
$\Pr(A)$:  There is a couple that sits together and four other individuals, so we have five objects to arrange, which can be done in $5!$ ways.  The couple can be arranged internally in $2!$ ways.  Hence, the number of favorable arrangements is $5!2!$.
$\Pr(B)$:  There are two couples and two other individuals, so we have four objects to arrange, which can be done in $4!$ ways.  Each couple can be arranged internally in $2!$ ways.  Hence, there are $4!2!^2$ favorable cases.
$\Pr(C)$:  There are three couples to arrange, which can be done in $3!$ ways.  Each couple can be arranged internally in $2!$ ways.  Hence, there are $3!2!^3$ favorable cases.
With these corrections, we obtain
$$\Pr(A \cup B \cup C) = \binom{3}{1}\frac{5!2!}{6!} - \binom{3}{2}\frac{4!2!^2}{6!} + \binom{3}{3}\frac{3!2!^3}{6!}$$


text:
Q: How to add default values to incoming variables having empty string value in Gson serialize/deserialize, when I am using lombok? Here is the class
package com.bablo.domain;

import com.google.gson.annotation.SerializedName;

import lombok.Getter;
import lombok.Setter;
import lombok.ToString;

@Getter @Setter
@ToString
public class PC {

   @SerializeName("name")
   private String name;

   @SerializeName("model")
    private String model;

   @SerializeName("processor")
    private String processor;
}

In the above class attribute for model can have an empty string in the json, how to give it default value at the time of serialization and deserialization.
That is in the requestbody json the value for the model key can have empty string as a value, how to read it and put instead default values in the place of empty string in the class attribute.
Should I disable lombok and add custom getter and setter methods in my class to override the default values?
Or is there any annotation available in Gson to achieve this?
Or lombok has some workaround to achieve this?

A: Probably, you need to use lombok Builder annotation here. Something like this:
@Getter @Setter
@ToString
class PC {

    @SerializedName("name")
    @Builder.Default
    private String name = "name1";

    @SerializedName("model")
    @Builder.Default
    private String model = "model1";

    @SerializedName("processor")
    @Builder.Default
    private String processor = "processor1";
}


text:
Q: How do I handle validation errors in ruby on rails 6 I am new to ruby and I am working on an error structure to be sent as response to my api. Currently, validation errors are returned like:
{
"status": 400,
"message": "Profile update was unsuccessfull",
"errors": {
    "first_name": [
        "is too short (minimum is 3 characters)"
    ],
    "phone_number": [
        "Enter a valid us phone number"
    ]
}

}
but I want something like:
{
"status": 400,
"message": "Profile update was unsuccessfull",
"errors": {
    "first_name": "firstname "is too short (minimum is 3 characters)",
    "phone_number": "Enter a valid us phone number"
}

}
My model:
validates :first_name, :last_name, :state, :referral_method, presence: true, length: { minimum: 3, maximum: 25 }
validates :phone_number, format: { with: VALID_PHONE_REGEX, message: "Enter a valid us phone number" }, if: :phone_number_changed?

Controller:
# Handle validation errors
rescue_from ActiveRecord::RecordInvalid do |exception|
 messages = exception.record.errors.messages
 messages.map {|k,v| messages[k]=v[0] }
 @response = { status: Status.bad_request, message: Message.profile_not_updated,
 errors:messages}
 json_response(@response, :bad_request)
end

A: You could overwrite default active record translations:
---
en:
  activerecord:
    errors:
      models:
        user:
          attributes:
            first_name:
              too_short: First name is too short (minimum is 3 characters)
            phone_number:
              too_short: Enter a valid us phone number

You can have a deeper in the documentation here:
https://guides.rubyonrails.org/i18n.html#error-message-scopes


text:
Q: Need to identify correct confidence interval A manufacturer of precision gaskets makes gaskets in two grades A and B. In A, the precision gaskets thickness is far more critical than in B. The production run for A is very small, whereas the production run for B is very large.
What should be the right confidence intervals for testing the thickness of A & B ? What should be the appropriate sample size?
My understanding is that a higher confidence interval makes more sense if the precision of attribute is important. Can somebody help me here please?

A: I see this is a coursework question so this answer may not be very useful but here we go...
I wonder whether the confidence interval is the right statistic to decide whether the manufacturing process is good enough. The problem is that increasing sample size will reduce the CI and eventually you will virtually always reject the null hypothesis.
Regarding the width of the CI, if you want to ensure the process is good enough and you want to be conservative, perhaps you want to choose a narrow CI, like 80%. A narrow CI means that you consider a smaller range of (true) means as compatible with the observed data so a narrow CI gives you more stringent quality control.

Perhaps an alternative approach could be to assume that thickness measures come from a known distribution, e.g. Gaussian, with unknown parameters values. Then from your sample of i.i.d. observations you can estimate the parameters of the probability density function and get the probability that a gasket is within an accepted interval of thickness.
For example, your sample has mean = 11 and sd = 1 and you tolerate thinckness between 8 and 12. Then you have 0.1% chance of producing a gasket too thin and 16% chance of producing a gasket too thick (R code below). (Questions I'm not sure about just now: How large has the sample size to be to ensure a good enough estimate of mean and sd? How do you add margins of error around the % chance above?)
(too_low <- integrate(dnorm, -Inf, 8, mean= 11, sd= 1))
(too_high <- integrate(dnorm, 12, Inf, mean= 11, sd= 1))


text:
Q: Integrate controlsfx 11.0.2 into JavaFX 14.0.1 I am new to JavaFX, when integrating controlsfx 11.0.2 with JavaFX 14.0.1, then run mvn clean javax:run, the following error occurs:
Caused by: java.lang.IllegalAccessError: class impl.org.controlsfx.skin.NotificationPaneSkin (in module org.controlsfx.controls) cannot access class com.sun.javafx.scene.traversal.ParentTraversalEngine (in module javafx.graphics) because module javafx.graphics does not export com.sun.javafx.scene.traversal to module org.controlsfx.controls

Also I added the following VM arguments(in pom.xml) as mentioned here:
<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>3.8.1</version>
    <configuration>
        <release>${maven.compiler.release}</release>
        <compilerArgs>
            <arg>--add-exports=javafx.graphics/com.sun.javafx.scene=org.controlsfx.controls</arg>
            <arg>--add-exports=javafx.graphics/com.sun.javafx.scene.traversal=org.controlsfx.controls</arg>
            <arg>--add-exports=javafx.controls/com.sun.javafx.scene.control.behavior=org.controlsfx.controls</arg>
            <arg>--add-exports=javafx.controls/com.sun.javafx.scene.control=org.controlsfx.controls</arg>
            <arg>--add-exports=javafx.controls/com.sun.javafx.scene.control.inputmap=org.controlsfx.controls</arg>
            <arg>--add-exports=javafx.base/com.sun.javafx.event=org.controlsfx.controls</arg>
            <arg>--add-exports=javafx.base/com.sun.javafx.collections=org.controlsfx.controls</arg>
            <arg>--add-exports=javafx.base/com.sun.javafx.runtime=org.controlsfx.controls</arg>
            <arg>--add-opens=javafx.controls/javafx.scene.control.skin=org.controlsfx.controls</arg>
            <arg>--add-opens=javafx.graphics/javafx.scene=org.controlsfx.controls</arg>
        </compilerArgs>
    </configuration>
</plugin>

I used mvn -X to check runtime arguments and ensure the --add-exports already applied.


text:
Q: Puzzled with @Resource injection with name attribute I'm puzzled with such kind of dependency injection shown as an example in spring data redis:
https://docs.spring.io/spring-data/data-redis/docs/current/reference/html/#redis:serializer
  // inject the template as ListOperations
  @Resource(name="redisTemplate")
  private ListOperations<String, String> listOps;

Taking into consideration that redisTemplate is a bean of type RedisTemplate, how does spring manage to retrieve the listOps from the redisTemplate bean ?
This is working and I'm mainly interested to find a piece of documentation explaining this behaviour or the piece of code handling that.
Thank for your help.

A: Actually, this is working thanks to ListOperationsEditor class.
class ListOperationsEditor extends PropertyEditorSupport {
    ListOperationsEditor() {
    }

    public void setValue(Object value) {
        if(value instanceof RedisOperations) {
            super.setValue(((RedisOperations)value).opsForList());
        } else {
            throw new IllegalArgumentException("Editor supports only conversion of type " + RedisOperations.class);
        }
    }
}


text:
Q: How do I layer parts using MEF? I'm working on some example programs using MEF.  In the simplest example I wrote, I've got an IDoSomething interface which looks like so:
public interface IDoSomething
{
   void DoIt();
}

and a class which implements it that looks like this:
[Export(typeof(IDoSomething))]
public class TestClass : IDoSomething
{
    public void DoIt()
    {
       Console.WriteLine("TestClass::DoIt");
    }
}

and a class that loads the plugin that looks like this:
public class PluginManager
{
    [ImportMany(typeof(IDoSomething))]
    private IEnumerable<IDoSomething> plugins;

    public void Run()
    {
        Compose();
        foreach (var plugin in plugins)
        {
            plugin.DoSomething();

        }
    }

    private void Compose()
    {
        var catalog = new DirectoryCatalog(@".\");
        var compositionContainer = new CompositionContainer(catalog);
        compositionContainer.ComposeParts(this);
    }

}

And this seems to work, but now what I'd like to do is extend on of my concrete plugins to itself have a plugin, something like this:
[Export(typeof(IDoSomething))]
public class TestClass2 : IDoSomething
{
    [Import(typeof(IDoAnotherThing))]
    public IDoAnotherThing Plugin { get; set; }

    public void DoIt()
    {
        Console.WriteLine("TestClass2::DoIt");
        Plugin.Func();
    }
}

where IDoAnotherThing looks like this:
public interface IDoAnotherThing
{
    void Func();
}

and my concrete implementation of that looks like this:
[Export(typeof(IDoAnotherThing))]
public class AnotherPlugin: IDoAnotherThing
{
    public void Func()
    {
        Console.WriteLine("AnotherPlugin::Func");
    }
}

The behavior I see when I run this is that my TestClass2 instance gets created and its DoIt function is called but its AnotherPlugin instance never gets called.  I see that the catalog has the AnotherPlugin listed.  What am I doing wrong here?

A: I thought was was specifying this correctly and it turns out that I was, but as Matthew Abbott commented above, something else was in fact occurring.  In this case, it was the fact that my concrete class plugins weren't all ending up in the same directory and as a result, my app wasn't discovery the correct one.  Live and learn.  Once I made sure that I had the latest of all of those assemblies, everything worked just fine.


text:
Q: Try-Catch sum two numbers I'm working on Exception Handling and making a new Java Project.Program waits for user type 2 numbers from keyboard. If user types two integer numbers it'll sum these numbers. If user doesn't type numbers program will print 'Type numbers!' on screen. Here's What I Tried:
public static void main(String[] args) {
    int a = 0;
    int b = 0;
    System.out.println("Type two numbers");
    Scanner scan = new Scanner(System.in);
    try {
        a = scan.nextInt();
        b = scan.nextInt();
    } catch (Exception ex) {
        System.err.println("Type number!");
    }
}

A: Try code below. It should work as you expect:
public static void main(String[] args) {
    System.out.println("Type two numbers");
    sum();
}

private static void sum(){
    int a = 0;
    int b = 0;
    Scanner scan = new Scanner(System.in);
    try {
        a = scan.nextInt();
        b = scan.nextInt();
        System.out.println(a+b);
    } catch (Exception ex) {
        System.err.println("Type numbers in correct format!");
        sum();
    }
}


text:
Q: d3 get object from a queue I am loading 3 csv with a d3.queue and a would like to get the object inside the function call in await. Is that even possible.
dmObj.loadAllData = function (url1,url2,url3) {
        d3.queue(1)
            .defer(d3.csv, url1)
            .defer(d3.csv, url2)
            .defer(d3.csv, url3)
            .await(processus);

        function processus(error,data1, data2, data3) {
            if (error) throw error;
            ref14data = data1;
            townsCSV = data2;
            learningProviders = data3;

            //Create master table
            combineLPwithTownData(learningProviders, townsCSV);
            console.log('ref data ',learningProviders);
            console.log('town',townsCSV);

            combineREFwithLPdata(ref14data, learningProviders);

            //Just consider "overall" assessments
            ref14data = ref14data.filter(function (e) { return e.Profile === "Overall" })

            console.log(ref14data);

I would like to acces the ref14data outsite this function to use it in my chart or any object.


text:
Q: TypeError: list indices must be integers or slices, not tuple, Issue happens in a parallel corpus The following is my dataset. It is a parallel corpus.
[['Service eka godaak hondai', 'සේවාව  ගොඩාක් හොඳයි '],
['Kama rasai ', 'කෑම රසයි '],
['Godak fresh and maarama rasaii, perfect. ', 'ඉතා රසවත් හා ඉතා රසවත්, පරිපූර්ණයි'],
['place eka piliwelai, clean , kama godaak rasai', 'ස්ථානය පිළිවෙලට, පිරිසිදුයි, කෑම හරිම රසයි']]
when I try this following code
singlish_tokenizer = create_tokenizer(dataset[:,0])

This error below is shown

   TypeError Traceback (most recent call last)

  <ipython-input-138-74d68e010cad> in <module>

  3 # a[:stop]       # items from the beginning through stop-1

  4 #a[:]  means a copy of the whole array

  5 singlish_tokenizer = create_tokenizer(dataset[:,0])

  TypeError: list indices must be integers or slices, not tuple

this is the create_tokenizer method
def create_tokenizer(lines):

   tokenizer = Tokenizer()

   tokenizer.fit_on_texts(lines)

   return tokenizer

Can anyone please help me in this issue. I tried different solutions but nothing worked. I am stuck with this code.


text:
Q: Please change your browser settings or upgrade your browser ( urllib, python 3.6) Good Evening ,
i have an error with my urllib code with websites that work with javascript .
this is the error that i get :
"
"This site requires JavaScript and Cookies to be enabled. Please change your browser settings or upgrade your browser".
"
im using python 3.6 with urllib (request), How Can I solve it ?

A: The site you are accessing requires javascript and cookies. Urllib only provides support for cookies (with cookie jar). To get around the need for javascript, check out a library like selenium, and use it with phantomjs.
pip install selenium

Selenium with phantomjs is more powerful then urllib, but you pay the penalty of it being a bit slower. Heres is some simple code to get off the ground with selenium and phantomjs:
from selenium import webdriver
driver = webdriver.PhantomJS()
driver.get("https://google.com/")
driver.quit()

For more information on how to do specific things with selenium, check out the documentation.


text:
Q: Forbidden File Type docx I'm testing the uploadifive plugin file upload restrictions and I cannot seem to get it to accept .docx files. In the documentation (http://www.uploadify.com/documentation/uploadifive/filetype/) I have followed the instructions (bar a small mistake - the pipe "|" character does not work) and have used the media types it refers to (http://www.iana.org/assignments/media-types/media-types.xhtml). No other file type seems to be causing a problem e.g. .doc, .xlsx.
Is there a solution for this, I have checked multiple sources and the mime type (application/vnd.openxmlformats-officedocument.wordprocessingml.document) is correct as far as i can tell?

UploadiFive Demo

<form>

    <input id="file_upload" name="file_upload" type="file" multiple="true">
    Upload Files
</form>

A: The issue was with Firefox assigning the MIME type "application/vnd.ms-word.document.12" to the file instead of "application/vnd.openxmlformats-officedocument.wordprocessingml.document" to .docx files. Chrome and presumably others use the correct one.
This post (How to check file MIME type with javascript before upload?) proved helpful to see how the browser is treating it.


text:
Q: Pandas DataFrame - Date/Time values incorrectly converting to integers when recreating DataFrame I have a a DataFrame - ES_15M - that looks as follows:
[![ES_15M][1]][1]
Below is some sample data that I'm using:

Ticker Date/Time Close
ES H7 10/18/16 1:44 PM 2128
ES H7 10/18/16 1:59 PM 2128.75
ES H7 10/18/16 2:14 PM 2125.75
ES H7 10/18/16 2:29 PM 2126.5
ES H7 10/18/16 2:44 PM 2126.5
ES H7 10/18/16 4:14 PM 2126
ES H7 10/18/16 4:44 PM 2126.25
ES H7 10/18/16 5:59 PM 2126.5

I want to remake the DataFrame, basically just copy in its image as I'm going to merge this dataframe with another one (from another python file). The 'ES_15M' Dataframe comes from 'ES_LR_15M' Python file below. So:
import sys
import os

sys.path.append(os.path.abspath(r"C:\Users\cost9\OneDrive\Documents\PYTHON\TEST-ASSURANCE FILES\LINEAR REGRESSION MULTI TREND IDENTIFICATION\LR\ES\STAGE 2"))

from ES_LR_1D import *
from ES_LR_1H import *
from ES_LR_15M import *

So after importing 'ES_15M' dataframe, I do the following:
ES_15M_Summary = ES_15M
ES_15M_Summary = pd.DataFrame(ES_15M_Summary)

The problem is, the dates go away on the new 'ES_15M_Summary:

     Ticker  Date     Open     High      Low    Close  Volume  Open Interest  \
0     ES H7     0  2128.25  2128.50  2128.00  2128.00      10              0
1     ES H7     1  2127.75  2129.25  2127.75  2128.75       6              0
2     ES H7     2  2127.25  2127.25  2124.50  2125.75      22              0
3     ES H7     3  2126.50  2126.50  2126.50  2126.50       1              0
4     ES H7     4  2125.75  2126.75  2125.75  2126.50       4              0
5     ES H7     5  2126.25  2126.25  2126.00  2126.00       6              0
6     ES H7     6  2126.50  2126.50  2126.25  2126.25       3              0
7     ES H7     7  2126.50  2126.50  2126.50  2126.50       2              0
8     ES H7     8  2127.00  2127.00  2127.00  2127.00       1              0
9     ES H7     9  2126.50  2127.75  2126.50  2127.75       2              0

I have to match these dates with the other dataframe I'll be merging on so this is a problem. How do I keep the dates when re-creating the dataframe?
edit: Okay here's a sample. I'm creating random AAPL stock price data and I need the same as above - to recreate the DataFrame:
stocks = pd.DataFrame({
    'ticker':np.repeat( ['aapl'], 25 ),
    'date':np.tile( pd.date_range('1/1/2011', periods=25, freq='D'), 1 ),
    'price':(np.random.randn(25).cumsum())})

        date     price ticker
0  2011-01-01 -1.642040   aapl
1  2011-01-02 -3.308491   aapl
2  2011-01-03 -4.843908   aapl
3  2011-01-04 -4.081345   aapl
4  2011-01-05 -3.356592   aapl
5  2011-01-06 -2.729077   aapl
6  2011-01-07 -2.011651   aapl
7  2011-01-08 -2.388161   aapl
8  2011-01-09 -1.198737   aapl
9  2011-01-10 -0.387553   aapl
10 2011-01-11  0.960245   aapl

When I re-create the DataFrame with the random price data here I get the same values as above, with dates still present rather than integers replacing them:
stocks2 = pd.DataFrame(stocks)

So I'm not sure what's wrong with my code in the original example.


text:
Q: Walk through on setting up a Server 2008 VPS? I'm a developer, who wanted a small VPS to use instead of a shared host. I don't deal much with the IT side of things.
So far, I've purchased a VPS from Thrust and installed 2008 on it.
I enabled updates, and set it to the Web Server Role.
Now, I'd like to use it as its own DNS server (so that is is easy to manage sub domains directly), but I'm not sure where to start... Install AD? Setup DNS?
This is all foreign to me, I'm used to just giving builds to the SA guys :)

A: In answer to your actual question, you just need to install the DNS server role, you do not need AD (unless you want to actually use Active Directory for things, but I doubt it). Once installed you can use the DNS mmc to create and edit your DNS zones.
That said, if you are going to be using this server for commercial purposes,  I would suggest either looking at getting a professional to look at it, or spend some time learning about Windows administration, especially how to secure your server.


text:
Q: How to flank an enemy? How to get the status "flanked" on an enemy? I've tried attacking them from several different angles, with not reliable success.

A: You are trying to get two characters are more-or-less opposite sides of the enemy, right?  So you have to have at least 2 characters to flank, and they have to have an enemy roughly directly between your 2 characters.  Some terrible Preformatted examples:
YOU ENEMY YOU

Yay!  Flanking
YOU ENEMY
    YOU

Boo, no flanking
YOU ENEMY
        YOU

Sometimes flanking, but I can't seem to find a consensus.


text:
Q: How to authenticate Proxy with Requests Python module? Here is the segment of code that is causing an issue:
proxies = {"http": "http://%s:%s@proxy_address:8080" %(user, pwd),
"https": "http://%s:%s@proxy_address:8080" %(user, pwd)}

requests.get('https://www.apple.com/', proxies=proxies)

I receive the error: '''ProxyError: HTTPSConnectionPool(host='www.apple.com', port=443): Max retries exceeded with url: / (Caused by ProxyError('Cannot connect to proxy.', OSError('Tunnel connection failed: 407 Proxy Authentication Required')))'''
Can someone please help me resolve this issue? I sure that my username and password is correct.
Thanks.


text:
Q: Making Odata Saves without the response Just wondering if there is anyway to save data across the line without the response coming back. i.e. Im using the objc odata sdk. If I create an employee entity on the ipad, than I save it, I dont need to receive the the saved entity back. So really its sending the data across the line than returning it for no reason. Only really need to send it across.
Any ideas on how I can set saves to be push to server and not have to wait for the return?
Thanks in advance

A: In the latest CTP (http://blogs.msdn.com/b/astoriateam/archive/2011/10/13/announcing-wcf-data-services-oct-2011-ctp-for-net-4-and-silverlight-4.aspx) you can use the Prefer header. The client can send the request with Prefer header set to return-no-content and the server will send an empty response back. The header is described here: https://datatracker.ietf.org/doc/html/draft-snell-http-prefer-01.


text:
Q: Visual Studio Code breaks Jekyll blog page layout I'm editing an HTML file from my Jekyll blog:

When I save the file, Visual Studio Code puts the layout reference in one line, breaking page's layout:

Is this a way to avoid this?

A: Disable auto formatting when saving the file in settings:
  "editor.formatOnSave": false

A: My issue was I have installed this extension: JS-CSS-HTML Formatter.
So, the solution is edit the formatter.json file and set the onSave property to false.
To do this, I have followed these steps:
1 - Press CTRL+SHIFT+P and type Formatter:

2 - Change the value of the property onSave to false:

After editing the file, is necessary to restart Visual Studio Code.
This answer helped me to solve the problem.


text:
Q: Getting configuration failure while executing TestNG xml I am running the TestNG xml and test is failing with configuration failure error.
TestNG xml:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE suite SYSTEM "https://testng.org/testng-1.0.dtd">
<suite name="Suite" configfailurepolicy="continue">
<listeners>
        <listener class-name="com.inetbanking.utilities.Reporting" />
    </listeners>
  <test name="Test">
  <parameter name="broswer" value="chrome"></parameter>
    <classes>
     <!--  <class name="com.inetbanking.testCases.TC_LoginDDT_002"/> -->
      <class name="com.inetbanking.testCases.TC_LoginTest_001"/>
    </classes>
  </test>
</suite>

Error
[RemoteTestNG] detected TestNG version 7.4.0
log4j:WARN No appenders could be found for logger (freemarker.cache).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.

===============================================
Suite
Total tests run: 1, Passes: 0, Failures: 0, Skips: 1
Configuration Failures: 1, Skips: 1
===============================================


text:
Q: Sharepoint workflow wont start automatically So I have a contact form on this website that populates a list, I then have a workflow that whenever a new item is created it sends an email with the contents of the form.
So I can actually go into the list and add a new item manually and it will send perfectly, however whenever I go and use the form on the website it does not send the email.
I've checked to make sure that the form is populating the list and it is. Anyone have any ideas why its not starting automatically?

A: If your form saves the item as a system account the workflow wont start. Is the form saving as the logged in user, using impersonation or elevated privileges?


text:
Q: Is it possible to run PowerShell Core in a Linux dotnet container? I can see there is no Powershell present in microsoft/dotnet:
C:\> docker run -it microsoft/dotnet:2.1-sdk bash
root@5397dac12c1e:/# pwsh
bash: pwsh: command not found

When I try to add it in the following way heavily inspired by PowerShell dockerfiles:
FROM microsoft/dotnet:2.1-sdk
RUN apt-get update     && apt-get install -y --no-install-recommends         apt-utils         ca-certificates         curl         apt-transport-https         locales    && rm -rf /var/lib/apt/lists/*
RUN curl https://packages.microsoft.com/keys/microsoft.asc | apt-key add -
RUN curl https://packages.microsoft.com/config/ubuntu/16.04/prod.list | tee /etc/apt/sources.list.d/microsoft.list
RUN apt-get update     && apt-get install -y --no-install-recommends     powershell

... step RUN [...] apt-get install [...] powershell fails with
Fetched 10.3 MB in 11s (914 kB/s)
Reading package lists...
Reading package lists...
Building dependency tree...
Reading state information...
Some packages could not be installed. This may mean that you have
requested an impossible situation or if you are using the unstable
distribution that some required packages have not yet been created
or been moved out of Incoming.
The following information may help to resolve the situation:

The following packages have unmet dependencies:
 powershell : Depends: libssl1.0.0 but it is not installable
              Depends: libicu55 but it is not installable
E: Unable to correct problems, you have held broken packages.

I guess it was too bold to try to use Ubuntu approach inside of a Debian Stretch container. I wonder whether there is an easier way to get container that has both dotnet-sdk and pwsh present.

A: It seems that the simplest solution is just to wait for a new release of PowerShell Core that's going to support Ubuntu 18.04 -- and then match it with dotnet:2.1-sdk-bionic.


text:
Q: PHP Output to variable File-1:
<?php

      something...

?>

File-2:
<?php
   $file1= What should I write to get output of File1?
?>

I need to get html output to the $file1 variable;
Please help.

A: I think this will work for you:
function read($file) {
  ob_start();
  include($file);
  $content = ob_get_contents();
  ob_end_clean();

  return $content;
}

Use it like this:
$file = 'path/to/your/file.php';
$content = read($file);

To pass variables you can modify function above like this:
  function read($file, $vars) {
    ob_start();
    extract($vars, EXTR_SKIP);
    include($file);
    $content = ob_get_contents();
    ob_end_clean();

    return $content;
  }

  $file = 'path/to/your/file.php';
  $vars = array(
    'var1' => 'value',
  );
  $content = read($file, $vars);

You can access variables in included file like this: print $var1;

A: you can use
http://www.php.net/manual/en/function.ob-start.php

to start output buffering, then include your file and use
http://www.php.net/manual/en/function.ob-get-contents.php

to read what was the output and finish with
http://www.php.net/manual/en/function.ob-end-clean.php

to end the buffering.

A: Maybe is this you are looking for:
http://www.tizag.com/phpT/fileread.php
Visit the section:
PHP - File Read: fread Function

A: Use this code:
   $content = file_get_contents('somefile.txt');

A: You could either set the variable in File-1 and include it:
include() / include_once() / require() / require_once()
Or you could print the contents of File-1 and use output buffering:
http://www.php.net/manual/en/function.flush.php


text:
Q: Evaluate and assign variables inside ssh session in shell script I'm trying to increment indx and eindx values inside a ssh session.but none of commands are working..
#!/bin/bash
hosts=( #10.xx.xx.xx )
PdidPrefix1=$1
Runtime=$2
indx=$3
eindx=`expr $indx + $4`
logfilename=$5
for i in "${hosts[@]}"
do
echo $i
ssh centos@$i << EOF
for var in {1..4}
do
indx=`expr $eindx + 1` // not working
eindx=$((indx+eindx))  // not working
done
EOF
done
exit

tried using let also
let "indx=indx+1" //not working
Kindly suggest best way to handle variables.

A: #!/bin/bash
hosts=( xx.10.20.30 )
PdidPrefix1=$1
Runtime=$2
indx=$3
eindx=`expr $indx + $4`
logfilename=$5
for i in "${hosts[@]}"
do
echo $i
ssh centos@$i "bash -s --  '$indx' '$eindx'" <<\EOF

echo "In remote shell with parameters $1 $2..."
indx=$1
eindx=$2

for (( var=1; var<=4; var++ ))
do

indx=`expr $eindx + 1`
eindx=$((indx+eindx))
echo "var=" $var " indx=" $indx " eindx=" $eindx
done
EOF
done
exit

A: I have run the same script. And it shows the proper value.


text:
Q: Get array value in loop based on redis return Fairly new to using nodejs and redis, but I have a short deadline project and I've run into a little bit of a wall.
I'm writing a script that will register a user when they first log in to our site and open a socket, then will check every n seconds to see if they have a new message populated in redis. If we find it, we will then query redis to get their socket ID and emit the message to them.
I've gotten the registration piece working and right now I'm using an object to try and emit a message, but when I'm looping through the connected users I keep getting the same id, even though there are two. I think it has something to do with nodejs being non-blocking, but I'm not sure where I need to make changes.
Redis looks like the following:
hash: socket_by_user_id
12345,
45678,
Once the server starts, I have:
setInterval(function() { checkForNotifications() }, 5000);

And that function (currently) does the following:
function checkForNotifications()
{
    redisDB.hkeys('sockets_by_user_id', function(err, keys)
    {
        if (err) return report_error(err);

        for (var i=0; i < keys.length; i++)
        {
            var user_id = keys[i];
            //console.log(user_id);

            redisDB.hget("sockets_by_user_id", user_id, function(err, socket_id){
                if (err) return report_error(err);
                console.log(user_id);
            });
        }
    });
}

When this runs, I'm seeing the following:
57905
57905

57905
57905

And I'm expecting to see
14175
57905

14175
57905

which would then also get me the correct socket that I'm going to emit to. Eventually I'll need another call to redis to get the actual message to send, but that's not very useful until I can get this part done.

A: Try this to keep your current user_id in scope:
function checkForNotifications()
{
    redisDB.hkeys('sockets_by_user_id', function(err, keys)
    {
        if (err) return report_error(err);

        for (var i=0; i < keys.length; i++)
        {
            (function(user_id){
                redisDB.hget("sockets_by_user_id", user_id, function(err, socket_id){
                    if (err) return report_error(err);
                    console.log(user_id);
                });
            })(keys[i]);
        }
    });
}


text:
Q: Calling Setter of JSF Bean possible if associated component not rendered? I have a question concerning the security of JSF. Would it be possible for an attacker to call a setter of a JSF Bean if the associated component is not rendered (for example with a tool like curl)?
Or is this checked by JSF so that I can assume this as secure?

A: It's only attackable if the rendered condition depends on data which comes along with the HTTP request like parameters, headers, cookies, etc. The entire HTTP request is namely fully user-controlled.
If you're for example only checking the role of the logged-in user, then it's safe -unless the enduser guesses the right username/password of an user with the desired role and logs in with it, of course.


text:
Q: How can I call any method inside a class depending on an input to another method in the same class? I am trying to call a particular method defined inside a class. This calling, however, is dependent on the input of an another method in the same class.
class my_class:
    def __init__(self, x):
        self.exam_score = x

    def math(self):
        print("Hello World!")

    def history(self):
        return "The top score is 12 out of {}.".format(self.exam_score)

    def subject_score(self, func):
        # Call either 'math' method or 'history' method based on input 'func'
        self.__getattribute__(func)()

my_class(30).subject_score('math')

Here, I am trying to call the method math of class my_class by passing math as an argument to subject_score method.
Running the above code will give out Hello World! as the output.
But is there any better way to do this than using self.__getattribute__(func)()?
Thanks!

A: In the subject_score(), you have to return the attribute like this:
class my_class:
    ...

    def subject_score(self, func):
        # Call either 'math' method or 'history' method based on input 'func'
        return self.__getattribute__(func)()

my_class(30).subject_score('math')

Then you will found the result.


text:
Q: Difference between WITH and WHERE Filter conditions in QUERY? Could you please someone let me know more about WITH and when its used as I came to know about it recently. I know WHERE and when and how its used. But when exactly WITH is used when compared to WHERE. Whether WITH can be used for all Std & Custom Object Fields.
I got something from below link but not able to find a usecase on it. If  someone can explain it with an example that will be great.
Filters used in SOQL

A: The Force.com SOQL and SOSL Reference is quite clear on the constraints of the WITH filter expression:

The WITH clause can only be used in the following cases:

*

*To filter records based on their categorization. See WITH DATA CATEGORY filteringExpression.

*To query and retrieve record changes tracked in a user profile feed. See UserProfileFeed in the Object Reference for Salesforce and Force.com.

So unless you are querying the UserProfileFeed object, it is only usable for data categories.


text:
Q: Struts2+Validation in liferay6 I have my view.jsp with the form :
<s:form action="action">
  <s:textfiled name="user"></textfield>
</s:form>

I created my ActionClass and ActionClass -Validation.xml in the same package.
ActionClass -Validation.xml:
<validators>
  <field name="user">
    <field-validator type="required">
      <message>You must enter a value.</message>
    </field-validator>
  </field>
</validators>

In my struts
<action name="action" class="com.action.ActionClass" method="execute" >
   <result name="success">/html/view/register-success.jsp</result>
   <result name="error">/html/view/register-error.jsp</result>
   <result name="input">/html/view/view.jsp</result>
</action>

But it doesn't work.
What it is wrong?

A: The required validator is for checking if the specified field is not null. You are probably want to use requiredstring validator which checks that a String field is non-null and has a length > 0.
Also your validation xml file name should be ActionClass-validation.xml, note lower case for -validation.


text:
Q: How to query for String AND NSDate property? I am facing an odd error with my code:
if let date = self.messages.last?.date {
    let newMessages = self.realm.objects(Message).filter("chatId == '\(self.chatId!)' AND date > \(date)")
}

This outputs the error:

Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Unable to parse the format string "chatId = 'oSgUGWH9fWURmBh5NQZK2POpxdI3yEdl7PrPzAU33l7cVFIpzR38otF3' AND date > 2016-07-17 10:56:07 +0000"'

What am I doing wrong?
EDIT:
Using NSPredicate it works:
let predicate = NSPredicate(format: "chatId = %@ AND date > %@", self.chatId!, date)
newMessages = self.realm.objects(Message).filter(predicate)

But why doesn't the first solution work?

A: If you want to filter an array using a predicate, you need to pass a predicate and not just a string literal as the argument, and also use the method filteredArrayUsingPredicate(_:).
Why "chatId == '\(self.chatId!)' AND date > \(date)" doesn't work is that the compiler interprets this as a string literal - and not a predicate as you've created in your other example:

NSPredicate(format: "chatId = %@ AND date > %@", self.chatId!, date)

The fix is to either instantiate an NSPredicate as you've done in your edit, and pass that value to filteredArrayUsingPredicate(:_) or just move the instantiation to inside the method:
newMessages = self.realm.objects(Message).filteredArrayUsingPredicate(NSPredicate(format: "chatId = %@ AND date > %@", self.chatId!, date))

If you want to use this method, the array needs to be an NSArray, and the objects in the array need to be KVC compliant, so you're better off in Swift with using the filter(_:) method as such:
let newMessages = self.realm.objects(Message).filter({ $0.chatId == self.chatId! && $0.date.compare(date) == NSComparisonResult.OrderedDescending })


text:
Q: Angular2 access parent component's @input values I'm trying to load a component dynamically using the ComponentResolver and ViewContainerRef services.
The child component loads ok and the template is rendered. However i want to access the inputs from the parent ('field' and 'values') inside the child component.
Any help would be much appreciated.
Parent component:
import {Component, Input, ViewChild, ComponentFactory, ViewContainerRef, ComponentResolver} from '@angular/core';
import {MyInputComponent} from './my-input.component';

@Component({
    selector: 'my-field',
    template: `

            {{field.label}}
            *

    `
})
export class MyFieldComponent {

    @Input() field;
    @Input() values;

    @ViewChild('target', { read: ViewContainerRef }) target;

    ngAfterViewInit() {
        this.compiler.resolveComponent(MyInputComponent).then((factory: ComponentFactory<any>) => {
            this.target.createComponent(factory);
        });
    }

    constructor(public viewContainerRef: ViewContainerRef, private compiler: ComponentResolver) {
    }

}

Child component:
import {Component, Input, ViewContainerRef} from '@angular/core';

@Component({
    selector: 'my-input',
    template: `
        This is an input component!!!
    `
})
export class MyInputComponent {

    @Input() field: any;
    @Input() values: any;

    ngOnInit() {
        console.log(this);
    }

    constructor(public viewContainerRef: ViewContainerRef) {
    }

}

A: I think that you can leverage something like this:
this.compiler.resolveComponent(MyInputComponent).then((factory: ComponentFactory<any>) => {
   let component = this.target.createComponent(factory);
   component.instance.field = this.field;
});

See also the example https://plnkr.co/edit/bdGYvTf8y9LEw9DAMyN1?p=preview


text:
Q: Selenium RC/Nunit/Firefox - Browser Crash on Click I am testing a complex web application using a test framework comprised of C#, Nunit 2.5.10 and Selenium RC 2.24.1 (Switching to WebDriver is not an option unfortunately).
We recently overhauled our application UI/UX, so we have been systematically updating our tests to fit the new version.
Everything has been pretty smooth until we ran into an issue where our browser seems to randomly crash when running certain tests. We use Firefox(Chrome Driver) for testing, but have various versions installed on our test clients from 3.6 to 15.01. The issue seems to be consistently reproducible on all browser versions running on Windows 7 and Windows Server 2008 R2.
When the browser crashes it leaves behind a dialog which remains even after we run our clean up method which kills any open browser sessions in preparation for the next tests. Because this dialog sticks around, it keeps an RC server session alive which causes the next set of tests to hang.
I traced the tests down to the specific actions which are causing the crash, and it seems to always be a click event, but on various buttons within the application, and not always the same one. The buttons have nothing in common except that they all trigger a javascript postback. I was also able to trace one crash to a postback event triggered by a drop down box selection.
Our test framework is fairly complex and we have thousands of tests, so we have resorted to commenting the crashing tests just to keep the rest of the suite running.
We have been unable to simulate the crash with manual testing, even when following the exact path taken by the selenium test.
Any thoughts on what might be causing this, or ways to troubleshoot it would be appreciated.

A: I've had issues with intermittent failure of Selenium tests caused by the real time protection on Microsoft Security Essentials.  For me unchecking Turn on real-time protection in Settings | Real-time protection while I was running tests fixed the issue.  Try disabling your anti virus while running tests and see if that solves your problem.  Apparently the actions taken by Selenium can be interpreted as virus activity.


text:
Q: $watch'ing for data changes in an Angular directive How can I trigger a $watch variable in an Angular directive when manipulating the data inside (e.g., inserting or removing data), but not assign a new object to that variable?
I have a simple dataset currently being loaded from a JSON file.  My Angular controller does this, as well as define a few functions:
App.controller('AppCtrl', function AppCtrl($scope, JsonService) {
    // load the initial data model
    if (!$scope.data) {
        JsonService.getData(function(data) {
            $scope.data = data;
            $scope.records = data.children.length;
        });
    } else {
        console.log("I have data already... " + $scope.data);
    }

    // adds a resource to the 'data' object
    $scope.add = function() {
        $scope.data.children.push({ "name": "!Insert This!" });
    };

    // removes the resource from the 'data' object
    $scope.remove = function(resource) {
        console.log("I'm going to remove this!");
        console.log(resource);
    };

    $scope.highlight = function() {

    };
});

I have a <button> that properly called the $scope.add function, and the new object is properly inserted into the $scope.data set.  A table I have set up does update each time I hit the "add" button.

      <input type="checkbox">
      {{child.name}}
      <button class="btn btn-small" ng-click="remove(child)" ng-mouseover="highlight()"> remove</button>

However, a directive I set set up to watch $scope.data is not being fired when all this happens.
I define my tag in HTML:
<d3-visualization val="data"></d3-visualization>

Which is associated with the following directive (trimmed for question sanity):
App.directive('d3Visualization', function() {
    return {
        restrict: 'E',
        scope: {
            val: '='
        },
        link: function(scope, element, attrs) {
            scope.$watch('val', function(newValue, oldValue) {
                if (newValue)
                    console.log("I see a data change!");
            });
        }
    }
});

I get the "I see a data change!" message at the very beginning, but never after as I hit the "add" button.
How can I trigger the $watch event when I'm just adding/removing objects from the data object, not getting a whole new dataset to assign to the data object?

A: You need to enable deep object dirty checking.
By default angular only checks the reference of the top level variable that you watch.
App.directive('d3Visualization', function() {
    return {
        restrict: 'E',
        scope: {
            val: '='
        },
        link: function(scope, element, attrs) {
            scope.$watch('val', function(newValue, oldValue) {
                if (newValue)
                    console.log("I see a data change!");
            }, true);
        }
    }
});

see Scope. The third parameter of the $watch function enables deep dirty checking if it's set to true.
Take note that deep dirty checking is expensive. So if you just need to watch the children array instead of the whole data variable the watch the variable directly.
scope.$watch('val.children', function(newValue, oldValue) {}, true);

version 1.2.x introduced $watchCollection

Shallow watches the properties of an object and fires whenever any of the properties change (for arrays, this implies watching the array items; for object maps, this implies watching the properties)

scope.$watchCollection('val.children', function(newValue, oldValue) {});

A: Because if you want to trigger your data with deep of it,you have to pass 3th argument true of your listener.By default it's false and it meens that you function will trigger,only when your variable will change not it's field.

A: My version for a directive that uses jqplot to plot the data once it becomes available:
    app.directive('lineChart', function() {
        $.jqplot.config.enablePlugins = true;

        return function(scope, element, attrs) {
            scope.$watch(attrs.lineChart, function(newValue, oldValue) {
                if (newValue) {
                    // alert(scope.$eval(attrs.lineChart));
                    var plot = $.jqplot(element[0].id, scope.$eval(attrs.lineChart), scope.$eval(attrs.options));
                }
            });
        }
});


text:
Q: Parameters inside the function I have a work to do in which I have to keep a loop inside the function expecting the following parameters:
-"i" to insert
-"s" to search
-"q" to quit
How do I keep this loop? I've looked up some options and it seems to be possible using a while or a switch, but I am not sure which is the best way to read those chars (with a fscanf perhaps?). I am also not sure how to read the things after the parameter "i" as the input would be "i word 9", so after detecting the i to insert I have to read a string and an int.
Anyone has any idea how to do this? I am sorry is this seems simple, but I am new to programming.
edit: Here is what I have so far
while (loop) {
        fscanf(stdin,"%c",&par);
        if (strcmp(&par,"i")){
            scanf("%s %d",palavra,p);
            raiz = insere(raiz,&palavra,p);
        }
        else if (strcmp(&par,"b")){
            scanf("%s",palavra);
            busca(raiz,&palavra);
        }
        else if (strcmp(&par,"q"))
                 loop = 0;
    }

edit 2: This is what I have now, I am having problems reading the string and integer when the parameter is i, somehow it crashes the function
while (1) {
        c = getchar();
        if (c == 'f')
            break;
        else if (c == 'i'){
            fscanf(stdin,"%s",&palavra);
            scanf("%d",&p);
            raiz = insere(raiz,palavra,p);
        }
        else if (c == 'b') {
            scanf("%s",palavra);
            busca(raiz,palavra);
        }
    }

Thanks in advance!

A: The code you have doesn't look too bad compared to what I believe you want.  You can replace the "while (loop)" with "while (1)" and then your exist code "loop = 0;" with "break;" which is a bit more standard way of doing things.  Also "fscanf(stdin..." is the same as "scanf(..." ... scanf will read from stdin by default.  You might want to check the docs for strcmp because it returns 0 for an exact match and I don't think that will do what you want in your 'if' statements.  You should be able to use scanf to read in the values you want, is it giving you an error?

A: You are using 3 separated scans. That means you can't input this "i word 9", but input one command or parameter at the time separated by EOL(pressing enter).. i, enter, word, enter, 9, enter ... Then the function should actually get further in those "if"s. With those scans you also should consider printing information about expected inputs ("Choose action q/i/f")
And I would recommend using something to test those inputs.
if (scanf("%d", &p) == 0) {
   printf("Wrong input");
   break;
}


text:
Q: Regex: group as an array of mathches with CR in between I am trying to parse in Python a file with information in this format
aaa    111(zzz)
       222
       333
bbb    555
       111

this is baically a way to relate aaa with 111, 222 and 333 (a kind of reference table). Note that zzz is optional although this is not important right now.
What I am trying to get is something like this:
Match 1

*

*group 1. 'aaa'

*group 2. ['111', '222', '333']

Match 2

*

*group 1. 'bbb'

*group 2. ['555', '111']

What I am struggling with is how to make group 2 as an array. Although I might be going in the wrong way.
Could somebody light me on this?
This is my current attempt. It is not even close to what I try to achieve, though.
Update
I will use Python and most probably re as regex module.

A: You need to match the blocks capturing the necessary parts into two groups, and then split/extract what you need from Group 2.
^(\S+)\s+(.*(?:[\r\n]+ +.*)*)

Details

*

*^ - start of the line (due to re.M)

*(\S+) - Group 1: one or more non-whitespace chars

*\s+ - 1  or more whitespaces

*(.*(?:[\r\n]+ +.*)*) - Group 2:

*

*.* - the rest of the line

*(?:[\r\n]+ +.*)* - zero or more occurrences of

*

*[\r\n]+ - 1 or more line break chars

* + - one or more spaces (you may replace it with [^\S\r\n]* to match any horizontal whitespace)

*.* -  the rest of the line

An example code
import re
s = """aaa    111(zzz)
       222
       333
bbb    555
       111"""
rx= r'^(\S+)\s+(.*(?:[\r\n]+ +.*)*)'
res =[]
for m in re.finditer(rx, s, re.M):
    res.append((m.group(1), re.findall(r"[0-9]+", m.group(2))))
    # res.append((m.group(1), m.group(2).split())) # or split with whitespace
print(res) # => [('aaa', ['111', '222', '333']), ('bbb', ['555', '111'])]


text:
Q: Why does training accuracy fall after reaching perfect training fit? I am training a NN in pytorch on MNIST data. The model start well, improves, reaches good accuracy for both training and testing data, stabilizes for a while and then both the testing and training accuracy collapse, as shown on the following base results graph.
As for MNIST, I use 60000 training images, 10000 testing, training batch size 100 and learning rate 0.01. Neural network consist of two fully connected hidden layers, each with 100 nodes, nodes having ReLU activation functions. F.cross_entropy is used for loss and SGD for gradients calculations.
This is not the over-fitting problem, as it is both the training and testing accuracy which collapse. I suspected that it has something to do with too large learning rate. In the base case I have used 0.01 but when I lower it to 0.001 the whole pattern repeats, just later, as shown on the following graph (please notice x-axis scale change, the pattern is happening roughly 10 times later, which is intuitive). Similar results were obtained using even lower learning rates.
I have tried unit testing, checking the individual parts and making the model smaller. Here are results when I am using only 6 data points in the training set, batch size 2. Perfect fit on training data (here clearly different from the test accuracy, as expected) is unsurprisingly reached, but it still collapses from 100% to 1/6 so no better than a random pick. What needs to happen for the network to spin out from a perfect fit on the training set, can anybody tell me?
Here is the structure of the network (the relevant libraries are added before), although I hope that the aforementioned symptoms will be sufficient for you to recognize what the problem is without it:
class Network(nn.Module):
def __init__(self):
    # call to the super class Module from nn
    super(Network, self).__init__()

    # fc strand for 'fully connected'
    self.fc1 = nn.Linear(in_features=28*28, out_features=100)
    self.fc2 = nn.Linear(in_features=100, out_features=100)
    self.out = nn.Linear(in_features=100, out_features=10)

def forward(self, t):

    # (1) input layer (redundant)
    t = t

    # (2) hidden linear layer
    # As my t consists of 28*28 bit pictures, I need to flatten them:
    t = t.reshape(-1, 28*28)
    # Now having this reshaped input, add it to the linear layer
    t = self.fc1(t)
    # Again, apply ReLU as the activation function
    t = F.relu(t)

    # (3) hidden linear layer
    # As above, but reshaping is not needed now
    t = self.fc2(t)
    t = F.relu(t)

    # (4) output layer
    t = self.out(t)
    t = F.softmax(t, dim=1)

    return t

The main execution of the code:
for b in range(epochs):
print('***** EPOCH NO. ', b+1)
# getting a batch iterator
batch_iterator = iter(batch_train_loader)
# For loop for a single epoch, based on the length of the training set and the batch size
for a in range(round(train_size/b_size)):
    print(a+1)
    # get one batch for the iteration
    batch = next(batch_iterator)
    # decomposing a batch
    images, labels = batch[0].to(device), batch[1].to(device)
    # to get a prediction, as with individual layers, we need to equate it to the network with the samples as input:
    preds = network(images)
    # with the predictions, we will use F to get the loss as cross_entropy
    loss = F.cross_entropy(preds, labels)
    # function for counting the number of correct predictions
    get_num_correct(preds, labels))
    # calculate the gradients needed for update of weights
    loss.backward()
    # with the known gradients, we will update the weights according to stochastic gradient descent
    optimizer = optim.SGD(network.parameters(), lr=learning_rate)
    # with the known weights, step in the direction of correct estimation
    optimizer.step()
    # check if the whole data check should be performed (for taking full training/test data checks only in evenly spaced intervals on the log scale, pre-calculated later)
    if counter in X_log:
        # get the result on the whole train data and record them
        full_train_preds = network(full_train_images)
        full_train_loss = F.cross_entropy(full_train_preds, full_train_labels)
        # Record train loss
        a_train_loss.append(full_train_loss.item())
        # Get a proportion of correct estimates, to make them comparable between train and test data
        full_train_num_correct = get_num_correct(full_train_preds, full_train_labels)/train_size
        # Record train accuracy
        a_train_num_correct.append(full_train_num_correct)
        print('Correct predictions of the dataset:', full_train_num_correct)
        # Repeat for test predictions
        # get the results for the whole test data
        full_test_preds = network(full_test_images)
        full_test_loss = F.cross_entropy(full_test_preds, full_test_labels)
        a_test_loss.append(full_test_loss.item())
        full_test_num_correct = get_num_correct(full_test_preds, full_test_labels)/test_size
        a_test_num_correct.append(full_test_num_correct)
    # update counter
    counter = counter + 1

I have googled and checked here for answers to this questions but people either ask about over-fitting or their NNs do not increase accuracy on the training set at all (i.e. they simply don't work), not about finding a good training fit and then completely loosing it, also on the training set. I hope I did not post something obvious, I am relatively new to NN but I did my best to research the topic before posting it here, thank you for your help and understanding!

A: The cause is a bug in the code. We need to add optimizator.zero_grad() at the beginning of the training loop and create the optimizator before the outer training loop, i.e.
optimizator = optim.SGD(...)
for b in range(epochs):

Why do we need to call zero_grad() in PyTorch? explains why.

A: So my take on this is that you are using way too many epochs and are overtraining the model (not overfitting).  After a certain point of constantly refreshing the biases/weights they are no longer able to distinguish values from noise.
I would recommend checking this out https://machinelearningmastery.com/early-stopping-to-avoid-overtraining-neural-network-models/ to see if it is aligning with what you are seeing since it was the first thing I thought of.
Also maybe give this post a look. https://stats.stackexchange.com/questions/198629/difference-between-overtraining-and-overfitting  (not saying this is a duplicate)
And this publication: Overtraining in Back-Propagation
Neural Networks: A CRT Color
Calibration Example
https://onlinelibrary.wiley.com/doi/pdf/10.1002/col.10027


text:
Q: Use Linear approximation to estimate a function Use linear approximation to estimate $\tan(\frac{\pi}{4} + 0.05)$. Identify the differentials $dy$ and $dx$ in the situation.
I know that the form for linear approximation is $f'(x)*dx$. I calculated the derivative of this function to be $0$, so I am not sure what to do when it comes to identifying $dy$ and $dx$.

A: This

the form for linear approximation is $f′(x)∗dx$

is too vague to be useful.
The definition of the derivative says that when $h$ is small,
$$
\frac{f(x+h) - f(x)}{h} \approx f'(x).
$$
Multiply that approximation by $h$ and rearrange to get
$$
f(x+h) \approx f(x) + h \times f'(x).
$$
Now cleverly choose $f$, $x$ and $h$ to get the approximation you want.
If you must use differentials (I wouldn't) then $dx$ is $h$,   the small change in $x$, and $dy$ is the corresponding small change in $f(x)$.

A: Approximate as follows,
$$dy=f'(x)dx$$
or, specifically,
$$\tan\left(\frac{\pi}{4} + 0.05\right)-\tan\left(\frac{\pi}{4}\right)=\left[\tan\left(\frac{\pi}{4}\right)\right]'\cdot 0.05$$
Thus, the approximation is,
$$\tan\left(\frac{\pi}{4}+0.05\right) = 1+\sec^2\left(\frac\pi4\right)\cdot0.05=1+2\cdot0.05=1.1$$
Note that the derivative $\sec^2(x)$ is evaluated at $\frac\pi4$, which is not zero.


text: Q: What is the configuration for inter-pod communication in microk8s I am setting up a set of applications using microk8s. I have two deployment resources - let us say - backend & application- Backend deployment has a service - let us say backend-service.myns.svc.cluster.local. From the pod running the other deployment (application), I am unable connect to the backend-service. Tools like ping, curl fail with Unknown host error. However, I am able to ping google.com or internet from the same (application) pod. What is the cause of the issue?


text:
Q: How to delete all Files on an FTP Server I need to write a script which deletes all files on an FTP server without changing the directory structure.
Since there is no find command or similar.
I tried using lftp but got stuck since the rm -r is not flexible enough.
Anyway it could be bash or python.
I do not have ssh access to that server. FTP only.

A: How is could be done in Python. You did not give any code, so I give the basics only, no code as well:

*

*put the root folder in a list

*pop one item off the list

*

*list the item

*append the directories in this listing to the list

*delete the files in the listing.

*repeat the second step incl. substeps until the list is empty

Helpful: https://docs.python.org/2/library/ftplib.html


text:
Q: CASE WHEN condition 1 AND condition 2 then x else y postgreSQL Im trying to put two conditions inside a case when statement but I am getting a syntax error in postgresql
case when
condition 1 and condition 2 then X else Y
condition 3 and condition 4 then Z else Y

end

What is the correct syntax to have the columns take x in the case of both conditions and y otherwise?

A: Try this way:
case
    when condition 1 and condition 2 then X
    when condition 3 and condition 4 then Z
    else Y
end


text:
Q: C++ List_tail_remove debug I'm not how to debug this one function of my code, When I remove and output my linked list it gives me a funky decimal. Any help would be appreciated.
void list_tail_remove(node*& head_ptr)
{
    if (head_ptr == NULL)
    {
        cout << "Error:The Double linked List was never Created" << endl;
    }
    else
    {
        node* current = head_ptr;
        while (current->link() != NULL)
        {
            current = current->link();
        }

        node* temp;
        for (temp = head_ptr; temp != current; temp = temp->link())
        {
            temp = temp->link();
        }
        temp->set_link(NULL);
        delete temp;
    }
}


text:
Q: nodejs/express, Controller send the response before to get the result of function setInterval the problem is :
In Controller, the response is send before the result of condition into function setInterval
Steps :

*

*Controller run function setInterval

*Then send the response to frontend with res.status.json

*The function setInterval run

*condition of setInterval work and finish

*setInterval don't return the resultto controller

*the controller have already sent a res...

import checkHealth from "./checkHealth.js";

async function checkHealthInterval(labelData) {
  console.log("labelData==>", labelData);

  let resultInterval = { health: "", message: "" };
  let i = 1;
  let interval;

  interval = await setInterval(async () => {
    let healthCheckers = await checkHealth();

    let healthCheckerStatus;
    if (labelData== "example1") {
      healthCheckerStatus = healthCheckers.statusInstanceGlobal;
      console.log(
        "healthCheckerStatus value from tenant1 : ",
        healthCheckerStatus
      );
    } else {
      healthCheckerStatus = healthCheckers.statusWam1Wam2;
      console.log(
        "healthCheckerStatus value from tenant2 : ",
        healthCheckerStatus
      );
    }
    i++;
    if (healthCheckerStatus !== true && i > 36) {
      clearInterval(interval);
      console.log("VMs are UNHEALTHY in the end of interval or before the end");
      this.isProcessing = false;
      throw new ApiError(
        500,
        "VMs are UNHEALTHY in the end of interval or before the end"
      );
    } else if (healthCheckerStatus == true) {
      clearInterval(interval);
      console.log(
        `VMs ${labelData} are HEALTHY and successfully started!`
      );
      resultInterval.health = "healthy";
      resultInterval.message = "VMs are successfully started!";
      console.log("resultInterval into interval===>", resultInterval);

      return resultInterval
    }
  }, 10000);
  console.log("Script interval is running to check health");

  return interval
}
export { checkHealthInterval };

getStartVms = async (req, res, next) => {
    console.log("You asked to start VMs: starting VMs");
    try {
      this.isProcessing = true;
      const responseStart = await this.instanceService.startInstances();

      // use interval to checkHealth of Vms with import function checkHealth()
      const resultInterval = await checkHealthInterval(responseStart?.labelData);

      res.status(200).json({
         health: "healthy",
         message: "VMs are successfully started!",
      });
       this.isProcessing = false;
       io.emit("processChanged", this.isProcessing);

    } catch (err) {
      this.isProcessing = false;
      io.emit("processChanged", this.isProcessing);
      next(err);
    }
  };


text:
Q: Presentations of the ring of modular forms I have seen two ways of describing the ring structure of modular (with respect to the full $SL (2, \mathbb Z)$) forms: $\mathbb C [E_4, E_6]$ and $\mathbb C [E_4,E_6, \Delta]/(E_4^3-E_6^2-1728\Delta )$, where $E_4$ and $E_6$ are the normalized Eisenstein series of weight 4 and 6, respectively.
As far as I've always known, every level 1 modular form is a polynomial in $E_4$ and $E_6$ so the first description is completely appropriate.  The second one has the virtue of promoting $\Delta$ to a special place in the ring, but since $E_4$, $E_6$, and $\Delta$ do satisfy the well known relationship $E_4^3-E_6^2=1728\Delta$ nothing is really gained.  So, unless I'm missing something, these two presentations are equivalent.
My question is then about a distinction that seems to be made in a paper by Sati: OP2 Bundles in M-theory.  In section 3 he describes the ring of modular forms as $\mathbb Z [E_4,E_6, \Delta]/(E_4^3-E_6^2-1728\Delta )$ and he states, by results of Mahowald and Hopkins, that there are certain manifolds which map under the Witten genus to the ring $\mathbb Q [E_4, E_6]$, indicating that these are modular forms "without the discriminant."
I guess I don't really understand what this last part means.  Can somebody please clarify this issue for me?  Thanks in advance.

A: Answered by Qiaochu in the comments:

Is there anything more sophisticated going on here beyond the fact that 1728 is not invertible in Z?


text:
Q: best way to arrange layout blocks I have container with 9 divs, I want to arrange the elements in the following way:
it would look something like this:
 _________ ____ ____
| A       | B  | C  |
|         |____|____|
|         | D  | E  |
|_________|____|____|
| F  | G  | H  | I  |
|____|____|____|____|

where all the elements will always be squares (width = height) and I will determine their size in percentages out of the container.
in the sample above for example A size (width and height) = 50% of width, B size = 25%. I also want to have some margin between each element about 5px.
My attempt is the following

and css:
#grid {width: 90%; position: relative}
.block {margin: 5px; background-size: cover; position: relative; display: inline-block}
.big {width: 50%; height: 0; padding-bottom: 50%; background-color: #eee}
.small {width: 25%; height: 0; padding-bottom: 25%; background-color: #eee}

A: The key to ingredients to the solution is a simple float: left and the use of css calc() function (which fortunately has quite good support these days) to account for mixing of those pixels with percentages:
(I've also added border-box sizing so the borders, which I'm using to display the boxes wouldn't mess up/complicate the calculations)

* {
  box-sizing: border-box;
}
#grid {
  width: 400px;
  height: 300px;
  border: solid 2px gray;
}
.block {
  min-width: 10px;
  min-height: 10px;
  border: solid 2px blue;
  float: left;
  margin: 5px;
}
.block.big {
  width: calc(50% - 10px);
  height: calc(50%*4/3 - 10px);
}
.block.small {
  width: calc(25% - 10px);
  height: calc(25%*4/3 - 10px);
}