text:
Q: [ERROR KubeletVersion]: the kubelet version is higher than the control plane version I'm new to kubernetes and I'm setting up my first testing cluster.  However, I'll get this error when I set up the master node.  But I'm not sure how to fix it.
[ERROR KubeletVersion]: the kubelet version is higher than the control plane version.
This is not a supported version skew and may lead to a malfunctional cluster.
Kubelet version: "1.12.0-rc.1" Control plane version: "1.11.3"

The host is fully patched to the latest levels
CentOS Linux release 7.5.1804 (Core)
Many Thanks
S

A: I hit the same problem and used the kubeadm option: --kubernetes-version=v1.12.0-rc.1

sudo kubeadm init --pod-network-cidr=172.16.0.0/12 --kubernetes-version=v1.12.0-rc.1

I'm using a JVM image that was prepared a few weeks ago and have just updated the packages. Kubeadm, kubectl and kubelet all now return version v1.12.0-rc.1 when asked but when 'kubeadm init' is called it kicks off with the previous version.

[init] using Kubernetes version: v1.11.3

specifying the (control plane) version did the trick.

A: Install the same version of kubelet & kubeadm
yum -y remove kubelet
yum -y install kubelet-1.11.3-0 kubeadm-1.11.3-0

A: I'm getting the same error on a clean Centos 7 install after fully updating with yum update, and then applying the instructions from https://kubernetes.io/docs/setup/independent/install-kubeadm/ for setup.
Adding the option for --ignore-preflight-errors=KubeletVersion allows the installer to continue but the installation is non-working afterwards.
I was able to remove everything and reinstall matching versions with the following:
yum -y remove kubelet kubeadm kubectl
yum install -y --disableexcludes=kubernetes kubeadm-1.11.3-0.x86_64 kubectl-1.11.3-0.x86_64 kubelet-1.11.3-0.x86_64


text:
Q: Convert async Task from c# to vb.net I try convert this code using code C# to VB.NET converter, have some error.
private async Task OnRequestBlockResourceEventHandler(object sender, SessionEventArgs e)
            => await Task.Run(
                () =>
                {
                    if (e.HttpClient.Request.RequestUri.ToString().Contains("analytics"))
                    {
                        string customBody = string.Empty;
                        e.Ok(Encoding.UTF8.GetBytes(customBody));
                    }
                });

and here are VB.NET converted code:
Private Async Function OnRequestBlockResourceEventHandler(ByVal sender As Object, ByVal e As SessionEventArgs) As Task
    Return Await Task.Run(Function()

                              If e.HttpClient.Request.RequestUri.ToString().Contains("analytics") Then
                                  Dim customBody As String = String.Empty
                                  e.Ok(Encoding.UTF8.GetBytes(customBody))
                              End If
                          End Function)
End Function

and have error like this:

Comma, ')', or a valid expression continuation expected.
'Return' statements in this Async method cannot return a value since
  the return type of the function is 'Task'. Consider changing the
  function's return type to 'Task(Of T)'

A: You need to change the lambda function to a sub:
Private Async Function OnRequestBlockResourceEventHandler(ByVal sender As Object, ByVal e As SessionEventArgs) As Task
   ' *** Change to Sub() ***
   Return Await Task.Run(Sub()

                                  If e.HttpClient.Request.RequestUri.ToString().Contains("analytics") Then
                                      Dim customBody As String = String.Empty
                                      e.Ok(Encoding.UTF8.GetBytes(customBody))
                                  End If
                              ' *** Change to End Sub ***
                            End Sub)
    End Function

FYI there is a free Visual Studio extension called Code Converter to/from VB.NET . "Based on Roslyn, this converter allows you to convert C# code to VB.NET and vice versa.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to Link the title How can i link the title in this code.
 echo "
";
      echo "
";
            echo '
';
    echo "

".html_entity_decode(substr($video['video_title'],0,100))."..

".html_entity_decode(substr($video['video_desc'],0,100))."

 View Count: ".$video['views']."

";

this is another code linked. its working
echo '

'.$video['video_title'].'

';
    }
    ?>

Thanks in advance.

A: echo "
";
echo "
";
echo '
';
echo "

".html_entity_decode(substr($video['video_title'],0,100))."..

".html_entity_decode(substr($video['video_desc'],0,100))."

 View Count: ".$video['views']."

";

It aint pretty though.  All you need to do is wrap the anchor:
YOUR LINK TEXT

Around the title in the string.  Because you are reusing the anchor href and it's quite a long one I would favour setting a variable to the href value then using the variable for clarity.


text:
Q: Creating more simple lines from multiple columns I have a dataframe that looks like this:
Movie        Action    Adventure    Duration Director   More info...
SpongeBob       0          1           123      Karl
The Avengers    1          1           134      Annie

But I want to split that up into lines containing only the movie, one genre at a time and some more columns, like 'Director' and 'Duration'. After the transformation, the DataFrame should look like this:
Movie            Genre       Duration Director  (No more extra info)
SpongeBob      Adventure        123      Karl
The Avengers   Adventure        134      Annie
The Avengers   Action           134      Annie

A: Here is one way to do it:
df.melt(['Movie', 'Duration', 'Director', 'More info'], var_name='Genre')\
  .query('value == 1')\
  .drop('value', axis=1)

Output:
          Movie  Duration Director More info      Genre
1  The Avengers       134    Annie         B     Action
2     SpongeBob       123     Karl         A  Adventure
3  The Avengers       134    Annie         B  Adventure

Reshape the dataframe using melt then filter for rows where value equals to 1, then drop the value column.


text:
Q: Making a Java SplitButton The following code seems like it should fill the given space evenly with two associated JButtons, but instead it fills the FlowLayout's entire top row with one button--ignoring the button's maximum size--and puts the other button on a new row, only partially visible. How can I get the buttons to evenly fill the JPanel side-by-side?
import java.awt.*;
import javax.swing.*;

public class SplitButton extends JPanel {

    // The other half.
    private JButton button2;
    private JButton button3;

    public SplitButton(String left, String right, int width, int height) {
        super();
        //setBackground(Color.GREEN);
        //setBorder(BorderFactory.createLineBorder(Color.BLUE));
        setMinimumSize(new Dimension(width, height));
        FlowLayout flow = new FlowLayout();
        flow.setAlignment(FlowLayout.LEFT);
        flow.setHgap(0);
        flow.setVgap(0);

        setLayout(flow);

        button2 = new JButton(right);
        button2.setMinimumSize(new Dimension(width / 2, height));
        button2.setMaximumSize(new Dimension(width / 2, height));
        button2.setPreferredSize(new Dimension(width / 2, height));
        add(button2);

        button3 = new JButton(right);
        button3.setMinimumSize(new Dimension(width / 2, height));
        button2.setMaximumSize(new Dimension(width / 2, height));
        button2.setPreferredSize(new Dimension(width / 2, height));
        add(button3);
    }
}

A: After a while of struggling, I tried a GridLayout--which makes SplitButtons in Swing a very rational UI element.
import java.awt.Font;
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.ActionListener;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JPanel;

public class SplitButton extends JPanel {

    // The buttons.
    private JButton[] buttons;

    // Self-explanatory.
    public Color prim, trim;
    public Font font;

    public SplitButton(String[] labels, Color prim, Color trim, Font font) {
        super();

        this.prim = prim;
        this.trim = trim;
        this.font = font;

        // Evenly lays out buttons evenly in a row.
        GridLayout grid = new GridLayout(1, labels.length);
        grid.setHgap(0);
        grid.setVgap(0);
        setLayout(grid);

        setOpaque(false);
        initButtons(labels);
    }

    /**
    * Constructs and styles the button array.
    * @param labels The button labels.
    */
    private void initButtons(String[] labels) {
        buttons = new JButton[labels.length];
        for(int i = 0; i < buttons.length; i++) {
            buttons[i] = new JButton(labels[i]);

            // Only outer borders are thick.
            int lb = (i == 0) ? 2 : 1;
            int rb = (i == buttons.length - 1) ? 2 : 0;

            buttons[i].setBorder(BorderFactory.createMatteBorder(2, lb, 2, rb, trim));
            buttons[i].setFocusPainted(false);
            buttons[i].setFont(font);
            buttons[i].setBackground(prim);
            buttons[i].setForeground(trim);
            add(buttons[i]);
        }
    }

    /**
    * Enable/disable the buttons.
    * @param enabled Is the button enabled?
    */
    public void setEnabled(boolean enabled) {
        if(buttons != null)
            for(int i = 0; i < buttons.length; i++)
                buttons[i].setEnabled(enabled);
    }

    /**
    * Listen to all the buttons.
    * @param listener The listening object.
    */
    public void addActionListener(ActionListener listener) {
        if(buttons != null)
            for(int i = 0; i < buttons.length; i++)
                buttons[i].addActionListener(listener);
    }
}


text:
Q: How to automatically load passwords into browser/MacOS/iOS keychain I am trying to figure out a shared family password scenario (for things like Amazon, Netflix, etc.). Basically, 1 password for each service that we can all use. However, to maximize security as well, I'm thinking about doing some sort of ejson thingy (still have more to learn there). Basically, a bunch of passwords in an encrypted JSON file that can be shared.
So then someone downloads the JSON file, decrypts it with their computer on the Mac. I know how to do that much. I don't know how you would securely do this on the iPhone. That's part of the question.
What I imagine is something like this. You decrypt the ejson passwords. You then somehow load them into your Mac keychain from the command line (or perhaps some Swift library). Likewise, you plug in your iPhone to your Mac, and can somehow inject the keychain info into the iPhone. Now it's simple, when you go to Netflix, the browser (iOS Safari, or Chrome) prompts you with your preexisting password for that service and boom, you don't even have to remember your password, or use a password manager like LastPass. By loading the decrypted ejson file into the keychain, you get everything else for free.
Note: I don't want to use a password manager like LastPass or any others.
What I'm wondering is if (a) something like this is even possible, and (b) roughly the pieces I would need to solve to get this working. I don't need step-by-step instructions on how to get it working, or necessarily commands on the command line (though that would be a helpful start). I basically just need to know the general approach to how I can share passwords like this in this sort of system, and get the browser to autofill them in, without requiring anyone to enter any passwords into Netflix/etc..

A: You could use a shared Note & thereby

*

*stay entirely within the Apple ecosystem.

*don't have to build anything yourself ;)

The first time each password is copy/pasted from the Note into the relevant area, each user's keychain would then save it [& re-distribute to all that user's devices if iCloud keychain is switched on]. The Note would then just become a 'text backup', or a way to redistribute any changes.
I just realised you can't specifically lock one Note & then share it. This, I have discovered empirically, means that though you are the only person who can delete it, anyone with access can modify it... usually accidentally.
My workaround for this is simply to share a copy, not your original, so you can copy back over if anyone fumbles it... like my partner does with remarkable frequency ;)


text:
Q: changing the destination on the map by the button shiny I have a shiny app which displays a map and can choose a few countries based on the selectinput function.  I'm trying to replace the selectInput with the button, so instead of choosing the country, the user should be able to click on the button and the next country will appear. Thanks in advance
library(shiny)
library(leaflet)

df <- structure(list(lng = c(101.901875, -95.712891, 108.339537, 37.618423
), lat = c(35.486703, 37.09024, 14.315424, 55.751244), country = structure(c(1L,
                                                                             3L, 4L, 2L), .Label = c("China", "Russia", "USA", "Vietnam"), class = "factor"),
number = c(35500L, 6267L, 2947L, 3070L)), .Names = c("lng",
                                                     "lat", "country", "number"), class = "data.frame", row.names = c(NA,

                                                                                -4L))

ui <- (fluidPage(
  titlePanel(title = "countries"),
  sidebarLayout(
    sidebarPanel( uiOutput("countrynames"),
                  shiny::actionButton("dd", "click")
    ),
    mainPanel(leafletOutput("mymap", height = "500")
    ))
)
)

server <- function(input, output){
  output$countrynames <- renderUI({
    selectInput(inputId = "country", label = "Select a country to view it's values (you can choose more than one):",
                c(as.character(df$country)))
  })

  map_data <- reactive({
    data <- data.frame(df[df$country == input$country,])
    data$popup <- paste0(data$country, " ", data$number)
    return(data)
  })
  output$mymap <- renderLeaflet({
    leaflet(data = map_data()) %>%
      setView( lng = -16.882374406249937, lat = -1.7206857960062047, zoom = 0) %>%
      addProviderTiles( provider = "CartoDB.Positron") %>%
      addMarkers(lng = ~lng, lat = ~lat, popup = ~popup)
  })
}
shinyApp(ui, server)

A: You can achieve this with a reactiveVal to represent the index of the list of countries. It would update on the button's click.
library(shiny)
library(leaflet)

countries = c("China", "Russia", "USA", "Vietnam")

df <- structure(list(lng = c(101.901875, -95.712891, 108.339537, 37.618423
), lat = c(35.486703, 37.09024, 14.315424, 55.751244), country = structure(c(1L,
                                                                             3L, 4L, 2L), .Label = c("China", "Russia", "USA", "Vietnam"), class = "factor"),
number = c(35500L, 6267L, 2947L, 3070L)), .Names = c("lng",
                                                     "lat", "country", "number"), class = "data.frame", row.names = c(NA,

                                                                                -4L))

ui <- (fluidPage(
  titlePanel(title = "countries"),
  sidebarLayout(
    sidebarPanel(
      # uiOutput("countrynames"),
      shiny::actionButton("dd", "click")
    ),
    mainPanel(leafletOutput("mymap", height = "500")
    ))
)
)

server <- function(input, output){
  output$countrynames <- renderUI({
    selectInput(inputId = "country", label = "Select a country to view it's values (you can choose more than one):",
                c(as.character(df$country)))
  })

  index = reactiveVal(1)

  selected_country = reactive({

    countries[index()]

  })

  observeEvent(input$dd,{
    i = index() + 1
    if(i > length(countries)){
      i = 1
    }
    index(i)
  })

  map_data <- reactive({
    data <- data.frame(df[df$country == selected_country(),])
    data$popup <- paste0(data$country, " ", data$number)
    return(data)
  })
  output$mymap <- renderLeaflet({
    leaflet(data = map_data()) %>%
      setView( lng = -16.882374406249937, lat = -1.7206857960062047, zoom = 0) %>%
      addProviderTiles( provider = "CartoDB.Positron") %>%
      addMarkers(lng = ~lng, lat = ~lat, popup = ~popup)
  })
}
shinyApp(ui, server)

To maintain the selectInput you could use an updateSelectInput.


text:
Q: How to strip string in .htaccess? I have URL:
http://www.mydomain.com/326-something/something.jpg
This follows to:
http://www.mydomain.com/img/p/3/2/6/something.jpg
But I have also URL:
http://www.mydomain.com/125-326-something/something.jpg
How can I ignore this 125- ? Of course I have urls with prefixes like 126, 127 etc. How can I ignore this in .htaccess?
I want to display http://www.mydomain.com/img/p/3/2/6/something.jpg from this url http://www.mydomain.com/125-326-something/something.jpg
Here is my htaccess rules:
RewriteCond %{HTTP_HOST} ^mydomain.com$
RewriteRule ^([0-9])(\-[_a-zA-Z0-9-]*)?(-[0-9]+)?/.+\.jpg$ %{ENV:REWRITEBASE}img/p/$1/$1$2$3.jpg [L]
RewriteCond %{HTTP_HOST} ^mydomain.com$
RewriteRule ^([0-9])([0-9])(\-[_a-zA-Z0-9-]*)?(-[0-9]+)?/.+\.jpg$ %{ENV:REWRITEBASE}img/p/$1/$2/$1$2$3$4.jpg [L]
RewriteCond %{HTTP_HOST} ^mydomain.com$
RewriteRule ^([0-9])([0-9])([0-9])(\-[_a-zA-Z0-9-]*)?(-[0-9]+)?/.+\.jpg$ %{ENV:REWRITEBASE}img/p/$1/$2/$3/$1$2$3$4$5.jpg [L]
RewriteCond %{HTTP_HOST} ^mydomain.com$
RewriteRule ^([0-9])([0-9])([0-9])([0-9])(\-[_a-zA-Z0-9-]*)?(-[0-9]+)?/.+\.jpg$ %{ENV:REWRITEBASE}img/p/$1/$2/$3/$4/$1$2$3$4$5$6.jpg [L]
RewriteCond %{HTTP_HOST} ^mydomain.com$
RewriteRule ^([0-9])([0-9])([0-9])([0-9])([0-9])(\-[_a-zA-Z0-9-]*)?(-[0-9]+)?/.+\.jpg$ %{ENV:REWRITEBASE}img/p/$1/$2/$3/$4/$5/$1$2$3$4$5$6$7.jpg [L]
RewriteCond %{HTTP_HOST} ^mydomain.com$
RewriteRule ^([0-9])([0-9])([0-9])([0-9])([0-9])([0-9])(\-[_a-zA-Z0-9-]*)?(-[0-9]+)?/.+\.jpg$ %{ENV:REWRITEBASE}img/p/$1/$2/$3/$4/$5/$6/$1$2$3$4$5$6$7$8.jpg [L]
RewriteCond %{HTTP_HOST} ^mydomain.com$
RewriteRule ^([0-9])([0-9])([0-9])([0-9])([0-9])([0-9])([0-9])(\-[_a-zA-Z0-9-]*)?(-[0-9]+)?/.+\.jpg$ %{ENV:REWRITEBASE}img/p/$1/$2/$3/$4/$5/$6/$7/$1$2$3$4$5$6$7$8$9.jpg [L]
RewriteCond %{HTTP_HOST} ^mydomain.com$
RewriteRule ^([0-9])([0-9])([0-9])([0-9])([0-9])([0-9])([0-9])([0-9])(\-[_a-zA-Z0-9-]*)?(-[0-9]+)?/.+\.jpg$ %{ENV:REWRITEBASE}img/p/$1/$2/$3/$4/$5/$6/$7/$8/$1$2$3$4$5$6$7$8$9$10.jpg [L]

A: Personally I would highly recommend routing all requests through a controlling PHP script and managing this in a real programming language instead of mod_rewrite.
But to answer the question directly:
RewriteCond %{HTTP_HOST} ^mydomain.com$
RewriteRule ^\d+-(\d+-[_a-zA-Z0-9-]*/.+?\.jpg)$ $1

Add these lines (untested) before the above rules, and it should strip off the part you don't want before allowing it to fall through the regular rewrite process.


text:
Q: Fire Event on change not firing the search In my online interface there is a client search. At the point when I embed PAN. Search motor discover the client with that PAN and I select something similar (When I select it every client has some extraordinary id at backend, it reflecting for half second). When I Select a similar it divert me to the page where full detail of client is there. I needed to divert there. However, codes are not supporting.
HTML Codes

                            CLIENTS:

                            1 result is available, use up and down arrow keys to navigate.<input class="ui-autocomplete-input ui-autocomplete-loading" id="SEARCH_CLIENT_ID" style="width: 100% !important; color: rgb(51, 51, 51);" autocomplete="off">
                            <input id="hdnSEARCH_CLIENT_ID" type="hidden">

I have taken a stab at fallowing Codes
IE.Document.getElementById("SEARCH_CLIENT_ID").Focus
IE.Document.getElementById("SEARCH_CLIENT_ID").Value = "ACPPL3488C"
IE.Document.getElementById("SEARCH_CLIENT_ID").FireEvent ("onchange")
IE.Document.getElementById("SEARCH_CLIENT_ID").selectedIndex = 1

In any case, its not working for me. generously control me my misstep

A: Create change event using Event constructor and then dispatch the change event on target element using  EventTarget.dispatchEvent() method.

const event = new Event('change');
const inputEle = document.getElementById("SEARCH_CLIENT_ID");

// Listen for the change event.
inputEle.addEventListener('change', function (e) {
  console.log(e.target.value); // output: ACPPL3488C
}, false);

inputEle.focus();
inputEle.value = "ACPPL3488C";

// Dispatch the change event.
inputEle.dispatchEvent(event);

                            CLIENTS:

                            1 result is available, use up and down arrow keys to navigate.<input class="ui-autocomplete-input ui-autocomplete-loading" id="SEARCH_CLIENT_ID" style="width: 100% !important; color: rgb(51, 51, 51);" autocomplete="off">
                            <input id="hdnSEARCH_CLIENT_ID" type="hidden">

Check MDN docs for more details.


text:
Q: Error: I can not connecting to server when connecting to Mongo Db Atlas using mongoose. How can i solve this error? I am using mongo db. I am trying to connected the server and mongodb. But it is not working and it show above error.
This is the server code.
    const uri = `mongodb+srv://${process.env.DB_USER}:${process.env.DB_PASS}@cluster0.6ptzk.mongodb.net/myFirstDatabase?retryWrites=true&w=majority`;

const client = new MongoClient(uri, { useNewUrlParser: true, useUnifiedTopology: true, serverApi: ServerApiVersion.v1 });
0
more server code
 try {
    await client.connect();
    const serviceCollection = client.db('geniusCar').collection('service')
    const orderCollection = client.db('geniusCar').collection('order')
    //jwt api
    app.post('/login', async (req, res) => {
        const user = req.body;
        const accessToken = jwt.sign(user, process.env.ACCESS_TOKEN_SECRET, {
            expiresIn: '1d'
        })
        res.send({ accessToken })
    })

I get this message:
Error: queryTxt ETIMEOUT cluster0-ghis2.mongodb.net

at QueryReqWrap.onresolve [as oncomplete] (dns.js:202:19) {
errno: 'ETIMEOUT',
code: 'ETIMEOUT',
syscall: 'queryTxt',
hostname: 'cluster0-ghis2.mongodb.net'
}
My dependencies:
 "dependencies": {
"express": "^4.17.2",
"mongodb": "^4.4",
"mongoose": "^5.9.14"

}


text:
Q: How to search data by using NEST API? I have ElasticSearch client which has default settings.
elasticClient = new ElasticLowLevelClient();

Also I have a simple post entity.
[ElasticsearchType(IdProperty = "Id", Name = "post")]
    public class Post
    {
        [Number(Name = "id")]
        public int Id { get; set; }
        [Text(Name = "title")]
        public string Title { get; set; }
        [Text(Name = "description")]
        public string Description { get; set; }
    }

I want to execute the query which is similar to query from Es documentation:
var searchResults = client.Search<Post>(p=>p
    .From(0)
    .Size(10)
    .Query(q=>q
         .Term(p=>p.Title, "stackoverflow")
    )
);

But I think that ES API was changed. The first argument should be PostData. That's why I don't know how my query should look.
Version of my ElasticSearch is 2.3.5
Version of NEST is 5.0.1
Maybe I need a lower version of NEST?

A: You're instantiating an instance of the low level client from Elasticsearch.Net.
If you change to using the high level client from NEST, all will be well
var elasticClient = new ElasticClient();

Internally, NEST uses the low level client, which is why Elasticsearch.Net is brought in as a dependency.


text:
Q: StreamReader not working as expected I have written a simple utility that loops through all C# files in my project and updates the copyright text at the top.
For example, a file may look like this;
//Copyright My Company, © 2009-2010

The program should update the text to look like this;
//Copyright My Company, © 2009-2010

However, the code I have written results in this;
//Copyright My Company, � 2009-2011

Here is the code I am using;
public bool ModifyFile(string filePath, List<string> targetText, string replacementText)
{
    if (!File.Exists(filePath)) return false;
    if (targetText == null || targetText.Count == 0) return false;
    if (string.IsNullOrEmpty(replacementText)) return false;

    string modifiedFileContent = string.Empty;
    bool hasContentChanged = false;

    //Read in the file content
    using (StreamReader reader = File.OpenText(filePath))
    {
        string file = reader.ReadToEnd();

        //Replace any target text with the replacement text
        foreach (string text in targetText)
            modifiedFileContent = file.Replace(text, replacementText);

        if (!file.Equals(modifiedFileContent))
            hasContentChanged = true;
    }

    //If we haven't modified the file, dont bother saving it
    if (!hasContentChanged) return false;

    //Write the modifications back to the file
    using (StreamWriter writer = new StreamWriter(filePath))
    {
        writer.Write(modifiedFileContent);
    }

    return true;
}

Any help/suggestions are appreciated. Thanks!

A: This is an encoing problem.
I think you should change this line
using (StreamWriter writer = new StreamWriter(filePath))

To a variant that saves with the correct encoding (the overload that looks like this)
using (StreamWriter writer = new StreamWriter(filePath, false, myEncoding))

To get the correct encoding, where you have opened the file add this line
myEncoding = reader.CurrentEncoding;

A: Try to use
StreamWriter(string path, bool append, Encoding encoding)

i.e.
new StreamWriter(filePath, false, new UTF8Encoding())

A: Get the Encoding from reader and use it in writer.
Changed code:
public bool ModifyFile(string filePath, List targetText, string replacementText)
{
    if (!File.Exists(filePath)) return false;
    if (targetText == null || targetText.Count == 0) return false;
    if (string.IsNullOrEmpty(replacementText)) return false;

    string modifiedFileContent = string.Empty;
    bool hasContentChanged = false;
    Encoding sourceEndocing = null;

    using (StreamReader reader = File.OpenText(filePath))
    {
        sourceEndocing = reader.CurrentEncoding;
        string file = reader.ReadToEnd();

        foreach (string text in targetText)
            modifiedFileContent = file.Replace(text, replacementText);

        if (!file.Equals(modifiedFileContent))
            hasContentChanged = true;
    }

    if (!hasContentChanged) return false;

    using (StreamWriter writer = new StreamWriter(filePath, false, sourceEndocing))
    {
        writer.Write(modifiedFileContent);
    }

    return true;
}

A: You have to specify the encoding
System.Text.Encoding.UTF8 should do the trick.
Once you've sorted it please promise me to read this.

A: I'll bet it's related to the encoding of the file contents. Make sure you instantiate your StreamWriter with the correct encoding. ( http://msdn.microsoft.com/en-us/library/f5f5x7kt.aspx )


text:
Q: Windows 7 : Prevent computer from sleeping while there is network traffic I have a python script that is downloading data on a remote computer. I want to prevent the computer from going to sleep as long as the data download is in progress. However if the program finishes/hangs/crashes, I want the computer to go to sleep.
I do not want to disable hibernation settings on my computer. I've looked around at programs like insomnia & command line shortcuts ( How can I put the computer to sleep from Command Prompt/Run menu? ) but they aren't perfect for the job. Any way I can put a try:except:finally block around my python code and call some function to put the computer to sleep ?
Update :
Found this answer useful : What is the command to use to put your computer to sleep (not hibernate)? . I created a little one line sleep app that I can call from my python finally block using os.system call.

A: One possible way to avoid this problem is to make use of your network adapter power management options.

*

*Type Device Manager in your Start Menu search box and run the application.

*Locate and Right-Click your network adapter

*Move to the Power Management tab.

*Either:

*

*Turn off "Allow the computer to turn off this device to save power", or

*Turn off "Only allow a magic packet to wake the computer".

I'd probably suggest 4.2 first and see if it works with your network adapter. This will keep power management features activated for your network adapter. 4.1 will remove them entirely.
Alternatively, you can try and keep magic packets on and use them from within python to keep the computer awake: Start here: Power Management for Network Devices in Windows 7. You are interested in the comments at the end of the article.

If you configure the Windows 7 network adaptor to "Only Allow Magic
  Packets to wake up the computer" you can send Magic Packets using the
  free WolCmd.exe command line utility. Since this method was not not
  100% reliable I created a batch file that sends the command 4 times as
  follows using 4 different inbound UDP ports forwarded to the LAN ip
  address of the Thinkpad. Using 4 different ports was an attempt to
  improve 'wake-up' and delivery reliability. Sending the command 4
  times definitely helped reliabilty. I don't know if using 4 different
  UDP ports through the firewall made any difference.

Wolcmd is available here.


text:
Q: Isomorphism between two groups of order $p^6$ Let $\mathbb{F}_{p^n}$ denote the finite field of order $p^n$. Let $G$ be the group
$$ \begin{Bmatrix}
\begin{bmatrix} 1 & a & b\\ 0 & 1 & c\\ 0 & 0 & 1\end{bmatrix}\colon a,b,c\in\mathbb{F}_{p^2}
\end{Bmatrix}
$$
and $H$ be the group
$$ \begin{Bmatrix}
\begin{bmatrix} 1 & a & b\\ 0 & 1 & c\\ 0 & 0 & 1\end{bmatrix}\colon a,b,c\in\mathbb{F}_{p}
\end{Bmatrix}.
$$
Question: Is it true that $G$ is isomorphic to $H\times H$ (external direct product)?
[The group $G$ appears in a paper of Burnside while talking about automorphisms preserving conjugacy classes. To understand the automorphism group of $G$, I tried to check whether $G$ and $H\times H$ are isomorphic?]

A: This involves a bit of calculation, but one way to show that these groups are not isomorphic is to show that all non-central elements of $G$ (i.e. those with $a \ne 0$ or $c \ne 0$) have centralizers of order $p^4$ and conjugacy class of sixe $p^2$. Any such $g$ is conjugate to $gz$ for all $z \in Z(G)$.
However, the non-central elements in the direct factors of $H \times H$ have centralizers of order $p^5$ and conjugacy class of size $p$.


text:
Q: MVC 4 Websecurity Hello I am starting an mvc 4 site.
I need to add security to the site.
So far i have used the websecutiy class
http://msdn.microsoft.com/en-us/library/webmatrix.webdata.websecurity(v=vs.111).aspx
I have read though on here that the webmatrix security class has some limitations as compared to  System.Web.Security.Membership
I want the greatest flexibility in the future.
I also want one database that is created with the code first approach. I have achieved this with webmatrix security with WebSecurity.InitializeDatabaseConnection.
If i am using the default System.Web.Security.Membership how do i go about do this with code first. I would like the database in one place. I presume i need these config setting added.

<clear/>

<add name="AspNetSqlMembershipProvider"

     type="System.Web.Security.SqlMembershipProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"

     connectionStringName="ApplicationServices"

     enablePasswordRetrieval="false"

     enablePasswordReset="true"

     requiresQuestionAndAnswer="false"

     requiresUniqueEmail="false"

     passwordFormat="Hashed"

     maxInvalidPasswordAttempts="5"

     minRequiredPasswordLength="6"

     minRequiredNonalphanumericCharacters="0"

     passwordAttemptWindow="10"

     passwordStrengthRegularExpression=""

     applicationName="/"

        />

What are the advantages of using webmatrix security over system.web.security.
I am really stuck so you help would be great


text:
Q: Why is sum(X, 1) the sum of the columns in MATLAB? >> X = [0 1 2
        3 4 5]

>> sum(X, 1)

ans =

     3     5     7

sum(X, 1) should sum along the 1st dimension(row) as per the document says:

S = SUM(X,DIM) sums along the
  dimension DIM.

But why does it actually sums along the 2nd dimension(column)?

A: In my opinion, it is perfectly consistent with everything else.
sum(A,dim) sums along the direction of dimension dim.
Rows are counted "down", so sum(A,1) sums "down". Columns are counted "to the right", so sum(A,2) sums "to the right".
Another way to look at this is that sum(A,dim) collapses dimension dim to 1 by taking the sum. Thus, a 4x3 array summed along dimension 1 collapses the first dimension, leading to a 1x3 array.

A: http://www.mathworks.com/access/helpdesk/help/techdoc/ref/sum.html

B = sum(A,dim) sums along the
  dimension of A specified by scalar
  dim. The dim input is an integer value
  from 1 to N, where N is the number of
  dimensions in A. Set dim to 1 to
  compute the sum of each column, 2 to
  sum rows, etc.

Your guess is as good as mine.

A: 1 means column,
according to http://www.mathworks.com/access/helpdesk/help/techdoc/ref/sum.html

B = sum(A,dim) sums along the
  dimension of A specified by scalar
  dim.
      The dim input is an integer value from 1 to N, where N is the number of
  dimensions in A.
      Set dim to 1 to compute the sum of each column, 2 to sum rows, etc.

A: I think that the Matlab documentation on this is quite clear.  It states:

B = sum(A,dim) sums along the dimension of A specified by scalar dim. The dim input is an integer value from 1 to N, where N is the number of dimensions in A. Set dim to 1 to compute the sum of each column, 2 to sum rows, etc.

You're welcome to think that Matlab is wrong, but it ain't going to change !


text:
Q: Custom Excerpt is returning 52 characters and not 52 words I have this custom function that get's the manually entered excerpt and trims it down but the problem I'm having is that it is trimming the characters down to 52 and instead I want it to return the first 52 Words like the normal excerpt.
Here's the custom that allows me to trim the manually entered excerpt
function themeTemplate_trim_excerpt( $content ) {
    return substr( strip_tags( $content ), 0, 52 );
}
remove_filter('get_the_excerpt', 'wp_trim_excerpt');
add_filter('get_the_excerpt', 'template_trim_excerpt');

This is the only way I've been able to cut the manually entered excerpt.
How do I make it trim it so it only shows the first 52 words?
Thanks for any feedback :)

A: The function you want is wp_trim_words(), example:
function themeTemplate_trim_excerpt( $content ) {
    $more = '...'; //where $more is optional
    return wp_trim_words($content, 52, $more);
}

remove_filter('get_the_excerpt', 'wp_trim_excerpt');
add_filter('get_the_excerpt', 'template_trim_excerpt');

A: explode, array_filter, array_slice, and implode can pull the world by looking operating on the whitespace.
function themeTemplate_trim_excerpt( $content ) {

    // split the content by spaces,
    // remove excess whitespace
    // pull the first 52 items,
    // glue back together...

    return implode( ' ', array_slice( array_filter( explode( ' ', $content ) ), 0, 52 ) );
}

remove_filter( 'get_the_excerpt', 'wp_trim_excerpt' );
add_filter( 'get_the_excerpt', 'template_trim_excerpt' );

Breakdown
// Convert the string to an array
$words = explode( ' ', $content );

// Remove any empty values
$words = array_filter($words);

// Grab the first 10 elements from the array
$first_x_words = array_slice($words, 0, 10);

// Convert the array to a string
$output = implode ( ' ', $first_x_words );

// Final value
echo $output;

Cons

*

*Since these operations act on spaces, if there is HTML in your content, each attribute can be viewed as a word.

*It's much easier to use wp_trim_words() - [ L2951 ]


text:
Q: JSOM : Unable to update Custom list item I have Read User having read Permission.
I'm trying to update the list item using JSOM. But I get below error
"Access denied. You do not have permission to perform this action or access this resource."
    try {
    var list = clientContext.get_site().get_rootWeb().get_lists().getByTitle("ListName");

    var reportListItem = list.getItemById(CommentId);
    reportListItem.set_item('Reported_Flag', '1');
    reportListItem.set_item('Report_Comment', commentText);
    reportListItem.update();

    clientContext.executeQueryAsync(function () {
        $('#reportModal textarea').val("");
        $("#reportModal").modal("hide");

    }, function (xhr, textStatus, errorThrown) {
        ULS.enable = true
        ULSOnError(" - Unable to get report the comment in Comments list - " + textStatus + errorThrown, location.href, 0)
    });
}
catch (error) {
    console.log("  - " + error.message);
    ULS.enable = true;
    ULSOnError(" - " + error.message, location.href, 0);
}

A: Using JSOM you have the exact same permissions as the current user (no more and no less), so if the current user only have read permission, then you can't update.

A: You cannot update the list items using JSOM with only Read permission.
In order to add/update/delete list items, you should at least have Contribute permissions.
For more understanding, check below article:
Understanding permission levels in SharePoint.


text:
Q: How to run code after UIView transitionWithView? I want to run a block of code after an animation is completed but the compiler shows the following error : "Incompatible block pointer types sending 'void (^)(void)' to parameter of type 'void (^)(BOOL)'"
Here is my code, I am not sure what I am doing wrong, please help, thanks.
[UIView transitionWithView:self.view duration:1.5
                   options:UIViewAnimationOptionTransitionFlipFromBottom //change to whatever animation you like
                animations:^ {
                    [self.view addSubview:myImageView1];
                    [self.view addSubview:myImageView2];
                }
                completion:^ {
                    NSLog(@"Animations completed.");
                    // do something...
                }];

A: You just have the wrong block type :) It needs a block like below. The key being ^(BOOL finished) {...}
[UIView transitionWithView:self.view duration:1.5
                   options:UIViewAnimationOptionTransitionFlipFromBottom //change to whatever animation you like
                animations:^ {
                    [self.view addSubview:myImageView1];
                    [self.view addSubview:myImageView2];
                }
                completion:^(BOOL finished){
                    if (finished) {
                        // Successful
                    }
                    NSLog(@"Animations completed.");
                    // do something...
                }];


text:
Q: How to concatenate all lines from a file in Bash? I have a file csv :
data1,data2,data2
data3,data4,data5
data6,data7,data8

I want to convert it to (Contained in a variable):
variable=data1,data2,data2%0D%0Adata3,data4,data5%0D%0Adata6,data7,data8
My attempt :
data=''
cat csv | while read line
do
data="${data}%0D%0A${line}"
done
echo $data  # Fails, since data remains empty (loop emulates a sub-shell and looses data)

Please help..

A: In bash,
data=$(
while read line
do
  echo -n "%0D%0A${line}"
done < csv)

In non-bash shells, you can use `...` instead of $(...).  Also, echo -n, which suppresses the newline, is unfortunately not completely portable, but again this will work in bash.

A: Some of these answers are incredibly complicated. How about this.
 data="$(xargs printf ',%s' < csv | cut -b 2-)"

or
 data="$(tr '\n' ',' < csv | cut -b 2-)"

Too "external utility" for you?
IFS=$'\n', read -d'\0' -a data < csv

Now you have an array! Output it however you like, perhaps with
data="$(tr ' ' , <<<"${data[@]}")"

Still too "external utility?" Well fine,
data="$(printf "${data[0]}" ; printf ',%s' "${data[@]:1:${#data}}")"

Yes, printf can be a builtin. If it isn't but your echo is and it supports -n, use echo -n instead:
data="$(echo -n "${data[0]}" ; for d in "${data[@]:1:${#data[@]}}" ; do echo -n ,"$d" ; done)"

Okay, now I admit that I am getting a bit silly. Andrew's answer is perfectly correct.

A: I would much prefer a loop:
for line in $(cat file.txt); do echo -n $line; done

Note: This solution requires the input file to have a new line at the end of the file or it will drop the last line.

A: Simpler to just strip newlines from the file:
tr '\n' '' < yourfile.txt > concatfile.txt

A: Another short bash solution
variable=$(
  RS=""
  while read line; do
    printf "%s%s" "$RS" "$line"
    RS='%0D%0A'
  done < filename
)

A: awk 'END { print r }
{ r = r ? r OFS $0 : $0 }
  ' OFS='%0D%0A' infile

With shell:
data=

while IFS= read -r; do
  [ -n "$data" ] &&
     data=$data%0D%0A$REPLY ||
    data=$REPLY
done < infile

printf '%s\n' "$data"

Recent bash versions:
data=

while IFS= read -r; do
  [[ -n $data ]] &&
     data+=%0D%0A$REPLY ||
    data=$REPLY
done < infile

printf '%s\n' "$data"

A: A very simple single-line solution which requires no extra files as its quite easy to understand (I think, just cat the file together and perform sed-replace):
output=$(echo $(cat ./myFile.txt) | sed 's/ /%0D%0A/g')

A: Useless use of cat, punished! You want to feed the CSV into the loop
while read line; do
 # ...
done < csv


text: Q: Coloring finite subsets of a fixed size with a single modular function Let $k$ and $N$ be positive integers so that $k\mid N$.  Let $M=(k/N){N\choose k}$. A function $f:[N]^k\rightarrow M$ is a coloring function if $f(s_1) = f(s_2)$ implies that $s_1=s_2$ or $s_1 \cap s_2 = \emptyset $.  Coloring functions exist for all $k$ and $N$ by Baranyai's theorem. When $k=2$, $M=N-1$ and it is widely known and easily shown that there is a function $f(i,j)$, such that for every even $N$, $f(s)=f(i,j)\bmod (N-1)$ is a coloring function for 2 and N where $s =\langle i, j \rangle$, $0 \leq i < j < N$. My question is whether there can exist for a $k>2$ an $f(i_0,i_1, \dotsc, i_{k-1})$ so that $f(\langle i_0,i_1, \dotsc, i_{k-1}\rangle) =  f(i_0,i_1, \dotsc, i_{k-1})\bmod M$ is a coloring function for all $N$ that are multiples of $k$. Probably not but I'd have no idea how to prove it.


text:
Q: urlopen method in Perl 6? I'm translating a Python module to Perl 6, but can't find a method called urlopen, which could accept data:
    from six.moves.urllib import request

    req = request.Request(url, headers=headers)

    if headers.get('Content-Type') == 'application/x-www-form-urlencoded':
        data = oauth_query(args, via='quote_plus', safe='').encode()

    elif 'form-data' in headers.get('Content-Type', ''):  # multipart/form-data
        data = args['form-data']
    else:
        data = None

    resp = request.urlopen(req, data=data)
    resp.json = lambda: json.loads(resp.read().decode() or '""')
    return resp

oauth_query is a method that return a sorted string:
def oauth_query(args, via='quote', safe='~'):
    return '&'.join('%s=%s' % (k, oauth_escape(v, via, safe)) for k, v in sorted(args.items()))

I translate the above code to Perl 6:
   use WWW;

   my $data = "";
   if %headers{'Content-Type'} eq 'application/x-www-form-urlencoded' {
       $data = oauth_query(%args);
   } elsif %headers{'Content-Type'}.contains('form-data') {
       $data = %args{'form-data'};
   } else {
       $data = Any;
   }

   my $res = get $url, |%headers; # but without data that contains Content-Type, it will
                                  # Died with HTTP::MediaType::X::MediaTypeParser::IllegalMediaType

I want to return a resp as in Python. Any help is welcome!

A: I have reduced the program to the bare minimum; you will still have to take care of headers and the OAuth query, but this works
use WWW;

sub MAIN( :$have-data = 0 ) {
    my $url='https://jsonplaceholder.typicode.com/posts/';
    my %args=%(form-data => "userId=1&id=2");
    my $data = "";

    if $have-data {
        $data = %args{'form-data'};
    }

    my $res;
    if $data {
        $res = post $url, $data;
    } else {
        $res= get $url~'1';
    }
    say $res;
}

Baseline is that urlopen in Python does get or post depending on whether there is data or not. In this case, I use a simple if for that purpose, since WWW is quite barebones and does not support that. I am using also a mock REST interface, so I have actually to change the URL depending on the data, which is also dummy data. You can call the program either with no argument or with
perl6 urlopen.p6 --have-data=1

and the mock server will return... something. It would be great if you contributed a module with a (somewhat) higher level than WWW, or to WWW itself. Hope this solves (kinda) your problem.

A: use Cro::HTTP::Client;

my $resp;
my $data = "";

if (%headers{'content-type'} // '') eq self.form_urlencoded {
    $data = oauth_query(%args);
} elsif (%headers{'content-type'} // '').contains('form-data') { # multipart/form-data
    $data = %args{'form-data'};
} else {
    $data = "";
}

my $client = Cro::HTTP::Client.new(headers =>  |%headers);

if $data {
    $resp = await $client.post: $url, body => |%args;
} else {
    $resp = await $client.get: $url;
}

return $resp;


text:
Q: Missing trailing elements after an HTML form? I really hope this isn't a stupid question, but this HTML seems too simple to fail.  Still, it fails.
I have a page that starts with a form, and after the form, I have some more elements.  Those elements are never displayed!  Here's the code:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <title>CGI Test</title>

    <form enctype="multipart/form-data" method="post" action="/cgi-bin/upload.cgi" target="upload_target">
        <input type="hidden" name="cmd" value="uploadBackgroundFile" />

File Upload:
     <input type="file" name="file" value="" /> (Select A Local File)

<input type="submit" name="cgitest" value="Submit Request" />

    </form>

List of uploaded files:

(Nothing loaded yet)

Also, if I call "document.getElementById('listBackgroundFiles')", it returns null.  The elements after the form aren't just not displayed, they don't seem to exist at all!
This doesn't appear to be a browser issue...I get the same problem in Internet Explorer 7.0.6002.18005, Firefox 3.6.12, Chrome 5.0.375.99, Opera 10.60.3445, and Safari 5.0.2 (7533.18.5), all running (sadly) under Windows Vista.  I ran the page through the W3C and WDG validators, and those didn't show any problems.  Finally, if I move those elements above the form, they display just fine.  It seems to be an issue with putting elements after the form.
Again, I apologize if this is a stupid question, but I'm baffled by how something this simple could fail so consistently.

A: change

to

As far as I know, <iframes> and


text:
Q: Django tables2. Render link for empty cells I needed render link for empty cells with some default text.
By default, django-tables2 for null values render "—", without any link attached to it.
I managed to do this using TemplateColumn like this:
import django_tables2 as tables
# template
TEMPLATE = """
{% if record.some_field %}{{ record.some_field }}{% else %}<default text>{% endif %}
"""
# column definition
link_column = tables.TemplateColumn(linkify=True, template_code=TEMPLATE)

I just wanted to ask if there is more convenient way to achieve this, cause it sure seems like this.

A: If I remember correctly, a tables2 field can also be a property of the model. So you might do the linkification in the model:
class Foo( models.Model):
    ...
    bar = models.CharField( ...)
    ...

    @property
    def bar_t2_link(self):

        # form desired_target and desired_text from Foo data
        # desired_target will probably use reverse()

        return format_html(
            '{}', desired_target, desired_text)


text:
Q: Is it normal to still see what's on the screen when it's fully dimmed? I'm using an external monitor, so most of the time I've got the MacBook Air's internal screen dimmed to 0. But it doesn't switch off completely at 0 brightness as I can still see some graphical elements. They're hardly discernible but still there.
I was wondering if this is normal.
Unfortunately I couldn't find any other way to disable the built-in screen.

A: If you use only the second screen, you can safely close the lid of your MacBook Air and work only on the second screen, it will automatically switch it as the main and only screen.

A: This is normal for LCDs that have the backlight off (which is what brightness at zero does), but which are still turned on. As far as I know, it's a side-effect of how LCDs work. The LCD screen itself turns the pixels on or off, but a CCFL or LED backlight behind the screen shines through to illuminate them. So while the backlight is off, the pixels are still active, just very hard to distinguish them.
I find on my old 2006 MBP, the Apple light from the lid leaks enough light that I can read a bit of text in the centre of my screen, even at zero brightness.


text:
Q: Laravel 8 [Yajra DataTable] - DataTables warning: table id=userTable - Invalid JSON response I am trying to display all User (Where status is = 1) Data from database into DataTable using Yajra Package in Laravel but it always displays this error:

DataTables warning: table id=userTrashBin - Invalid JSON response. For more information about this error, please see http://datatables.net/tn/1

When I check the response (In Developer's tools > Network Tab) it does not have any or it show Failed to load response data:

Here's my datatable() inside the UserController.php:
public function datatable()
{
    $data = User::where('status', '=', 1)->get();

    return DataTables::of($data)
        ->addColumn('action', function($data){

        $url_edit = url('user/'.$data->id.'/edit');
        $url_deact = url('user/deactivateUser/'.$data->id);
        $url = url('user/'.$data->id);

        $view = "";
        $edit = "";
        $delete = "<button data-url = '".$url_deact."' onclick = 'deleteData(this)' class = 'btn btn-action btn-danger' title = 'Deactivate'></button>";

        return $view."".$edit."".$delete;
    })->editColumn('user_type', function($data){

        $dataUser = User::find($data->id)->first();
        $returnStr = "";

        if($dataUser->hasRole('A')){
            $returnStr = "Administrator";
        }else{
            $returnStr = "Employee";
        }

        return $returnStr;
    })
    ->rawColumns(['action'])
    ->make(true);
}

Here's the script file in index.blade.php:
$("#userTable").DataTable({
      responsive:true,
      processing:true,
      pagingType: 'full_numbers',
      stateSave:false,
      scrollY:true,
      scrollX:true,
      autoWidth: false,
      ajax:"{{ url('user/datatable') }}",
      columns:[
        {data:'first_name', name: 'first_name'},
        {data:'last_name', name: 'last_name'},
        {data:'email', name: 'email'},
        {data:'user_type', name: 'user_type'},
        {data:'action', name: 'action', searchable: true, sortable:true},
      ]
    });

The route for user/datatable inside web.php:
Route::get('user/datatable', 'UserController@datatable')->name('user/datatable')->middleware('role:A');

And finally the index.blade.php file where the userTable is located:

                  First Name
                  Last Name
                  E-Mail Address
                  User Type
                  Action

                  First Name
                  Last Name
                  E-Mail Address
                  User Type
                  Action

I don't know what causes the error and how to fix it for now because it doesn't have any response data or other error/s that will give me a hint.


text:
Q: What is the maximum gold find that can be obtained from each type of follower? Gold find, magic find and bonus experience for the follower adds a 20% to your total. From rings and an amulet the follower can get 100% more gold find, so you get 20% more gold find.
What is the maximum gold find that can be obtained from each type of follower?

A: The best you can achieve is 150% (30% for you) with Eirena (the enchantress) :

*

*50% on a rare amulet

*50% on rare rings(2x)

*50% on The Grand Vizier
The other possibilities is 135% (27% for you) for Kormac (the templar) :

*

*50% on a rare amulet

*50% on rare rings(2x)

*25% on the shield

*10% with the Wirt's original Leg

The scoundrel can't achieve much (only amulet and rings) since I don't remember any crossbow or bow giving gold find


text:
Q: Hibernate saveorupdateall not doing save not update I have a spring integration hibernate application. My application picks up files and checks their entries against the database. For this i am using Hibernate.
I want to disable certain rows in the database. I am retrieving the rows using criteria. Editing one field and using saveorupdateall method. This is not changing my db rows at all!!
Following are the code snippets
  <bean id="dmsdbDetectionJob" class="com.polling.scheduler.job.DMSDBDetectionJob">

 </bean>
 <bean id="dmsdbDetectionJobDetail" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
    <property name="targetObject" ref="dmsdbDetectionJob" />
    <property name="targetMethod" value="deleteDBMaster" />
    <property name="concurrent" value="false" />
 </bean>
<bean id="simpleTriggerDB" class="org.springframework.scheduling.quartz.CronTriggerBean">
    <property name="jobDetail" ref="dmsdbDetectionJobDetail" />
    <!-- <property name="cronExpression" value="1 * * * * ?" /> -->
<!--    <property name="cronExpression" value="0 0/1 * * * ?" />  -->
    <property name="cronExpression" value="0 52 11 ? * *" />
 </bean>

This fires at given time properly. deleteDBMaster method calls this code:
        //get Document files not having any links
        List<DocumentFile> strayFiles = documentDaoImpl.getStrayDocumentFiles();
        try
        {
            if (strayFiles.size() > 0)
            {
                //delete
                strayFiles = documentDaoImpl.softDelete(strayFiles, DocumentFile.class);
                documentDaoImpl.saveOrUpdateAll(strayFiles);}
}...

The softDelete method uses generics
    @Override
public <T extends GenericEntity> List<T> softDelete(List<T> stray,
        Class<T> clazz)
{
    for (T tObj : stray)
    {
        clazz.cast(tObj).setActive(Constants.INACTIVE.getVal());

    }
    return stray;
}

When I debug I see the value changed in the active property of the objects in the strayFiles list, inside saveOrUpdateAll() method. The saveOrUpdateAll method is:
@Override
public void saveOrUpdateAll(Collection<?> objects) throws DMSException  {
    try {
        for (Object object : objects) {
            getCrntSession().saveOrUpdate(object);
        }
    } catch (final HibernateException e) {
        throw new DMSException("Exception while save or update All ", ErrorCode.BASE_DB_ERROR, e);
    }
}

When the saveorupdate is called no query is logged by hibernate. Nothing changes in the db!!
Since this is in spring integration I have just added a @Transactional to the method. I am presuming that spring must do the flush or commit. Is that wrong? And even then I should see the query right??
Please let me know what is wrong in the code...
Thanks
EDIT::
Change my softdelete code to the following. Thought maybe the generics are causing this.
    @Override
@Transactional
public void softDeleteDocumentFile(
        List<DocumentFile> stray)
{
    for (DocumentFile tObj : stray)
    {
        tObj.setActive(Constants.INACTIVE.getVal());
        saveEntity(tObj);
    }
}

Still no change. The rows are not getting updated. Hibernate is not printing the update query on the console!!
Please let me know if anyone finds any mistake in the code..
EDIT::
This is the configuration
    <mvc:annotation-driven />

<context:component-scan base-package="com.polling" />
    <bean
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix">
            <value>/WEB-INF/</value>
        </property>
        <property name="suffix">
            <value>.jsp</value>
        </property>
    </bean>
     <context:property-placeholder location="classpath:config/jdbc.properties,classpath:config/config.properties,classpath:config/ftp.properties"/>
      <bean id="dataSource"
        class="org.springframework.jdbc.datasource.DriverManagerDataSource"
        >
        <property name="driverClassName" value="${jdbc.driverClassName}"/>
        <property name="url" value="${jdbc.url}"/>
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
        </bean>
      <!-- Configure Hibernate 4 Session Factory -->
      <bean id="sessionFactory"
            class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">

            <property name="dataSource">
                  <ref bean="dataSource" />
            </property>

            <property name="hibernateProperties">
                  <props>
                        <prop key="hibernate.dialect">${hibernate.dialect}</prop>
                        <prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
                        <prop key="hibernate.format_sql">${hibernate.format_sql}</prop>
                        <prop key="hibernate.generate_statistics">${hibernate.generate_statistics}</prop>
                  </props>
            </property>
            <property name="packagesToScan">
            <list>
                <value>com.polling.entity</value>
            </list>
        </property>
            </bean>
            <tx:annotation-driven />
<bean id="transactionManager"
    class="org.springframework.orm.hibernate4.HibernateTransactionManager">
    <property name="sessionFactory" ref="sessionFactory" />
</bean>

EDIT::
Tried using a hardcoded id. Used update instead of save. But still same result, no update query and hence no change in row!!
EDIT::
This is the log at trace level
    14:31:12.644 T|TransactionInterceptor                  |Completing transaction for [com.polling.service.DocumentServiceImpl.deActivateStrays]
14:31:12.644 T|TransactionInterceptor                  |Completing transaction for [com.polling.scheduler.job.DMSDBDetectionJob.deleteDBMaster]
14:31:12.675 T|HibernateTransactionManager             |Triggering beforeCommit synchronization
14:31:12.675 T|HibernateTransactionManager             |Triggering beforeCompletion synchronization
14:31:12.675 D|HibernateTransactionManager             |Initiating transaction commit
14:31:12.675 D|HibernateTransactionManager             |Committing Hibernate transaction on Session [SessionImpl(PersistenceContext[entityKeys=[EntityKey[com.polling.entity.DocumentFile#273], EntityKey[com.polling.entity.DocumentGroup#107], EntityKey[com.polling.entity.DocumentFile#275]],collectionKeys=[CollectionKey[com.polling.entity.DocumentFile.docgroups#275], CollectionKey[com.polling.entity.DocumentGroup.files#107], CollectionKey[com.polling.entity.DocumentFile.docgroups#273]]];ActionQueue[insertions=org.hibernate.engine.spi.ExecutableList@2a6f7180 updates=org.hibernate.engine.spi.ExecutableList@7a84a043 deletions=org.hibernate.engine.spi.ExecutableList@1935cd8c orphanRemovals=org.hibernate.engine.spi.ExecutableList@1b49af42 collectionCreations=org.hibernate.engine.spi.ExecutableList@291240d collectionRemovals=org.hibernate.engine.spi.ExecutableList@6d5d2cc collectionUpdates=org.hibernate.engine.spi.ExecutableList@40025295 collectionQueuedOps=org.hibernate.engine.spi.ExecutableList@587bd507 unresolvedInsertDependencies=UnresolvedEntityInsertActions[]])]
14:31:12.675 D|AbstractTransactionImpl                 |committing
14:31:12.675 T|SessionImpl                             |Automatically flushing session
14:31:12.675 T|AbstractFlushingEventListener           |Flushing session
14:31:12.675 D|AbstractFlushingEventListener           |Processing flush-time cascades
14:31:12.675 T|Cascade                                 |Processing cascade ACTION_SAVE_UPDATE for: com.polling.entity.DocumentFile
14:31:12.675 T|Cascade                                 |Done processing cascade ACTION_SAVE_UPDATE for: com.polling.entity.DocumentFile
14:31:12.675 T|Cascade                                 |Processing cascade ACTION_SAVE_UPDATE for: com.polling.entity.DocumentFile
14:31:12.675 T|Cascade                                 |Done processing cascade ACTION_SAVE_UPDATE for: com.polling.entity.DocumentFile
14:31:12.675 D|AbstractFlushingEventListener           |Dirty checking collections
14:31:12.675 T|AbstractFlushingEventListener           |Flushing entities and processing referenced collections
14:31:12.675 D|Collections                             |Collection found: [com.polling.entity.DocumentFile.docgroups#273], was: [com.polling.entity.DocumentFile.docgroups#273] (uninitialized)
14:31:12.691 D|Collections                             |Collection found: [com.polling.entity.DocumentFile.docgroups#275], was: [com.polling.entity.DocumentFile.docgroups#275] (uninitialized)
14:31:12.691 D|Collections                             |Collection found: [com.polling.entity.DocumentGroup.files#107], was: [com.polling.entity.DocumentGroup.files#107] (uninitialized)
14:31:12.691 T|AbstractFlushingEventListener           |Processing unreferenced collections
14:31:12.691 T|AbstractFlushingEventListener           |Scheduling collection removes/(re)creates/updates
14:31:12.691 D|AbstractFlushingEventListener           |Flushed: 0 insertions, 0 updates, 0 deletions to 3 objects
14:31:12.691 D|AbstractFlushingEventListener           |Flushed: 0 (re)creations, 0 updates, 0 removals to 3 collections
14:31:12.691 D|EntityPrinter                           |Listing entities:
14:31:12.691 D|EntityPrinter                           |com.polling.entity.DocumentFile{encodingKey=yyy, docgroups=<uninitialized>, contactNumber=12121212, documentType=com.polling.entity.DocumentType#5, totalLinks=1, modifiedBy=com.polling.entity.UserApplicationGroup#3, documentFileName=f11, documentDescription=null, totalDownloads=0, uploaderCompletePath=somepath/somepath, modifiedDate=2014-12-16 14:36:57.707, size=0, DMSPath=c:/DMSFinalRoot\dir0\File0, id=273, createdBy=com.polling.entity.UserApplicationGroup#3, documentFormat=com.polling.entity.DocumentFormat#1, uploadDateTime=2014-12-16 14:36:56.86, keyWords=null, active=3, uploadStage=1, uploaderIP=0:0:0:0:0:0:0:1, createdDate=2014-12-16 14:36:57.707, contactPerson=some name, uploaderName=scmsname}
14:31:12.691 D|EntityPrinter                           |com.polling.entity.DocumentGroup{files=<uninitialized>, expiryPresent=false, modifiedBy=com.polling.entity.UserApplicationGroup#3, uploadStatus=0, documentDescription=null, modifiedDate=2014-12-22 14:28:09.027, id=107, nodeId=206, totalFiles=0, createdBy=com.polling.entity.UserApplicationGroup#3, documentFormat=null, objectId=101, active=3, documentName=doc1, nodeType=document, objectType=demand, createdDate=2014-12-22 14:28:09.027, expiryAt=null}
14:31:12.691 D|EntityPrinter                           |com.polling.entity.DocumentFile{encodingKey=azaz, docgroups=<uninitialized>, contactNumber=12121212, documentType=com.polling.entity.DocumentType#5, totalLinks=1, modifiedBy=com.polling.entity.UserApplicationGroup#3, documentFileName=f11, documentDescription=null, totalDownloads=0, uploaderCompletePath=somepath/somepath, modifiedDate=2014-12-17 16:52:23.163, size=0, DMSPath=c:/DMSFinalRoot\dir2\File0, id=275, createdBy=com.polling.entity.UserApplicationGroup#3, documentFormat=com.polling.entity.DocumentFormat#1, uploadDateTime=2014-12-17 16:52:22.127, keyWords=null, active=9, uploadStage=1, uploaderIP=0:0:0:0:0:0:0:1, createdDate=2014-12-17 16:52:23.163, contactPerson=some name, uploaderName=scmsname}
14:31:12.691 T|AbstractFlushingEventListener           |Executing flush
14:31:12.691 T|JdbcCoordinatorImpl                     |Starting after statement execution processing [ON_CLOSE]
14:31:12.691 T|AbstractFlushingEventListener           |Post flush
14:31:12.691 T|SessionImpl                             |before transaction completion
14:31:12.691 D|JdbcTransaction                         |committed JDBC Connection
14:31:12.691 D|JdbcTransaction                         |re-enabling autocommit
14:31:12.691 T|TransactionCoordinatorImpl              |after transaction completion
14:31:12.707 T|SessionImpl                             |after transaction completion
14:31:12.707 T|HibernateTransactionManager             |Triggering afterCommit synchronization
14:31:12.707 T|HibernateTransactionManager             |Triggering afterCompletion synchronization
14:31:12.707 T|TransactionSynchronizationManager       |Clearing transaction synchronization
14:31:12.707 T|TransactionSynchronizationManager       |Removed value [org.springframework.orm.hibernate4.SessionHolder@711fbb66] for key [org.hibernate.internal.SessionFactoryImpl@5e2ed6a9] from thread [org.springframework.scheduling.quartz.SchedulerFactoryBean#0_Worker-7]
14:31:12.707 T|TransactionSynchronizationManager       |Removed value [org.springframework.jdbc.datasource.ConnectionHolder@67914078] for key [org.springframework.jdbc.datasource.DriverManagerDataSource@7bc247d0] from thread [org.springframework.scheduling.quartz.SchedulerFactoryBean#0_Worker-7]
14:31:12.707 D|HibernateTransactionManager             |Closing Hibernate Session [SessionImpl(PersistenceContext[entityKeys=[EntityKey[com.polling.entity.DocumentFile#273], EntityKey[com.polling.entity.DocumentGroup#107], EntityKey[com.polling.entity.DocumentFile#275]],collectionKeys=[CollectionKey[com.polling.entity.DocumentFile.docgroups#275], CollectionKey[com.polling.entity.DocumentGroup.files#107], CollectionKey[com.polling.entity.DocumentFile.docgroups#273]]];ActionQueue[insertions=org.hibernate.engine.spi.ExecutableList@2a6f7180 updates=org.hibernate.engine.spi.ExecutableList@7a84a043 deletions=org.hibernate.engine.spi.ExecutableList@1935cd8c orphanRemovals=org.hibernate.engine.spi.ExecutableList@1b49af42 collectionCreations=org.hibernate.engine.spi.ExecutableList@291240d collectionRemovals=org.hibernate.engine.spi.ExecutableList@6d5d2cc collectionUpdates=org.hibernate.engine.spi.ExecutableList@40025295 collectionQueuedOps=org.hibernate.engine.spi.ExecutableList@587bd507 unresolvedInsertDependencies=UnresolvedEntityInsertActions[]])] after transaction
14:31:12.707 T|SessionImpl                             |Closing session
14:31:12.707 I|StatisticalLoggingSessionEventListener  |Session Metrics {
    36322379 nanoseconds spent acquiring 1 JDBC connections;
    0 nanoseconds spent releasing 0 JDBC connections;
    16153296 nanoseconds spent preparing 2 JDBC statements;
    20467177 nanoseconds spent executing 2 JDBC statements;
    0 nanoseconds spent executing 0 JDBC batches;
    0 nanoseconds spent performing 0 L2C puts;
    0 nanoseconds spent performing 0 L2C hits;
    0 nanoseconds spent performing 0 L2C misses;
    7830765 nanoseconds spent executing 1 flushes (flushing a total of 3 entities and 3 collections);
    85953666 nanoseconds spent executing 2 partial-flushes (flushing a total of 2 entities and 2 collections)
}

A: Have found the crux of my problem. Wasnt related to transactions at all. By mistake I had added updatable=false to my entity class property(active) get accessor. Sorry for the trouble. Really a very elementary mistake!!! Apologies to all that have spent time on this..

A: session.saveOrUpdate(Object) method only converts any transient object into persistence object, means object associates with current hibernate session. When current hibernate session will be flushed or hibernate transaction will be committed then only actual query will run to store object data into the database.
Hibernate saveOrUpdate(Object) works like above comment. I don't know much about Spring.
I hope above description will work for you.
Example code : Hibernate
Session session = sessionFactory.getCurrentSession();
session.setFlush(FlushMode.COMMIT);// Session will be flushed when transation.commit will be called
Transaction tx = session.beginTransaction();
session.saveOrUpdate(Object obj);
tx.commit();// this line will run query to map your object on database

 OR

Session session = sessionFactory.getCurrentSession();
session.setFlush(FlushMode.MANUAL);// Session will be only ever flushed when session.flush() will be explicitely called by aaplication
Transaction tx = session.beginTransaction();
session.saveOrUpdate(Object obj);
session.flush();// this line will run query to map your object on database
tx.commit();

Thanks

A: What you've written so far seems that your Spring TransactionManagement configuration is wrong.
A simple solution if you don't want to configure aspects is to use a programmatic approach using the Spring Framework TransactionTemplate
public class DMSDBDetectionJob {

    private final TransactionTemplate transactionTemplate;

    public DMSDBDetectionJob(PlatformTransactionManager transactionManager) {
       Assert.notNull(transactionManager, "The 'transactionManager' argument must not be null.");
       this.transactionTemplate = new TransactionTemplate(transactionManager);
       // optional configuration of the Transaction like timeout
       // this.transactionTemplate.setTimeout(30); // 30 seconds
    }

    public void deleteDBMaster() {
      transactionTemplate.execute(new TransactionCallbackWithoutResult() {
          protected void doInTransactionWithoutResult(TransactionStatus status) {
             deleteDBMasterImpl();
         }
       });

    }

    private void deleteDBMasterImpl() {
        List<DocumentFile> strayFiles = documentDaoImpl.getStrayDocumentFiles();
        try
        {
           if (strayFiles.size() > 0)
           {
              //delete
              strayFiles = documentDaoImpl.softDelete(strayFiles, DocumentFile.class);
              documentDaoImpl.saveOrUpdateAll(strayFiles);
              ...
            }

         } catch (...) {...}
    }

Your Spring Configuration should have at least two entries like:
<!-- PlatformTransactionManager which are going to drive transaction-->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
  <property name="dataSource" ref="dataSource"></property>
</bean>

<!-- Instance of transaction template -->
<bean id="transactionTemplate" class="org.springframework.transaction.support.TransactionTemplate">
  <property name="transactionManager" ref="transactionManager"></property>
</bean>


text:
Q: Mostrar un card en miniatrura cuando este en hover con JQUERY Espero estén bien me podrían ayudar por favor!
Tengo unas cards  que contienen información de cada producto como podría que al hacer hover en la imagen aparezca esa misma card pero en miniatura en posicion fixed
he tratado de clonarla y mostrarla en otro div pero se duplica mas de una vez y tengo varias cards.

TARJETA DE MEMORIA MICRO SD KINGSTON CLASE 10 (16 GB)

A:

$("#tarjeta").hover(function() {
 $('#card:first').clone(true).appendTo('#copias');
  $('#copias').toggle();

});

 </script>


text:
Q: What (if any) is the relationship between Gwyneth and Gwen Cooper? Watching episode 3, "The Unquiet Dead" of Series 1 of the new Doctor Who, it seemed the parlor maid, Gwyneth, was familiar. A quick Google revealed the actress as Eve Myles, also known for playing Gwen on Torchwood.
This seemed too much of a coincidence to me. Two characters with similar names (Gwen and Gwyneth) who both grew up in Cardiff on top of the (in)famous rift, both played by the same actress across two closely related shows.
Google fuelled research has found only this speculation:

 there is a lot of fan speculation that Gwyneth goes through the rift and
 reappears in present time, and is in fact the same person as "Gwen" in Torchwood.

I'm not convinced, as Gwyneth clearly has telepathic (or similar) capabilities, never demonstrated by Gwen.

Are these characters actually (in-show) related to each other, or is this just a coincidence?
I've seen most episodes of both Dr Who and Torchwood, but haven't seen any of the "Confidentials"; I don't recall seeing Gwen ever talk about her family history - might be a better testimony about my fallible memory than anything else.

A: It would be great if there's a story built around that, but for now- not likely.
Many long-running TV shows have been known (coughtrek) to reuse actors, especially science-fiction and procedural ones (Law & Order apparently).  I can theorize that the nature of these shows makes it more important that actors that are known to work in the show already in a manner that doesn't distract from the immersion that the genre requires be used.  Likely RTD just liked her.
That being said- after the fact, they did half-heartedly retcon the 'similarities'.  This is a link that mentions it, also with Russell T. Davies denying a connection previous to the throw-away Rift explanation.
Incidentally, if you looked farther down her imdb profile, she also played a 'Gwen' in an Eastenders movie.

A: "Gwen's family was established in Cardiff by the 19th century. The Tenth Doctor believed that this, coupled with the influence of the space-time rift in Cardiff, might explain her physical resemblance to a funeral home employee named Gwyneth, who died on 24 December 1869 in one of the earliest known effects involving the rift. (TV: Journey's End, The Unquiet Dead)" Via http://tardis.wikia.com
'Keep It In The Family Eve Myles, who plays Gwen Cooper in Torchwood, also played Gwyneth in series one episode The Unquiet Dead. The Doctor comments on spacial genetic multiplication when he asks her about her family coming from Cardiff. According to Russell T Davies, "It's not familial as we understand it. There's no blood tie. Spatial genetic multiplicity means an echo and repetition of physical traits across a Time Rift."' Via    www.bbc.co.uk/doctorwho/s4/episodes/?episode=s4_13&action=factfile

A: According to canon, they are not related at all.
This is addressed specifically at the end of "Journey's End" when The Doctor and Rose first see Gwen Cooper on the TARDIS screen at Torchwood. Both of them recognize her, since she looks exactly like Gwyneth. He asks her if she is from Cardiff, and when she says yes, he explains to Rose that it is an effect of "spatial genetic multiplicity".
According to Russell T Davies, this is not a blood relationship; it is an effect of the Time Rift causing physical features to echo and repeat across the space/time area around the Rift.
Most of this is explained on the BBC site: "Fact File" for Journey's End.

A: Doctor Who has a history of bringing back someone used for an episode to become a regular or companion.
Karen Gillan was Amy Pond in Doctor Who but first a Soothsayer in the Fires of Pompeli.
http://en.wikipedia.org/wiki/Karen_Gillan#cite_note-dm2-6
Freema Agyeman was of course Martha Jones on Doctor Who and Torchwood but also seen previously on Doctor Who as well as Adeola Oshodi (a scientist at Torchwood One) in the Rise of the Cybermen / Age of Steel.
http://en.wikipedia.org/wiki/Adeola_Oshodi#Adeola_Oshodi

A: My theory is maybe at some point the doctor went back and brought Gwyneth to modern England when jack found Gwen, or the other way around, Jack might have gotten the Doctor to send her before Torch Wood. I noticed in the episode that when Gwyneth gave the Doctor a cup of tea she says "two sugars, just how you like it." And then winked at the Doctor is that a sign? Or did Russell T Davis do this to make people talk?


text:
Q: React native offline maps using OpenStreetMap React Native - rookie question how to built an app with offline maps based on OpenStreetMap tiles?
Business needs are: user download the app after that download the tiles from remote server.
Where to store the tiles? Which way would be the best optimal solution:

*

*Using expo + react-native-maps download tiles from remote server and after that save locally in device and display it as LocalTile?

*Using Leaflet with React Native WebView get tiles from remote server save it locally in IndexedDB
Any other, better idea?


text:
Q: How to transform a WebService call that is using behaviours? We have some really old code that calls WebServices using behaviours (webservice.htc), and we are having some strange problems... since they've been deprecated a long time ago, I want to change the call.
What's the correct way of doing it? It's ASP.NET 1.1

A: You should be able to generate a proxy class using wsdl.exe. Then just use the web service as you normally would.

A: While I'm not 100% sure what the Web Service behavior does, I recall it allows client-side script to call Web Services, which would make AJAX it's contemporary replacement.
Since you're using .NET 1.1 how about using Ajax.NET Professional to connect to the web services?


text:
Q: Why is it possible to add define elements in an array of length 0 in C++ Im reading up for a exam in C++ and just fideling around in order to get a better sense of the language. My understanding is that arrays in c++ are defined with a fixed length either before run time or dynamically. Knowing this I don't understand why C++ accepts this. I wouldn't think that it would be possible to add element to an array of length 0;
int * TestArray = new int[0];
TestArray[0]=10;
TestArray[1]=20;
TestArray[2]=30;

A: Writing to array elements outside of the valid size is Undefined Behaviour. It's a bug and your program is ill formed. But the compiler is not required to issue a diagnostic (although most will with the right warning options).
 It's your responsibility to follow the rules.

A: You may not access any elements in a zero sized array. It results in undefined runtime behavior.
However, zero sized arrays are allowed for various reasons.
First, it allows you to make functions less complicated by skipping size checks:
   void f(size_t n)
   {
    int * ptr = new int[n];
    //...
    delete[] ptr;
   }

instead of:
void f(size_t n)
{
 if (n>0)
 {
  int * ptr = new int[n];
  //...
  delete[] ptr;
 }
}

Second, the intent was to make it easy for compiler writers to implement new using malloc, and this is the defined behavior for malloc.
The GCC c compiler docs give this reason:
"Zero-length arrays are allowed in GNU C. They are very useful as the last element of a structure that is really a header for a variable-length object: "
struct line {
  int length;
  char contents[0];
};

struct line *thisline = (struct line *)
  malloc (sizeof (struct line) + this_length);
thisline->length = this_length;

[without it], you would have to give contents a length of 1, which means either you waste space or complicate the argument to malloc.

A: My professor told me that because c++ and c can  access and write outside of array bounds,it is one of the main reasons they are used to create operating systems. For example you can even do something like
arr[-1]=5;

I believe it is worth mentioning.However this can lead to undefined behavior.


text:
Q: Tune SSH for bad connections What options can be used on Linux' OpenSSH Server and the ssh command itself (or their config files) to make ssh most reliable on flaky connections (eg. long distance WiFi)?
Is it useful to tune the ssh configuration, or are there better options tuning Linux TCP parameters?

A: Mosh is a replacement for SSH. It's more robust and responsive, especially over Wi-Fi, cellular, and long-distance links.

A: I've had fantastic luck with autossh* and tmux when working over troublesome connections. Something like this:
autossh remotehost -t tmux att -t session-name

http://www.harding.motd.ca/autossh/

A: I realize this is an old question.  I use mosh mostly but sometimes I like to have gvim working remotely.
I have not tried this yet
http://blogs.perl.org/users/smylers/2011/08/ssh-productivity-tips.html
specifically the section on Resilient Connections


text:
Q: retrieving files from database by their path in jsp i want to download a file by its path(local server path) which is stored in a database table ,i have done the coding part to view the database in a html table but i dont have any idea how to hyperlink the table in order to download the file(any type and size) from the ouput folder that is stored in a server.
here is the jsp code :
<%@ page import="java.io.*,java.sql.*"%>

<%
String id=request.getParameter("id");
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306  /ksa","root","root");
Statement st=con.createStatement();
ResultSet rs=st.executeQuery("Select id,file_path,file_date from file12 where id like '"+id+"%'");
%>

<%
while(rs.next()){
%>

<%=rs.getString("id")%>
<%=rs.getString("file_path")%>
<%=rs.getString("file_date")%>

<%}%>

the above code will retrieve the table from database to html table.

A:  <%@ page import="java.io.*,java.sql.*"%>
 <%
   String id=request.getParameter("id");
   Class.forName("com.mysql.jdbc.Driver").newInstance();
   Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/ksa","root","root");
   Statement st=con.createStatement();
   ResultSet rs=st.executeQuery("Select id,file_path,file_date from file12 where id like '"+id+"%'");
   %>

  <%
    while(rs.next()){
  %>

    <a href="<%=rs.getString("file_path")%>"> click here to download the file with  id :<%=rs.getString("id")%>

 <%}%>

A: If the rs.getString("file_path")  returns a path is /home/Desktop/output/something.jpeg means you cannot download.Because when you click the given link surely it will show PAGE NOT FOUND (404) Exception.
"> click here to download the file
please note your URL it will look like
http://localhost:8080/prjname/home/Desktop/output/something.jpeg
So in this situation we can pass the path into one servlet ,through this servlet we can download the file.


text:
Q: Unable to execute jar from powershell I am trying to execute a jar by using java -jar test.jar. However, when I keep the jar name in a variable e.g
$a = "test.jar"
And try the execution using java -jar $a, it gives me an error
ERROR: Unable to access jarfile test.jar

A: Error meassage is quite clear, java cannot access the file: check whether you're launching this command in correct directory (where the .jar is located) and your powershell process has permissions to access it.


text:
Q: How to import specified class (or varaibles from this class) to another class? I have 3 classes:
First and second class - have variables as listed below:
First class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Project_1
{
    class First_class
    {
        int variable_1 = 1;
        int variable_2 = 1;
        int variable_3 = 3;
        string variable_4 = "test1"

    }
}

Second class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Project_1
{
    class Second_class
    {
        int variable_5 = 5;
        int variable_6 = 6;
        int variable_7 = 7;
        string varaible_8 = "test_2"

    }
}

Third class is empty::
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Project_1
{
    class Program
    {
        static void Main(string[] args)
        {
        }
    }
}

*

*What should I do to have possibility to use all variables from First class - in Third Class ?

*What should I do to have possibility to use only some variables from First class and only some variables from Second class - in Third Class ?

A: If you want to use those variables outside of First_class, they must be declared as public variables.
class First_class
{
    public static int variable_1 = 1; // This can be accessed from outside
    public int variable_2 = 1; // This can be accessed from outside too
    int variable_3 = 3; // This can not be accessed from outside
    string variable_4 = "test1"; // This also can not be accessed from outside
}

class Program
{
    static void Main(string[] args)
    {
        var o = new First_class();
        Console.Writeline(First_class.variable_1);
        Console.Writeline(o.variable_2);
        Console.Writeline(o.variable_3); // Error: variable_3 is private
    }
}

A: 1.Here you have two possibilities:
a) To use all variables from First class in Third Class you have to make all of them public.
b) You can make all of them static and public or protected but in such case, the Program class needs to inherit
from the First class so it would look like:
public class First_class
{
    protected static int variable_1 = 1;
    protected static int variable_2 = 1;
    protected static int variable_3 = 3;
    protected static string variable_4 = "test1";
}

class Program: First_class
{
    static void Main(string[] args)
    {
        Console.WriteLine(variable_1);
        Console.WriteLine(variable_2);
        Console.WriteLine(variable_3);
        Console.WriteLine(variable_4);
    }
 }

2.The example:
class Second_class
{
    int variable_5 = 5;
    int variable_6 = 6;
    int variable_7 = 7;
    public string varaible_8 = "test_2"; //only this field can be accessed
}

public class First_class
{
    public int variable_1 = 1;
    public int variable_2 = 1;
    protected int variable_3 = 3; // can be accessed via inheritance
    private string variable_4 = "test1"; // cannot be accessed due to privacy level
}

class Program
{
    static void Main(string[] args)
    {
        var obj1 = new First_class();
        Console.WriteLine(obj1.variable_1);
        Console.WriteLine(obj1.variable_2);

        var obj2 = new Second_class();
        Console.WriteLine(obj2.varaible_8);

    }
}


text:
Q: Linux Mint: Can't open display I recently upgraded my system from Linux Mint 18.3 to Linux Mint 19.
After upgrade I can't login to XFCE session. After entering password on the login screen, the screen goes black and a message is displayed:
 rc.local[1314]: Cannot open display "default display"

And then the login screen is displayed again.
Just booting in recovery mode works, but without proper graphics support. Also I can boot normally if I select Linux 4.10.0.38 in GRUB menu, although the message above appears on system reboot. How can fix it, so I can login normally?
I've tried fiddling with default display settings /etc/init.d/lightdm, but it seems it doesn't have any impact on this issue.
EDIT:
I found out that the message comes from /var/log/syslog:
systemd[1]: Started Network Manager Wait Online.

systemd[1]: Reached target Network is Online.

systemd[1]: Starting LSB: Start NTP daemon...

systemd[1]: Starting /etc/rc.local Compatibility...

systemd[1]: Starting LSB: disk temperature monitoring daemon...

systemd[1]: Starting LSB: Cisco AnyConnect Secure Mobility Client for Linux...

rc.local[1376]: Cannot open display "default display"

systemd[1]: rc-local.service: Control process exited, code=exited status=255

systemd[1]: rc-local.service: Failed with result 'exit-code'.

systemd[1]: Failed to start /etc/rc.local Compatibility.

EDIT-2:
This question made me learn a bit more about Linux internals.
I found out that systemd runs rc.local for compatibility purposes and the  topic from AskUbuntu community helped me debug rc.local.
I found out that the cause of the error message was the /etc/rc.local file, which was empty apart from the setxkbmap command which caused this message.
After commenting out this line the rc.local fails no more, but XFCE desktop fails to start anyway.
I installed MATE and Cinnamon alongside and there seems to be no issues with them.
Removing and installing XFCE didn't help, but that's of little concern to me as I can continue to use my system without any trouble.
The major lesson from it is that it may be safer to reinstall from scratch than to upgrade, but in case of not so critical system yoy may get away with upgrade with minor trouble.
The original question however is likely to remain unanswered.

A: EDIT
    I googled the last line of the logs and found this
How to Enable /etc/rc.local with Systemd
Copied from Shawn J. Goff
chvt allows you to change your virtual terminal.
From man chvt:

The command chvt N makes /dev/ttyN the foreground terminal. (The
corresponding screen is created if it did not exist yet. To get rid of
unused VTs, use deallocvt(1).) The key combination (Ctrl-)LeftAlt-FN
(with N in the range 1-12) usually has a similar effect.


text:
Q: Symfony 2 Override Entity and add extra properties I have entity A and entity B which extend entity A.
Entity A - in vendor bundle.
Entity B - in /src bundle.
I search a lot of time and only solution works for me. It's using ClassMetadataListener on Doctrine Event loadClassMetadata.
But extending on entity B not works. I need add all properties form entity A to entity B.
I can't understand why.

A: You cannot simply extend a class like normally when using Doctrine2.
Check the documentation on chapter 6. Inheritance Mapping on how to implement inheritance on your entity classes.
You are probably interested in chapter 6.1. Mapped Superclasses.

A mapped superclass is an abstract or concrete class that provides persistent entity state and mapping information for its subclasses, but which is not itself an entity. Typically, the purpose of such a mapped superclass is to define state and mapping information that is common to multiple entity classes.

For this to work you have to use the @MappedSuperclass annotation to your entity base class.

A: Add @MappedSuperclass annotation in top of A. That would be enough :)


text:
Q: MS's Apr 10 update sends Server 2008 R2 to recovery mode Just applied the April 10, 2018 MS patches to a pair of Windows 2008 R2 servers running under VMWare Workstation 7.1.6 build-744570. Host is a Dell Precision 4800, 32GB, i74800MQ CPU with Win7 pro.  Both server instances bluescreen when starting: "STOP: 0x0000007E" then reboot into the recovery console.  Link to screenshot on IMGUR. Options in recovery mode are:

*

*System Image Recovery (not an option - I don't have any)

*Windows Memory Diagnostic

*Command Prompt

Rebooting the VM brings me right back to the recovery mode.  I think the KB notes for KB4093118 and KB4093108 indicate possible stop problems: "Stop error on PCs that don't support SIMD or SSE2".  I don't know how to verify those might be my problem.
Has anyone got any ideas on how to fix this?

A: Upgrade your VMWare Workstation, we had our ESXI 4.1 environment have this issue this morning, migrating the VMs to a ESXI 5.5 host resolved the issue.


text:
Q: Modeling kind-of-random discrete events in a set period of time I'm looking to consider models which provide a probability distribution of the number of tweets from a given account by a certain point in a week (e.g. noon on Tuesday) given a the set of events part way through the week. From the "undergraduate statistics" level of complexity, a Poisson distribution seems like an appropriate start.
Given that a part of a week has passed, however, what are possible models which can take into account an unusually active week, extra weights like popularity of a tweet, the possibility of an event triggering a lull, or other more complex phenomena? NN's seems like they should be capable of this. How can discrete events and progress through a time period be encoded as NN inputs? Is there a general name for this problem?
Meta-note: looking for a set of starting points for this as a research project rather than concrete solutions.

A: I haven't seen your repost on Cross Validated or Data Science, so I'll offer an answer here.
Your problem seems like a good fit for Bayesian modeling. A priori, you start off with a distribution over $\lambda$, the parameter for your Poisson distribution, representing your beliefs in what number of tweets are likely.
As you receive information, you can use Bayes rule to update your beliefs in $\lambda$, allowing you to incorporate events or a particularly active week.
$$P(\lambda | events) = \frac{P(events | \lambda) P(\lambda)}{P(events)$$


text:
Q: Copy resources from one module to another by maven I have a maven managed project with some modules. One common parent module and some children. One children module contains resources directory. Second children module packages all related modules to a jar file. It's using assembly plugin in for this.
Question: How can I copy the resources directory from first module to a directory in the second (packaging) module?
I found maven-dependency-plugin, but still do not understand how to configure it.
Below is an example of my packaging module that creates jar from other modules, but without copying resources:
<modelVersion>4.0.0</modelVersion>
<parent>
    <groupId>com.rm</groupId>
    <artifactId>rm-core-parent</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <relativePath>../rm-core-parent/pom.xml</relativePath>
</parent>
<artifactId>rm-app-package</artifactId>
<packaging>pom</packaging>
<name>rm-app-package</name>
<description>rm-app-package</description>

<dependencies>
    <dependency>
        <groupId>com.rm</groupId>
        <artifactId>rm-core-app</artifactId>
        <version>0.0.1-SNAPSHOT</version>
    </dependency>
</dependencies>

<build>
    <plugins>
        <plugin>
            <artifactId>maven-assembly-plugin</artifactId>
            <groupId>org.apache.maven.plugins</groupId>
            <version>2.5.5</version>
            <configuration>
                <archive>
                    <manifest>
                        <mainClass>rm.core.app.RMCore</mainClass>
                    </manifest>
                </archive>
                <descriptorRefs>
                    <descriptorRef>jar-with-dependencies</descriptorRef>
                </descriptorRefs>
                <appendAssemblyId>false</appendAssemblyId>
            </configuration>

            <executions>
                <execution>
                    <id>make-assembly</id>
                    <phase>package</phase> <!-- bind to the packaging phase -->
                    <goals>
                        <goal>single</goal>
                    </goals>
                </execution>
            </executions>

        </plugin>

    </plugins>
</build>

Thanks in advance.


text:
Q: Get list of relations for an entity in typeORM? I am using repository pattern with typeORM. For an entity defined below like this
@Entity()
export class Apple extends BaseEntity {
  @Column({ type: 'timestamp', default: () => 'CURRENT_TIMESTAMP' })
  createdDate: Date;

  @ManyToOne((type) => xyz, (xyz) => xyz.fruit)
  @JoinColumn({ name: 'fruit' })
  fruit: Fruit;

  @ManyToOne((type) => ABC, (abc) => abc.juice)
  @JoinColumn({ name: 'juice' })
  juice: Juice;

}

Is there a way to get a list of all relations i.e. an array like format ['fruit','juice']

A: This will list you the propery names.
entityManager.getRepository(Apple)
      .metadata
      .relations
      .filter(relation => relation.isManyToOne)
      .map(relation => relation.propertyName)

If you want the column names, you can use:
entityManager.getRepository(Apple)
      .metadata
      .relations
      .filter(relation => relation.isManyToOne)
      .map(relation => relation.joinColumns.map(column => column.databaseName))

Mind that due to multi-column keys, each property may have multiple columns.


text:
Q: Get friend list of facebook login user using FacebookSDK I want to access friend list and their profile picture using FacebookSDK in my iphone application.
Please suggest a demo or code.

A: FBRequest* friendsRequest = [FBRequest requestForMyFriends];
[friendsRequest startWithCompletionHandler: ^(FBRequestConnection *connection,
                              NSDictionary* result,
                              NSError *error) {
NSArray* friends = [result objectForKey:@"data"];
NSLog(@"Found: %i friends", friends.count);
for (NSDictionary<FBGraphUser>* friend in friends) {
    NSLog(@"I have a friend named %@ with id %@", friend.name, friend.id);
}
}];

A: [FBRequestConnection startForMyFriendsWithCompletionHandler:^(FBRequestConnection *connection,
                                                                  NSDictionary* result,
                                                                  NSError *error) {

            NSArray        *data_array = [result objectForKey:@"data"]; //array of friends
            NSMutableArray *pictures = [NSMutableArray array]; // array for pictures

            for (NSDictionary *friend in data_array)
            {
                NSString *friend_id = friend[@"id"];
                NSString *urlString = [NSString stringWithFormat:@"https://graph.facebook.com/%@/picture",friend_id];
                NSURL    *url       = [NSURL urlWithString:urlString];
               [pictures addObject:[NSData dataWithContentsOfURL:url]];

            }
        }];

Since [NSData dataWithContentsOfURL:url] is pretty slow you may consider running this code in background

A: You need to use FBRequest, requestForMyFriends method it creates a request representing a Graph API call to the "me/friends" endpoint using the active session.
FBRequest* friendsRequest = [FBRequest requestForMyFriends];
[friendsRequest startWithCompletionHandler: ^(FBRequestConnection *connection,
                              NSDictionary* result,
                              NSError *error) {
    NSArray* friends = [result objectForKey:@"data"];
    NSLog(@"Found: %i friends", friends.count);
    for (NSDictionary<FBGraphUser>* friend in friends) {
        NSLog(@"My friend named %@ and id %@", friend.name, friend.id);
    }
}];

A: NSArray *permissions = [[NSArray alloc] initWithObjects:
                        @"user_birthday",@"friends_hometown",
                        @"friends_birthday",@"friends_location",
                        nil];
[FBSession openActiveSessionWithReadPermissions:permissions allowLoginUI:YES completionHandler:write handler code..]


text:
Q: AngularJS ng-show ternary conditional with multiple conditions Im working on a complex app where I need to disable a link if the ID sent from backend meets a certain criteria.
I'm using this now but not sure if it is correct:
ng-show="parentheaderData.casid === '807' || '806' || '808' ?false:true"

Does this look right?

A: you can do like this:
ng-show="(parentheaderData.casid === '807' || parentheaderData.casid ==='806' parentheaderData.casid === || '808') ? false : true"

or:
ng-show=" !(parentheaderData.casid === '807' || parentheaderData.casid ==='806' parentheaderData.casid === || '808')"

A: Why don't you move this logic to a controller so you have
html :
ng-show="showParentheader(parentheaderData.casid)"

controller:
 $scope.showParentheader = function(id) {
     return  ! (id === '807' || id ==='806' || id ==='808');
 }

A: Thanks for all the support. The correct solution was:
ng-hide="parentheaderData.casid == '806' || parentheaderData.casid == '807' || parentheaderData.casid == '808'"

A: ng-show="(parentheaderData.casid === '807' || parentheaderData.casid ==='806' parentheaderData.casid === || '808') ? false : true"