text:
Q: LoadIFilter() fails on all PDFs (but MS's filtdump.exe doesn't.) I'm trying to write a C# utility that mimics the behavior of filtdump.exe from the Windows Search SDK (since filtdump doesn't appear to be redistributable itself.) I'm running into a combination of contradictory and/or non-existent documentation and technical problems I can't seem to track down. I'm hoping someone can help eliminate one or the other of those hurdles...
According to MSDN, filtdump uses ILoadFilter::LoadIFilter to load it's IFilter. I contend that MSDN is lying, since it also claims ILoadFilter::LoadIFilter only exists on Windows 7, but filtdump works fine on earler OS's. Process Monitor indicates that it's actually calling LoadIFilter() from query.dll, so that's what I'm doing:
public static class NativeMethods
{
    // From Windows SDK v7.1, NTQuery.h
    [DllImport("query.dll", CharSet = CharSet.Unicode)]
    public static extern int LoadIFilter(
        string pwcsPath,
        [MarshalAs(UnmanagedType.IUnknown)]
        ref object pUnkOuter,
        ref IFilter ppIUnk);
}

object iUnknown = null;
IFilter filter = null;
var result = NativeMethods.LoadIFilter(args[0], ref iUnknown, ref filter);
if (result != ResultCodes.S_OK)
{
  Console.WriteLine("Failed to load an IFilter for {0}: {1}", args[0], result);
  return;
}

For the most part, this application and filtdump give me the same results -- they can both open and extract text from text, Word document, and Outlook emails, and both fail on the same set of other documents that have no IFilter. However, PDFs are giving me a problem. Filtdump manages to open and extract the text from most of the PDFs I've thrown at it, but every single one of the PDFs I try with my own application gives me an HRESULT of 0x80004005, E_FAIL.
This is the same error from this question but I'm getting it on every PDF, and filtdump is not, so I know that the IFilter is working on at least some documents. Has anyone done this kind of thing before with PDFs that can see what I'm doing wrong?

A: You may want to see this blog post. In short, v10 of Adobe's PDF filter uses a whitelist of applications allowed to use the filter, including Microsoft's diagnostic tools like filtdump.exe, supposedly as a "security measure".

A: Load IFilter fails because Adove PDF Filter is marked as STA and our c sharp application are by default MTA so that is why it can not load PDF Filter. Try to make your application STA then load PDF Filter.
Ajax

A: I also expect filtdump is using the old Win32 LoadIFilter call which was available from Windows 2000.
I've seen the same problem as you solved by running the calling process in a job. https://stackoverflow.com/a/8841476/1111659.
I also got a similar problem with Reader 10.1.5 installed although the Win32 LoadIFilter() returned E_NOTIMPL not E_FAIL.
Seems like Adobe broke the standard Win32 LoadIFilter() call by removing the ability to load the content into the IFilter via the IStorage interface's Load method but the object still returns that interface as available via QI.
For that problem on Windows 7 and later you can create the FilterRegistration object which implements the ILoadFilter and then call ILoadFilter::LoadIFilter() to create the filter COM object. Then get the IPersistStream and call Load() on that with an IStream containing the file content.
For older versions you need to search for the Filter CLSID in the registry first or statically set the Adobe CLSID as a config value if you want to make it constant.


text:
Q: Ternary expression with a javascript object Let's say I have the following javascript object:
var __error__ = {0: 'ok'}

I want to return an empty string if the key is not in the obj, and an error message otherwise. For example:
var value = __error__[col_num] ? "The value cannot be converted" : ""

How could this be done with a ternary expression properly? Do I need to do __error__[col_num] == undefined ? Or does the above expression evaluate to false by itself?

A: If you only want to check if they key exists in the object and not that the troothy of the value is false you should use the in operator
var value = col_num in __error__ ? "The value cannot be converted" : ""

You can also use Object.hasOwnProperty which returns true only if the object has that property (will return false if the property was inherited).
Here are a couple of examples to illustrate the differences

var parent = {
  foo: undefined
};

var child = Object.create(parent);

console.log("foo" in parent); // parent has the "foo" property
console.log("foo" in child); // child has the "foo" property

console.log(parent.hasOwnProperty("foo")); // parent has the "foo" property
console.log(child.hasOwnProperty("foo")); // child has the "foo" property but it belonds to parent

console.log(child.foo !== undefined); // the foo property of child is undefined
console.log(!!child.foo); // the troothy of undefined is false

console.log(parent.foo !== undefined); // the foo property of parent is undefined
console.log(!!parent.foo); // the troothy of undefined is false

A: You can also use hasOwnProperty which returns a boolean indicating whether the object has the specified property

var __error__ = {
  0: 'ok'
}

var value = __error__.hasOwnProperty(1) ? "The value cannot be converted" : "Empty";
console.log(value)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Portrait Camera Images when Uploaded via Library rotates in ImageView Android In my Android App, I have an option where a user can take his photograph or upload an image from his Gallery at the time of registration. This image, once successfully taken by camera or selected from Gallery, is shown in an ImageView. Below is the onClick of ImageView code that starts this process.
This is from Activity Layout.
<ImageView
        android:id="@+id/imgUserImage"
        android:layout_width="150dp"
        android:layout_height="150dp"
        android:scaleType="centerCrop"
        android:onClick="changePicture"
        app:srcCompat="@drawable/profile_image_not_provided"
        android:layout_below="@+id/textView2"
        android:layout_alignParentEnd="true"
        android:layout_marginTop="10dp" />

This is from Activity.java
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    ImageView imgProfilePicture = (ImageView)findViewById(R.id.imgUserImage);

    int exif_orn_a;

    if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
        Bitmap mphoto = (Bitmap) data.getExtras().get("data");

        Uri selectedImage = data.getData();
        imgProfilePicture.setImageURI(selectedImage);

        imgProfilePicture.setImageBitmap(mphoto);

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        mphoto.compress(Bitmap.CompressFormat.JPEG, 100, baos); //bitmap is required image which have to send  in Bitmap form
        byte[] byteArray = baos.toByteArray();

        encodedImage = Base64.encodeToString(byteArray, Base64.DEFAULT);
    }
    else if (requestCode == PICK_IMAGE_GALLERY) {
        Uri selectedImage = data.getData();

        String[] orientationColumn = {MediaStore.Images.Media.ORIENTATION};

        Bitmap lphoto = null;

        Cursor cur = this.getContentResolver().query(selectedImage, orientationColumn, null, null, null);

        int orientation = -1;

        if (cur != null && cur.moveToFirst()) {
            orientation = cur.getInt(cur.getColumnIndex(orientationColumn[0]));

            Toast.makeText(Register.this, "Picture Orientation "+orientation, Toast.LENGTH_LONG).show();
        } else {
            Toast.makeText(Register.this, "Wrong Orientation", Toast.LENGTH_LONG).show();
        }

        if (cur != null) cur.close();

        try {
            lphoto = MediaStore.Images.Media.getBitmap(this.getContentResolver(), selectedImage);

            imgProfilePicture.setImageURI(selectedImage);

            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            lphoto.compress(Bitmap.CompressFormat.JPEG, 100, baos); //bitmap is required image which have to send  in Bitmap form
            byte[] byteArray = baos.toByteArray();

            encodedImage = Base64.encodeToString(byteArray, Base64.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

I have managed to get the Orientations properly. Now the problem is, how should I rotate the image before imgProfilePicture.setImageURI(selectedImage);.

A: I managed to find the solution. Please feel free to post a better solution, if you think this can be improvised.
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        ImageView imgProfilePicture = (ImageView)findViewById(R.id.imgUserImage);

        int exif_orn_a;

        if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
            Bitmap mphoto = (Bitmap) data.getExtras().get("data");

            Uri selectedImage = data.getData();
            imgProfilePicture.setImageURI(selectedImage);

            imgProfilePicture.setImageBitmap(mphoto);

            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            mphoto.compress(Bitmap.CompressFormat.JPEG, 100, baos); //bitmap is required image which have to send  in Bitmap form
            byte[] byteArray = baos.toByteArray();

            encodedImage = Base64.encodeToString(byteArray, Base64.DEFAULT);
        }
        else if (requestCode == PICK_IMAGE_GALLERY) {
            Uri selectedImage = data.getData();

            //Starting from here, I am checking the Orientation and storing the result in orientation variable.
            String[] orientationColumn = {MediaStore.Images.Media.ORIENTATION};

            Bitmap lphoto = null;

            Cursor cur = this.getContentResolver().query(selectedImage, orientationColumn, null, null, null);

            int orientation = -1;

            if (cur != null && cur.moveToFirst()) {
                orientation = cur.getInt(cur.getColumnIndex(orientationColumn[0]));

                Toast.makeText(Register.this, "Picture Orientation "+orientation, Toast.LENGTH_LONG).show();
            } else {
                Toast.makeText(Register.this, "Wrong Orientation", Toast.LENGTH_LONG).show();
            }

            if (cur != null) cur.close();
            //This is the end of Orientation Check.

            try {
                lphoto = MediaStore.Images.Media.getBitmap(this.getContentResolver(), selectedImage);

                imgProfilePicture.setImageURI(selectedImage);

                //Based on the Orientation Check result, I rotate the ImageView Image to make it straight.
                if (orientation == 270) {
                    imgProfilePicture.setRotation(-90);
                } else if (orientation == 0) {
                    imgProfilePicture.setRotation(0);
                }
                //This is the end of Image Rotation based on the Orientation Check Result.

                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                lphoto.compress(Bitmap.CompressFormat.JPEG, 100, baos); //bitmap is required image which have to send  in Bitmap form
                byte[] byteArray = baos.toByteArray();

                encodedImage = Base64.encodeToString(byteArray, Base64.DEFAULT);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


text:
Q: Perform network operation to check if user has internet connection with async task I am getting below exception

android.os.NetworkOnMainThreadException

because I don't use an async task to make the particular network operation. I  have searched for this, but it got me so confused. Could someone make it work with async task and the particular functions?
Below are two functions i use :
1)  isNetworkAvailable()
private boolean isNetworkAvailable() {

    ConnectivityManager connectivityManager
            = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
    NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
    return activeNetworkInfo != null;

}

2)  hasInternetAccess(Boolean showMessage)
When i want to display a toast i call this function, setting the parameter to true.
public boolean hasInternetAccess(Boolean showMessage) {

    if (isNetworkAvailable()) {
        try {
            HttpURLConnection urlc = (HttpURLConnection)
                    (new URL("http://clients3.google.com/generate_204")
                            .openConnection());
            urlc.setRequestProperty("User-Agent", "Android");
            urlc.setRequestProperty("Connection", "close");
            urlc.setConnectTimeout(1500);
            urlc.connect();
            return (urlc.getResponseCode() == 204 &&
                    urlc.getContentLength() == 0);
        } catch (IOException e) {
            Log.w("connection", "Error checking internet connection", e);
        }
    } else {
        if(showMessage) // If i want to show the toast, it's true
            showAToast("No Internet Connection", Toast.LENGTH_SHORT); // Just another function to show a toast
    }
    return false;
}

A: This is how you can use an AsyncTask by creating an inner class which extends AsyncTask.
private class NetworkInAsync extends AsyncTask<String, Void, Boolean> {

    private Context context;
    private Activity activity;

    NetworkInAsync(Activity activity) {
        this.context = activity.getApplicationContext();
        this.activity = activity;
    }

    @Override
    protected void onPreExecute() {
    }

    @Override
    protected void onPostExecute(Boolean result) {
        // Do something with the result here
    }

    @Override
    protected Boolean doInBackground(String... params) {
        if (isNetworkAvailable()) {
            try {
                HttpURLConnection urlc = (HttpURLConnection)
                (new URL("http://clients3.google.com/generate_204")
                        .openConnection());
                urlc.setRequestProperty("User-Agent", "Android");
                urlc.setRequestProperty("Connection", "close");
                urlc.setConnectTimeout(1500);
                urlc.connect();
                return (urlc.getResponseCode() == 204 &&
                urlc.getContentLength() == 0);
            } catch (IOException e) {
                Log.w("connection", "Error checking internet connection", e);
            }
        } else {
            if(showMessage) // If i want to show the toast, it's true
            showAToast("No Internet Connection", Toast.LENGTH_SHORT); // Just another function to show a toast
        }
        return false;
    }
}

You can execute the AsyncTask as follows
new NetworkInAsync(this).execute();

I would still recommend you go through the docs here to clarify yourself how AsyncTask works in Android.

A: The code should work when you call it from AsyncTask's doInBackground method
call test();
private void test() {
HttpURLConnection urlc = (HttpURLConnection)
                    (new URL("http://clients3.google.com/generate_204")
                            .openConnection());

            urlc.setConnectTimeout(1500);
            urlc.connect();
}

You can check the network connection before making the call, but any how, you should catch the exception in TimeOut exception. So I dont think, that you have any much benifit to check the connectivity before making the call.


text:
Q: Sorting arrays, probably rookie mistake how are u? This is the thing, ive been trying to make a btn that order an array of products by price when the user clicks on it, but its not working, and i think is my ordering function using sort, cause i dont quite get sort function already, this is what im trying to do:
function ordmayorPrecio(arrprod) {
    arr = arrprod.sort(function (a,b){
    let precioa = parseInt(a.cost)
    let preciob = parseInt(b.cost)

    return precioa-preciob;
})
}

function ordmenorPrecio(arrprod) {
    arr = arrprod.sort(function (a,b){
    let precioa = parseInt(a.cost)
    let preciob = parseInt(b.cost)

    return preciob-precioa;
})
}

This is how im trying to make the buttons functional:
document.addEventListener("DOMContentLoaded", function (e) {
     getJSONData(PRODUCTS_URL)
    .then((result) => result.data)
    .then((productdata) => mostrarProductos(productdata));

    document.getElementById("sortDescPrice").addEventListener("click", function(){
        mostrarProductos(ordmenorPrecio(productdata));
    });

    document.getElementById("sortAscPrice").addEventListener("click",function(){
        mostrarProductos(ordmayorPrecio(productdata));
})

});

And this is how I try to append it to the HTML:
function mostrarProductos(arr){

    let productosAppend = '';

for(let i = 0; i < arr.length; i++){
        let producto = arr[i];

        productosAppend += `

                        <img src="` + producto.imgSrc + `" alt="` + producto.description + `" class="img-thumbnail">

`+ producto.name +`

                            ` + producto.soldCount + ` artículos

                            ` + producto.cost + " " + producto.currency + `

` + producto.description + `

            `
}
    document.getElementById("produto").innerHTML = productosAppend;
}

A: Your sorting looks reasonable, assuming that the API returns an array of objects with a cost property. But you then need to return the sorted array:
function ordmayorPrecio(arrprod) {
    return arrprod.sort(function (a, b) {
        let precioa = parseInt(a.cost)
        let preciob = parseInt(b.cost)
        return precioa - preciob;
    })
}
function ordmenorPrecio(arrprod) {
    return arrprod.sort(function (a, b) {
        let precioa = parseInt(a.cost)
        let preciob = parseInt(b.cost)
        return preciob - precioa;
    })
}

The event listeners need to have a reference to the productdata argument from the .then - at the moment, they don't, they're referencing something outside instead (which may not even exist?). Add the listeners only after the response comes back.
document.addEventListener("DOMContentLoaded", function (e) {
    getJSONData(PRODUCTS_URL)
        .then((result) => result.data)
        .then((productdata) => {
            mostrarProductos(productdata);
            document.getElementById("sortDescPrice").addEventListener("click", function () {
                mostrarProductos(ordmenorPrecio(productdata));
            });
            document.getElementById("sortAscPrice").addEventListener("click", function () {
                mostrarProductos(ordmayorPrecio(productdata));
            })
        })
        .catch(handleErrors); // don't forget this part
});


text:
Q: IOS navigationBar not to edge of screen I have a Navigation Bar in my storyboard, and set the folowing constraints:
Horizontal Space - (-16) - View Navigation Bar
Horizontal Space - (-16) - Navigation Bar View
Vertical Space - (8) - Navigation Bar - Top Layout Guide

However it appears like this:

Both in portait and Landscape oriantation.
How can i fix it so that i do not have 3  pixels of White space? (also does this on my Iphone 6plus)
I used the Inferred Size option.
It works on Iphone 4S, Iphone 5, iphone 5S, iphone 6.

A: My constrains seem to indicate that i have constrained the view against its Superview's margins, rather then against its actual edges. Because the margins are different between other phones and iPhone 6 Plus, my navigation bar ends up inset (because constant 16 isn't large enough).
I turned margin based constrains off in the same popup that i used to create these, but i had to remove the constraints i set first.
Steps to fix:

*

*Click navigation bar

*Click pin (the |-[]-| ) thing on the right bottom corner (3rd from the right 2nd from the left).

*Click 'constrains to margins'

Source Rincewind from Apple: https://devforums.apple.com/message/1099289#1099289


text:
Q: How can I make selected item in listbox scroll to the top? I creating a simple list off of array items. Scroll bars will appear if the list is big. However, my question is - when an item is selected, I would like to see that item to the top of the visible position, pushing all above items hidden above under scrollbar. So no matter what I item I select, it should be on top of the visible list box. This is not same as positioning the item to the top, just on the scrolling top. Hope my question is understood here.
Thanks for any help or direction I can get.

A: You can use this code:
$('#scrollable li').on('click', function(e){
    $('#scrollable').animate({scrollTop: $(e.target).position().top + $('#scrollable').scrollTop()});
});

See also this JSFiddle: http://jsfiddle.net/729nX/1/

A: after much googling,
i found you can either use scrollTo() using javascript with a code similar to this
function scrollToElem(elem) {
    if(pageElement != null){
        window.scrollTo(elem.offsetTop, 0);
    }
}
var elem= document.getElementById('your_element');
scrollToElem(elem);

or use use location.hash which seems to me the simplest solution
with something alone the lines of
location.hash = '#' + 'your_element';

A: in case you have a scroll bar in an element instead of the whole window.
Element.scrollTop - MDN
Element.scrollTop - W3 school
function onSelect(list, selectedItem){
    list.scrollTop = selectedItem.offsetTop - list.offsetTop;
}


text:
Q: C# writing JSON to a file without backslashes I'm working on a console application that writes certain data to a JSON file. The problem is that the backslashes that VS uses to escape characters in a string, are being written to the file. I did find a similar question like this on stackoverflow, but that person was serializing twice which caused the problem. I don't think that's the case with me (unless I'm missing something) and that's why I created a seperate question on here.
I've tried doing string.Replace("\","") but since the backslashes aren't really there ('cause it's just VS escaping the double quotes), this doesn't help.
I have a class called listItem which has some properties;
class ListItem
    {
        public string title;
        public string textline;
        public string docuType;
    }

and I have a class SPList, containing a list of those ListItems;
class SPList
    {
        public string listTitle;
        public List<ListItem> listItems;
    }

I have an example of what's being written to the JSON-file with 2 lists;
[
  {
    "listTitle": "\"Another List\"",
    "listItems": [
      {
        "title": "\"Here\"",
        "textline": "\"Another test value\"",
        "docuType": null
      },
      {
        "title": "\"Look at this\"",
        "textline": "\"It's another value for testing\"",
        "docuType": null
      }
    ]
  },
  {
    "listTitle": "\"Sample List\"",
    "listItems": [
      {
        "title": "\"Sample value\"",
        "textline": null,
        "docuType": "\"Analyse\""
      },
      {
        "title": "\"Sample value 2\"",
        "textline": null,
        "docuType": "\"IetsAnders\""
      },
      {
        "title": "\"SampleValue3!\"",
        "textline": null,
        "docuType": "\"Offerte\""
      }
    ]
  }
]

And finally, the code I use to make this happen;
Task <List<string>>listIDs = GetListIDs();
            listIDs.Wait();
            foreach (string id in listIDs.Result)
            {
                Task<string> lijstTitel = GetListTitle(id);
                lijstTitel.Wait();
                Task<List<string>> listitemIDs = GetItemIDs(id);
                listitemIDs.Wait();
                // Write all the items here
                foreach (string itemID in listitemIDs.Result)
                {

                    Task<ListItem> itempje = GetItem(itemID, id);
                    itempje.Wait();
                    listItems.Add(itempje.Result);
                }

                list.Add( new SPList{
                    listItems = listItems,
                    listTitle = lijstTitel.Result
                });
                listItems = new List<ListItem>();
            }
            string json = JsonConvert.SerializeObject(list, Formatting.Indented);

            System.IO.File.WriteAllText(path, json);

In the other example of the similar question I found, the person was serializing his JSON object twice, 'causing this problem to happen. Since I think I'm only serializing it once, does it have something to do with the fact that I'm using Tasks or is it something else entirely?

A: The problem is not the backslashes \, it is the quotation marks ".
Looks like the data you are serializing is already quoted.
If you could remove the backslash you would still end up with double quotations marks in the output "".


text:
Q: android tv app with live satellite channels A friend asked me to make an app for a TV that shows some information on one halve of the TV and on the other halve he wants to put some TV channel. My question is if it is possible to create an app that does that for android TV. Showing on half of the screen a TV channel and on the other half some information.

A: Everything is possible.
If you want to make TV application, Google encourages you to use Tv Input Framework TIF.
It consists of 2 parts: service which acquires channels from cable and application which binds to that service and shows channels lists.
You can use Leanback library by Google:
leanback
EDIT:
Example of TIF service:
TIF service commectial app example


text:
Q: url response not able to map in React App I'm new to react and trying to create a ecommerce website. For the navigation and category items, I have used a endpoint url.
http://149.129.128.3:3737/search/resources/store/1/categoryview/@top?depthAndLimit=-1,-1,-1,-1
and the screenshot of response is given below

The problem which I'm facing is that when I click on the categories like Apparel, Electronics, upto the first level of category, I'm able to render it.

But under that subsection, there is another category, which I'm not able to render(E.g under Girls there is shoes, pants etc) and the code is given below
topNavigation.js
import React, { Component } from 'react';
import axios from 'axios';
import SubMenu from './subMenu';

class Navigation extends Component {

  state = {
    mainCategory: []
  }

  componentDidMount() {
    axios.get('http://localhost:3030/topCategory')
      .then(res => {
        console.log(res.data.express);
        this.setState({
          mainCategory: res.data.express.catalogGroupView
        })
      })
  }

  render() {

    const { mainCategory } = this.state;
    return mainCategory.map(navList => {
      return (

          {navList.name}

          <SubMenu below={navList.catalogGroupView}/>

      )

    })

  }

}

export default Navigation;

subMenu.js
import React, { Component } from 'react';
import SubListMenu from './subListMenu';

class SubMenu extends Component {
    render() {
        const {below} = this.props;
        return below.map(sub => {

            return (

 {sub.name}

                     <SubListMenu subBelow={this.props}/>

            )
        })

    }

}

export default SubMenu;

subListMenu.js
import React, { Component } from 'react';

class SubListMenu extends Component {

        render() {
            const {subBelow} = this.props;
            return subBelow.map(sub => {

                return (

 {sub.name}

                )
            })

        }

    }

    export default SubListMenu;

Can someone please help me on this. I'm not able to figure it out. I don't know where my code is getting wrong. Or if somebody could atleast give an insight how to proceed further.

A: Try to change this line:
<SubListMenu subBelow={this.props}/>
to this:
<SubListMenu {...this.props}/>
or to this
<SubListMenu subBelow={this.props.below}/>
You are passing the whole props object to subBelow, so you are trying to map through an object, but Object.prototype.map is not a function.


text:
Q: Logout and redirect user back to login blade with a message on change password in laravel I'm trying to logout and redirect my user back to login blade once the user's password is changed successfully.
This is my controller so far (only the function is included),
public function store(Request $request)
    {
        $request->validate([
            'current_password' => ['required', new MatchOldPassword],
            'new_password' => ['required', 'string', 'min:12', 'confirmed','regex:/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[@$!%*?&])[A-Za-z\d@$!%*?&]{12,}$/'],
            'new_confirm_password' => ['same:new_password'],
        ]);

        User::find(auth()->user()->id)->update(['password'=> Hash::make($request->new_password)]);

        //dd('Password change successfully.');

    }

Here on success how can I logout and redirect my user back to login blade with a success message (Pass word has been changed. Please log in again)

A: I have two solution to this problem. Simply add with function to create a flash message you wanted.

Solution 1: Go to the AuthenticatesUsers.php and inside the logout function change the redirected route from / to /login. (Assuming your using make:auth)

public function logout(Request $request)
{
    //more codes here

    return $request->wantsJson()
        ? new Response('', 204)
        : redirect('/login')->with('success', 'Password change successfully.');
}

Solution 2: Make a customed one. Create a controller function and add these following codes below:

public function logout()
{
    \Auth::logout();
    return redirect('/login')->with('success', 'Password change successfully.');
}

A: I think you can redirect to your logout function and return a session message to the login blade.

A: Auth::logout();
return redirect('/login');
For showing a message you can use
https://github.com/CodeSeven/toastr


text:
Q: How can I compute the distribution function of $\Bbb{E}(Z|N)$?
Let $(X_i)$ be a collection of i.i.d. r.v. in $L^1$ and $N\sim \mathrm{Poi}(1)$ independent from $(X_i)$. We define $Z=\sum_{i=1}^N X_i$. I need to compute the distribution function of $\Bbb{E}(Z|N)$.

From the lecture I know that $\Bbb{E}(Z|N=n)=n\Bbb{E}(X_1)$. Now I know that I need to compute $\Bbb{P}(\Bbb{E}(Z|N)\leq x)$ for all $x\in \Bbb{R}$. But somehow I don't know where to start.
I know that by definition $\Bbb{E}(X|Y=y)=\frac{\Bbb{E}(X1_{Y=y})}{\Bbb{P}(Y=y)}$ therefore I thought about doing a partition in $\Bbb{E}(Z|N)$ to get $\Bbb{E}(Z|N)=\sum_k \Bbb{E}(Z|N)1_{N=k}=\sum_k\Bbb{E}(Z|N=k)1_{N=k}$. But I do not get something nice. Can maybe someone help me?
Thanks a lot

A: You're on the right track.
$\Bbb{E}(Z|N)=\sum_k \Bbb{E}(Z|N)1_{N=k}=\sum_k\Bbb{E}(Z|N=k)1_{N=k} = =\sum_kk \Bbb{E}(X_1)1_{N=k} = \Bbb{E}(X_1)\sum_kk 1_{N=k} = \Bbb{E}(X_1) N$.
So in the end $\Bbb{P}(\Bbb{E}(Z|N)\leq x) = \Bbb{P}(N\Bbb{E}(X_1)\leq x)$ and you can finish from here using the known distribution function of $N$.


text:
Q: Adobe air native installer is not including .class files and .properties files I have some files in my src directory, some are .class files (Java class files) and some are .properties files, when I create the Adobe air native installer these files are not included. Why is that? How can I work around that?
Also it excludes .mxml files, but that's good. I'm sure that's related, how to change what it includes or excludes?

A: Honestly not sure why it's excluding those on you.  But you can right click the project in the project navigator panel, go to properties, on the left side navigation select "Flex Build Packaging", click the "Package Contents" tab on the right, make sure the files you want are selected.  If they aren't there I would guess somehow these files aren't being seen in the source path, check that under Flex Build Path -> Source Path.
EDIT:
Found this as a duplicate, following the steps to go to window preferences and remove the exclusions seems to have worked.
Add .properties file to output folder of Flex project


text:
Q: google charts change total number in Y axis I have a chart like so

What I am trying to do is change the total number on top which is 1,000 to a higher number. I can't figure out what the options value I need to make that change.
    var options = {
        title: 'This is my title',
        curveType: 'function',
        legend: { position: 'bottom' }
    };

A: you can use the viewWindow option for vAxis (vertical axis)...
    vAxis: {
      viewWindow: {
        max: 2000  // <-- set maximum number
      }
    }

you can also set the min, if needed...
    vAxis: {
      viewWindow: {
        min: 0,
        max: 2000
      }
    }

e.g.
var options = {
    title: 'This is my title',
    curveType: 'function',
    legend: { position: 'bottom' },
    vAxis: {
      viewWindow: {
        max: 2000
      }
    }
};


text:
Q: How to destroy host component on pressing escape key using directive in angular? Following is my implementation for destroying a popup on pressing escape.
@Directive({
  selector: '[escapeHostDestroy]',
})

export class DestroyPopUpOnEscapeDirective {
    constructor(
      private renderer: Renderer2,
      private el: ElementRef,
      private viewContainerRef: ViewContainerRef
    ) {}

    @HostListener('document:keydown.escape', ['$event']) destroyHost(ev: KeyboardEvent) {
        this.renderer.destroy();
    }
  }

But it seems out that it is not working.
I can hide/show this pop using renderer(set style).
But I don't want that. Instead I want to destroy the host component where the directive sits on.
How can I achieve that?
& also one more doubt, How can I access a components methods inside a directive (so that I can trigger events from the directive itself... something like injecting the componenet in to directive)
//main component.html

<app-popup *ngIf="showPopup"></app-popup>

// popup component.html
<div escapeHostDestroy>
... {%rest of popup contents here%}
</div>

A: In the way you want it, it's not really possible. Better would be to use a service which controls the showing of the dialog. If you still want to use a directive, you can do it with a service like this:
export enum Popup {
  Main = 'main',
  Foo = 'foo',
  Bar = 'bar'
}

@Injectable({ providedIn: 'root' })
export class PopupService {
  readonly popups: Partial<Record<Popup, boolean>> = {};

  isOpen(popup: Popup): boolean {
    return !!this.popups[popup];
  }

  showPopup(popup: Popup): void {
    this.popups[popup] = true;
  }

  hidePopup(popup: Popup): void {
    this.popups[popup] = false;
  }
}

Which you can use in your template (after injecting the service in your parent component):
<app-popup *ngIf="popupService.isOpen('main')"></app-popup>

And you can change your directive to this. This also answers your question how to access the popup from the directive, you need to inject the PopupComponent in your directive, and use the @Host() annotation to be sure you get the right one:
@Directive({
  selector: '[escapeHostDestroy]',
})

export class DestroyPopUpOnEscapeDirective {
  constructor(@Host() private popup: PopupComponent) {}

  @HostListener('document:keydown.escape')
  hidePopup(): void {
    this.popup.hide();
  }
}

and update your popup component:
@Component({
  selector: 'app-popup',
  template: ``
})
export class MainPopupComponent extends PopupComponent {
  readonly popup: Popup = Popup.Main;

  constructor(popupService: PopupService) {
    super(popupService);
  }
}

And create an abstract popup component which your popups extends:
@Directive()
export abstract class PopupComponent {
  abstract readonly popup: Popup;

  protected constructor(protected popupService: PopupService) {}

  hide(): void {
    this.popupService.hidePopup(this.popup);
  }
}

There are obviously, like you know, a lot of libraries out there which can do this for you as well. Especially angular material or the angular cdk is a nice starting point for this, but if you like to keep things simple and educational, you can first try to do it yourself :). That's to say, my answer is a very simplified version on how to control the showing of dialogs.

A: The below may be of help given your comments and use case:
https://stackblitz.com/github/ClientsideDesign/ngx-dialog-injection-starter-pack
This is an implementation of a reusable material dialog with an injected child component (which has a form) and communication between parent and child component. As per the answer from @poul, setting up a service to communicate when the dialog should be closed is key.

*

*dialog-wrapper is a dialog component

*dialog-form is an example of a dynamic component being injected into dialog-wrapper, with the necessary supporting services.

*name (Alice) is an example of arbitrary data being passed from the parent component to dialog-form via dialog-wrapper

*An object with name and favouriteFood is then passed back to the parent when the form in dialog-form is submitted. This also tiggers the parent component to close dialog-wrapper.

I've tried to keep the code as straightforward as possible so it can be easily retasked. The dialog wrapper itself is fairly simple; most of the heavy lifting is in the injected component and the parent component.
As per your original post, the dialog is closed and the child components destroyed when you press escape.
The full code can be reviewed on https://github.com/ClientsideDesign/ngx-dialog-injection-starter-pack.


text:
Q: SQL split values to multiple columns I have table:
+---------------+------------------------------+-----+------+
| id_order      | id_product                   | qty | size |
+---------------+------------------------------+-----+------+
| ORD-0413-17-1 | PRD-0408-17-2,PRD-0412-17-11 | 2,3 | M,S  |
+---------------+------------------------------+-----+------+

I would like to have an output like this:
+---------------+---------------+-----+-------+
| id_order      | id_product     | qty | size |
+---------------+----------------+-----+------+
| ORD-0413-17-1 | PRD-0408-17-2  |  2  |  M   |
| ORD-0413-17-1 | PRD-0412-17-11 |  3  |  S   |
+---------------+----------------+-----+------+

How I can do this?

A: Here's one way in which to build a normalized 'result' from your 'data'... I'm using a simple utility table of integers (0-9), but you could just use a bunch of UNIONs instead.
DROP TABLE IF EXISTS my_table;

CREATE TABLE my_table
(id_order VARCHAR(20) NOT NULL
,id_product VARCHAR(255) NOT NULL
,qty VARCHAR(30) NOT NULL
,size VARCHAR(30) NOT NULL
);

INSERT INTO my_table VALUES
('ORD-0413-17-1','PRD-0408-17-2,PRD-0412-17-11','2,3','M,S');

DROP TABLE IF EXISTS ints;

CREATE TABLE ints(i INT NOT NULL PRIMARY KEY);

INSERT INTO ints VALUES (0),(1),(2),(3),(4),(5),(6),(7),(8),(9);

SELECT DISTINCT id_order
              , SUBSTRING_INDEX(SUBSTRING_INDEX(id_product,',',i+1),',',-1) id_product
              , SUBSTRING_INDEX(SUBSTRING_INDEX(qty,',',i+1),',',-1) qty
              , SUBSTRING_INDEX(SUBSTRING_INDEX(size,',',i+1),',',-1) size
           FROM my_table,ints;

    id_order      id_product    qty size
    ORD-0413-17-1 PRD-0408-17-2   2 M
    ORD-0413-17-1 PRD-0412-17-11  3 S

A: in my case, am using method in class php, this is the method :
public function user_checkout($params){

    $date = new DateTime(date('Y-m-d'));
    $date->modify('+3 day');

    $query = "SELECT * FROM cart WHERE id_session='".$params['id_user']."'";
    $sql = $this->db->query($query);
    $data1 = array();
    $data2 = array();
    $data3 = array();
    while($result = $sql->fetch_assoc()){

        $data1[] = $result['id_product'];
        $data2[] = $result['qty'];
        $data3[] = $result['size'];

    }

    $data_insert = array(
        "id_order" => $params['id_order'],
        "id_product" => implode(',', $data1),
        "id_user" => $params['id_user'],
        "qty" => implode(',', $data2),
        "size" => implode(',', $data3),
        "account_name" => $params['name_of_account'],
        "account_number" => $params['no_rekening'],
        "amount" => $params['amount'],
        "total_price" => $params['total_price'],
        "out_of_date" => $date->format('Y-m-d'),
        "order_date" => date('Y-m-d')
    );

    $insert = "INSERT INTO `order_product`(`id_order`, `id_product`, `id_user`, `qty`,`size`, `account_name`, `account_number`, `amout`, `total_price`, `out_of_date`, `order_date`, `status`) VALUES ('".$data_insert['id_order']."','".$data_insert['id_product']."','".$data_insert['id_user']."','".$data_insert['qty']."','".$data_insert['size']."','".$data_insert['account_name']."','".$data_insert['account_number']."','".$data_insert['amount']."','".$data_insert['total_price']."','".$data_insert['out_of_date']."','".$data_insert['order_date']."',0)";
    $sql_insert = $this->db->query($insert);

    $delete = "DELETE FROM cart WHERE id_session = '".$params['id_user']."'";
    $sql_delete = $this->db->query($delete);

    return true;

}


text: Q: Load project's mp3 into MPMediaItem I've got an mp3 in my project's "Supporting Files" folder, and I'd like to create an MPMediaItem for that song. Normally, I'd use MPMediaQuery if I were creating an MPMediaItem from the user's library, but I'm not sure how that would work with a project file.  Any pointers would be terrific. Thanks for reading!


text:
Q: Inverse Matrix and matrix multiplication If I got the invertible matrix $A$, I can calculate the inverse matrix $A^{-1}$, so that $A \cdot A^{-1} = E$, where $E$ is the identity matrix.
Wikipedia says that not only $A\cdot A^{-1} = E$ must be fulfilled, but also $A^{-1} \cdot A = E $. Can someone explain to me why this is not a contradiction to the fact that matrix multiplication is not commutative ? Is the inverse matrix really defined as a matrix which fulfills both?

A: They are inverses of each other by definition,
therefore $AA^{-1} = E$ holds
now take $A= (A^{-1})^{-1}$ then $A^{-1}(A^{-1})^{-1} = E = A^{-1}A$  also holds as they are inverses of each other
commutativity of matrix multiplication holds in certain cases for example $AE =EA$ where $E$ is the identity matrix

A: The inverse of a matrix is defined as the matrix that satisfies both relationships.
For square matrices $A$ and $B$,
$$
B\mbox{ is the inverse of }A:=B\mbox{ such that } AB{}={}BA{}={}I\,.
$$
Incidentally, this also means that $A$ is the inverse of $B$.

A: Let $A$ be a matrix.
The inverse of $A$ is by definition both a left and a right inverse.
Hence by definition, a matrix $B$ is an inverse of $A$, if and only if
$$
AB=BA=I.
$$
The fascinating aspect of matrices is, that one of the defining equation implies also the other. That is, if $B$ satisfies $AB=E$ only, then it follows $BA=E$.
To see this, use the rank theorem to show that $AB=E$ implies that $A$ has full rank, thus is invertible. Thus, there is a matrix $A^{-1}$ such that $AA^{-1}=A^{-1}A=E$. Multiplying $AB=E$ from the left mit $A^{-1}$ yields $B=A^{-1}$.
This implies that the matrix $B$ is the inverse, and also satisfies $BA=E$.
An alternative proof would be to use determinants: The existence of $B$ with $AB=E$ implies $\det(A)\ne0$, hence $A$ is invertible.
In the light of the above comments, we can compensate the lack of commutativity
of  matrix multiplication by other matrix specific tools (rank, determinant) to prove this result.


text:
Q: When the EM vector field is given a mass by Higgs mechanism, why isn't this equivalent to a massive photon? In chapter 6 of Classical Theory of Gauge Fields (Rubakov), we are presented with a scalar field $\phi$ coupled to the electromagnetic vector potential $A_\mu$. In this Lagrangian there is a quartic term which provides us with spontaneous symmetry breaking. After working through some transformations and recasting this in terms of a perturbation $\chi$ away from the equilibrium field value we are left with the following Lagrangian:
$$ \mathcal{L}=-\dfrac{1}{4} B^2_{\mu\nu} + \dfrac{e^2\phi_0^2}{2}B_{\mu}B_{\mu} + \dfrac{1}{2}\left(\partial_{\mu}\chi\right)^2-\mu^2 \chi^2 $$
where $B_\mu$ and $B_{\mu\nu}$ are the vector potential and field strength tensor respectively, after an appropriate gauge transformation.
This is where we see the Higgs mechanism, our $\chi$ field still has mass as we expect. Our massless vector field $B_\mu$ is now given a mass. On the following page (p108) we are told that the Nambu-Goldstone field $\theta$ (the part of $\phi$ which is orthogonal to $\chi$, and is massless by Goldstone's theorem) has been 'eaten'by the vector field and has given $B$ a mass.
Given that the $B$ potential has a mass, and that this potential describes the electric and magnetic fields, surely this implies that photons (excitations in EM fields and thus in $B$ potential) have a mass given by $e\phi_0$?


text:
Q: Problems adding a picture in checkbox in checkedchanged event Good morning everyone.
I´m trying to put an image in a checkbox when its status changes (checkedchanged event) and then, make a screenshot with this checkbox changed status, but, when event is fired, and screenshot is done, picture does not appear before next code executes.
I´m wondering if is there any way to make it like vb after update event.
Does anyone know how can I make it?
Thanks!!
My code:
Private Sub CheckBox_accept_terms_CheckedChanged(sender As Object, e As EventArgs) Handles CheckBox_accept_terms.CheckedChanged

Try
    If CheckBox_accept_terms.Checked Then

        CheckBox_accept_terms.Image = My.Resources.cancelar

        If moveTmpPic_finalPic() Then
            If agreement_screenshot() Then
                If generate_xml() Then
                    If generate_zip() Then
                        send_email_agreement = False
                        Common_functions.savedCapture = New Saved_capture_form
                        Common_functions.savedCapture.Show()
                        Me.Close()
                    End If
                End If
            End If
        End If
    End If

Catch

End Try

End Sub

I also tried:
Private Sub CheckBox_accept_terms_BackgroundImageChanged(sender As Object, e As EventArgs) Handles CheckBox_accept_terms.BackgroundImageChanged

Try
    If CheckBox_accept_terms.Checked Then

        If moveTmpPic_finalPic() Then
            If agreement_screenshot() Then
                If generate_xml() Then
                    If generate_zip() Then
                        send_email_agreement = False
                        Common_functions.savedCapture = New Saved_capture_form
                        Common_functions.savedCapture.Show()
                        Me.Close()
                    End If
                End If
            End If
        End If
    End If

Catch

End Try

End Sub

Private Sub CheckBox_accept_terms_CheckedChanged(sender As Object, e As EventArgs) Handles CheckBox_accept_terms.CheckedChanged

    CheckBox_accept_terms.BackgroundImage = My.Resources.cancelar

End Sub

A: You can add an Update() call, or a Refresh() call, to see if that helps.
Try:
Private Sub CheckBox1_CheckedChanged(sender As System.Object, e As System.EventArgs) Handles CheckBox1.CheckedChanged
    CheckBox1.BackgroundImage = My.Resources.garbage

    CheckBox1.Update()
    'or use refresh
    CheckBox1.Refresh()
End Sub

Update makes the control "update", and should force show your image.
If your problem is that the image is not displaying properly, it may be the layout of your background image. Stretch will make the image fit into the size of your control (rather than stay full-size).
        CheckBox1.BackgroundImageLayout = ImageLayout.Stretch


text:
Q: Kiama: dup illegal arguments exception I am getting dup illegal arguments exception in the following code.
package tests.kiama

import org.junit.runner.RunWith
import org.scalatest.FunSuite
import org.scalatest.junit.JUnitRunner
import org.kiama.rewriting.Rewriter._

@RunWith(classOf[JUnitRunner])
class KiamaRewrite extends FunSuite {
    test("test1") {
        abstract class E
        case class B(l: E, r: E) extends E
        case class P() extends E
        case class Q() extends E
        case class PP() extends E
        case class QQ() extends E

        val t = B(P(), Q())
        val d = rule {
            case P() => PP()
            case Q() => QQ()
        }

        val s = bottomup(d)(t)
        println("done")
    }
}

Exception:
java.lang.RuntimeException: dup illegal arguments: public tests.kiama.KiamaRewrite$$anonfun$1$B$2(tests.kiama.KiamaRewrite$$anonfun$1,tests.kiama.KiamaRewrite$$anonfun$1$E$1,tests.kiama.KiamaRewrite$$anonfun$1$E$1) (PP(),QQ()), expects 3

I am using the kiama library. http://code.google.com/p/kiama/

A: The Kiama dup method is responsible for creating new instances of the same type as existing instances. dup uses reflection to find the constructor and is complaining that the constructor arguments do not match the arguments given. In your test it is trying to make a B node with two children, but the B constructor has three arguments because B is an inner class of KiamaRewrite.
Move the B etc class declarations out of KiamaRewrite and the test passes.


text:
Q: specify minimum height divs to stop footer div crashing body divs This is so simple I'm sure, but I'm stumped.
I have a footer on a webpage, and all I want to do is make sure that it is always a fixed height from the bottom, BUT specify a minimum height for the page, so that it never crashes over content divs, and instead scrolls.
Any ideas?
Take a look here http://jsfiddle.net/vF4L3/

square box

horozontal box

.height {
    background-color: hsla(121,90%,48%,1);
    position: fixed;
    height: 100px;
    width: 100px;
    left: 100px;
    top: 50px;
}
.height2 {
    background-color: hsla(359,90%,48%,1);
    position: fixed;
    height: 50px;
    width: 100%;
    left: 0px;
    bottom: 60px;
}

A: Here is an example of what I use to lock my footer, I hope this helps you.
.Footer
{
    clear: both;
    height: 30px;
    width: 100%;
    text-align: center;
    line-height: normal;
    background: #4b6c9e;
    color: #FFFFFF;
    font-weight: bold;
    position: absolute;
    bottom: 0; /* stick to bottom */
    margin: 0;
    padding: 8px 0px 0px 0px;
}

A: Do you mean like this perhaps...?
http://jsfiddle.net/vF4L3/3/
.body {
    position:relative;
    width:100%;
    min-height:100%;
    margin-bottom:-150px;
    padding-bottom:150px;
    background:#CCC;
}

.footer {
    position:fixed;
    bottom:50px;
    height:100px;
    width: 100%;
    background:#C00;
}

What do you mean by "crash the content"? If you could elaborate more on this I'm sure I can help.


text:
Q: C++ Pointer and Object Initialization I'm designing a data structure that looks like this:

I'm using redirected input to get the data needed to fill the data structure.
Here is the code. I know it's a lot to slog through but the important stuff is near the bottom of the code.
#include <iostream>
using namespace std;

template <class DT>
class Cell {
protected:
    DT* info;
    Cell<DT>* right;
public:
    Cell();
    Cell(const DT& info);
    Cell(const DT& info, Cell<DT>* next);
    Cell(const Cell<DT>& copy);
    void copy(const Cell<DT>& copy);
    ~Cell();
    void operator=(const Cell<DT>& check);
    bool isEmpty();
    DT getInfo();
    Cell<DT>* next();
    int size();
    DT& find(const DT& key);
    DT& infoAt(int position);
    void add(const DT& object);
    void insertAt(const DT& newObj, int position);
    Cell<DT>* setNext(Cell<DT>* next);
    DT remove();
    DT removeAt(int position);
};

template <class DT>
Cell<DT>::Cell()
{
    info = NULL;
}

template <class DT>
Cell<DT>::Cell(const DT& info) {
    this->info = new DT(info);
    right = NULL;
}

template <class DT>
Cell<DT>::Cell(const DT& info, Cell<DT>* next) {
    this->info = new DT(info);
    right = next;
}

template <class DT>
Cell<DT>::~Cell() {
    if (info != NULL) {
        delete info;
        info = NULL;
    }
    if (right != NULL) {
        delete right;
        right = NULL;
    }
}

template <class DT>
void Cell<DT>::copy(const Cell<DT>& copy) {
    if (copy.info == NULL) info = NULL;
    else info = new DT(*(copy.info));
    if (copy.right == NULL) right = NULL;
    else right = new Cell<DT>(*(copy.right));
}

template <class DT>
Cell<DT>::Cell(const Cell<DT>& copy) {
    this->copy(copy);
}

template <class DT>
void Cell<DT>::operator=(const Cell<DT>& check) {
    if (info != NULL) delete info;
    if (right != NULL) delete right;
    copy(check);
}

template <class DT>
bool Cell<DT>::isEmpty() {
    return (info == NULL);
}

template <class DT>
DT Cell<DT>::getInfo() {
    return *info;
}

template <class DT>
Cell<DT>* Cell<DT>::next() {
    return right;
}

template <class DT>
int Cell<DT>::size() {
    if (next == NULL) {
        if (info == NULL) return 0;
        else return 1;
    }
    else return 1 + right->size();
}

template <class DT>
DT& Cell<DT>::find(const DT& key) {
    if (key == *info) return *info;
    return right->find(key);
}

template <class DT>
DT& Cell<DT>::infoAt(int position) {
    if (isEmpty()) return NULL;
    if (position == 0) return *info;
    if (right == NULL) return NULL;
    return right->infoAt(position - 1);
}

template <class DT>
void Cell<DT>::add(const DT& object) {
    if (info == NULL) info = new DT(object);
    else {
        Cell<DT>* newList = new Cell<DT>(*info, right);
        *info = object;
        right = newList;
    }
}

template <class DT>
void Cell<DT>::insertAt(const DT& newObj, int position) {
    if (position == 0) add(newObj);
    else {
        if (right == NULL) right = new Cell<DT>(newObj);
        else right->insertAt(newObj, position - 1);
    }
}

template <class DT>
Cell<DT>* Cell<DT>::setNext(Cell<DT>* next) {
    Cell<DT>* temp = this->right;
    this->right = (Cell<DT>*) next;
    return temp;
}

template <class DT>
DT Cell<DT>::remove() {
    DT temp = *info;
    delete info;
    if (right == NULL) info = NULL;
    else {
        Cell<DT>*  oldnext = right;
        info = right->info;
        right = right->right;
        oldnext->info = NULL;
        oldnext->next = NULL
            delete oldnext;
    }
    return temp;
}

template <class DT>
DT Cell<DT>::removeAt(int position) {
    if (position == 0) return remove();
    return right->removeAt(position - 1);
}

template <class DT1, class DT2>
class CellNode {
protected:
    DT1* info;
    Cell<DT2>* myCell;
public:
    CellNode();
    CellNode(DT1 title, DT2* info);
    CellNode(DT1 title);
    CellNode(DT2* info);
};

template <class DT1, class DT2>
CellNode<DT1, DT2>::CellNode() {
    info = new DT1();
    myCell = new Cell<DT2>();
}

template <class DT1, class DT2>
CellNode<DT1, DT2>::CellNode(DT1 title, DT2* info) {
    this->info = new DT1(title);
    myCell = new Cell<DT2>(info[0]);
    for (int i = 1; info[i] != NULL; i++) myCell->add(info[i]);
}

template <class DT1, class DT2>
CellNode<DT1, DT2>::CellNode(DT1 title) {
    this->info = new DT1(title);
    myCell = new Cell<DT2>();
}

template <class DT1, class DT2>
CellNode<DT1, DT2>::CellNode(DT2* info) {
    this->info = new DT1();
    if (myCell == NULL) {
        myCell = new Cell<DT2>(info[0]);
    }
    for (int i = 0; info[i] != NULL; i++) myCell->add(info[i]);
}

template <class DT1, class DT2>
class MasterCell {
protected:
    CellNode<DT1, DT2>* myCellNodes;
    int cellsFilled;
public:
    MasterCell();
    MasterCell(int size);
    void add(DT1 title, DT2* info);
};

template<class DT1, class DT2>
MasterCell<DT1, DT2>::MasterCell() {
    //This can't do anything.
}

template<class DT1, class DT2>
MasterCell<DT1, DT2>::MasterCell(int size) {
    myCellNodes = new CellNode<DT1, DT2>[size];
    cellsFilled = 0;
}

template<class DT1, class DT2>
void MasterCell<DT1, DT2>::add(DT1 title, DT2* info) {
    myCellNodes[0] = new CellNode<DT1, DT2>(title, info);
}

int main() {
    MasterCell<char, char*>* master;
    char * check = new char[100000];
    char* buffer;
    int size = 0;
    int lineAmount = 0;
    int cellCounter = 0;
    while (!cin.eof()) {
        cin.get(check[size]);
        size++;
    }
    size;
    buffer = new char[size - 1];
    for (int i = 0; i < size - 1; i++) {
        buffer[i] = check[i];
        if (buffer[i] == '\n') lineAmount++;
    }
    delete[] check;
    lineAmount++;
    cout << size << endl;
    for (int i = 0; i < size - 1; i++) {
        cout << buffer[i];
    }
    master = new MasterCell<char, char*>(lineAmount);
    cout << endl << lineAmount << endl;
    char* test = new char[5];
    test = "hello";
    char** test2 = new char*[2];
    test2[0] = new char[5];
    test2[0] = "hello";
    test2[1] = new char[5];
    test2[1] = "world";
    master->add((*test), test2);
    return 0;
}

The problem I'm having has to do with MasterCell's add method. First I have created the myCellNodes array in the initializer of MasterCell. Next, the I want to add nodes to that array using MasterCell's add method except I get an error message when I try to compile and for the life of me I can't figure out why.
This line is the one that gives me trouble:
myCellNodes[0] = new CellNode<DT1, DT2>(title, info);

This is the error I get:
Error   C2679   binary '=': no operator found which takes a right-hand operand of type 'CellNode *' (or there is no acceptable conversion)
Note: A lot of the junk in main is me interpreting the redirected input in such a way that I don't have to deal with re-sizing arrays.

A: Probably you want to keep a dynamic array of pointers:
CellNode<DT1, DT2>* myCellNodes;
should be:
CellNode<DT1, DT2>** myCellNodes;

and
myCellNodes = new CellNode<DT1, DT2>[size];

should be
myCellNodes = new CellNode<DT1, DT2> *[size];


text:
Q: Event based trigger for a sequential run of the same data factory pipeline I would like to use an event based trigger to run a data factory pipeline.
The trigger will check a folder in a data lake for any new file and start a pipeline once a new CSV file is copied.
The pipeline will then copy the data to an intermediate table to check its consistency (multiple checks using different data flow activities) and if everything's correct, copies it into a stage table.
It is thus very important that the intermediate table will contain the data from only one single CSV file before it is checked.
I have read though that the event based trigger will start in parallel as many pipelines as the (simultaneously) downloaded CSV files.
Is this right? in this case how can I force each Pipeline to wait until the previous one is done?
Thank you for your help.

A: There is a flag on the pipeline properties (accssible in the top-right of the editor pane) called concurrency.  Set this to 1 and only one copy will run and any other invocations will be queued until that one finishes.


text:
Q: How to convert from column-based CoNLL format to the Penn Treebank annotation style? Does anybody know about any tool, script, etc. to convert from column-based CoNLL format to the Penn Treebank annotation style?

A: As has been related in other threads on this topic, it's actually an open area of research to convert dependency parses into constituency parses.  Stanford CoreNLP has no functionality for attempting this at this time.


text:
Q: Not able to select Availability Zones on AWS Elastic Beanstalk I created an Elastic Beanstalk environment with custom configuration. I was able to change Availability Zones and placement, and I picked them.
After I created the environment, Elastic Beanstalk complained about
- Stack named 'awseb-e-**********-stack' aborted operation. Current
  state: 'CREATE_FAILED' Reason: The following resource(s) failed to
  create: [AWSEBInstanceLaunchWaitCondition].

- The EC2 instances failed to communicate with AWS Elastic Beanstalk,
  either because of configuration problems with the VPC or a failed EC2
  instance. Check your VPC configuration and try launching the
  environment again.

I wanted to check out the AZs and placements; however, they are disabled

Why is that disabled? Is there a way to enable it? If so, how?

A: If you use Elastic Beanstalk with Load Balancer, you need to control Auto Scaling Group under Configuration > Network.
For example, if you just want to deploy on us-east-1b, select a subnet which uses that Availability Zone.


text:
Q: Using shared-ptr vs. unique-ptr for a specific binary-tree algorithm I have been working on implementing various binary-tree algorithms using smart pointers instead of raw pointers. I have a pretty solid understanding of differences between shared/unique pointers and when to use each but this one specific algorithm has been giving me a lot of trouble.
This is my TreeNode implementation with unique_ptr to their left and right children.
struct UniqueTreeNode {

    /*Construction via int value*/
    explicit UniqueTreeNode(const int v) : val(v), left(nullptr), right(nullptr), parent(nullptr) {}

    ~UniqueTreeNode() { std::wcout << L"Destroy: " << val << std::endl; }

    /*Printing Utility for unique_ptr to tree node.*/
    friend std::wostream& operator<<(std::wostream& wout, const std::unique_ptr<UniqueTreeNode>& n) {
        std::wstringstream wss;
        print(n.get(), std::wstring(), wss, Child::LEFT);
        return wout << wss.rdbuf();
    }

    /*Printing Utility shared_ptr to tree node.*/
    friend std::wostream& operator<<(std::wostream& wout, const std::shared_ptr<UniqueTreeNode>& n) {
        std::wstringstream wss;
        print(n.get(), std::wstring(), wss, Child::LEFT);
        return wout << wss.rdbuf();
    }

    /*Printing Utility for tree node pointer.*/
    friend std::wostream& operator<<(std::wostream& wout, UniqueTreeNode* n) {
        std::wstringstream wss;
        print(n, std::wstring(), wss, Child::LEFT);
        return wout << wss.rdbuf();
    }

    /*Enum utility to pick child*/
    enum class Child { LEFT, RIGHT };
    static void print(UniqueTreeNode* n, std::wstring ws, std::wstringstream& wss, const Child& c);

    /*Construction level-by-level via vector*/
    static std::unique_ptr<UniqueTreeNode> construct(const std::vector<int>& v);

    int val; // Data element in node.
    std::unique_ptr<UniqueTreeNode> left, right; // left & right child pointers.
    UniqueTreeNode* parent; // parent raw pointer.
};

/**
* \brief Prints the tree level by level.
* \param n current node being processed.
* \param ws wide-string for storing prefix.
* \param wss appends result incrementally.
* \param c child being considered currently.
*/
inline void UniqueTreeNode::print(UniqueTreeNode* n, const std::wstring ws, std::wstringstream& wss, const Child& c) {
    if (!n) wss << L"Empty Tree";
    else {
        if (n->right) print(n->right.get(), ws + (c == Child::LEFT ? L"│   " : L"    "), wss, Child::RIGHT);
        wss << ws << (c == Child::LEFT ? L"└── " : L"┌── ") << std::to_wstring(n->val) << L"\n";
        if (n->left)  print(n->left.get(), ws + (c == Child::LEFT ? L"    " : L"│   "), wss, Child::LEFT);
    }
}

/**
* \brief Construction of tree via vector elements.
* \param v vector of elements to add.
* \return the tree after its constructed.
*/
inline std::unique_ptr<UniqueTreeNode> UniqueTreeNode::construct(const std::vector<int>& v) {
    if (v.empty()) return nullptr;
    auto it = v.cbegin();
    auto n = std::make_unique<UniqueTreeNode>(*it);
    std::queue<UniqueTreeNode*> q({ n.get() });
    while (++it != v.cend()) {
        auto *x = q.front(); q.pop();
        x->left = std::make_unique<UniqueTreeNode>(*it), q.push(x->left.get());
        if (++it == v.cend()) break;
        x->right = std::make_unique<UniqueTreeNode>(*it), q.push(x->right.get());
    }
    return n;
}

The implementation below is my attempt at solving the Maximum Binary Tree Problem
from leetcode. However, no matter what I try I cannot figure out a way to solve this one using unique-ptrs. Thats simply due to the fact that I need to store a pointer to my node in the std::deque as well as the their subsequent children. Of course I was able to easily do it via shared-ptr children but I was wondering if it was even possible to do this via unique ptrs. I am aware of the possibility to convert the unique_ptr to shared_ptr to take advantage of reference counting but I cannot move a shared_ptr into the right/left children in my unique_ptr nodes. Here is the code with unique_ptrs.
uTreeNode ConstructMaxTree(const vector<int>& v) {
    deque<uTreeNode> s;
    for (const auto val : v) {
        auto n = make_unique<UniqueTreeNode>(val);
        while (!s.empty() && s.back()->val < val) {
            n->left = move(s.back());
            s.pop_back();
        }
        if (!s.empty()) {
            s.back()->right = move(n);
        }
        s.emplace_back(move(n));
    }
    return move(s.front());
}

Here uTreeNode is just an alias for std::unique_ptr. I am also aware that n is moved twice and that isnt allowed for unique_ptrs. I was wondering if anyone had any insight as to what alternatives exist, if any to using a shared_ptr to solve this problem.


text:
Q: Load jar dynamically through javassist I'm trying to load a jar with javassist to make it available in the application's current classloader, and I'm getting a CannotCompileException due to a NoClassDefFoundError
What I got so far is as below:
ClassPool pool = ClassPool.getDefault();
pool.insertClassPath(jarFile);

List<String> classes = listJarClasses(jarFile);
for (final String className : classes) {
    CtClass ctClass = pool.get(className);
    ctClass.toClass(getClass().getClassLoader(), getClass().getProtectionDomain());
}

The listJarClasses method will just iterate the jar's entries and return the found class names.
I understand this method will indeed load classes to the current classloader, but so far I can't guarantee they will be created in a proper order.
For example, I'm iterating the classes and I got ClassA to be added, but this class needs ClassB to be compiled and ClassB is yet to be added to the classloader by the loop, thus the NoClassDefFoundError.
I also understand that there is a way to load classes through URLClassLoader as shown here, but this will not solve the problem, since the class will not be available on the current classloader for future use.
Is there a way to make it simpler to add a jar to the classloader and avoid this?


text:
Q: issue with hide and show content plus changing image on click I am trying to hide and show some content and it is working but i can not make the button image to change from Minus to Plus when I have to hide the content back to it's normal state.
Anu suggestions ?
Here is my code until this moment.

$(document).ready(function() {
    $('#show-content img').click(function() {
        $('.hidden-content').slideToggle("fast");
        $('.default-plus').attr('src','https://s11.postimg.org/7w0jbixvz/hide_content.jpg');
    });
});

How to Sign-In on the Device

This is a subtext, if needed

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Placeat nisi maxime, sapiente iste nostrum assumenda, deserunt. Repellendus commodi labore eligendi, ipsum inventore reiciendis. Ipsum voluptatum cumque consequuntur error id quidem.

thank you guys but what if I have several same divs and i want to press this button to show and hide content then all others divs which are the same are opening and closing their content. How can I isolate them ?

A:

$(document).ready(function() {
    $('#show-content img').click(function() {
        $('.hidden-content').slideToggle("fast");
        if ($('.default-plus').attr('src') == "https://s11.postimg.org/40x58yeq7/show_content.jpg")  {
            $('.default-plus').attr('src','https://s11.postimg.org/7w0jbixvz/hide_content.jpg');
        }else {
            $('.default-plus').attr('src','https://s11.postimg.org/40x58yeq7/show_content.jpg');
        }

    });
});

How to Sign-In on the Device

This is a subtext, if needed

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Placeat nisi maxime, sapiente iste nostrum assumenda, deserunt. Repellendus commodi labore eligendi, ipsum inventore reiciendis. Ipsum voluptatum cumque consequuntur error id quidem.

A:

$(document).ready(function() {

    // get the default Image source before clicking
    // also it will not change it will remain the default image source
    var toggleImageDefaultSrc = $('.default-plus').attr('src');

    $('#show-content img').click(function() {

      var iconSrc = toggleImageDefaultSrc;

        // if element is toggled change image source
        if($( ".hidden-content" ).is( ":hidden" )) {
          iconSrc = 'https://s11.postimg.org/7w0jbixvz/hide_content.jpg';
        }

        $('.hidden-content').slideToggle("fast");

        $('.default-plus').attr('src', iconSrc);
    });
});

How to Sign-In on the Device

This is a subtext, if needed

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Placeat nisi maxime, sapiente iste nostrum assumenda, deserunt. Repellendus commodi labore eligendi, ipsum inventore reiciendis. Ipsum voluptatum cumque consequuntur error id quidem.

A:

$(document).ready(function() {
    $('#show-content img').click(function() {
        var $plus = $('.default-plus');
        var $content = $('.hidden-content');

        if ($plus.hasClass('minus')) {
            $content.slideUp("fast");
            $plus
                .removeClass('minus')
                .attr('src','https://s11.postimg.org/40x58yeq7/show_content.jpg');
        } else {
            $content.slideDown("fast");
            $plus
                .addClass('minus')
                .attr('src','https://s11.postimg.org/7w0jbixvz/hide_content.jpg');
        }
    });
});

How to Sign-In on the Device

This is a subtext, if needed

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Placeat nisi maxime, sapiente iste nostrum assumenda, deserunt. Repellendus commodi labore eligendi, ipsum inventore reiciendis. Ipsum voluptatum cumque consequuntur error id quidem.

A: Use if condition inside the click event, and change the src of image like this
$(document).ready(function() {
    $('#show-content img').click(function() {
        $('.hidden-content').slideToggle("fast");
        if(!$('.hidden-content').is(':visible'))
        {
            $('.default-plus').attr('src','https://s11.postimg.org/7w0jbixvz/hide_content.jpg});
        }
        else
        {
            $('.default-plus').attr('src','https://s11.postimg.org/40x58yeq7/show_content.jpg});
        }
});

Hope it should works, if not please change the if condition little bit, it should work.

A: In this cases, I recommend to use CSS instead of editing the image source.
At least I would have did it this way instead.
You should keep your JS as simple as possible to achieve something you want and this can arguably improve the overall performance.

$(document).ready(function() {
    $('.default-plus').on('click', function() {
        $('.hidden-content').slideToggle("fast");
        $(this).toggleClass("clicked");
    });
});
.default-plus {
  display: block;
  width: 66px;
  height: 66px;
  background: url('https://s11.postimg.org/40x58yeq7/show_content.jpg') no-repeat;
  background-size: 66px;
  cursor: pointer;
}

.default-plus.clicked {
  background-image: url('https://s11.postimg.org/7w0jbixvz/hide_content.jpg');
}

How to Sign-In on the Device

This is a subtext, if needed

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Placeat nisi maxime, sapiente iste nostrum assumenda, deserunt. Repellendus commodi labore eligendi, ipsum inventore reiciendis. Ipsum voluptatum cumque consequuntur error id quidem.

A: Try running this code.Hope it works for you.

$(document).ready(function() {
    $('#show-content img').click(function() {
        $('.hidden-content').slideToggle("fast");
        if($('.default-plus').attr('src') == 'https://s11.postimg.org/7w0jbixvz/hide_content.jpg')
        {
           $('.default-plus').attr('src','https://s11.postimg.org/40x58yeq7/show_content.jpg');
        }
        else
        {
          $('.default-plus').attr('src','https://s11.postimg.org/7w0jbixvz/hide_content.jpg');
        }
    });
});

How to Sign-In on the Device

This is a subtext, if needed

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Placeat nisi maxime, sapiente iste nostrum assumenda, deserunt. Repellendus commodi labore eligendi, ipsum inventore reiciendis. Ipsum voluptatum cumque consequuntur error id quidem.

A: Use 2 classes with background images:

 $('.default').toggleClass('plus minus')

UPDATE
OP requested multiple buttons independently functioning. Used the keyword this and .parent() and .next() to target .hidden-content

$(document).ready(function() {
  $('.show-content button').click(function() {
$(this).parent().next('.hidden-content').slideToggle("fast");
$(this).toggleClass('plus minus')
  });
});
.default {
  width: 66px;
  height: 66px;
  display: inline-block;
  cursor: pointer;
  border-radius: 50%;
  border: 0 none transparent;
}
button:focus {
  outline: 0;
}
.plus {
  background: url(https://s11.postimg.org/40x58yeq7/show_content.jpg)no-repeat;
  background-size: contain;
  background-color: transparent;
}
.minus {
  background: url(https://s11.postimg.org/7w0jbixvz/hide_content.jpg)no-repeat;
  background-size: contain;
  background-color: transparent;
}

  <button title="someText" class="default plus"></button>

How to Sign-In on the Device

This is a subtext, if needed

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Placeat nisi maxime, sapiente iste nostrum assumenda, deserunt. Repellendus commodi labore eligendi, ipsum inventore reiciendis. Ipsum voluptatum cumque consequuntur error id quidem.

  <button title="someText" class="default plus"></button>

How to Sign-In on the Device

This is a subtext, if needed

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Placeat nisi maxime, sapiente iste nostrum assumenda, deserunt. Repellendus commodi labore eligendi, ipsum inventore reiciendis. Ipsum voluptatum cumque consequuntur error id quidem.

  <button title="someText" class="default plus"></button>

How to Sign-In on the Device

This is a subtext, if needed

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Placeat nisi maxime, sapiente iste nostrum assumenda, deserunt. Repellendus commodi labore eligendi, ipsum inventore reiciendis. Ipsum voluptatum cumque consequuntur error id quidem.

  <button title="someText" class="default plus"></button>

How to Sign-In on the Device

This is a subtext, if needed

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Placeat nisi maxime, sapiente iste nostrum assumenda, deserunt. Repellendus commodi labore eligendi, ipsum inventore reiciendis. Ipsum voluptatum cumque consequuntur error id quidem.


text:
Q: Does the primary dns suffix on our Windows 2008 servers have anything to do with internet connections? Windows 2008 R2 servers:

*

*No Active Directory

*

*All servers are WorkGroup members - not domain members

*No internal DNS servers

*Single NICs

*IIS 7.5

*Each server has its own Windows SMTP Server

These servers send email notifications, through on-server SMTP servers, to our customers when they have activity. We are having some email bounce-backs that are saying they can't resolve the sending server name.
I'm looking at a lot of things - DNS, SMTP, etc. But I'm wondering if it is something as simple as this....

*

*Does the [system properties][primary dns suffix] on our Windows 2008 servers have anything to do with internet connections?

I believe that this setting only affects intranet connections, and not internet connections - (since it's not a connection level dns suffix that gets set per-connection in the network interface settings).... but I don't want to try to fix something unless I'm sure of all the moving pieces.

A: Does the [system properties][primary dns suffix] on our Windows 2008 servers have anything to do with internet connections?
What's happening here is that the SMTP server is using it's FQDN from the system properties when it identifies itself to external SMTP servers. It's almost a certainty that this FQDN is not a valid FQDN in your public DNS zone and therefore can't be resolved by those external SMTP servers.
What you need to do is to configure the properties of the SMTP virtual server to use a valid FQDN to identify itself and create the appropriate A record for this name in your public DNS zone. Also have your ISP create the appropriate PTR record for the public ip address from which email from your server originates.


text:
Q: How to add new credit card type in Magento 2? I need to add some news credit cards type to Magento 2 like:
"DC" => "Diners Club"
"EL" => "ELO"

I know that Magento 2 has the default credit card above:
"AE" => "American Express"
"VI" => "Visa"
"MC" => "MasterCard"
"DI" => "Discover"
"JCB" => "JCB"
"SM" => "Switch/Maestro"
"DN" => "Diners"
"SO" => "Solo"
"MI" => "Maestro International"
"MD" => "Maestro Domestic"
"OT" => "Other"

But how to add Diners Club and Elo?
Thanks!

A: Haven't tested this, but seems like it should be possible to do it like this:
Create a basic custom module and in /etc/payment.xml add new CC types:
<payment xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:module:Magento_Payment:etc/payment.xsd">
    <credit_cards>
        <type id="DC" order="110">
            Diners Club
        </type>
        <type id="EL" order="120">
            ELO
        </type>
    </credit_cards>
</payment>

This should declare new types for the entire Magento app.
I think you also need this in /etc/module.xml:
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
    <module name="Vendor_Module" setup_version="1.0.0">
        <sequence>
            <module name="Magento_Payment"/>
        </sequence>
    </module>
</config>


text:
Q: Splitting a Sentence and select only required string in sql I have column in my table named billing_cycle which contains only below given two strings and i need to retrieve only monthly and Quarterly from that string.
Using the below query i can fetch string  Quarterly properly but not string monthly.In the out put the word A overlapping with the string Monthly.It can be replaced using case and stuff command but i dont want to use those. I would like to get the output using
substring and charindex or with any other function.
SELECT substring('208-Billing Period - Quarterly Average Daily Balance', charindex('- ', '208-Billing Period - Quarterly Average Daily Balance') + 2, 9)

SELECT substring('210-Billing Period - Monthly Average Daily Balance', charindex('- ', '210-Billing Period - Monthly Average Daily Balance') + 2, 9)

Anyone could help me?

A: One method would be a couple of nested CHARINDEX functions. I do this is the FROM as it avoids repetition of expressions:
SELECT SUBSTRING(V.YourColumn,CI1.I, CI2.I - CI1.I)
FROM (VALUES('208-Billing Period - Quarterly Average Daily Balance'),('210-Billing Period - Monthly Average Daily Balance'))V(YourColumn)
     CROSS APPLY (VALUES(CHARINDEX('- ',V.YourColumn)+2))CI1(I)
     CROSS APPLY (VALUES(CHARINDEX(' ',V.YourColumn,CI1.I)))CI2(I);

A: I recommend you make use of like and a case to simplify this so you don't have to hardcode specific position values into substring
  select
    case when v.Value like '%Monthly%'
        then 'Monthly'
        when v.Value like '%Quarterly%'
        then 'Quarterly'
    end as [Type],
    v.Value
from (
    select '210-Billing Period - Monthly Average Daily Balance' as [Value]
    union select '208-Billing Period - Quarterly Average Daily Balance'
) V

Results:

A: It is much easier using CASE/LIKE etc., but as you are not going to use those (is it a homework?), instead of having 9 at end of the substring(), you will have to use the position - 1 of the next space after the word Quarterly or Monthly. I have left some additional columns to help you understand it.
declare @test table
(
ID int identity(1,1)
,Billing varchar(100)
)

insert into @test(Billing)
select '208-Billing Period - Quarterly Average Daily Balance' UNION
select '210-Billing Period - Monthly Average Daily Balance'

select *
,charindex('- ', Billing) + 2 position_of_first_dash
,substring(Billing, charindex('- ', Billing) + 2, LEN(Billing)) substring_from_first_dash_pos_plus_2
,charindex(' ', substring(Billing, charindex('- ', Billing) + 2, LEN(Billing))) pos_first_space_after_dash_word
,substring(Billing, charindex('- ', Billing) + 2, charindex(' ', substring(Billing, charindex('- ', Billing) + 2, LEN(Billing)))-1 )
from
@test

Result returned is:


text:
Q: Capture which video id the user played from video array This code works great on a page with only 1 video. I am trying to adapt it to work on a page with an array of videos (8 per page) All i need is to capture the video id which is stored in $item.vid when the player clicks play button.
I have tried adding a div with the video id value and all the divs on the page which are created by the look do in fact have different values which is great, however they all have the same div id.  So that does not help me.

 //foreach starts here

<video id="myVideo" width="320" height="176" controls autoplay>
    <source src="http://www.w3schools.com/tags/mov_bbb.mp4" type="video/mp4">
    <source src="http://www.w3schools.com/tags/mov_bbb.ogg" type="video/ogg">
</video>

  //foreach ends here

Expected results should be that when user clicks play js can grab that video record id from the page of multiple videos.

A: The trick to this was to think "keep it simple" and once i thought about that then the answer came.
Solution is to individualize each video tag in the array and i did this by adding the onclick option to the video tag (i was not aware this was possible till now).  Then inside that onclick you call a function and pass it the video id via the onclick event.
Something like this (i am working with smarty so vars go inside of {} brackets )
<video id="example_video_1" class="video-js vjs-default-skin vjs-big-play-centered" controls preload="none" height="{$item.height}"  width="{$item.width}" poster="{$item.vbigthumb}" data-setup="{}" onclick="getVidId({$item.vid});">
          <source src="{$item.urlvid}" type="{$item.vtype}">

To view this video please enable JavaScript, and consider upgrading to a web browser that supports HTML5 video

</video>

And then the getVidId function grabs the video id passed to it via the onclick and then you can do whatever you want with the id at that point.   :)


text:
Q: How to remove all records from a DFS table but keep its schema? I have defined the DFS table schema and write test data into it.
Now, I want to delete all test data but keep my table schema, how?
Suppose I have the following DFS table:
n=1000000
ID=rand(150, n)
dates=2017.08.07..2017.08.11
date=rand(dates, n)
x=rand(10.0, n)
t=table(ID, date, x)
dbDate = database(, VALUE, 2017.08.07..2017.08.11)
dbID = database(, RANGE, 0 50 100 150)

dbName="dfs://compoDB"
if(existsDatabase(dbName)){
        dropDatabase(dbName)
}
db = database(dbName, COMPO, [dbDate, dbID])
pt = db.createPartitionedTable(t, `pt, `date`ID)
pt.append!(t);

A: You can use DolphinDB built-in function truncate.
Let's conduct a test.

*

*Check the number of rows of your DFS table.

select count(*) from loadTable("dfs://compoDB", `pt)

Return:
count
1000000

*Use the truncate function (takes around 100ms).

truncate(dbName, `pt)

*Check the rows again.

select count(*) from loadTable("dfs://compoDB", `pt)

Return:
count
0

All your records are removed.


text:
Q: MSSQL and PHP Advanced Search Engine not Querying Properly I have an advanced, yet simple, PHP search engine for my MSSQL table products. The search engine has three text inputs. The first input is for the make column of the table, the second is for the product_name column of the table, and the last is for my material column from the table. My problem, from what I can see, is that when I leave two inputs blank and type in valve, the query should echo SELECT * FROM products WHERE 1=1 AND product_name = 'valve'. Instead, the query is echoing SELECT * FROM products WHERE 1=1. I don't know why that is happening, and I think I could use another set of eyes to figure out this issue.
Here is the full PHP code:
<form action="<?php $_PHP_SELF ?>" method="post">
      <input type="text"   name="make">
      <input type="text"   name="parttype">
      <input type="text"   name="material">
      <input type="submit" name="submit">
</form>

<?php
$conn = mssql_connect('gdm','ger','Rr1!');
mssql_select_db('Ggler',$conn);

if (isset($_POST['submit'])) {

$cheack = "";

if(isset($_GET["make"])&&$_GET["make"] != ""){
    $make = $_POST['make'];
    $cheack.="  AND make =  '$make' ";
}

if(isset($_GET["parttype"])&&$_GET["parttype"] != ""){
    $parttype = $_POST['parttype'];
    $cheack.="  AND product_name =  '$parttype' ";
}

if(isset($_GET["material"])&&$_GET["material"] != ""){
    $material = $_POST['material'];
    $cheack.="  AND material =  '$material' ";
}

   $DB = "SELECT * FROM products WHERE 1=1 ".$cheack;
   $runquery = mssql_query($DB, $conn);
   $dad =  mssql_fetch_assoc($runquery);
   echo "".$DB."";
}else {
    echo "No search made"; }
?>

Thank you for any help. All help is greatly appreciated.

A: Spot the problem:
<form action="<?php $_PHP_SELF ?>" method="post">
                                           ^^^^^

if(isset($_GET["make"])&&$_GET["make"] != ""){
          ^^^^            ^^^^

As well, you are vulnerable to SQL injection attacks.


text:
Q: Does quantum collapse involve a loss of information? Does it require energy as suggested by the Landauer limit? I read in the context of quantum computing or of the minimal energy required for computation that there has to be a minimum possible amount of energy required to change one bit of information, called the Landauer limit.   During  collapse of a wave function, for example for one of a pair of entangled particles, it seems one is losing information content (losing one bit as the wave function goes from either possible state to one).   If so does this imply that collapse requires energy?  Or is the Landuaer limit not relevant to this setting.

A: The collapse of the wavefunction is not a real physical process. It's a feature of a particular interpretation of quantum mechanics, the Copenhagen interpretation (CI). Other interpretations, such as the many-worlds interpretation (MWI), don't have such a collapse. The different interpretations make the same predictions about all observables, and therefore wavefunction collapse can't have any observable consequences, such as consumption of energy.

A: Perhaps not a real yes/no answer: Landauer principle is about something resembling the collapse of wave function, but deeply different: erasure of information such that it is indistinguishable from thermal noise. A collapse is not the same thing.
The following papers will perhaps be helpful:

*

*"(Im-)Proving Landauer's Principle"

*"Landauer's principle in the quantum domain"

A: Erasing the results of a quantum mechanical measurement has the cost in free energy required by Landauer's principle, see:
https://arxiv.org/abs/quant-ph/0301076.


text:
Q: Как в ScrollView сделать один элемент без прокручивания вниз? У меня есть ScrollView я хочу добавить рекламный LiearLayout в низу экрана что бы он не скролися вниз со всеми элементами как это сделать?
Вот моё активити
<?xml version="1.0" encoding="utf-8"?>
<ScrollView
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity"
    android:layout_below="@+id/ads_line"
    android:background="@color/blue_dark">

        <androidx.constraintlayout.widget.ConstraintLayout
            android:id="@+id/scrollView"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical">

            <TextView
                android:id="@+id/title"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_marginTop="50dp"
                android:fontFamily="@font/poppinsbold"
                android:gravity="center"
                android:text="@string/app_title"
                android:textColor="@color/white"
                android:textSize="25sp"
                android:textStyle="bold"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toTopOf="parent" />

            <TextView
                android:id="@+id/description"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:fontFamily="@font/poppinsmedium"
                android:gravity="center"
                android:layout_marginHorizontal="8dp"
                android:text="@string/description"
                android:textColor="@color/white"
                android:textSize="15sp"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toBottomOf="@+id/title" />

            <Button
                android:id="@+id/one"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:backgroundTint="@color/blue_light"
                android:text="Bitcoin"
                android:textColor="@color/white"
                app:layout_constraintEnd_toEndOf="parent"
                app:layout_constraintStart_toStartOf="parent"
                app:layout_constraintTop_toBottomOf="@id/description" />

        </androidx.constraintlayout.widget.ConstraintLayout>

</ScrollView>


text:
Q: open word doc with c# Im using some code I found to open word docs from a webpage using c#.
I have added the docs to the project as existing items, im just wondering the besy way to refer to them in the code,
eg
        object filename = "f:\\Online_signup1\\DONE-Signup_Step1.dot";

or just
            object filename = "DONE-Signup_Step1.dot";
thanks again

A: I'd put them all in a "Resources" folder or similar inside your project, add a Project Settings file ("app.config") which has the name of that folder, and then refer to them using that -
In your app.config file:
<setting name="DocumentDirectory" serializeAs="String">
     <value>F:\Online_signup1\Resources</value>
</setting>

Somewhere during program startup:
string docDir = Settings.Default.DocumentDirectory;

Everywhere else:
string filename = Path.Combine(docDir, myfile)

That way, if you ever distribute your program / move anything around, you won't be stuck going through your code and changing filenames everywhere, just change the directory in the settings file and you're golden.
For web projects, you can put it in the web.config file, like so:
<appSettings>
    <add key="DocumentDirectory" value="F:\Online_signup1\Resources"/>
</appSettings>

And access via:
string docDir = ConfigurationManager.AppSettings["DocumentDirectory"];


text:
Q: Google Analytics dimension and metrics validation When I request some metrics and dimensions (ga:users, ga:1dayUsers for example)
from google analytics i have follow error: Ack! There was an error (400)Selected dimensions and metrics cannot be queried together.
In this guide when I check ga:users ga:1dayUsers is disabled. How to validate all combinations of metrics and dimensions for querying?

A: At this time there is no way to programmatically validate them.  There is also no way to programmatically validate the query without just sending it to google and see if it works or not.
You can manually check if they can be combined using the Dimensions and metrics explorer.


text:
Q: to_json converts DateTime from MongoDB to Python and back operation is not working I have a MongoDB with dates fields. I define the object like this one:
"
{
    "_id" : ObjectId("5d019fbdace49e498de7d915"),
    "created_date" : ISODate("2018-05-18T16:00:00.000Z"),
    "published_date" : ISODate("2018-05-18T16:00:00.000Z")
}
"

Mongoengine model looks like this one:
MyObject(Document):
    created_date = DateTimeField(default = datetime.datetime.utcnow)

When I get an object from database it comes to Python as:
'created_date':{'$date': 1463587200000}

I get objects doing to_json and back from_json. to_json() functions converts the Python datetime to this format. The problem is I don't know how to handle it back.
If I just try to save the object back (even if I don't touch this field, data is json)
doc = MyDoc(**data)
doc.save()

I have the following exception:
mongoengine.errors.ValidationError: ValidationError (MyObject:5d019aca1c9d4400008cb934) (cannot parse date "{'$date': 1463587200000}"

A: to_json() doesn't help to handle this date conversion. The possible solution is to convert data using to_mongo() after retrieving from DB and after that convert it to Python-object using to_dict().

A: I don't have any problem using the data you mentioned.
I've inserted it in mongo with:
obj = {
    "_id" : ObjectId("5d019fbdace49e498de7d915"),
    "created_date" : ISODate("2018-05-18T16:00:00.000Z"),
    "published_date" : ISODate("2018-05-18T16:00:00.000Z")
}
db.my_doc.insertOne(obj)

Then I'm able to read it, modify and save in mongoengine:
from  mongoengine import *
import datetime as dt

connect()

class MyDoc(Document):
    created_date = DateTimeField(default=dt.datetime.utcnow)
    published_date = DateTimeField(default=dt.datetime.utcnow)

doc = MyDoc.objects.first()
assert doc.created_date == dt.datetime(2018, 5, 18, 16, 0)
assert doc.published_date == dt.datetime(2018, 5, 18, 16, 0)

doc.created_date = dt.datetime.utcnow()
doc.save()

But if I insert the following:
{
    "_id" : ObjectId("5d019fbdace49e498de7d916"),
    "created_date" : {
        "$date" : 1463587200000
    },
    "published_date" : ISODate("2018-05-18T16:00:00Z")
}

Then I get the ValidationError you mentioned. Mongoengine's DateTimeField correctly resolves to ISODate in mongodb, in this case it simply sounds like some of your documents have a different structure (or perhaps its your schema that should be changed). Double check the raw objects in mongodb and make sure they are all the same.


text:
Q: TI CC2541 (BLE): Send data (to an Android phone) I am experimenting with Bluetooth Low-Energy (BLE) for the purpose of connecting a hardware device to an Android application. My goal is to send a recognizable piece of data to an Android phone.
I am using the keyfob from Texas Instrument's CC2541 Mini-development kit, and am programming it using the IAR Workbench (which I am learning on the fly). My issue is that I cannot figure out what code should be used to send data from the keyfob to the phone.
I understand that this is somewhat vague, but because of the non-disclosure policies of my company I cannot share the code that I am working with. Does anyone have any references to code for the IAR Workbench that will allow the CC2541 to send a piece of data? Right now, I prefer to use GATT if that helps.
Thanks, and please ask me more questions if I need to clarify anything.

A: Assuming you're working from a pre-existing service profile, there is a function for every service called ServiceName_SetParameter().  Calling that function will change the characteristic value.  When the characteristic is read by the phone, it will receive this value.  If the characteristic supports notifications, and your phone has registered for notifications on that characteristic, the new value will be transmitted whenever SetParameter is called.

A: You can implement any proprietary protcol to connect to and interact with your beacon device. It can assume other roles than just the beacon task. It can also listen to and respond to connection attempts thus expanding into a lot more than a regular beacon.
If you study the cc2541 close you realize it is a pretty advanced IO controller that offers a lot of IO signal possibilities. That way you could use the cc2541 as the heart of an IO control application where you measure and control equipment.  Mobile apps can then easily connect to your beacon/IO Controller device and interact with the machinery it is hooked up to. As you see, it´s a remarkably versatile system on chip and a cool circuit to learn to program.


text:
Q: How to write python script on linux to run a specific command requiring two files, which have similar file names I am struggling for creating python script in Linux terminal. I am trying to make command to analyze hundreds of files.
And there is a python program(ngCGH) which analyze bam.file. ngCGH's command is following:
ngCGH -o /mnt/data/A/B/C.txt [normal.bam] [tumor.bam]

Two .bam files have following naming role
1N-------.bam
1T-------.bam

2N-------.bam
2T-------.bam

In short, files having matched number should be analyzed.
In addition, I want to make output file name differently like in following way.
1N------.bam 1T------.bam
Result: 1NT analysis.txt

2N------.bam 2T------.bam
Result: 2NT analysis.txt

The output files should be txt files having different names.

A: import os
j = 1
files = set(x[2:len(x)-4] for x in os.listdir() if x.endswith('.bam'))

for i in files:
    command = 'ngCGH -o <path>/'+str(j)+'NT analysis.txt '+str(j)+'N'+i+'.bam '+str(j)+'T'+i+'.bam'
    os.system(command)

replace <path> with actual path.
Hope this was what you were expecting.