text:
Q: How to set default value of SelectListItem equal to a result of a stored procedure I have a stored procedure that retrieves existing data from the database and I want to set my DropDownListFor to a value that is equal to the data from the stored procedure's result. This is for an edit module.
Here is my code for my controller:
    [HttpPost]
    public ActionResult EditGetProjDetails(int id)
    {
        var vm = new ProjectsViewModel();

        sp_GetProjectDetails_Result result = db_RIRO.sp_GetProjectDetails(id).FirstOrDefault();

        vm.BusinessLineList = db_RIRO.sp_GetAllBusinessLine()
        .Select(a => new SelectListItem
        {
            Value = a.BusinessLineID.ToString(),
            Text = a.BusinessLine,
            Selected = // what code do i put here?
        })
        .ToList();

        vm.ProjectID = result.ProjectID;
        vm.BusinessUnit = result.BusinessUnit;

        return PartialView("~/Views/Project/_EditProjDetails.cshtml", vm);

This is my View:
 @Html.DropDownListFor(a => a.BusinessLineID, Model.BusinessLineList, new { @class = "form-control input-sm", placeholder = "Business Line", required = "required", autocomplete = "off" })

and here is my ViewModel:
    public int BusinessLineID { get; set; }
    public List<SelectListItem> BusinessLineList { get; set; }
    public string BusinessLine { get; set; }

Solution:
        var vm = new ProjectsViewModel()
        {
         BusinessLineID = 2
        };

        sp_GetProjectDetails_Result result = db_RIRO.sp_GetProjectDetails(id).FirstOrDefault();

        vm.BusinessLineList = db_RIRO.sp_GetAllBusinessLine()
        .Select(a => new SelectListItem
        {
            Value = a.BusinessLineID.ToString(),
            Text = a.BusinessLine
        })
        .ToList();

        return PartialView("~/Views/Project/_EditProjDetails.cshtml", vm);

A: You are looping over all business lines, then creating a list of selectlist items with a value and text for each BusinessLine.
sp_GetProjectDetails_Result result has the single business line id you want selected?
If so, in your loop for each business line, set the select list item's selected property to true if the id is the same as result id from the procedure.
Something like:
 Selected = (a.BusinessLineID == result.ID) //or whatever result is from the procedure


text:
Q: How can I force doxygen to generate deterministic, readable URLs? I'd like my documentation to have deterministic urls, and (preferably readable) for our doc writers to link to.
Here is an example of what I don't want:
https://sdk.amazonaws.com/cpp/api/0.13.11/d7/d76/class_aws_1_1_client_1_1_a_w_s_client.html
Each time I publish a new build, the urls change.
Here is a link to my current doxygen config:
https://github.com/aws/aws-sdk-cpp/blob/master/doxygen/doxygen.config
Any ideas?

A: Answer for this was to turn off CREATE_SUBDIRS.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to shrink webpage to any size screen- I can't tell what I'm doing wrong After learning a little bit of web development in one of my college classes I decided to give it a shot on my own and make my own webpage. I want it to serve as a virtual resume. I have it's visuals and styling set up and it looks good on my laptop screen however it's not adaptive to the screen size. I've looked at others similar question and have tried implementing their ideas (such as setting my wrapper div  width and height to 100%) but nothing works. Can someone tell me where I am going wrong. I'll provide an image of what it should look like in case your screen may be larger or smaller. Webpage visual goals
Github repo- development branch: branch1/land-page
My HTML:
<!Doctype html>

    <title>Jordyn N. Smith</title>

    <link rel="stylesheet" href="stylesheet.css">

    <link rel="stylesheet" type="text/css" href="https://fonts.googleapis.com/css?family=Marck+Script|Poiret+One">

    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">

            {{Information}}

                About Me
                Skills
                Experience
                Awards/Honors
                Contacts
                Download Resume

Jordyn Niara Smith

Welcome to my page. Take a look around.

My CSS:
/*Background image styling*/
body{
background-image: url(Resources/FaceQ.jpg);
background-repeat: no-repeat; /*don't repeat image*/
background-position: center top; /*position image in center from top*/
background-color: black !important; /*override default color value w/ image*/
/*height: 100%; fix height of page*/
/*position: fixed;*/
overflow-x: scroll;
overflow-y: scroll;
padding: 0;
margin: 0;
 min-width:900px;
min-height: 450px;
}

body#wrapper{
width:100%;
height: 100%;
}

/*Name and welcome message div styling */
div.name{
color:white;
/*    text-align: center; */
font-size: 7em;
font-weight: bold;
font-variant: small-caps;
font-family: 'Marck Script', cursive; /*googl font*/
text-shadow: 4px 4px 4px black;
width: 913px;
}
div.wel-message{
color: white;
text-align: center;
font-variant: small-caps;
font-size: 2em;
font-family: 'Poiret One', cursive;
text-shadow: 2px 2px 2px black;
margin-top: 0px;
width: 900px;
}
div.message{
/*keeps message fixed to center of screen*/
position: fixed;
/*
height: 200px;
width: 994px;
*/
height: 30%;
width: 90%;
margin: -100px 0 0 -200px;
top: 375px;
left: 458px;
}

/*nav bar styling*/
body div.col-lg-3{
padding: 0;
width: 278px;
height: auto;
position: fixed;
z-index: -1; /*position behind splash message*/
top: 200px; /*set position from top*/
left: 0;/*set position from left*/
}
div.sidenav {
height: 330px; /* 100% Full-height */
width: 278px; /* 0 width - change this with JavaScript */
background-color: transparent;
overflow-x: hidden; /* Disable horizontal scroll */
}

a.menu-btn{
padding: 8px 8px 8px 32px;/*spaces out buttons*/
font-family: 'Poiret One', cursive; /*google font*/
font-size: 2em;
width: 100%;
float:left;
}

#aboutMe{
color:red;
}
/*change color on hover */
a.abt:hover{
color:white !important;
background-color: red;
text-decoration:none;
}

#skills{
color:dodgerblue;
float: none;
padding-right: 70%;
}
a.skill:hover{
color:white !important;
background-color: dodgerblue;
text-decoration:none;
}

#exp{
color:greenyellow
}
a.exp:hover{
color:white !important;
background-color: greenyellow;
text-decoration:none;
}

#contact{
color:yellow;
}
a.contact:hover{
color:white !important;
background-color: yellow;
text-decoration:none;
}

#dlResume{
color: mediumpurple;
}
a.dl:hover{
color:white !important;
background-color:mediumpurple;
text-decoration:none;
}

#award{
color:darkorange;
}
a.award:hover{
color:white !important;
background-color: darkorange;
text-decoration:none;
}

/* The info drawer */
.drawer {
height: 100%; /* 100% Full-height */
width: 0; /* 0 width - change this with JavaScript */
position: fixed; /* Stay in place */
z-index: 1; /* Stay on top */
opacity: .9;
top: 0;
right: 0;
background-color:#111; /* Black*/
overflow-x: hidden; /* Disable horizontal scroll */
padding-top: 60px; /* Place content 60px from the top */
transition: 0.5s; /* 0.5 second transition effect to slide in the sidenav */
}
.drawerFont{
/*font styling*/
font-family: 'Poiret One', cursive; /*google font*/
color: white;
z-index: 1;
font-size: 4em;
}

A: I added the background size attribute to the body a set it to a percent, and modified my font size to use vw instead of pixels or percent, and found it to be more adaptive to browser size. Now I just need to keep them from shift around...


text:
Q: Load multiple OBJ-files together with multple textures Using the many examples on ThreeJS, I'm able to load multiple OBJ files into my scene. I'm also able to load multiple images as textures. However, the textures get assigned to the objects in 'order of appearance' and therefore, sometimes the wrong image gets assigned to the OBJ files.
I retrieve a list of OBJ files and textures from a JavaScript array, let's say:
…
"arr_threejs": [{
    "geometry": "my_first_object.obj",
    "material_uvmap": "my_first_texture.jpg",

}, {
    "geometry": "my_second_object.obj",
    "material_uvmap": "my_second_object.obj",

}],…

Then, I use this 'loader' class to load the textures:
for (var i = 0; i < arr_threejs.length; i++) {

    var loader = new THREE.ImageLoader(manager);

    str_material_uvmap_url = arr_threejs[i].material_uvmap;

    loader.load(str_material_uvmap_url, function (image) {

        console.log(image);
        var index = textures.push(new THREE.Texture()) - 1;
        textures[index].image = image;
        textures[index].needsUpdate = true;

    });
}

And, simillary, the geometry:
var loader = new THREE.OBJLoader(manager);
for (var i = 0; i < arr_threejs.length; i++) {

    str_model_url = arr_threejs[i].geometry;

    loader.load(str_model_url, function (object, i) {

        var index = get_index_by_url(str_model_url); //doesn't work
        objects[index] = object;

        objects[index].traverse(function (child) {

            if (child instanceof THREE.Mesh) {

                child.material.map = textures[index];
                child.material.side = THREE.DoubleSide;
            }
        });

        scene.add(objects[index]);

    }, onProgress, onError);
}

It seems I have no way in the callback function to know what object or what texture I'm dealing with. var index = get_index_by_url(str_model_url); doesnt work, because str_model_url isn't passed as arguement.
So, my question is,
specifically:
Is there a way to know the index of the image or object that I'm trying to load?
or generally:
Is there a standard way to load multple OBJ-files with textures?

A: You can use anonymus functions. For example:
loader.load(str_model_url, (function (url,scale) { return function (object, i) {
        console.log( url );
        console.log( scale );
    }}) (str_model_url, 0.5)
    , onProgress
    , onError
);

A: Here's @stdob answer implemented in my code:
   // MODEL

    // model - LOAD TEXTURE

    for (var i = 0; i < arr_threejs.length; i++) {

        var loader = new THREE.ImageLoader(manager);

        str_material_uvmap_url = arr_threejs[i].material_uvmap;

        loader.load(str_material_uvmap_url, (function (url, index) {
                return function (image, i) {
                    textures[index] = new THREE.Texture();
                    textures[index].image = image;
                    textures[index].needsUpdate = true;
                }
            })(str_material_uvmap_url, i)
            , onProgress
            , onError
        );
    }

    // model - LOAD OBJECT

    var loader = new THREE.OBJLoader(manager);

    for (var i = 0; i < arr_threejs.length; i++) {

        str_model_url = arr_threejs[i].geometry;

        loader.load(str_model_url, (function (url, index) {
                return function (object, i) {

                    objects[index] = object;

                    objects[index].traverse(function (child) {

                        if (child instanceof THREE.Mesh) {
                            child.material.map = textures[index];
                            child.material.side = THREE.DoubleSide;
                        }
                    });

                    scene.add(objects[index]);

                }
            })(str_model_url, i)
            , onProgress
            , onError
        );
    }


text:
Q: Finding the number of occurrences of an element in every list inside a list Here I have a nested list:
[['a,b,c,d,e'], ['d,e,c,b,a'], ['e,b,a,e,c'], ['a,c,b,e,d'], ['e,d,c,b,a'], ['a,c,b,d,e']]

I want to count the number of occurrences of "a" in the beginning of each list, so that will be 3. I also want to be able to do the same for each letter in the lists, so I know that the number of "b" in the second position of each list is 2.
This is perhaps easier to imagine if you put each list on top of each other and look down the column.
I want to be able to give the letter and position to scan through and receive the number of occurrences of that letter in that position. I hope I'm clear.
Here is what I have tried so far:
number=sum(x.count("a") for x in data[0][0])

A: In most simple case you may use the following:
data = [['a,b,c,d,e'], ['d,e,c,b,a'], ['e,b,a,e,c'], ['a,c,b,e,d'], ['e,d,c,b,a'], ['a,c,b,d,e']]
letter = 'b'
pos = 1
result = sum(1 for i in data if letter in i[0] and i[0].split(',')[pos] == letter)

print(result)

The output:
2

To get a more accurate and robust solution:
data = [['a,b,c,d,e'], ['d,e,c,b,a'], ['e,b,a,e,c'], ['a,c,b,e,d'], ['e,d,c,b,a'], ['a,c,b,d,e']]
letter = 'b'
pos = 1
result = 0

for i in data:
    if letter in i[0]:
        items = i[0].split(',')
        if pos < len(items) and items[pos] == letter:
            result += 1

print(result)

A: You should use a function instead of just loops. Because it's easier to give a parameter as index no and letter:
Here is solution with a function:
list_1= [['a,b,c,d,e'], ['d,e,c,b,a'], ['e,b,a,e,c'], ['a,c,b,e,d'], ['e,d,c,b,a'], ['a,c,b,d,e']]

    def find(index,letter,list_1):
        count=0
        for item in list_1:
            for subitem in item:
                if subitem[index]==letter:
                    count+=1
        return count

Test with 'a' with index 0:

print(find(0, 'a', list_1))

Output:
3

Test with 'b' with index 2:
print(find(2, 'b', list_1))

Output:
2


text:
Q: javascript If statement not working I'm trying to show an alert if the value of the input (inp_val) isn't between minvalue and maxvalue but it doesn't work, it shows the alert even if the value is between minvalue and maxvalue.
function compare(e){
    this_id = e.id.slice(10,15);
    inp_val = e.value;
    minvalue = document.getElementById('min_' + this_id).value;
    maxvalue = document.getElementById('max_' + this_id).value;
    console.log(maxvalue);
    console.log(minvalue);
    console.log(inp_val);
    if(inp_val < minvalue){
        alert('Minimum Value: ' + minvalue + 'Input Value: ' + inp_val);
    }
    if(inp_val > maxvalue){
        alert('Maximum Value: ' + maxvalue + ' Input Value: ' + inp_val);
    }
}

I'm calling the function compare with an onBlur():
echo '<input class="result_fields" autocomplete="off" onBlur="compare(this)" id="result_inp' . $idc . '" type="text" name="test_res' . $idc . '" />'

I've tried to do this in jQuery but is the same error.
Minvalue and maxvalue are input type hidden and its values are stored in a DB on MySQL and retrieved with php like this:
echo '<input type="hidden" value="' . $val_test . '" name="test_name' . $idc . '" id="test_name' . $idc . '" class="testN" />';

The php variable $idc is an incremental function $idc++.

A: You need to apply < and > operators on integer value so parse string value to integer and then compare.
if(parseInt(inp_val,10) < parseInt(minvalue,10)){
        alert('Minimum Value: ' + minvalue + 'Input Value: ' + inp_val);
    }

A: You need to parse your integers or floats from the values you get from the text box
if they are integers:
minvalue = document.getElementById('min_' + this_id).value;
maxvalue = document.getElementById('max_' + this_id).value;
minvalue = parseInt(minvalue,10);
maxvalue = parseInt(maxvalue,10);

Or if they are floats:
minvalue = document.getElementById('min_' + this_id).value;
maxvalue = document.getElementById('max_' + this_id).value;
minvalue = parseFloat(minvalue);
maxvalue = parseFloat(maxvalue);

A: Try this:
if(!(inp_val >= minvalue && inp_val <= maxvalue)){
     alert('Max Val: ' + maxvalue + ' Min Val: ' + minvalue + ' Input Value: ' + inp_val);


text:
Q: What are the Qt ownership rules? I have three classes - Main, A and B with the following definitions:
class Main : public QObject {
    Q_OBJECT

    A* a;
public:
    explicit Main(QObject* parent = nullptr) : QObject(parent), a(new A(this)) {}

    Q_INVOKABLE A* getA() { return a; }
    Q_INVOKABLE B* getB() { return new B(); }
}

class A : public QObject {
    Q_OBJECT
public:
    explicit A(QObject* parent = nullptr) : QObject(parent) {}
}
// class B has the same definition as A

Main class is a singleton responsible for handling interactions between C++ objects and QML, so I set it as a context property.
Main* main = new Main();
QQmlApplicationEngine engine;
engine.rootContext()->setContextProperty("main", main);

Now, I want to access objects A and B in QML (JavaScript function).
function ownershipTest() {
    let a = main.getA()
    let b = main.getB()
    // do something with these objects
}

The question is, what happens with these objects when the function returns?
I think that object A should stay in memory because it is owned by Main. Object B should be deleted because it has no parent, so QML should assume ownership.
Is my understanding correct? Are there more rules regarding Qt ownership which I should know?


text:
Q: Why the global variable not works in .rb file but works in irb? I was trying to add indentation based on how deep the block goes. I used a global variable to record the depth of block.
$depth = 0

def log(des, &block)
  indentation = "  " * $depth
  $depth += 1
  puts "#{indentation}Begginning the #{des} block"
  puts "#{indentation}Finished #{des} and returned: #{block.call}"
  $depth -= 1
end

log "outer block" do
  log "second level block" do
    log "third level block" do
      "I am number 3"
    end
    "I am number 2"
  end
  "I am out most!"
end

In terminal I tried several times ruby file_name.rb, it showed no indentation, it even won't puts the global variable out. After then I copy the code to irb and it worked.
Why this happened?
What's the difference when running ruby code in between these two places?

A: I suspect you have a different definition of log() in your environment.  Changing the name of your routine to something else (say 'mylog') will test this hypothesis.


text: Q: How to delete multiple parse users from an android app? I'm making an android app that have 2 user types the first is an ordinary user that browses through news, the second type is  administrator that can add  news, edit them and delete.The admin can also add users and delete them .My question is about how can the administrator  delete a user or multiple users at the same time ???


text:
Q: How can I prevent ZygoteInit Exception? I got an Exception report from my app in Google Play:
java.lang.NullPointerException
at com.dominionmobile.android.weather.l.handleMessage(Unknown Source)
at android.os.Handler.dispatchMessage(Handler.java:130)
at android.os.Looper.loop(SourceFile:351)
at android.app.ActivityThread.main(ActivityThread.java:3814)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:538)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:901)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:659)
at dalvik.system.NativeStart.main(Native Method)

There is a nearly identical Exception reported in this forum entry:
What are ZygoteInit calls?
I can't reproduce the problem, but going off that forum entry, it looks like they
are launching the app, doing something, then doing a back, putting the app
in the background, then launching it again.
So my question is, what kind of preventive code can I add to help avoid this issue?
I'm assuming it's all happening in my Main Activity.
I do have some OnClickListeners that I'm not setting to null on onStop(),
and I don't think I need to try to preserve any state of the app on re-entry,
it gets what it needs from it's database and from SharedPreferences when it starts up.
I think I've seen this same Exception before, from the Exception Reports, but it rarely happens.
Thanks!

A: You have an NPE when calling handle message. See the first lines of the log. If you kept your mapping.txt file you can symbolicate to get readable information from the report.


text:
Q: Prove that there exists at least one point $t_0 \in [0,1]$ such that $f(t_0) = 0$ for all $f \in \mathscr F.$
Let $\mathscr F$ be an infinite family of continuous real-valued functions on the interval $[0,1]$ with the property that given any finite subfamily of functions $\mathscr F' \subset \mathscr F,$ there exists at least one point $t \in [0,1]$ (depending on the subfamily) such that $f(t) = 0$ for all $f \in \mathscr F'.$ Prove that there exists at least one point $t_0 \in [0,1]$ such that $f(t_0) = 0$ for all $f \in \mathscr F.$

How do I proceed to prove it? Any help in this regard will be highly appreciated.
Thanks in advance.

A: Let $A_f=\{t: f(t)=0\}$ for $f \in \mathcal F$. Then $A_f$ is closed, hence compact, by continuity of $f$. This family of compact set has finite intersection property: the intersection of any finite number of them is non-empty by hypothesis. Now compactness of $[0,1]$ implies that intersection of all of these sets is non-empty which is what we have to prove.


text:
Q: Using MVVM, how can I dynamically generate view by using App.config I have application with two views in a separate xaml files (FirstView.xaml and SecondView.xaml). In the default mode the application generates the view from FirstView.xaml:
<Application x:Class="WpfDemo.App"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:local="clr-namespace:WpfDemo"
         StartupUri="View\FirstView.xaml">
<Application.Resources>

</Application.Resources>

I can switch to the second view by editing the line:
StartupUri="View\SecondView.xaml"

This works fine on compile time but I would like to achieve this on run time. I created application settings with the following contents:
<applicationSettings>
    <WpfDemo.Properties.Settings>
        <setting name="View" serializeAs="String">
            <value>FirstView</value>
        </setting>
    </WpfDemo.Properties.Settings>
</applicationSettings>

I can read the contents of the App.config file with:
string view = Properties.Settings.Default.View.ToString();

I would like to switch the view according to the view variable at run time.

A: First step: Remove the StartupUri from your App.xaml.
Second Step: In the Code-Behind of your App.xaml do the following
protected override void OnStartup(StartupEventArgs e) {
            Uri dynamicUri = null;
            string view = Properties.Settings.Default.View.ToString();
            var result = Uri.TryCreate(view, UriKind.RelativeOrAbsolute, out dynamicUri);
            if (!result) throw new ApplicationException("Invalid settings found.");
            this.StartupUri = dynamicUri;
            base.OnStartup(e);
        }

Note
The question and the answer both have nothing to do with MVVM. For such a behavior, there is no MVVM solution, since everything has to happen before we get into DataBinding or else


text:
Q: Get image from clipboard and save it to the server from client browser chrome or firefox I am using this tutorial, it works in chrome, it shows me an image as a div background image
now I want to save that image on the server side in specific folder... mine sample code
just copy and save it in .html and open with chrome ... and press printscreen button of keyboard and click on this page and press Ctrl+V
you will see the image... now I want that image to save on server side in a specific folder
My code

            <meta charset="UTF-8" />
            <meta name="viewport" content="width=device-width" />
            <title>HTML5 JavaScript Pasting Image Data in Chrome   </title>

            <link rel="stylesheet" type="text/css" media="all" href="http://strd6.com/wp-content/themes/twentyeleven/style.css" />

A: You'll need to send the data to the server, probably with an Ajax POST request. The data can be extracted from dataURL, it's a base64 encoded image with some metadata at the front.

A: yesterday i am facing that problem now i solve that in Firefox ......
sample code
index.jsp
    <%@page contentType="text/html" pageEncoding="UTF-8"%>
    <!DOCTYPE html>

    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>JSP Page</title>

Press Keyboard "Print Screen key" Than Click in the Colored Area and Press Control+V then Click  Upload Button

      <Button href="#" id="submit" >Upload</button>

in the it send the ajex request to the servlet   name /ImageCreator
that is the code of servlet
        import java.awt.image.BufferedImage;
        import java.io.File;
        import java.io.IOException;
        import java.io.PrintWriter;
        import java.text.DateFormat;
        import java.text.SimpleDateFormat;
        import java.util.Date;
        import javax.imageio.ImageIO;
        import javax.mail.Session;
        import javax.servlet.ServletException;
        import javax.servlet.http.HttpServlet;
        import javax.servlet.http.HttpServletRequest;
        import javax.servlet.http.HttpServletResponse;
        import javax.servlet.http.HttpSession;
        import util.ImageUtils;

        /**
         *
         * @author Zeeshan Akhter
         */
        public class ImageCreator extends HttpServlet {

            protected void processRequest(HttpServletRequest request, HttpServletResponse response)
                    throws ServletException, IOException {
                response.setContentType("text/html;charset=UTF-8");
                PrintWriter out = response.getWriter();
                BufferedImage newImg;
                HttpSession session = request.getSession(true);
                String minedata = request.getParameter("html");
              //  System.out.println("minedata" + minedata);
                newImg = ImageUtils.decodeToImage(minedata.replace("data:image/png;base64,", ""));

                String date = "";
                Date date1 = new Date();
                DateFormat formatter = new SimpleDateFormat("ddMMyyhhmmss");
                date = formatter.format(date1);
                //  File FilePathsdd = new File(FilePaths);
                //  JOptionPane.showConfirmDialog(null,application.getRealPath(request.getContextPath()+"/js/") );
                File dateFolder = new File(((String) session.getAttribute("imagePath")) + "/js/" + date);
                if (!dateFolder.exists()) {
                    dateFolder.mkdir();
                    dateFolder.setExecutable(true);
                    dateFolder.setReadable(true);
                    dateFolder.setWritable(true);
                }
                String path = dateFolder.getAbsolutePath();
                while ((path.contains("\\"))) {
                    System.out.println("\nPath1=" + path);
                    path = (path.replace("\\", "/"));
                    System.out.println("\nPath2=" + path);
                }
                File Save = new File(path + "/ForexImage.png");
                System.out.println("ImagePath=" + Save.getAbsolutePath().replace("\\", "/"));
                session.setAttribute("createdFilePath", Save.getAbsolutePath().replace("\\", "/"));
                ImageIO.write(newImg, "png", Save);

            }

        }

A: Here is the class util.ImageUtils
package util;

/**
 *
 * @author ZeeshanAakhter
 *http://latest-tutorial.com
 *http://zeeshanakhter.com
 */
import java.io.IOException;

import sun.misc.BASE64Encoder;
import sun.misc.BASE64Decoder;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;

public class ImageUtils {

    /**
     * Decode string to image
     *
     * @param imageString The string to decode
     * @return decoded image
     */
    public static BufferedImage decodeToImage(String imageString) {

        BufferedImage image = null;
        byte[] imageByte;
        try {
            BASE64Decoder decoder = new BASE64Decoder();
            imageByte = decoder.decodeBuffer(imageString);
            ByteArrayInputStream bis = new ByteArrayInputStream(imageByte);
            image = ImageIO.read(bis);
            bis.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return image;
    }

    /**
     * Encode image to string
     *
     * @param image The image to encode
     * @param type jpeg, bmp, ...
     * @return encoded string
     */
    public static String encodeToString(BufferedImage image, String type) {
        String imageString = null;
        ByteArrayOutputStream bos = new ByteArrayOutputStream();

        try {
            ImageIO.write(image, type, bos);
            byte[] imageBytes = bos.toByteArray();

            BASE64Encoder encoder = new BASE64Encoder();
            imageString = encoder.encode(imageBytes);

            bos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return imageString;
    }
}


text:
Q: How can I optimize with an array? I'm starting to learn about google app script with JavaScript.
I wrote this code, but it is really slow and executing the function takes too long. I think this isn't the best way to do the function.
Is there any option/way (array), to make it faster or in other way to reduce to the time waiting?
All I wish to do is to insert  "today's date", when a column cell value is set true, in another cell column.
function onEdit() {
  sConfDate();
}

function sConfDate(){
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var dataSheet = ss.getSheetByName("Data");
  var dataRange = dataSheet.getRange(9, 1, dataSheet.getLastRow(), 43);
  var data = dataRange.getValues();
  var d = new Date();
  var dd = d.getDate();
  var mm = d.getMonth() +1;
  var yyyy = d.getFullYear();
  var date = dd + "/" + mm + "/" + yyyy;
  var needSay = 'SUC';
  var needSay2 = '-';

  for(var i = 0; i < data.length; i++){
    //row items
    var values = data[i];
    //column items
  for(var j = 0; j < values.length; j++){
    var row = values[j];
    var checkRow = row;
    //Logger.log(checkRow);
       if(checkRow === needSay && checkRow === needSay2){
         dataSheet.getRange(9 + i, 43).setValue(date);
      };
    };
  };
}

A: Perhaps this is what you had in mind:
function sConfDate(){
  var ss=SpreadsheetApp.getActive();
  var dataSheet=ss.getSheetByName("Data");
  var dataRange=dataSheet.getRange(9, 1, dataSheet.getLastRow()-8, 43);
  var data=dataRange.getValues();
  var datacol43=dataSheet.getRange(9,43,dataSheet.getLastRow()-8,1).getValues();
  var date=Utilities.formatDate(new Date(), Session.getScriptTimeZone(), "dd/MM/yyyy");
  data.forEach(function(r,i){
    r.forEach(function(c,j){
      if(c=='SUC' || c=='-') {
        datacol43[i][0]=date;
      }
    });
  });
  dataSheet.getRange(9,43,dataSheet.getLastRow()-8,1).setValues(datacol43);
}

This might actually run faster:
function sConfDate(){
  var ss=SpreadsheetApp.getActive();
  var sh=ss.getSheetByName("Data");
  var rg=sh.getRange(9, 1, sh.getLastRow()-8, 43);
  var data=rg.getValues();
  var crg=sh.getRange(9,43,sh.getLastRow()-8,1);
  var cdata=crg.getValues();
  var date=Utilities.formatDate(new Date(), Session.getScriptTimeZone(), "dd/MM/yyyy");
  for(var i=0;i<data.length;i++) {
    for(var j=0;j<data[i].length;j++) {
      if(data[i][j]=='SUC' || data[i][j]=='-') {
        cdata[i][0]=date;
        break;
      }
    }
  }
  crg.setValues(cdata);
}

Perhaps this would be better.
function sConfDate2(){
  var ss=SpreadsheetApp.getActive();
  var sh=ss.getSheetByName("Data");
  var rg=sh.getRange(9, 1, sh.getLastRow()-8, 8);
  var data=rg.getValues();
  var crg=sh.getRange(9,8,sh.getLastRow()-8,1);
  var cdata=crg.getValues();
  var date=Utilities.formatDate(new Date(), Session.getScriptTimeZone(), "dd/MM/yyyy");
  for(var i=0;i<data.length;i++) {
    var row=data[i];//Im guessing this is probably what you want unless you have particular columns in mind
    if(row.indexOf('SUC')!=-1 && row.indexOf('-')!=-1) {
      cdata[i][0]=date;
    }
  }
  crg.setValues(cdata);
}


text:
Q: What is useState() in React? I am currently learning hooks concept in React and trying to understand below example.
import { useState } from 'react';

function Example() {
    // Declare a new state variable, which we'll call "count"
    const [count, setCount] = useState(0);

  return (

You clicked {count} times

      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>

  );
}

The above example increments the counter on the handler function parameter itself. What if I want to modify count value inside event handler function
Consider below example:
setCount = () => {
  //how can I modify count value here. Not sure if I can use setState to modify its value
  //also I want to modify other state values as well here. How can I do that
}

<button onClick={() => setCount()}>
  Click me
</button>

A: useState is one of the hooks available in React v16.8.0. It basically lets you turn your otherwise non-stateful/functional components to one that can have its own state.
At the very basic level, it's used this way:
const [isLoading, setLoading] = useState(true);

This then lets you call setLoading passing a boolean value.
It's a cool way of having "stateful" functional component.

A: useState() is an example built-in React hook that lets you use states in your functional components. This was not possible before React 16.7.
The useState function is a built in hook that can be imported from the react package. It allows you to add state to your functional components. Using the useState hook inside a function component, you can create a piece of state without switching to class components.

A: useState is one of build-in react hooks available in 0.16.7 version.
useState should be used only inside functional components. useState is the way if we need an internal state and don't need to implement more complex logic such as lifecycle methods.
const [state, setState] = useState(initialState);

Returns a stateful value, and a function to update it.
During the initial render, the returned state (state) is the same as
  the value passed as the first argument (initialState).
The setState function is used to update the state. It accepts a new
  state value and enqueues a re-render of the component.

Please note that useState hook callback for updating the state behaves differently than components this.setState. To show you the difference I prepared two examples.

class UserInfoClass extends React.Component {
  state = { firstName: 'John', lastName: 'Doe' };

  render() {
    return

userInfo: {JSON.stringify(this.state)}

      <button onClick={() => this.setState({
        firstName: 'Jason'
      })}>Update name to Jason</button>

;
  }
}

// Please note that new object is created when setUserInfo callback is used
function UserInfoFunction() {
  const [userInfo, setUserInfo] = React.useState({
    firstName: 'John', lastName: 'Doe',
  });

  return (

userInfo: {JSON.stringify(userInfo)}

      <button onClick={() => setUserInfo({ firstName: 'Jason' })}>Update name to Jason</button>

  );
}

ReactDOM.render(

    <UserInfoClass />
    <UserInfoFunction />

, document.querySelector('#app'));

New object is created when setUserInfo callback is used. Notice we lost lastName key value. To fixed that we could pass function inside useState.
setUserInfo(prevState => ({ ...prevState, firstName: 'Jason' })

See example:

// Please note that new object is created when setUserInfo callback is used
function UserInfoFunction() {
  const [userInfo, setUserInfo] = React.useState({
    firstName: 'John', lastName: 'Doe',
  });

  return (

userInfo: {JSON.stringify(userInfo)}

      <button onClick={() => setUserInfo(prevState => ({
        ...prevState, firstName: 'Jason' }))}>
        Update name to Jason
      </button>

  );
}

ReactDOM.render(
    <UserInfoFunction />
, document.querySelector('#app'));

Unlike the setState method found in class components, useState does
  not automatically merge update objects. You can replicate this
  behavior by combining the function updater form with object spread
  syntax:
setState(prevState => {
  // Object.assign would also work
  return {...prevState, ...updatedValues};
});

For more about useState see official documentation.

A: Thanks loelsonk,  i did so

const [dataAction, setDataAction] = useState({name: '', description: ''});

    const _handleChangeName = (data) => {
        if(data.name)
            setDataAction( prevState  => ({ ...prevState,   name : data.name }));
        if(data.description)
            setDataAction( prevState  => ({ ...prevState,   description : data.description }));
    };

    ....return (

          <input onChange={(event) => _handleChangeName({name: event.target.value})}/>
          <input onChange={(event) => _handleChangeName({description: event.target.value})}/>
    )

A: Hooks are a new feature in React v16.7.0-alpha useState is the "Hook". useState() set the default value of the any variable and manage in function component(PureComponent functions).  ex : const [count, setCount] = useState(0); set the default value of count 0. and u can use setCount to increment or decrement the value. onClick={() => setCount(count + 1)} increment the count value.DOC

A: useState is a hook that lets you add state to a functional component. It accepts an argument which is the initial value of the state property and returns the current value of state property and a method which is capable of updating that state property.
Following is a simple example:
import React, { useState } from react

function HookCounter {
  const [count, setCount]= useState(0)
    return(

        <button onClick{( ) => setCount(count+1)}> count{count}</button>

    )
 }

useState accepts the initial value of the state variable which is zero in this case and returns a pair of values. The current value of the state has been called count and a method that can update the state variable has been called as setCount.

A: React useState is the React Hook that allows you to manage the state within functional components.
For example:
import React, { useState } from 'react'

const Example = () => {
  // create the "counter" state
  const [count, setCount] = useState(0)

  return (

Button clicked {count} times

      <button onClick={() => setCount(count + 1)}>
        Count + 1
      </button>

  )
}

export default Example

With useState you can easily create stateful functional components.
The old equivalent way, using class components with Component class and setState is:
import React, { Component } from 'react'

class Example extends Component {
  constructor(props) {
    super(props)
    this.state = { count: 0 }
  }

  render() {
    const { count } = this.state
    return (

Button clicked {count} times

        <button onClick={() => this.setState({ count: count + 1 })}>
          Count + 1
        </button>

    )
  }
}

export default Example

Source:

*

*React useState Hook: what's new and to use it
Links:

*

*React Hooks documentation

A: The syntax of useState hook is straightforward.
const [value, setValue] = useState(defaultValue)
If you are not familiar with this syntax, go here.
I would recommend you reading the documentation.There are excellent explanations with decent amount of examples.

import { useState } from 'react';

function Example() {
    // Declare a new state variable, which we'll call "count"
    const [count, setCount] = useState(0);

  // its up to you how you do it
  const buttonClickHandler = e => {
   // increment
   // setCount(count + 1)

   // decrement
   // setCount(count -1)

   // anything
   // setCount(0)
  }

  return (

You clicked {count} times

         <button onClick={buttonClickHandler}>
             Click me
         </button>

   );
 }

A: React hooks are a new way (still being developed) to access the core features of react such as state without having to use classes, in your example if you want to increment a counter directly in the handler function without specifying it directly in the onClick prop, you could do something like:
...
const [count, setCounter] = useState(0);
const [moreStuff, setMoreStuff] = useState(...);
...

const setCount = () => {
    setCounter(count + 1);
    setMoreStuff(...);
    ...
};

and onClick:
<button onClick={setCount}>
    Click me
</button>

Let's quickly explain what is going on in this line:
const [count, setCounter] = useState(0);

useState(0) returns a tuple where the first parameter count is the current state of the counter and setCounter is the method that will allow us to update the counter's state. We can use the setCounter method to update the state of count anywhere - In this case we are using it inside of the setCount function where we can do more things; the idea with hooks is that we are able to keep our code more functional and avoid class based components if not desired/needed.
I wrote a complete article about hooks with multiple examples (including counters) such as this codepen, I made use of useState, useEffect, useContext, and custom hooks. I could get into more details about how hooks work on this answer but the documentation does a very good job explaining the state hook and other hooks in detail.
update: Hooks are not longer a proposal, since version 16.8 they're now available to be used, there is a section in React's site that answers some of the FAQ.

A: Basically React.useState(0) magically sees that it should return the tuple count and setCount (a method to change count). The parameter useState takes sets the initial value of count.
  const [count, setCount] = React.useState(0);
  const [count2, setCount2] = React.useState(0);

  // increments count by 1 when first button clicked
  function handleClick(){
    setCount(count + 1);
  }

  // increments count2 by 1 when second button clicked
  function handleClick2(){
    setCount2(count2 + 1);
  }

  return (

A React counter made with the useState Hook!

You clicked {count} times

You clicked {count2} times

      <button onClick={handleClick}>
        Click me
      </button>
      <button onClick={handleClick2}>
        Click me2
      </button>
  );

Based off Enmanuel Duran's example, but shows two counters and writes lambda functions as normal functions, so some people might understand it easier.

A: Lets understand useState very easily in simple manner
suppose we have react code:-
index.js
import React from 'react';
import ReactDOM from 'react-dom';
import Test from './components/Test.jsx'
ReactDOM.render(

      <Test />

,
  document.getElementById('root')
);

Test.jsx
import React from "react";

function Test() {
  var x = 5;
  function update() {
    console.log(x);
    return x++;
  }
  return (

{x}

      <button onClick={update}>click</button>

  );
}
export default Test;

here,the page will show 5 , although we invoke update function by clicking button because we update x but not at between h1 tag , but in real, x is continiously change whenever we click on but it can saw on console
see result and check console by clicking this link
here usState works magically ,
Test.jsx with using useState
import React, { useState } from "react";

function Test() {
  var x = 5;
  const [value, setValue] = useState(x);

  function update() {
    setValue(value + 1);
  }

  return (

{value}

      <button onClick={update}>click</button>

  );
}
export default Test;

see result by clicking this link
here, by clicking button the value will continiously update, because here we use useState ,it is a function which return 2 things one is current state value and another one is function , if we pass any value to this function it will update current state vlue and current state value update its value in all places wherever it used without writing any extra code.

A: useState() is a React hook. Hooks make possible to use state and mutability inside function components.
While you can't use hooks inside classes you can wrap your class component with a function one and use hooks from it. This is a great tool for migrating components from class to function form. Here is a complete example:
For this example I will use a counter component. This is it:

class Hello extends React.Component {
  constructor(props) {
    super(props);
    this.state = { count: props.count };
  }

  inc() {
    this.setState(prev => ({count: prev.count+1}));
  }

  render() {
    return <button onClick={() => this.inc()}>{this.state.count}</button>
  }
}

ReactDOM.render(<Hello count={0}/>, document.getElementById('root'))

It is a simple class component with a count state, and state update is done by methods. This is very common pattern in class components. The first thing is to wrap it with a function component with just the same name, that delegate all its properties to the wrapped component. Also you need to render the wrapped component in the function return. Here it is:

function Hello(props) {
  class Hello extends React.Component {
    constructor(props) {
      super(props);
      this.state = { count: props.count };
    }

    inc() {
      this.setState(prev => ({count: prev.count+1}));
    }

    render() {
      return <button onClick={() => this.inc()}>{this.state.count}</button>
    }
  }
  return <Hello {...props}/>
}

ReactDOM.render(<Hello count={0}/>, document.getElementById('root'))

This is exactly the same component, with the same behavior, same name and same properties. Now lets lift the counting state to the function component. This is how it goes:

function Hello(props) {
  const [count, setCount] = React.useState(0);
  class Hello extends React.Component {
    constructor(props) {
      super(props);
      this.state = { count: props.count };
    }

    inc() {
      this.setState(prev => ({count: prev.count+1}));
    }

    render() {
      return <button onClick={() => setCount(count+1)}>{count}</button>
    }
  }
  return <Hello {...props}/>
}

ReactDOM.render(<Hello count={0}/>, document.getElementById('root'))

Note that the method inc is still there, it wont hurt anybody, in fact is dead code. This is the idea, just keep lifting state up. Once you finished you can remove the class component:

function Hello(props) {
  const [count, setCount] = React.useState(0);

  return <button onClick={() => setCount(count+1)}>{count}</button>;
}

ReactDOM.render(<Hello count={0}/>, document.getElementById('root'))

While this makes possible to use hooks inside class components, I would not recommend you to do so except if you migrating like I did in this example. Mixing function and class components will make state management a mess. I hope this helps
Best Regards

A: The answers provided above are good but let me just chip in, useState is async so if your next state is dependent on your previous state it is best you pass useState a callback. See the example below:
import { useState } from 'react';

function Example() {
    const [count, setCount] = useState(0);

  return (

You clicked {count} times

      // passing a callback to useState to update count
      <button onClick={() => setCount(count => count + 1)}>
        Click me
      </button>

  );
}

This is the recommended way if your new state depends on computation from the old state.

A: useState is a Hook that allows you to have state variables in functional components.
There are two types of components in React: class and functional components.
Class components are ES6 classes that extend from React.Component and can have state and lifecycle methods:
class Message extends React.Component {
constructor(props) {
super(props);
this.state = {
  message: ''
 };
}

componentDidMount() {
/* ... */
 }

render() {
return
{this.state.message}
;
  }
}

Functional components are functions that just accept arguments as the properties of the component and return valid JSX:
function Message(props) {
  return
{props.message}

 }
// Or as an arrow function
const Message = (props) =>
{props.message}

As you can see, there are no state or lifecycle methods.


text:
Q: Login Error when using invoke-command as job When i run PS script (robocopy cmd) on remote machine using invoke-command as job, it throws login error. The account i am running has admin privileges and when i run the same command onthe remote machine, it works fine.
Invoke-Command -session $servers -FilePath D:\script.ps1

Error
    2016/10/04 10:39:00 ERROR 64 (0x00000040) Accessing Source Directory
    The specified network name is no longer available.
My question is what login does the script use when i run it from remote server ?

A: I found the issue, its a problem with multihop authentication.
http://www.ravichaganti.com/blog/powershell-2-0-remoting-guide-part-12-%E2%80%93-using-credssp-for-multi-hop-authentication/
Thanks everyone.


text:
Q: Html email template not working outlook I've searched a lot before coming here.
I'm trying to use a background-image, but when I send it to outlook it doesn't appears. Can you help me to find the solution for this issue?

        Eletrolar Show
 A maior feira B2B da América Latina

A: background images using background are not supported by Outlook, Notes, certain versions of Android and a few other email clients.

*

*https://www.campaignmonitor.com/css/color-background/background/
The only way to get a background image to work with Outlook is to use VML code. I posted an example and a link to the JS Fiddle code.

*

*https://jsfiddle.net/wallyglenn/7zLaLrfx/15/

            Background Image with text on top

I tested this code using http://litmus.com just before I posted it to ensure it currently works in every email client that supports background images in some form.
What you should see is a 600x450px image, a red background for contrast,
 text on top of the image with some css to help it stand out in contrast.
To use this, swap out the image url, adjust the size, change the color and delete the text if you don't need it.
Good luck.

A: As information is very less so difficult to identify the exact issue but you can try by setting width="100%" instead of width="600".
Current is:

Change to:

A: I found out that you cannot use background-images for outlook that is installed in your desktop or notebook. There is some sites that can help if you want a background image for the body and it works. But when we talk about tables, tr, td outlook does not recognize it as a background-image.
Thank you very much for your help. Person like as who develop email templates knows how hard is to figure out how to write the best html that we can. <3

A: CSS background support isn't great for Outlook. You may need to replace with the VML equivalent. There's a tool for this here: https://backgrounds.cm/
Just paste in your img URL, select your fallback bg-color, and select "single table cell". Then, you'll want to replace the opening and ending td tags with the output provided.

A: I add this code to my table.
It does not work on Outlook on Windows and that is what the bgcolor is for.
style="background-position: center center !important; background-size: cover !important;" background="http:wwww.yourlink.com/folder/image.jpg" bgcolor="#9cb0b0"


text:
Q: linux: links don't work after mount This is not your classic programming question and since I'm quite new to this (really cool!) site, I'm not sure if this is the place, so I'll try anyway.
I work in a lab when all the guys use PCs with Windows and access the lab linux servers via ssh.
I prefer linux, so I have a local installation of ubuntu 10.4 on my PC. I mount the home of our lab server using mount server:/home /mnt/home/. I can then access the files on the server (I had to change my local UID to match the one assigned to me on our server in order to be able to write to my home dir).
The problem is all the (symbolic) links I have on the server don't work when I access them through the mounted location. I guess the system simply tries following the link in my local /home instead on server:/home.
Is there a way to make the links work?
Thanks,
Dave

A: A symbolic link (unlike a hard link) is simply a "file" that contains the destination file.
So you're right. If the symbolic link contains /home/bob, then that's the file it will attempt to use, not server:/home/bob.
I don't think there's an way around this other than to:

*

*mount server:/home over your home directory, not a good idea since it'll hide your real home filesystem; or

*mount all softlinks under your own home as well, not a good idea just due to mount management issues.


text:
Q: DataTables server-side pagination I have working Spring REST app with client side pagination, default by DataTables and everything works. Now i need to change it to server-side pagination i have problem, because have no idea how to get information from DataTables what page number client want to see. I can't find anything usefull in DT manual.

A: Please see the sample about DataTables server-side processing:
https://datatables.net/examples/server_side/simple.html
After change page, you can capture the request to server as following format:
https://.../server_processing.php?draw=3&columns...&order=0&dir=asc&start=20&length=10&search%5Bvalue%5D=&search%5Bregex%5D=false&_=1534436781912
That means DataTable requests page number 3 (draw=3), order by first column ascending, ....
At server side (REST), you can get page number by (for example) request.getParameter("draw")

A: When you say Datatable I assume you are talking about DataTables jQuery plugin.
To activate serverside pagination you need to pass
"serverSide": true,

like this:
$('#example').DataTable( {
    "processing": true,
    "serverSide": true,
    "ajax": "/your_url"
});

Doing the above will activate your server-side pagination. But you need to do few changes on the server-side too. Let's see them step by step.
1. What happens when you mark serverSide as true
DataTables plugin adds custom parameters to the AJAX call with information like
order:  asc
start:  20
length: 10

// and many more.

You can inspect this demo link and see the parameters passed in request when you click the next page button.
2. Similarly, DataTables plugin expects some fields in response in order to preserve pagination logic.
"draw": 3,             // unique ID
"recordsTotal": 57,    // total number of records
"recordsFiltered": 57  // total number of filtered records

You can inspect this demo link and see response data this time.
3. Now changes are on serverside in your API
You need to add these parameters as queryParam for GET and attr in POST call in your controller API:
order: asc
start: 20
length: 10

4. Service Layer Changes - DB query
In-Service Layer where you get details from a database.
You need to get the total number of records and in search query pass a LIMIT clause LIMIT 10, 10 in case of MySQL.
E.g.:
SELECT * FROM User LIMIT 20,10;

Use start and length to calculate the next set of records.
It can be trickier but if you understand and implement properly it's fun.
Read more in detail here which also contains code and live demo.


text:
Q: Cast to bool: `!!` vs `(bool)` Is there any difference in using !!x vs (bool)x?
Assuming __STDC_VERSION__ >= 199901L and #include <stdbool.h>
Do both of them guarantee that the result is either 0 or 1, and that no overflow occurs, no matter the size and value of x?

A: !!x (in C, not C++) has type int. (bool)x (with <stdbool.h> included) has type _Bool.
While _Bools are quick to be promoted to ints, the two can be told apart from inside a _Generic.
!!x (or the equivalent 0!=x) will always be either 0 or 1 and (bool)x will always be either (bool)0 or (bool)1 and if it compiles (=doesn't violate any constraints) and x is defined, it will always be well defined.
Overflow in expressions like !!x+INT_MAX or (bool)x+INT_MAX (bool promoted to int) is still a concern.

References:
6.3.1.2: (_Bool)x <=> (_Bool)(0!=x)

1 When any scalar value is converted to _Bool, the result is 0 if the
  value compares equal to 0; otherwise, the result is 1.59)

(
6.2.5p18, 6.2.5p21 -- scalars are numeric types or pointers

Integer and floating types are collectively called arithmetic types.
  ...
Arithmetic types and pointer types are collectively called scalar
  types. ...
  )

6.5.3.3p5: !!x <=> 0!=x

The result of the logical negation operator ! is 0 if the value of its
  operand compares unequal to 0, 1 if the value of its operand compares
  equal to 0. The result has type int. The expression !E is equivalent
  to (0==E).


text:
Q: openid Authentication for multi domain website we have a website hosted in IIS, we have pointed the multiple domains to the same website.
like
www.exmple.com
www.example.in
www.wxaple.co.uk

and so on.
similarly, we have pointed more than 30 domains to this website.
Before there was no authentication on this website, now we need to implement authentication. so we have used OpenID connect and Azure AD for authentication.
https://learn.microsoft.com/en-us/azure/active-directory/azuread-dev/v1-protocols-openid-connect-code
This is working fine for one domain because we can configure the redirection URL for 1 domain. But how we can make sure this will work fine for all domains.
or any other approach to implementing this.

A: Though you have many domains in a website, when you login in your website the appId is the same. So, you could use the access token to request your domain website.
BTW, you need to add your domain into your Redirect Uri in App registered in your Azure AD.


text:
Q: Script to kill a specified process when it reached some % cpu I have an Ubuntu server 20. I am running 4 processes with the following names:
project-A
project-B
project-C
project-D

All is running good but some times I see one of the projects consuming CPU and reaches to 300%.
So I want script to kill (for example) "project-B" when it reaches 300% CPU.

A: The following script should kill any md5sum process which uses more than 50% CPU. Replace the md5sum and 50 as needed.
while true; do
    PID=$(pidof -s md5sum || cat /proc/sys/kernel/pid_max)
    if [[ $(ps -p $PID -o %cpu= |grep -Po '^\s*\K[0-9]+') -gt 50 ]]; then
        echo killing PID $PID
        kill $PID
    fi
    sleep 1
done

Notes:

*

*Try pidof -s your_process to make sure it works before replacing md5sum in the above script.

*If the above does not actually kill the process, it may be necessary to use the brute force kill -9 $PID instead of kill $PID, but only do this if the first method doesn't work.

*To do the above once (without a loop) in a single line:

PID=$(pidof -s md5sum || cat /proc/sys/kernel/pid_max); if [[ $(ps -p $PID -o %cpu= |grep -Po '^\s*\K[0-9]+') -gt 50 ]]; then echo killing PID $PID; kill $PID; fi

Explanations:

*

*while true; do ... sleep 1; done loop until ctrl-c is pressed; this also allows killing of multiple matching processes

*pidof -s md5sum || cat /proc/sys/kernel/pid_max first (-s) process id of an md5sum process, or a non-existent PID if there aren't any

*ps -p $PID -o %cpu= CPU utilization of the $PID process as a decimal percentage

*|grep -Po '^\s*\K[0-9]+' strip CPU percentage to an integer

*if [[ ... -gt 50 ]] if ... is greater than 50


text:
Q: Decompose into simple fractions over $\mathbb{C}$
Decompose into simple fractions over $\mathbb{C}$:
$$f(x) = \frac{1}{(x^2-1)^n}$$

I know how to decompose some fractions by $\mathbb{R}$, but I have no idea how analyze this over $\mathbb{C}$ and solve dependency from $n$.

A: $x^2-1 = (x+1)(x-1)$, so you want a partial fraction decomposition of the form
$$ \dfrac{1}{(x+1)^n (x-1)^n} = \sum_{j=1}^n \frac{a_j}{(x+1)^j} + \sum_{j=1}^n \frac{b_j}{(x-1)^j}$$
If $ t = x+1$, we have by the binomial series
$$ \frac{1}{t^n(t-2)^n} = (-1)^n \sum_{k=0}^\infty {k+n-1 \choose k} t^{k-n} 2^{-n-k} $$
so that $$a_j =(-1)^n {2n-1-j \choose n-j} 2^{j-2n},\ j=1 \ldots n$$
and similarly
$$b_j = (-1)^{n+j} {2n-1-j \choose n-j} 2^{j-2n},\ j=1 \ldots n$$

A: If, for instance, $n=3$, you can do it by writing $\frac1{(x^2-1)^3}$ as$$\frac{A_1}{x+1}+\frac{A_2}{x-1}+\frac{A_3}{(x+1)^2}+\frac{A_4}{(x-1)^2}+\frac{A_5}{(x+1)^3}+\frac{A_6}{(x-1)^3},$$This will lead you to the system$$\left\{\begin{array}{l}-A_1+A_2-A_3-A_4-A_5+A_6=1\\A_1+A_2+2A_3-2A_4+3A_5+3A_6=0\\2A_1-2A_2-3A_5+3A_6=0\\-2A_1-2A_2-2A_3+2A_4+A_5+A_6=0\\-A_1+A_2+A_3+A_4=0\\A_1+A_2=0.\end{array}\right.$$Its solution is$$A_1=-\frac3{16},\ A_2=\frac3{16},\ A_3=-\frac3{16},\,A_4=-\frac3{16},\ A_5=\frac18,\text{ and }A_6=-\frac18.$$


text:
Q: Only Allow Schema Change from Backendless Console I want to restrict creating or modifying the data model schema for backendless. Specifically, only want to create or modify the data model schema using the console.  The data model schema should not be modified using the API.
How can this be achieved?

A: It this point it can be achieved by you making sure that your code stays consistent and does not introduce new fields/properties. Adding a new field to a class and then saving an instance of the class with the API will result in a new column being created. So to avoid that make sure that your classes at any point of time represent the schema of the backend.


text:
Q: Erro na função jason_decode() Bem, estou fazendo uma página simples para consumir dados de uma api do wikipedia através de um pequeno formulário:
    <form action="" method="get">
    <input type="text" name="busca">
    <input type="submit" value="Busca">
</form>

<?php

    if($_GET['busca']){
        $api_url = "https://en.wikipedia.org/w/api.php?format=json&action=query&prop=extracts&titles=".ucwords($_GET['busca']).".redirects=true";
        $api_url = str_replace(' ', '%20', $api_url);

        if($data = jason_decode(file_get_contents($api_url))){
            foreach($data->query->pages as $key=>$val){
                $pageId =$key;
                break;
            }
            $conteudo = $data->query->pages->$pageId->extract;

            header('Content-Type:text/html; charset=utf-8');
            echo $content;
        }
        else{
            echo 'Nenhum resultado encontrado.';
        }
    }
?>

O php informa

Fatal error: Uncaught Error: Call to undefined function jason_decode()

Como podemos ver abaixo, a extensão json está funcionando:

Cheguei a achar que era por causa da verificação com IF, mas o erro persiste.

A: O correto é json_decode() e não jason_decode()


text:
Q: How to get a score of a Field on Zend Lucene I have something similar to the following code:
[...]
while($result=mysql_fetch_assoc($query)){
    //Build a doc
    $doc = new Zend_Search_Lucene_Document();

    [...]

    $doc->addField(Zend_Search_Lucene_Field::text('category', sanitize($result["category"])));
    $all_values=explode(',',$result["value"]);
    $i=0;
    foreach ($all_values as $value) {
        $doc->addField(Zend_Search_Lucene_Field::text('value_'.($i++), urlencode($value)));
    }

    [...]

    //Add to doc
    $index->addDocument($doc);
}
[...]

Now I would like to show only the field value_... which have the greater score after a search.
How could I do it?

A: After thinking a bit more on this, I've got a solution to my problem.
Zend Lucene orders the results by score and so, what I need to do is create a doc for each $value of the foreach loop and then, create an index for the ID of my current result (called res_id) that is inside of the foreach. This way, i can programatically show only one result of the same res_id after a search.
So my code becomes:
[...]
while($result=mysql_fetch_assoc($query)){
    $all_values=explode(',',$result["value"]);
    //Create a Doc foreach value of $all_values and gave them the same category of the result of the query
    foreach ($all_values as $value) {
        //Build a doc
        $doc = new Zend_Search_Lucene_Document();

        [...]

        //Added res_id just to help grouping the results
        $doc->addField(Zend_Search_Lucene_Field::unIndexed('res_id', sanitize($result["id"])));

        $doc->addField(Zend_Search_Lucene_Field::text('category', sanitize($result["category"])));
        //Renamed the field to value
        $doc->addField(Zend_Search_Lucene_Field::text('value', urlencode($value)));

        [...]

        //Add to doc
        $index->addDocument($doc);
    }
}
[...]

Now, when I make a search, I show only the first occurrence of res_id (the one that have more score).
Here's the code that I have on my Controller that sends to the view an array with the items and the total items found:
[...]
public function indexAction()
{
    $this->view->query=urldecode($this->_getParam("query"));
    if ($this->view->query){
        //open the index
        $index = new Zend_Search_Lucene('path/to/lucene/index');
        $hits = $index->find($this->view->query);
        $executed_ids=array();
        $total=0;
        $this->view->items=array();
        foreach ($hits as $hit) {
            //Pass item to view only if it is not listed yet on $executed_ids
            if (!$executed_ids[$hit->res_id]){
                $this->view->items[]=$hit;
                $executed_ids[$hit->res_id]=true;
                $total++;
            }
        }
        $this->view->total_hits=$total;
    }
}
[...]


text:
Q: Указание DataContext для ListBox ItemSourse, который находится внутри DataGrid ячейки Здравствуйте.
Имеется окно WPF MVVM. В окне находится DataGrid, одна из колонок грида содержит ListBox, данные которой должна предоставить ViewModel.
<DataGrid Name="OperativeScheduleTable"
          Grid.Row="1"
          ItemsSource="{Binding Path= OperativeSchedules}">
    <DataGrid.Columns>
        <DataGridTextColumn Width="Auto"
                            Binding="{Binding Path=Id}"
                            Header="Id"
                            IsReadOnly="True"/>
        <DataGridTemplateColumn Header="Станция отправления">
            <DataGridTemplateColumn.CellTemplate>
                <DataTemplate>
                    <ListBox ItemsSource="{Binding Path=Stations}" Padding="5">
                        <ListBox.ItemTemplate>
                            <DataTemplate>
                                <StackPanel Orientation="Horizontal">
                                    <TextBlock Width="50" Text="{Binding Path=Name}" />
                                </StackPanel>
                            </DataTemplate>
                        </ListBox.ItemTemplate>
                    </ListBox>
                </DataTemplate>
            </DataGridTemplateColumn.CellTemplate>
        </DataGridTemplateColumn>
    </DataGrid.Columns>
</DataGrid>

ViewModel:
public class RailwayStationEditViewModel : Screen
{
    private readonly IUnitOfWork _unitOfWork;

    public RailwayStation RailwayStations { get; private set; }

    public ObservableCollection<Station> Stations { get; set; }  //Сюда нужно Байндится!!!

    public RailwayStationEditViewModel(IUnitOfWork unitOfWork, RailwayStation railwayStation)
    {
        _unitOfWork = unitOfWork;

        RailwayStations = railwayStation;
        Stations = new ObservableCollection<Station>(RailwayStations.Stations.ToList());
    }
}

Необходимо указать скорее всего через DataContext:
 <ListBox ItemsSource="{Binding Path=Stations, указать что коллекция находится во ViewModel}" Padding="5">

А сейчас поиск коллекции Stations осуществляется в элементе OperativeSchedules (байндинг DataGrid)

A: Дайте имя окну Window у которого ViewModel в котором находится Stations.
Дальше привязывайтесь так:
<ListBox ItemsSource="{Binding DataContext.Stations, ElementName=имяОкна}"/>


text:
Q: convergence of integrals to 0 Let $\Omega \subset R^n$ be  a domain.
It is given that $\lim_{n \to \infty}\int_{K}|f_n|=0  $ for every compact set $K \subset \Omega$
$|f_n|$ are bounded by some integrable function $g$ on $\Omega$
Can I say that $\lim_{n \to \infty}\int_{\Omega}|f_n|=0  $ ?

A: Since $\Omega$ is a domain in $\Bbb{R}^n$ (which I assume implies at least that $\Omega$ is open), we have $\Omega = \bigcup_n K_n$ for suitable compact subsets $K_n \subset \Omega$. By switching to $K_1 \cup \dots \cup K_n$ instead of $K_n$, we can also assume $K_n \subset K_{n+1}$.
Since $g$ is integrable on $\Omega$, we have (by dominated convergence) that
$$
\int_{\Omega \setminus K_n} |g| \, dx \xrightarrow[n\to\infty]{}0.
$$
So for $\epsilon > 0$, we can choose some $N$ with $\int_{\Omega \setminus K_N} |g| \, dx < \epsilon$.
All in all, we get
$$
\int_\Omega |f_n| \, dx = \int_{K_N} |f_n| \, dx + \int_{\Omega \setminus K_n} |f_n| \, dx \leq \int_{K_N} |f_n| \, dx + \int_{\Omega \setminus K_N} |g| \, dx < \int_{K_N} |g| \, dx + \epsilon \to \epsilon,
$$
as $n\to \infty$.
Since $\epsilon > 0$ can be chosen arbitrarily, it is not hard to see that this implies $\int_\Omega |f_n| \, dx \to 0$.


text:
Q: Flac playback in Iceweasel Which package provides Flac support in Iceveasel on Debian Wheezy? At http://hpr.dogphilosophy.net/test/ all test clips work except the Flac file.

A: As far as I or anyone here or in newsgroup linux.debian.user know there is no such package in the Debian Wheezy repositories.


text:
Q: eyefi-config with 2GB eyefi card? So I bought a $7 Eye-Fi card.  After all, there's a linux config utility and a standalone linux server, so the fact that Ricoh has killed their cloud server shouldn't really matter, right?
Apparently it does matter.
Even after finding a hidden mailing-list post detailing how to setup the virgin card such that eyefi-config can find it (see answer below), it is still unable to find the local server.
I've got the server on the local segment, even connecting by wifi on the same access point.  The server is exposed to the network, I can telnet to port 59278 from another host on the same network.
But mysteriously, the card can't find the server in test mode, never attempts to access it (according to the server log) and even the card's log never shows an attempted upload.
Any suggestions are appreciated... but for now, this card is going into the long-term storage bin.

A: Partial answer (still not working)
The author of eyefi-config had a mailing list about it for a while.  Deep in the mailing list, I found a post detailing the procedure for the similar X2 card.
Basically, the answer is to create the following files:
cd /media/NAME_HERE_OF_CARD
mkdir -p EyeFi
dd if=/dev/zero bs=16384 count=1 of=EyeFi/reqm
dd if=/dev/zero bs=16384 count=1 of=EyeFi/reqc
dd if=/dev/zero bs=16384 count=1 of=EyeFi/rspm
dd if=/dev/zero bs=16384 count=1 of=EyeFi/rspc

The rest of the setup procedure appears to be what's detailed in the README.
I don't actually have it working yet, but until I have further evidence, I'm blaming that on the server.


text:
Q: Mybatis returning different class T I would like to know if there's any way that I can make Mybatis Interface return different class.
I'am using @SelectProvider to create the sql;
It would be like next:
public interface DaoTemplate<T extends Common> {

  @SelectProvider(method = "findById", type = DaoTemplateImpl.class)
  public T findfindById(T bean);

}

A: As far as I understand the requirement, it looks like something I have done for my app:
I have defined a common generic mapper interface:
public interface DataMapper<F, D> {
    List<D> list(@Param("filter") F filter);
    D getById(@Param("filter") F filter);
Then the "concrete" mapper does not need to declare the methods:
public interface OrderMapper extends DataMapper<OrderFilter, OrderDto> {}
But The SQL is defined in XML files (1 for each concrete mapper), cannot be done in @Select or @SelectProvider annotations because the SQL has to change for each type, and variable cannot be used because annotation property values are resolved on compile time.


text:
Q: How to automate sftp and remote shell calls? I am on windows and I have remote linux server. I do not have admin access to neither of them. I have following set of steps/commands
cp C:/ ... /file.war C:/temp/update/file.war
sftp server
write password
cd /tmp
put file.war
exit
ssh server
write password
chmod 755 /tmp/file.war
pbrun -u server_user bash
cd /tomcat_location/webap
rm -r file
rm file.war
cp /tmp/file.war file.war
ps -ax | grep tomcat
kill -9 tomcat_pid
cd /tomcat_location/commands
./startup.sh

If I would be doing all of that locally. I would easilly write shell/bash script for it. But I am on two different computrers. The password is the same all the time. The pbrun is command to switch users using my own password.
Is there some simple way how to transform this to single script? Which would ask for the password and do all the steps automatically. Or at least to the part where the tomcat is being restarted (sftp, chmod, removing and copig part)? I am not able to install any new software. I have java 8 and perl installed on my local pc.
I tried a few things with perl exec but I do not know how to keep state of its cmd. It would be nice if the result would be as close to the original commands as possible.

A: First, figure out which commands do something on their own, and which ones need sub-commands being passed as input. For example, sftp is in the latter category – everything below "sftp server" and up to "exit" is not a separate top-level command, but merely input to stdin of the 'sftp' process.
So in your script, there are really just 3 commands to be executed: the cp, the sftp, and the ssh. Everything else is text to be fed to their standard input (stdin).

*

*In Bash scripts, you would most commonly use "heredoc" <<EOF to pass multiple lines of text to a program's stdin (although other methods are possible).

*In Perl scripts you can use open() to start a process – look up what the "-|" and "|-" special MODE values do in perldoc -f open (section "Opening a filehandle into a command").

*And in Java, from a quick google, when you start a process through Runtime.exec(), the resulting Process object has the confusingly named .getOutputStream() which allows you to write to its stdin.
(And even within the commands run through ssh, technically there's another layer of the same – when you start bash through pbrun, it also takes further commands through stdin, so you could use another << there as well, but it might not be necessary. I would still try to automate this "inside-out", i.e. first turn the pbrun part into a script that's being run on the server.)
The password prompt of both sftp and ssh is an exception, in that it specifically deals with interactive keyboard input even if stdin comes from some other source. To avoid the password prompt, ideally you would set up an authentication method that doesn't involve passwords, namely public-key auth – this is supported by all SSH clients and servers, and does not need any sort of admin privileges on either side (unless someone deliberately disabled it). Look up ssh-keygen and authorized_keys.
(Normally I'd also suggest OpenSSH's built-in "connection multiplexing" feature, i.e. -o ControlPath=... and related options, but you're using Windows and I'm not sure whether this feature is available on the Windows builds of OpenSSH. However, if it does work, then it would also allow you to start a single "background" connection, enter the password once, then run both SFTP and shell over that connection.)
There's also another way to approach this. Your goal isn't to "run the sftp command" – your goal is to upload a file using the SFTP protocol, and you don't need the sftp command for that. You can instead directly use an SSH/SFTP client module for Perl or Java – then you can develop the deployment tool like you're developing the application itself.
(For Java, sshj appears to be a popular one, while JSch is getting slightly out-of-date. Perl has Net::SSH2 which might be difficult to install on Windows.) Most of them will even allow you to use both SFTP and shell commands over the same SSH connection.


text:
Q: Android Video View turns black This seems to be a very common problem, but I couldn't search for it on SO.
I have a simple videoview and it play video from a mp4 file. It continously plays video and loop through the video.
Problem is when playing I went to settings and came back then video turns black.
This is my Code:
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_video);
    video = (VideoView) findViewById(R.id.video);
    // Load and start the movie
    Uri video1 = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.videoplayback);
    video.setVideoURI(video1);
    video.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
        @Override
        public void onPrepared(MediaPlayer mp) {
            mp.setLooping(true);
        }
    });
    video.start();

I don't want anything special in this, just a full screen of video playback which loops video till user tap back button.

A: try this
private int stopPosition;
   private VideoView splashVideoView;  <-- my Video view

in onCreate
 //video player

    if (savedInstanceState != null) {
            stopPosition = savedInstanceState.getInt("position");
        }

  @Override
    protected void onResume() {
        super.onResume();
        splashVideoView.seekTo(stopPosition);
        splashVideoView.start();
    }

// This gets called before onPause so pause video here.
    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        stopPosition = splashVideoView.getCurrentPosition();
        splashVideoView.pause();
        outState.putInt("position", stopPosition);
    }

A: try this
  private int videoViewStopPosition ;

   @Override
    protected void OnPause(){
    super.onPause();
    videoViewStopPosition = vidView.getCurrentPosition();
    vidView.pause();
    }

  @Override
    protected void OnResume() {
     super.onResume();
     vidView.seekTo(videoViewStopPosition);
     vidView.start();

    }

A: I had the same issue. I found that the main reason for that was the use of FrameLayout as the parent layout. I changed it into RelativeLayout as parent layout of the VideoView and the problem get solved.

A: You need to create Video view in onResume() also. Try this:
    protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_video);

        setVideoBackground();
    }

    @Override
    protected void onResume() {
      super.onResume();

        setVideoBackground();
    }

   private void setVideoBackground(){
       video = (VideoView) findViewById(R.id.video);
       // Load and start the movie
       Uri video1 = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.videoplayback);
       video.setVideoURI(video1);
       video.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
       @Override
       public void onPrepared(MediaPlayer mp) {
       mp.setLooping(true);
    }
  });
       video.start();
}


text:
Q: Dual NON-APPLE Monitors on Macbook Pro w/ Thunderbolt
Possible Duplicate:
Macbook Pro Dual Monitors
Dual-Monitor Output from a new Macbook Pro

I've seen many questions posted here about how to setup a dual display on a MBP, and the answers all cite Thunderbolt as the best option for image quality.
My MBP has a Thunderbolt port and currently I'm using it with a mini-DP to DVI converter into a single 24" HP monitor.  I'd like to buy a second, 24" monitor and use them side-by-side.  I've read that this can be done by "chaining", but I'm unclear on the requirements for this.  Is that feature ONLY available through displays that have a built-in Thunderbolt hub?  And, are the only monitors with this feature made by Apple?
I'd hate to get the second monitor only to find out that I am limited to using it over USB and with some sub-par resolution. And I don't want to spend $999 on an Apple display :)


text:
Q: JMeter ForEach Controller transaction name with multiple iteration Im using JMeter foreach controller and depending on the list of values the transactions names are updated.
Problem is transaction names are starting from the point where iteration:1 is ended.
But i want the value to ** restart ** every iteration.
screen1:

Screen2:

Screen3:

Screen4:

A: You can remove your Beanshell Sampler and get current iteration number as
${__jm__ForEach Controller__idx}

More information:

*

*Bug 61802 - Loop / ForEach Controller should expose a variable for current iteration

*What's New in JMeter 4.0?

Also be aware that according to JMeter Best Practices you should:

*

*Always use the latest version of JMeter

*Switch to JSR223 Test Elements and Groovy language for scripting

A: Instead of User Defined Variables, set val variable in User Parameters and check Update Once Per Iteration:

Update Once Per Iteration A flag to indicate whether the User Parameters element should update its variables only once per iteration

This way it'll update val with 0 every iteration and not only once.


text:
Q: CoreData many to many relationship insert and delete operations I have a question about CoreData relationships.
I have this situation:
I have DOG and BONE entity.

*

*Each DOG can have more BONE.

*Each BONE can have more DOG.

So I need a many to many relationship.
how do I set the report delete in CoreData? what kind?
I think I need something as this:

*

*When I delete a BONE I do not have to remove the DOG;

*When I delete a DOG I do not have to remove the BONE if this is used from a DOG.

*When I delete a DOG I have to remove the BONEs if these are used only from this DOG.

Is this mechanism automatic for CoreData if I impose this relationship type?
About insert?
For example: I need to insert a DOG with some Bones: How do I check if the bone already exists?
Every bone in my table has an ID

A: First of all, it is difficult to get a handle on your example as it doesn't make intuitive sense. That being said, ignoring the entity type, if you have an entity A and B with a mutual to-many relationship (many-to-many).
Apple: Relationships and Fetched Properties
(for the sake of brevity assume 'entity' = 'entity instance' below)
To Insert:

*

*You must insert both entity A and insert entity B. Core data will not
automagically create entity B if you create entity A, just because they have a relationship

*If you wish to associate an existing entity B to a new entity A, then
you must insert entity A then link entity A to entity B via the
relationship. Just because you defined the relationship in the object model, doesn't mean the objects will be automagically related when you insert them. you need to explicitly do this

To Delete:

*

*Coredata will allow you to set the 'relationship delete rules'. This will govern what happens when you delete an object on one end of the relationship. You must set the rules on each end as you may choose to delete either entity A or entity B. Delete rules include: deny, nullify, cascade, no action. Check out Apple's doc on this to get you question above answered (it is clear).

*To apply your example to the delete rules:

When I delete a BONE I do not have to remove the DOG; (no action)
When I delete a DOG I do not have to remove the BONE if this is used from a DOG. (deny or nullify)
When I delete a DOG I have to remove the BONEs if these are used only from this DOG. (cascade)


text:
Q: How do i best handle custom plugin page actions? I'm constantly running into the same annoyance, so i thought i'd see if there's any ideas or experience out there...
I've created a plugin that uses it's own admin page. It has to. Now that i sorted out the WP_List_Table() stuff, i must say it's great...but....
Custom plugin pages always load as admin.php?page=... unless i want to load them from the plugin directory directly, which i don't. Now if i do an 'action' from that page, i need to process that somehow and then redirect back to the page without the action parameter. No matter if i do a GET or POST, really.
On all it's internal pages WP does this on the same page, it checks if there's an action, if so processes it and then redirects to itself without the action. This is possible, because on these pages the admin-header hasn't been loaded, yet.
If you try doing it on your own page, though, half the admin interface has already been sent to the browser, so a redirect isn't possible anymore. Clearly, the solution is to POST/GET directly to another page, load the WP framework on that, do the processing and then redirect back to the original page...but...that's a bit annoying, because...my original page is loaded via a callback, so it runs within a method of my class. That's beautiful.
If i load a separate page, i have to manually include wp-load.php and am outside of my class, which is annoying, and in my particular case bugs me especially, because i'm only instanciating my plugin class anonymously so that no-one can access it from the outside.
So after this long story...did anyone come up with a good solution to load another page via a callback without having the whole admin interface already setup around it?
(I know of a workaround...i can hook a function into load-.... that checks for the action parameter and does the processing and redirect. But i'm wondering if there's a better way.)
Thanks.

A: As a rule of thumb, you should use a POST request for most actions, to make sure they are not executed by accident. But it is also a good practice to redirect to a normal page after a POST request, to prevent duplicate execution when the user refreshes the page.
So the flow is like this:

*

*Your plugin page with a POST form, which submits to

*A page that handles the request, which redirects to

*Your plugin page, which shows the result of the action

The middle page doesn't have to be your plugin page. This means that you can use the "generic POST handler" that was included three years ago, the 'admin_action_' . $_REQUEST['action'] hook in admin.php.
An example user is the Akismet plugin. If you want to use it reliably, you have to submit to admin.php directly, not to another page that happens to include admin.php.
Here is a very basic example of how to use it:
add_action( 'admin_action_wpse10500', 'wpse10500_admin_action' );
function wpse10500_admin_action()
{
    // Do your stuff here

    wp_redirect( $_SERVER['HTTP_REFERER'] );
    exit();
}

add_action( 'admin_menu', 'wpse10500_admin_menu' );
function wpse10500_admin_menu()
{
    add_management_page( 'WPSE 10500 Test page', 'WPSE 10500 Test page', 'administrator', 'wpse10500', 'wpse10500_do_page' );
}

function wpse10500_do_page()
{
?>
<form method="POST" action="<?php echo admin_url( 'admin.php' ); ?>">
    <input type="hidden" name="action" value="wpse10500" />
    <input type="submit" value="Do it!" />
</form>
<?php
}

A: I approached this slightly differently by simply adding noheader=true to the action url on the page where the user submits takes the action
My handler then performs the action (ie. typically an add, update or delete) then finisheswith a wp_redirect() to the next page action (e.g add page -> edit page, delete page -> list page, edit page -> edit page). I also pass a message on the URL so I can displayed a status such as update successfully or failed.
This approach keeps all the actions: list, add, edit, delete, bulk-delete, etc in the same class and with the same admin slug so it is pretty easy to maintain and to understand.

A: Another different approach is just adding a hidden input field to the form:
<input type="hidden" name="page" value="your-page-slug" />

This way, WordPress seems to handle the redirect automatically.


text:
Q: Configure LeftHand iSCSI SAN for jumbo frames after clients are configured This is similar to enabling jumbo frames on an iSCSI network after the fact but in our case we configured the switches and then went through all the hosts, enabling jumbo frames (we may have screwed ourselves here).  The SAN is a Lefthand (actually 2 SANs mirrored).  So the plan is to configure one of the SANs for jumbo frames, bring it back on line, wait for replication and then do the same with the other SAN.  Are we in for a world of hurt with one SAN having jumbo enabled and the other not yet configured while we wait for SAN replication?  Of course all of this has to be done live.  Should we go through the pain of resetting all the hosts back to 1500 MTU and then configure the SANs for jumbo first?
Some clarifying info.  Each SAN device is connected to two dedicated switches (each SAN has two nics).  The switches have an ether channel link between them.  The SANs have MPIO configured.  Each host has two nics configured for the SAN network connected to each switch (full mesh configuration).
UPDATE:  It worked.  When taking the second SAN offline all the hosts experienced problems connecting to the SAN for about a minute (very scary), but they all came back except for our OCS server which we had to reboot.

A: Answering my own question here in the hopes it will help others.  We did this today and I have to say the pucker factor was pretty high:)  Changing the first SAN to jumbo had no problems at all.  When we broke the MPIO on the second SAN all the hosts got very angry (stopped responding) and it took about a minute for them to recover.  Our Office Communications Server 2007R2 refused to play ball and required a reboot.  Other than that it worked but I'm thinking next time (never will happen now that I know to configure jumbo before going live) I'd rather do the hosts last because then we just worry about a single host at a time.


text:
Q: Applescript doesn't work on OSX startup I wrote my applescript app to hide the window of my wifi card.
I ran into some problem checking if the window is visible or not (to avoid the command+h keypress have no effect), so I decided to use a delay 15 to make (not at all) sure the window pops up. If I run the script from the editor or by double-click on the app file, it works, but if I set it to start at the login of the user (under Settings>Account>Login Elements), it doesn't work!
I tried to change the checkbox in the Save as... page of applescript editor: I tried both setting for only execute, but anything change.
With the start screen option in fact it works, but it ask me a confirmation and I don't want it (I'll prefere to press cmd+h instead).
Anyone can explain me why I have this issue?
tell application "System Events"
set progList to (name of every process)
set cond to false
repeat while cond is false
    if (progList contains "WirelessUtilityCardbusPCI") is true then
        delay 5
        activate application "WirelessUtilityCardbusPCI.app"
        tell application "System Events" to keystroke "h" using [command down]
        set cond to true
    else
        delay 5
        set progList to (name of every process)
    end if
end repeat
end tell

EDIT: Now it seems to work! I forgot to re- set progList to (name of every process). Now the code is correct.

A: I see your code is working. That's great. However I'm posting this to help you learn. I see a couple small issues with your code. For example in your repeat loop you tell system events to keystroke "h". There's no need to tell system events to do that in that line because you're already in a system events tell block of code, so system events already knows to do that.
Here's how I would write your code. This doesn't require keystrokes, which is always a good thing, and is a little more efficient. It works because if the process doesn't exist then the "set theProcess to" line errors, the code then goes into the "on error" section to delay 5, then the repeat loop tries to find the process again. If the process is found then it sets its visible property which is the same as hiding it.
It also has a timeout mechanism to prevent the script from running forever. Use this if you like. Good luck.
set processName to "WirelessUtilityCardbusPCI"
set maxTime to 180 -- we only check for 3 minutes, then end

set inTime to current date
repeat
    try
        tell application "System Events"
            set theProcess to first process whose name is processName
            set visible of theProcess to false
        end tell
        exit repeat
    on error
        if (current date) - inTime is greater than maxTime then
            tell me
                activate
                display dialog "The process " & processName & " could not be found!" buttons {"OK"} default button 1 with icon 0
            end tell
            exit repeat
        end if
        delay 5
    end try
end repeat

EDIT: I have checked the above code using the TextEdit application and it works fine. To check it with your application run the following. Make sure the application is running when you run this code. If there's an error this will display it. If there's no error 2 dialogs will display showing the progress. Report what you find.
set processName to "WirelessUtilityCardbusPCI"

try
    tell application "System Events"
        set theProcess to first process whose name is processName
        display dialog "I have found the process"
        set visible of theProcess to false
        display dialog "I just performed the \"set visible\" code"
    end tell
on error theError number errorNumber
    tell me
        activate
        display dialog "There was an error: " & (errorNumber as text) & return & return & theError buttons {"OK"} default button 1 with icon stop
        return
    end tell
end try

A: I have used the Login Items to launch an AppleScript applet at login with success, so my first suggestion is to make sure that it's not running. Have it show a custom dialog or beep or something like that to confirm whether it's running or not.
Other than that, I'm not sure what suggestion to offer unless you'd like to post the code you're executing in the script.


text:
Q: Laravel 5.8: parse_url() expects parameter 1 to be string, array given I want to insert some data into the DB like this via Eloquent:
public function postDarkhast(Request $request)
    {
        RequestTable::create([
            'course_name' => 1,
            'course_start' => 2,
            'course_end' => 3,
            'course_sessions' => 4,
            'course_time' => 5,
            'course_members' => 6,
            'course_mentor' => 7,
            'course_samaneh' => 8,
        ]);

        Session::flash('darkhastSubmitted','Request submitted');

        return redirect()->back();
    }

But I don't know why I get this error:
parse_url() expects parameter 1 to be string, array given
I don't know where this parse_url() comes from and the reason behind this error.
So if you know, please help me out solving this issue?
Here is also the Model RequestTable:
class RequestTable extends Model
{
    protected $table = "requests";
    protected $guarded = [];
}

And the fields of requests table has this config:
varchar(191)    utf8_general_ci   NULL

UPDATE #1:
I put the RequestTable::create([...]); in a Try.. Catch and this error return:

A: It looks like you are importing theRequest from Symfony's HttpFoundation instead of Illuminate. Please try importing the Request at the top like: use Illuminate\Http\Request;.
Looking at your error, I believe you are importing the Symfony\Component\HttpFoundation\Request instead.


text:
Q: PHP SSL certificate digest I'm not a very experienced PHP developer but I have been given the task to check the digest of an x509 certificate. I know that for PHP 5.6 there is a function called openssl_x509_fingerprint() but I need to display the digest on a PHP 5.3 server. Is there an older or alternate function for this one?
Thanks,
taiBsu

A: http://php.net/openssl-x509-certificate . Doesn't look like the function that you're thinking is in 5.6 actually is.
Anyway, using phpseclib, you could do this:
<?php
include('File/X509.php');

$x509 = new File_X509();
$result = $x509->loadX509(...);
echo $result['signature'];


text:
Q: C# compiler doesn't optimize unnecessary casts A few days back, while writing an answer for this question here on overflow I got a bit surprised by the C# compiler, who wasn't doing what I expected it to do. Look at the following to code snippets:
First:
object[] array = new object[1];

for (int i = 0; i < 100000; i++)
{
    ICollection<object> col = (ICollection<object>)array;
    col.Contains(null);
}

Second:
object[] array = new object[1];

for (int i = 0; i < 100000; i++)
{
    ICollection<object> col = array;
    col.Contains(null);
}

The only difference in code between the two snippets is the cast to ICollection<object>. Because object[] implements the ICollection<object> interface explicitly, I expected the two snippets to compile down to the same IL and be, therefore, identical. However, when running performance tests on them, I noticed the latter to be about 6 times as fast as the former.
After comparing the IL from both snippets, I noticed the both methods were identical, except for a castclass IL instruction in the first snippet.
Surprised by this I now wonder why the C# compiler isn't 'smart' here. Things are never as simple as it seems, so why is the C# compiler a bit naïve here?

A: This is a rough guess, but i think it's about the Array's relationship to its generic IEnumerable.

In the .NET Framework version 2.0, the
  Array class implements the
  System.Collections.Generic.IList,
  System.Collections.Generic.ICollection,
  and
  System.Collections.Generic.IEnumerable
  generic interfaces. The
  implementations are provided to arrays
  at run time, and therefore are not
  visible to the documentation build
  tools. As a result, the generic
  interfaces do not appear in the
  declaration syntax for the Array
  class, and there are no reference
  topics for interface members that are
  accessible only by casting an array to
  the generic interface type (explicit
  interface implementations). The key
  thing to be aware of when you cast an
  array to one of these interfaces is
  that members which add, insert, or
  remove elements throw
  NotSupportedException.

See MSDN Article.
It's not clear whether this relates to .NET 2.0+, but in this special case it would make perfect sense why the compiler cannot optimize your expression if it only becomes valid at run time.

A: My guess is that you have discovered a minor bug in the optimizer. There is all kinds of special-case code in there for arrays. Thanks for bringing it to my attention.

A: This doesn't look like more than just a missed opportunity in the compiler to suppress the cast.  It will work if you write it like this:
    ICollection<object> col = array as ICollection<object>;

which suggests that it gets too conservative because casts can throw exceptions.  However, it does work when you cast to the non-generic ICollection.  I'd conclude that they simply overlooked it.
There's a bigger optimization issue at work here, the JIT compiler doesn't apply the loop invariant hoisting optimization.  It should have re-written the code like this:
object[] array = new object[1];
ICollection<object> col = (ICollection<object>)array;
for (int i = 0; i < 100000; i++)
{
    col.Contains(null);
}

Which is a standard optimization in the C/C++ code generator for example.  Still, the JIT optimizer can't burn a lot of cycles on the kind of analysis required to discover such possible optimizations.  The happy angle on this is that optimized managed code is still quite debuggable.  And that there still is a role for the C# programmer to write performant code.