text:
Q: "Parameter not valid" exception loading System.Drawing.Image Why am I getting the exception "Parameter not valid" in my code:
MemoryStream ms = new MemoryStream(byteArrayIn);
System.Drawing.Image returnImage = System.Drawing.Image.FromStream(ms);

The length of byteArrayIn is 169014. I am getting this exception despite the fact that no value in it is greater than 255.

A: byte[] fileData = null;
using (var binaryReader = new BinaryReader(Request.Files[0].InputStream))
{
    fileData = binaryReader.ReadBytes(Request.Files[0].ContentLength);
}
ImageConverter imageConverter = new System.Drawing.ImageConverter();
System.Drawing.Image image = imageConverter.ConvertFrom(fileData) as System.Drawing.Image;
image.Save(imageFullPath, System.Drawing.Imaging.ImageFormat.Jpeg);

A: The "parameter is not valid" exception thrown by Image.FromStream() tells you that the stream is not a 'valid' or 'recognised' format. Watch the memory streams, especially if you are taking various offsets of bytes from a file.
// 1. Create a junk memory stream, pass it to Image.FromStream and
// get the "parameter is not valid":
MemoryStream ms = new MemoryStream(new Byte[] {0x00, 0x01, 0x02});
System.Drawing.Image returnImage = System.Drawing.Image.FromStream(ms);`

// 2. Create a junk memory stream, pass it to Image.FromStream
// without verification:
MemoryStream ms = new MemoryStream(new Byte[] {0x00, 0x01, 0x02});
System.Drawing.Image returnImage = System.Drawing.Image.FromStream(ms, false, true);

Example 2 will work, note that useEmbeddedColorManagement must be false for validateImageData to be valid.
May be easiest to debug by dumping the memory stream to a file and inspecting the content.

A: Which line is throwing the exception? The new MemoryStream(...)? or the Image.FromStream(...)? And what is the byteArrayIn? Is it a byte[]? I only ask because of the comment "And none of value in it is not greater than 255" - which of course  is automatic for a byte[].
As a more obvious question: does the binary actually contain an image in a sensible format?
For example, the following (although not great code) works fine:
    byte[] data = File.ReadAllBytes(@"d:\extn.png"); // not a good idea...
    MemoryStream ms = new MemoryStream(data);
    Image img = Image.FromStream(ms);
    Console.WriteLine(img.Width);
    Console.WriteLine(img.Height);

A: I had the same problem and apparently is solved now, despite this and some other gdi+ exceptions are very misleading, I found that actually the problem was that the parameter being sent to a Bitmap constructor was not valid. I have this code:
using (System.IO.FileStream fs = new System.IO.FileStream(inputImage, System.IO.FileMode.Open, System.IO.FileAccess.ReadWrite))
{
    try
    {
        using (Bitmap bitmap = (Bitmap)Image.FromStream(fs, true, false))
        {
            try
            {
                bitmap.Save(OutputImage + ".bmp", System.Drawing.Imaging.ImageFormat.Bmp);
                GC.Collect();
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
    }
    catch (ArgumentException aex)
    {
        throw new Exception("The file received from the Map Server is not a valid jpeg image", aex);
    }
}

The following line was causing an error:
Bitmap bitmap = (Bitmap)Image.FromStream(fs, true, false)

The file stream was built from the file downloaded from the Map Server. My app was sending the request incorrectly to get the image, and the server was returning something with the jpg extension, but was actually a html telling me that an error ocurred. So I was taking that image and trying to build a Bitmap with it.
The fix was to control/ validate the image for a valid jpeg image.
Hope it helps!

A: My guess is that byteArrayIn doesn't contain valid image data.
Please give more information though:

*

*Which line of code is throwing an exception?

*What's the message?

*Where did you get byteArrayIn from, and are you sure it should contain a valid image?

A: This error is caused by binary data being inserted into a buffer.
To solve this problem, you should insert one statement in your code.
This statement is:
obj_FileStream.Read(Img, 0, Convert.ToInt32(obj_FileStream.Length));

Example:
FileStream obj_FileStream = new FileStream(str_ImagePath, FileMode.OpenOrCreate, FileAccess.Read);
Byte[] Img = new Byte[obj_FileStream.Length];
obj_FileStream.Read(Img, 0, Convert.ToInt32(obj_FileStream.Length));
dt_NewsFeedByRow.Rows[0][6] = Img;

A: Just Follow this to Insert values into database
//Connection String
  con.Open();

sqlQuery = "INSERT INTO [dbo].[Client] ([Client_ID],[Client_Name],[Phone],[Address],[Image]) VALUES('" + txtClientID.Text + "','" + txtClientName.Text + "','" + txtPhoneno.Text + "','" + txtaddress.Text + "',@image)";

                cmd = new SqlCommand(sqlQuery, con);
                cmd.Parameters.Add("@image", SqlDbType.Image);
                cmd.Parameters["@image"].Value = img;
            //img is a byte object
           ** /*MemoryStream ms = new MemoryStream();
            pictureBox1.Image.Save(ms,pictureBox1.Image.RawFormat);
            byte[] img = ms.ToArray();*/**

                cmd.ExecuteNonQuery();
                con.Close();

A: Most of the time when this happens it is bad data in the SQL column. This is the proper way to insert into an image column:
INSERT INTO [TableX] (ImgColumn) VALUES (
(SELECT * FROM OPENROWSET(BULK N'C:\....\Picture 010.png', SINGLE_BLOB) as tempimg))

Most people do it incorrectly this way:
INSERT INTO [TableX] (ImgColumn) VALUES ('C:\....\Picture 010.png'))

A: all the solutions given doesnt work.. dont concentrate only on the retrieving part. luk at the inserting of the image. i did the same mistake. I tuk an image from hard disk and saved it to database. The problem lies in the insert command. luk at my fault code..:
 public bool convertImage()
    {
        try
        {
            MemoryStream ms = new MemoryStream();
            pictureBox1.Image.Save(ms, ImageFormat.Jpeg);
            photo = new byte[ms.Length];
            ms.Position = 0;
            ms.Read(photo, 0, photo.Length);
            return true;
        }
        catch
        {
            MessageBox.Show("image can not be converted");
            return false;
        }
    }
    public void insertImage()
    {
       // SqlConnection con = new SqlConnection();
        try
        {
            cs.Close();
            cs.Open();
            da.UpdateCommand = new SqlCommand("UPDATE All_students SET disco = " +photo+" WHERE Reg_no = '" + Convert.ToString(textBox1.Text)+ "'", cs);
            da.UpdateCommand.ExecuteNonQuery();
            cs.Close();
            cs.Open();
            int i = da.UpdateCommand.ExecuteNonQuery();
            if (i > 0)
            {
                MessageBox.Show("Successfully Inserted...");
            }

        }
        catch
        {
            MessageBox.Show("Error in Connection");
        }
        cs.Close();
    }

The above code shows succesfully inserted... but actualy its saving the image in the form of wrong datatype.. whereas the datatype must bt "image".. so i improved the code..
  public bool convertImage()
    {
        try
        {
            MemoryStream ms = new MemoryStream();
            pictureBox1.Image.Save(ms, ImageFormat.Jpeg);
            photo = new byte[ms.Length];
            ms.Position = 0;
            ms.Read(photo, 0, photo.Length);
            return true;
        }
        catch
        {
            MessageBox.Show("image can not be converted");
            return false;
        }
    }
    public void insertImage()
    {
       // SqlConnection con = new SqlConnection();
        try
        {
            cs.Close();
            cs.Open();
            //THIS WHERE THE CODE MUST BE CHANGED>>>>>>>>>>>>>>

            da.UpdateCommand = new SqlCommand("UPDATE All_students SET disco = @img WHERE Reg_no = '" + Convert.ToString(textBox1.Text)+ "'", cs);
            da.UpdateCommand.Parameters.Add("@img", SqlDbType.Image);//CHANGED TO IMAGE DATATYPE...
            da.UpdateCommand.Parameters["@img"].Value = photo;
            da.UpdateCommand.ExecuteNonQuery();
            cs.Close();
            cs.Open();
            int i = da.UpdateCommand.ExecuteNonQuery();
            if (i > 0)
            {
                MessageBox.Show("Successfully Inserted...");
            }

        }
        catch
        {
            MessageBox.Show("Error in Connection");
        }
        cs.Close();
    }

100% gurantee that there will be no PARAMETER NOT VALID error in retrieving....SOLVED!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!


text:
Q: Javascript mobile redirect script I'm working a wordpress website that needs a mobile redirect to the mobile home page in case the user is using a cell. I'm trying to utilize this Javascript code but I'm having major difficulties getting it to work properly.

*

*I need help removing the conformation section that asks the user if they want to continue to mobile site.

*I also need help figuring out how to restructure the code so it doesn't keep forwarding mobile user to home page. For example, I load the page on mobile, the code runs and it forwards me to mobile page. From there I click on another link in the top navigation and it takes me back to the home page no matter what I do.
Keep in mind I am very new to this so any Input and Help from you experienced folks out there would be much appreciated.
Thank You
P.
<script type="text/javascript">
if (screen.width < 1081) {
var ref = document.referrer;
var urls = new       Array("http://www.mymainsite.com","http://m.mymobilesite.com");
var n = ref.match(urls[0]);
var m = ref.match(urls[1]);
if ((m!==null) || (n!==null)) {
stop;
}
else if (ref=='') {
var r = confirm("Small Display is Detected.\nClick \"OK\" for MOBILE  SITE.");
if (r==true) {
window.location = "http://m.mymobilesite.com";
}
else {
stop ;
}
}
else
{
window.location = "http://m.mymobilesite.com";
}
}
</script>

A: We only activate this code on your main site. Then we check whether or not your screen width is small enough and look into localStorage to see whether or not the user has made a decision before. Then we put up the confirmation box. If the user clicks okay, we go to the mobile site, if not we set the localStorage variable to true. Keep in mind that localStorage is only available IE8+
if(location.hostname === 'mymainsite'){
    if (screen.width < 1081 && !localStorage.isMainSite) {
        if(confirm('Small Display is Detected.\nClick \"OK\" for MOBILE  SITE.')){
            window.location = "http://m.mymobilesite.com";
        } else {
            localStorage.isMainSite = true;
        }
    }
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Is it possible to communicate between two android phones? I already read following question and answers.
How to communicate between same application installed on two android handset?
I think the use case is totally same as mine.
But I still have a remaining question - what does 'using internet' in the article above mean between two phones each far away?
I think I need some more explanation in detail.
Thanks in advance.

A: Yes, two applications can talk over the internet (or bluetooth or sms/mms for that matter, but less practical). Just like any two computers can communicate over the internet. There's a wide variety of protocols. A whole world really. Do you need references to some tutorials on networking or am I totally missing your question?
EDIT: You can try The TCP/IP Guide for an intro
EDIT: And for android you probably want to use their socket interface
UPDATE: About how to communicate between clients - you probably don't want to rely on knowing a particular peer's IP address. Usually what you do is work with some known host as a server, which coordinates between the peers, sometimes relaying the messages between them, or alternatively just notifying the clients about each other's addresses.


text:
Q: java.lang.NoClassDefFoundError: org/apache/poi/POIXMLDocument I am trying to read Excel using Apache POI which is deployed as bundle in Karaf.
Used POI versions as per order:

*

*poi-3.11.jar

*poi-ooxml-3.11.jar

*poi-ooxml-schemas-3.11.jar

feature.xml snippet(For wrapping the bundles in Karaf):
<bundle>wrap:mvn:org.apache.poi/poi/3.11</bundle>
<bundle>wrap:mvn:org.apache.poi/poi-ooxml/3.11</bundle>
<bundle>wrap:mvn:org.apache.poi/poi-ooxml-schemas/3.11</bundle>

pom.xml(dependency jars)
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
    <version>3.11<version>
</dependency>
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>3.11<version>
</dependency>
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml-schemas</artifactId>
    <version>3.11</version>
</dependency>

Above jars used as dependency in project as well as bundles in Karaf.
Tried servicemix version of POI. But it also doesn't help.
I understand NoClassDefFoundError is runtime error, which is caused while the class is not found at runtime. Please give me resolution for this issue.
Stack Trace:
java.lang.NoClassDefFoundError: org/apache/poi/POIXMLDocument
    at java.lang.ClassLoader.defineClass1(Native Method)[:1.8.0_25]
    at java.lang.ClassLoader.defineClass(Unknown Source)[:1.8.0_25]
    at org.apache.felix.framework.BundleWiringImpl$BundleClassLoader.findClass(BundleWiringImpl.java:2128)
    at org.apache.felix.framework.BundleWiringImpl.findClassOrResourceByDelegation(BundleWiringImpl.java:1432)
    at org.apache.felix.framework.BundleWiringImpl.access$400(BundleWiringImpl.java:72)
    at org.apache.felix.framework.BundleWiringImpl$BundleClassLoader.loadClass(BundleWiringImpl.java:1843)
    at java.lang.ClassLoader.loadClass(Unknown Source)[:1.8.0_25]
    at org.apache.felix.framework.BundleWiringImpl.getClassByDelegation(BundleWiringImpl.java:1317)
    at org.apache.felix.framework.BundleWiringImpl.searchImports(BundleWiringImpl.java:1481)
    at org.apache.felix.framework.BundleWiringImpl.findClassOrResourceByDelegation(BundleWiringImpl.java:1427)
    at org.apache.felix.framework.BundleWiringImpl.access$400(BundleWiringImpl.java:72)
    at org.apache.felix.framework.BundleWiringImpl$BundleClassLoader.loadClass(BundleWiringImpl.java:1843)
    at java.lang.ClassLoader.loadClass(Unknown Source)[:1.8.0_25]

A: I've worked in a project that uses servicemix bundle rather directly POI.
<bundle>mvn:org.apache.servicemix.bundles/org.apache.servicemix.bundles.poi/3.15_1</bundle>


text:
Q: Vim Hotkeys For Specific File Is it possible to set hotkey for specific file types in vim.
For example, if I am editing a .java file, I'd like vim to run javac .java when I press 5.
Is this possible?

A: ~/.vimrc
autocmd FileType java map <F5> :! javac %<cr>

More info about key mapping and external commands.

A: (I fail to understand the point of the dichotomy between SO and SU for such questions... Anyway:)
Your question has already been answered, a few days later, on SO: ftplugins + local mappings/abbreviations/commands are the way to go.
Regarding javac call, Just use %< to obtain the filename without the extension. A first correct mapping thus becomes:
:nnoremap <buffer> <f5> :!javac %<<cr>

But prefer instead to rely on the quickfix mode with:
:setlocal makeprg=javac\ $*
:nnoremap <buffer> <f5> :make %<<cr>

A: I don't have any direct experience writing anything like this from scratch with Vim, but here's what you'll want to look for examples to follow.
You probably want a filetype plugin (ftplugin) for .java files:

A filetype plugin is like a global
  plugin, except that it sets options
  and defines mappings for the current
  buffer only.  See
  |add-filetype-plugin| for how this
  type of plugin is used.

And use it with a mapleader+hotkey:

To define a mapping which uses the
  "mapleader" variable, the special
  string "" can be used.  It is
  replaced with the string value of
  "mapleader". If "mapleader" is not set
  or empty, a backslash is used instead.
  ... To define a mapping which uses the
  "mapleader" variable, the special
  string "" can be used.  It is
  replaced with the string value of
  "mapleader". If "mapleader" is not set
  or empty, a backslash is used instead.

You might have a look at the Vim JDE scripts, or this guide on configuring Vi(m) for Java development. This page has some information on using javac in Vim.


text:
Q: Inverse and Derivative of $g'(x)=(1+x^{3})^{-1/2}$ Question I am stuck on the following question:

Suppose that $g$ is differentiable with derivative $g'(x)=(1+x^{3})^{-1/2}$. Show that the inverse function $h=g^{-1}$ satisfies $h''(x)=\frac{3}{2}[h(x)]^{2}$.

I feel like I've missed something in my notes. I need to find $g^{-1}(x)$ I suppose. I've been searching for theorems relating to inverses and derivatives in order to find $g^{-1}(x)$ from $g'(x)$.

A: Note that $g'(x)$ is undefined when $x\le -1$. So we are only interested in values of $x$ greater than $-1$. Since $g'(x)>0$ for $x>-1$, our function $g$ is increasing in the interval $(-1,\infty)$. Thus, with a suitable restriction on the domain, an inverse function $h$ exists.
For all suitable $x$, we have $g(h(x))=x$, and for all suitable $x$, we have $h(g(x))=x$, by the definition of inverse function.
We use the identity $g(h(x))=x$. Differentiate both sides with respect to $x$, using the Chain Rule.
We obtain
$$h'(x)g'(h(x))=1.$$
But we are told that $g'(u)=(1+u^3)^{-1/2}$. It follows that
$$h'(x)(1+[h(x)]^3)^{-1/2}=1.$$
More simply,
$$h'(x)=(1+[h(x)]^3)^{1/2}.$$
To find $h''(x)$, differentiate. We get, by the Chain Rule, applied twice,
$$h''(x)=3[h(x)]^2h'(x)(1/2)(1+[h(x)]^3)^{-1/2}.$$
The term $h'(x)(1+[h(x)]^3)^{-1/2}$ sort of hidden in the right-hand side is equal to $1$. It follows that
$$h''(x)=\frac{3}{2}[h(x)]^2.$$
Comment: One might imagine integrating $g'(x)$ to find $g(x)$, and then finding the inverse function $h(x)$ explicitly. However, the function $(1+x^3)^{-1/2}$ does not have an elementary antiderivative, so that approach
 will not succeed.


text:
Q: How do I retrieve the Linkedin API for my company page? I have installed the LinkedIn Campaign Manager app to our MA tool Eloqua but to configure it I need the API for our LinkedIn company page and I do not know how to retrieve it? Can someone help me?
BR,
Josefine

A: To retrieve the API for your LinkedIn Company Page:
> Sign in to Campaign Manager.
> Select the account you would like set up with data integration.
> Click Tools in the top navigation bar.
> Click Matched Audiences.
> Select the Uploaded list audiences tab.
> Select Connect to data integration.
>Review the terms and click Next to view API Keys

Let me know if this helps, BR, Sheressa


text:
Q: GlusterFS, how to server files using http or https? I am very new to glusterfs and I am trying to set up a 3 node combination. I have done the setup for 3 nodes and a client machine which has the volume mounted. Now after this I am stuck to find answers for these 3 questions:

*

*How to serve the files over http (something like https://gfs1.com/1.jpg)?

*Secondly, every time I have to put a file inside glusterfs cluster, I
have to do it through client server (placing inside volume) and then it getting replicated and distributed automatically?

*What happens in case the client server dies? I can't access the volume or upload new files?

Questions may sound very naive, but I am stuck with them and need help.

A: *

*How to serve the files over http (something like https://gfs1.com/1.jpg)?

It depends on your content. If you want to serve them as static resources, you can serve them via reverse proxy Nginx, Apache httpd,... by pointing resource URL to your mounted volume (FUSE module). Something like:
location /images {
    root /mounted_point/;
}

If it is secret content, needs authorization and so on, you can serve them by your own web API

*Secondly, every time I have to put a file inside glusterfs cluster, I have to do it through client server (placing inside volume) and then it getting replicated and distributed automatically?

There are two ways to deal with files from Gluster. It is FUSE modules using Gluster Native Client and libgfapi interact directly with Gluster. You can read more about it here https://staged-gluster-docs.readthedocs.io/en/release3.7.0beta1/Features/libgfapi/
By the first one with FUSE module, the only thing you need to do is put your files into the mounted volume in your Glusterfs Client server. Glusterfs will take care of the rest (distributed, replicate,...)

*What happens in case the client server dies? I can't access the volume or upload new files?

*

*You can keep the availability of your Glusterfs Client by adding more Glusterfs Client server. All of it would show the same files from your Gluster.

*libgfapi, interact directly to your Gluster server, no client needed.


text:
Q: Docking a form on a MDI I am trying to dock a form onto a MDI, but when I use the following code, it just flashes itself and the form disappeared.
        using (frmDock formDock = new frmDock())
        {
            formDock.MdiParent = this;
            formDock.Dock = DockStyle.Left;
            formDock.Show();

        }

A: That's because as soon as that using block ends it disposes the new form you just created.  If you did it without the using, the form would stay there.  You don't need a using statement as long as you just close it with formDock.Close().  Using statements normally accompany connections to databases or streams to ensure that they get closed/disposed properly and don't cause problems later in your program.
Here's one of I'm sure many articles about the using statement out there on the web.


text:
Q: Magento2 core javascript object in custom javascript i would like to access the javascript object for the product custom options and need to change the price of the custom option.
I have found below data for the custom options.
<script type="text/x-magento-init">
    {
        "#product_addtocart_form": {
            "priceOptions": {
                "optionConfig": {"1":{"1":{"prices":{"oldPrice":{"amount":1,"adjustments":[]},"basePrice":{"amount":1},"finalPrice":{"amount":1}},"type":"fixed","name":"Option1-1"},"2":{"prices":{"oldPrice":{"amount":2,"adjustments":[]},"basePrice":{"amount":2},"finalPrice":{"amount":2}},"type":"fixed","name":"Option1-2"},"3":{"prices":{"oldPrice":{"amount":3,"adjustments":[]},"basePrice":{"amount":3},"finalPrice":{"amount":3}},"type":"fixed","name":"Option1-3"},"4":{"prices":{"oldPrice":{"amount":4,"adjustments":[]},"basePrice":{"amount":4},"finalPrice":{"amount":4}},"type":"fixed","name":"Option1-4"}}},
                "controlContainer": ".field",
                "priceHolderSelector": "[data-role=priceBox]"
            }
        }
    }
</script>

My concern is that how can i access the optionConfig from the above object. So I can modified it before magento change update price and then magento will update price accordingly.
I have created the below javascript widget.
define([
    'jquery',
    'underscore',
    'mage/template',
    'priceUtils',
    'priceBox',
    'priceOptions',
], function ($, _, mageTemplate, utils) {
    'use strict';
    var globalOptions = {
        qtyFieldSelector: 'input.qty',
    };
    $.widget('mage.fixedprices', $.mage.priceOptions, {
        options: globalOptions,
        /**
         * @private
         */
        _create: function() {
            console.log('hey, fixedprices is loaded!')
            //bind click event of elem id
            this.element.on('change', function(e){
                console.log('change ME!');
            });
            this.element.on('change', this._onQtyFieldChanged.bind(this));
        },

        _onQtyFieldChanged: function onQtyFieldChanged(event) {
            console.log("Magentoins fixedPrices", this.options);
        }
    });

    return $.mage.fixedprices;

});

I am getting optionConfig as null.

A: You can create the file view/frontend/requirejs-config.js in your module with this contents:
var config = {
    map: {
        '*': {
            priceOptions: 'Your_Module/js/your-script'
        }
    }
};

This will cause 'priceOptions' to refer to your script instead of Magento_Catalog/js/price-options. You should then have access to the options array from inside your script.


text:
Q: Docker API to automate pull and run I want to integrate my Go code with Docker which is also in Go. I want to do something like:
myapp.Run()
IMG := dockerapi.Pull("namespace/my image")
IMG.Run()

What do you recommend if I want to run docker commands in the middle of my Go program program flow.
Thanks!

A: Docker offers a rest based API for interacting with it programatically:
Example request:
POST /images/create?fromImage=base HTTP/1.1

Example response:
HTTP/1.1 200 OK
Content-Type: application/json

{"status":"Pulling..."}
{"status":"Pulling", "progress":"1 B/ 100 B", "progressDetail":{"current":1, "total":100}}
{"error":"Invalid..."}
...

there is a wrapper written in go here, though I have not used it myself.


text:
Q: Magento 2 customer address not showing properly I have done migration from M1 to M2 but the customer addresses not showing properly. There are some magento variables appearing instead.
Please check below screenshot:
I got stuck with this issue from past few days. Please suggest the best possible solution.
Thanks in advance.

A: Here is a workarround
https://github.com/magento/magento2/issues/5873
its about the primary key on eav_attribute_set

A: I face similar problem recently when I migrated from magetno 1.9.1.0 to 2.3.4, probaply I solved the issue.
The problem is in : ATTRIBUTE_SET_ID_ADDRESS . By default it is 2.
Change the ATTRIBUTE_SET_ID_ADDRESS id according to the databse. For me it was ATTRIBUTE_SET_ID_ADDRESS =3, Hope it works for you.
Override this file: vendor\magento\module-customer\Api\AddressMetadataInterface.php
app/code/[YourVendor]/[ModuleName]/Api/AddressMetadataInterface.php
namespace [YourVendor]\[ModuleName]\Api;

/**
 * Interface for retrieval information about customer address attributes metadata.
 * @api
 */
interface AddressMetadataInterface extends \Magento\Customer\Api\AddressMetadataInterface
{
    const ATTRIBUTE_SET_ID_ADDRESS = 2;

    const ENTITY_TYPE_ADDRESS = 'customer_address';

    const DATA_INTERFACE_NAME = 'Magento\Customer\Api\Data\AddressInterface';
}

app/code/[vendorname]/[vendorname]Customer/etc/di.xml
<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../lib/internal/Magento/Framework/ObjectManager/etc/config.xsd">
      <preference for="Magento\Customer\Api\AddressMetadataInterface" type="[vendorname]\[vendorname]Customer\Api\AddressMetadataInterface" />
</config>


text:
Q: Need all elements of list to be integers I'm currently taking a beginning programming course and need help correcting a function. I need all elements in this list to be integers and not a string. And to do this I need to change one line from the function but I have no idea which line to change! Any help would be greatly appreciated.
def read_magic_square(filename):
    """
    Read values from a file into a 2D list

    Parameter:
    filename: the name of the file

    Returns a 2D list of integer values read.
    """

    infile = open(filename, "rt")
    square = []  # start with an empty list

    for line in infile:  # read text from file
        row = []
        numbers = line.split()

        # Loop through the list of numbers.
        # Append each number to the row.
        for num in numbers:
            row.append(num)

        if len(row) > 0:  # Don't count blank lines
            square.append(row)  # Append the row to the 2D list

    return square

A: To avoid errors if there are strings in the line, you can only change the appending line to be (you can change the invalid_replacement to be whatever you want, here I put it as zero):
invalid_replacement = 0
try:
    row.append(int(num))
except:
    row.append(invalid_replacement)


text:
Q: how do we call a javascript function after executing controller method I have a Vf page with save button. i am calling a controller method in the VF page. I would like to close the VF page once the save method is executed.
   <apex:commandButton value="Save" action="{!Save}"/>

I think we can close the page using javascript function.
Thanks
Prady

A: Here's the easiest way I've found to accomplish this.
Create a Visualforce Page (I have the same page named "CloseMe") with this Markup:
<apex:page >
    <script type="text/javascript">
        window.close();
    </script>
</apex:page>

Then, redirect (by JavaScript or Apex PageReference) to the page.
Also, make sure all Profiles have the necessary security to access the page.
Instead, you could try using an ActionFunction that calls the Apex Save action, then put the window.close(); JavaScript on the OnComplete ActionFunction parameter, but I think that's unnecessarily complicated.


text:
Q: Assigning values to variables in a list using a loop var_list = [one, two, three]
num = 1
for var in var_list:
    var = num
    num += 1

The above gives me an error that 'one' doesn't exist. Can you not assign in this way? I want to assign an incrementing number for each var in the list. So I want the equivalent of
one = 1
two = 2
three = 3

but without having to manually create and initialize all variables. How can I do this?

A: No, it doesn't work like that.
You can try:
one, two, three = range(1, 4)

This work by defining the variables in a multiple assignment. Just as you can use a, b = 1, 2. This will unroll the range and assign its values to the LHS variables, so it looks like your loop (except that it works).
Another option (which I wouldn't recommend in a real program...) would be to introduce the variable names in an exec statement:
names = ['one', 'two', 'three']
num = 1
for name in names:
    exec "%s = %s" % (name, num)
    num += 1
print one, two, three

A: A variable doesn't exist until you create it. Simply referencing a variable isn't enough to create it. When you do [one, two, three] you are referencing the variables one, two and three before they are created.

A: You can access the dictionary of global variables with the globals() built-in function. The dictionary uses strings for keys, which means, you can create variables with names given as strings at run-time, like this:
>>> var_names = ["one", "two", "three"]
>>> count = 1
>>> for name in var_names:
...  globals()[name] = count
...  count += 1
...
>>> one
1
>>> two
2
>>> three
3
>>> globals()[raw_input()] = 42
answer
>>> answer
42

Recommended reading

A: Python variables are names for values. They don't really "contain" the values.
for var in var_list: causes var to become a name for each element of the list, in turn. Inside the loop, var = num does not affect the list: instead, it causes var to cease to be a name for the list element, and instead start being a name for whatever num currently names.
Similarly, when you create the list, if one, two and three aren't already names for values, then you can't use them like that, because you are asking to create a list of the values that have those names (and then cause var_list to be a name for that list). Note that the list doesn't really contain the values, either: it references, i.e. shares them.

A: I would simply use list comprehension.
one, two, three = range(1, 4)
one, two, three = [val for val in ['one', 'two', 'three']]
v1, v2, v3 = [func(idx) for idx in range(1, 4)]


text:
Q: How do I read and write repeatedly from a process in vim? It was hard to phrase this as a question, but here is what I want to do:
I want vim to execute a process and to write to its stdin and read from its stdout file descriptors repeatedly. In other words, I want a back-and-forth dialogue between vim and another program.
I'll use cat as a simple example. If you run cat with no command-line arguments, then whatever you type on stdin is output to stdout after each newline character.
What I would like is to have a vim window which displays the most recent output of some program and to be able to write to its stdin upon certain events. So, unlike the following:
:read !cat

which waits for you to finish typing and press Ctrl-D to close cat's stdin, I want to display the output immediately after I press enter and to keep the process running so that I can type more.
Ultimately, I don't intend to be typing the input to the process; I want events (e.g. moving the cursor) to trigger vim to write specific commands to this process and display the output.
The reason I want the program to continue running instead of invoking the process once for each event is that the output to the program will be commands that generate state. If the program had to be invoked for each command, it would have to save the state to a file and read it in each time.
An alternative I am considering: writing the program to listen on a port. Then, vim invokes a command that simply opens the socket and passes the vim command to the program and returns the message from the program. This would require me writing two programs, though, which I hope is unnecessary.
What I am trying to do here is write a tool that analyses your code and provides an interactive command-line interface (e.g commands like that do things like "output a list of all the lines which set this variable). However, rather than running this program in a separate terminal or screen session, I would like vim to be able to integrate the output of this program in a window, if that is possible.

A: You should check out vimproc. You can use vimproc#popen3 to start the process. vimproc#popen3 returns an object(=dictionary) with a stdin member field that has a write method and a stdout member field that has a read method.
The problem is how to trigger the reading and writing. Vim is single thread, so you'll have to rely on autocmd events. Obviously you'll want to try reading whenever you write something(just in case), but you should also use the CursorHold event.
You can also use Python for IO. While it seems like you can use Python threading to trigger the reading, I would advise against it as Vim was never built for multithreading and from my experience, trying to hack multithreading into it with Python threads often causes race conditions and crashes Vim.


text:
Q: Split string (from C# functions) in breaks Javascript Hi I have a code in my asp to request some hours from a mysql database
C# code
        string cmd = "SELECT DepartureTime FROM dbtest";
        MySqlCommand mycmd = new MySqlCommand(cmd, conn);
        MySqlDataReader dataReader = mycmd.ExecuteReader();

        while (dataReader.Read())
        {
            times += dataReader.GetString(0) + "\n";
        }
        dataReader.Close();

Javascript
 function SendForm() {
       PageMethods.ConnectDatabase(OnSucceeded, OnFailed);
        function OnSucceeded(msg) {
            var vierkant = document.getElementById("Vierkant");
            var context = vierkant.getContext('2d');

            context.font = '15pt Calibri';
            context.fillStyle = 'blue';
            context.fillText('Departure Times bus X19:' + msg, 150, 100);
        }

When I call this function in my javascript it gives all the hours in one line
I like to have a break after each result I thought it was enough to pout a "\n" in my c# code
How can I fix this?
Thanks

I tried do following but still didn t work
Is there something wrong with my canvas or with the variable 'msg'?
Javascript:
 var msg;
    function Connect() {
        PageMethods.ConnectDatabase(OnSucceeded, OnFailed);

        function OnSucceeded(msg)
        {

            //Set context + Formatting
            var context = document.getElementById("canvas").getContext('2d');
            context.font = '15pt Calibri';
            context.textAlign = "center";
            context.textBaseline = "top";
            context.fillStyle = 'blue';

            //Prepare textarea value to be drawn as multiline text
            var textval = msg.value;
            var textvalArr = toMultiLine(textval);
            var linespacing = 25;
            var startX = 0;
            var startY = 0;

            //Draw each line on canvas.
            for (var i = 0; i < textvalArr.length; i++) {
                context.fillText(textvalArr[i], x, y);
                y += linespacing;
            }
        }

        //Create an array where the
 tag splits the values.
        function toMultiLine(text) {
            var textArr = new Array();
            text = text.replace(/\n\r?/g, '
');
            textArr = text.split("
");
            return textArr;

            /*var vierkant = document.getElementById("canvas");
            var context = vierkant.getContext('2d');
            //formatting
            context.font = '15pt Calibri';
            context.fillStyle = 'blue';

            context.fillText('Departure Times bus X19:' + msg, 150, 100);*/
        }

        function OnFailed(error) {
            alert("failed");
        }

    }

HTML:
  <form id="Form1" runat="server">

    <input type="button" onclick="return Connect()" value="Bushours:" />

<canvas id="canvas" width="1900" height="200">Test<canvas> element.
</canvas>

A: If you want break than use
 instead of \n
So your C# code will be like this:
times += dataReader.GetString(0) + "
";

Because \n is not get interpreted in break, but

There's a sample of how to do this in this answer:  HTML5 canvas ctx.fillText won't do line breaks?


text:
Q: GUI/TUI linux library Is there any UI library that can be to build both a text user interface (ncurses) and graphical user interface (GTK? QT?) from the same source?
I know that debconf can be used with various frontends, I would like to build something similar but programmable.

A: The library that powers YaST independence to do ncurses, gtk and qt with one codebase provides what you are looking for, and it is not tied to YaST itself.
Actually libyui only requires the standard C++ library and phtreads (IIRC). The UI plugins require of course the respective libraries (Qt, ncurses). YaST uses libyui via a set of YCP bindings that export a YCP like API on top of libyui.
The library is a bit lowlevel (one layer below an event loop), my colleage Klaus Kämpf wrote about using it some time ago in his blog, including binding to scripting languages it using swig.
The only part that is SUSE specific is the packaging, so you would need to package it yourself. Stackoverflow did not allow me to link more than once. The code of the library is linked from Klaus blog. Replace libyui for "qt" and "ncurses" for the plugin's code.
Also google for "YaST Independence From YCP" to find a blog entry from Andreas Jäger on the subject.

A: you could write your program to uses ncurses, and then use PDCurses to convert it to an X11 application - as the readme advertise.
I know it because I've used it as portable curses, though I've never tested its X11 capabilities

A: Not exactly a library but you could consider writing a web app that degrades well to Lynx

A: The GoboLinux guys have created their own toolkit for python called AbsTK, they use it for their installer, which actually works really good. I have never used the toolkit myself, but the apps built with it seems solid.

A: There's Cursed GTK, but it seems a bit dated.  I found some references to a port of Qt to ncurses called Qt Console, but it seems to have disappeared.

A: By using a library that targets both the text-mode and GUI environments, you have a big risk of getting stuck with the worst of both worlds.
You will be better off structuring your code using the MVC pattern, and providing separate views and controllers for each platform you target. Pushing all the logic down to the model classes has several other benefits:

*

*The code will be easier to test because you are forced to keep the user interface out of the actual domain logic.

*Your program can have user interfaces that have very little in common, e.g. a web UI, or an UI driven by speech.

*You can run the program easily with no UI at all (i.e. script it) by accessing the model classes directly in the same way that the controller classes do.

A: Maybe tcl/tk would provide what you want http://www.tcl.tk/
Here's the page on interfacing with curses. There is a claim there of integration with ncurses.
http://www2.tcl.tk/2372

A: I think what's used for configuring the linux kernel when compiling is dialog/cdialog/xdialog. But it's been a while since I've compiled a kernel, so my memory may be off. The most promising link I can find is this one for Xdialog.


text:
Q: return the labels and their encoded values in sklearn LabelEncoder I'm using LabelEncoder and OneHotEncoder from sklearn in a Machine Learning project to encode the labels (country names) in the dataset. Everything works good and my model runs perfectly. The project is to classify whether a bank customer will continue with or leave the bank based on a number of features(data), including the customer's country.
My issue arises when I want to predict (classify) a new customer (one only). The data for the new customer is still not pre-processed (i.e., country names are not encoded). Something like the following:
new_customer = np.array([['France', 600, 'Male', 40, 3, 60000, 2, 1,1, 50000]])

In the online course, where I learn machine learning, the instructor opened the pre-processed dataset that included the encoded data and manually checked the code for France and updated it in the new_customer, as the following:
new_customer = np.array([[0, 0, 600, 'Male', 40, 3, 60000, 2, 1,1, 50000]])

I believe that this is not practical, there must be a way to automatically encode France to the same code used in the original dataset, or at least a way to return a list of the countries and their encoded values. Manually encoding a label seems tedious and error-prone. So how can I automate this process, or generate the codes for the labels? Thanks in advance.

A: It seems like you may be looking for the .transform() method of your estimator.
>>> from sklearn.preprocessing import LabelEncoder

>>> c = ['France', 'UK', 'US', 'US', 'UK', 'China', 'France']
>>> enc = LabelEncoder().fit(c)
>>> encoded = enc.transform(c)
>>> encoded
array([1, 2, 3, 3, 2, 0, 1])

>>> encoded.transform(['France'])
array([1])

This takes the "mapping" that was learned when you called fit(c) and applies it to new data (in this case, a new label).  You can see this mapping in reverse:
>>> enc.inverse_transform(encoded)
array(['France', 'UK', 'US', 'US', 'UK', 'China', 'France'], dtype='<U6')

As mentioned by the answer here, if you want to do this between Python sessions, you could serialize the estimator to disk like this:
import pickle

with open('enc.pickle', 'wb') as file:
    pickle.dump(enc, file, pickle.HIGHEST_PROTOCOL)

Then load this in a new session and transform incoming data with it.

A: In machine learning it is a custom to keep the preprocessing pipeline in memory so that, after picking its hyperparameters and training the model, you can apply the same preprocessing on the test data.
If all of that is run in the same python instance, as is common for small/middle size projects, then it means keeping your LabelEncoder online or not sending it to garbage collection. In case of running training and testing in different instances, I think the easiest solution is to store it on disk, and load it in the testing script.
I advise you to use pickle. Here is an example.

A: The problem is you didn't encode the country attribute of your dataset.
from sklearn.preprocessing import LabelEncoder
from sklearn.preprocessing import OneHotEncoder
# define example
data = ['cold', 'cold', 'warm', 'cold', 'hot', 'hot', 'warm', 'cold', 'warm',
'hot']
values = array(data)
print(values)
# integer encode
label_encoder = LabelEncoder()
integer_encoded = label_encoder.fit_transform(values)
print(integer_encoded)
# binary encode
onehot_encoder = OneHotEncoder(sparse=False)
integer_encoded = integer_encoded.reshape(len(integer_encoded), 1)
onehot_encoded = onehot_encoder.fit_transform(integer_encoded)
print(onehot_encoded)

output :-
['cold' 'cold' 'warm' 'cold' 'hot' 'hot' 'warm' 'cold' 'warm' 'hot']
[0 0 2 0 1 1 2 0 2 1]
[[1. 0. 0.]
 [1. 0. 0.]
 [0. 0. 1.]
 [1. 0. 0.]
 [0. 1. 0.]
 [0. 1. 0.]
 [0. 0. 1.]
 [1. 0. 0.]
 [0. 0. 1.]
 [0. 1. 0.]]

For your problem, this data = ['cold', 'cold', 'warm', 'cold', 'hot', 'hot', 'warm', 'cold', 'warm',  'hot'] should be your dataset's country attribute. Then you can choose the integer or binary encoding method. Then continue the learning process.


text:
Q: Login com Sha256 Boa tarde a todos,
tenho um problema que me tem intrigado já a uns dias para cá, o meu chefe e orientador de estagio propôs-me para fazer uma segurança acrescida no site e para isso teria de usar um Hash de palavras passes, depois de muita investigação não consegui fazer login nas contas previamente "encriptadas" e não encontro maneira de encontrar o meu problema .
Página de registo
include("connect.php");

function generateSalt(){
  $characters = '0123456789abcdef';
  $length = 64;

  $string = '';
  for ($max = mb_strlen($characters) - 1, $i = 0; $i < $length; ++ $i)
  {
    $string .= mb_substr($characters, mt_rand(0, $max), 1);
  }
  return $string;
}

$userAccountInput = $_POST['userName'];
$userPasswordInput = $_POST['pass'];
$salt = generateSalt();
$hash = hash_hmac("sha256", $userPasswordInput, $salt);

$sql = "INSERT INTO username VALUES (NULL,'$userAccountInput','$salt','$hash');";

$resultado = mysql_query ($sql);

Página de Login
function testPassword($fPassword, $fSaltFromDatabase, $fHashFromDatabase){
              if (hash_hmac("sha256", $fPassword, $fSaltFromDatabase) === $fHashFromDatabase){
                  return(true);
                  }else{
                  return(false);
  }
  }

function SignIn()
{
//session_start();
if(!empty($_POST['userName']) || !empty($_POST['pass']))
{

                $query = mysql_query("SELECT * FROM username where userName = '".$_POST['userName']."'") or die(mysql_error());
                $row = mysql_fetch_array($query) or die(mysql_error());

                //$userAccountInput = $_POST['userName'];
                $userPasswordInput = $_POST['pass'];
                $saltFromDatabase = $row['salt'];
                $hashFromDatabase = $row['hash'];

                $var_dump($row);

                if(testPassword($userPasswordInput, $saltFromDatabase, $hashFromDatabase)){
                    echo "<script type='text/javascript'>alert('LOGIN COM SUCESSO!')</script>";
                    header('Location: ./clientes.php');
                }else{

                    echo "<script type='text/javascript'>alert('LOGIN FALHADO!')</script>";
                }

}

}
        if(isset($_POST['submit']))
        {
            SignIn();
        }
?>

Estou a ficar extramamente frustrado pois já estou a cerca de 5 dias a mudar o código e não encontro solução para este problema, espero bem que possam ajudar, qualquer ajudar é bem vinda e bastante agradecida, muito obrigado a todos.


text:
Q: Trying to implement a linear search on an ordered array for a specific number(n) but return statement keeps returning nothing I am trying to perform a linear search on an ordered array for a specific number. If the number is found, the algorithm must return its index. If we reach an element that is greater than the number, the algorithm should break. Lastly, if the number is not in the array print None. When I run the code, it returns no output. I have tried different variations of even including the number I am looking for in the array but the code still produces no output.
def linear_search(array, number):
    for el in range(len(array)):
        if el == number:
            return array[el]
        elif el > number:
            break
        else:
            return None

print(linear_search([10,11,12,22],22))

A: A couple things:

*

*You should be checking if array[el] == number

*return None outside of the IF statement, otherwise it will return None when el == 0

A: I hope this code helps you out!
    def LinearSearch(array, n, k):
    for j in range(0,n):
        if (array[j] == k):
            return j
    return -1

array = [10,20,30,40,50]
k = 30
n = len(array)
result = LinearSearch(array, n, k)
if (result == -1):
    print("Element not found")
else:
    print("Element found at index:", result)

A: def linear_search(array, number):
    for el in range(len(array)):
        if array[el] == number:
            return el
    return None


text:
Q: eliminating duplicates in std::vector I have a very large std::vector of std::vectors containing a fixed number of unsigned integers.
All vectors of uints are sorted ascending.
My current way to eliminate duplicate vectors is
unsigned int i = 0;
while ( i < new_combs.size() )
{
  unsigned int j = i + 1;
  while ( j < new_combs.size() )
  {
     unsigned int k = 0;
     while ( k < new_combs.at(i).size() && new_combs.at(i).at(k) == new_combs.at(j).at(k) )
        ++k;
     if ( k == new_combs.at(j).size() )
        new_combs.erase(new_combs.begin() + j);
     else
        ++j;
  }
  ++i;
}

here, new_combs is a vector containing vectors as mentioned above.
Is there a more efficient way to eliminate duplicates if the vector of vectors is unsorted?

A: A shorter way would be using <algorithm>:
std::sort(new_combs.begin(), new_combs.end());
new_combs.erase(std::unique(new_combs.begin(), new_combs.end()), new_combs.end());

Unless you specifically need a std::vector, you can use std::set to avoid duplicates.

A: Have you considered using std::set? It is ordered and doesn't allow duplicates to begin with.

A: Not much you can do if the vector is unsorted. If it is sorted however you can use the unique method defined in algorithm:
new_combs.erase(unique(new_combs.begin(), new_combs.end()), new_combs.end());

A: There are several elements in your code that ring my alarm bell regarding performance.
First, you are using vectors.  Erasing elements from vectors is always slow.
You might consider using a different container (std::list) or adjust your code so that you have a special value for nothing (e.g. zero or -1).
Second, you could use an std::set or std::unordered_set to keep values that you already encountered.
That way, you only have to loop over your vectors once.
EDIT: Forget this answer.  I misread the question and thought that duplicate values (not duplicate vectors) had to be removed.
Nevertheless, some reactions on the comments given:

*

*@Jerry: I agree that vectors are in most cases faster than lists, but only if the size of the vector is limited.  If the vector contains 1 million elements and you need to remove the 3rd, then the 5th, then the 10th, ... you end up moving lots of elements.  In such a case a list could be faster.

*@James: in the original question, the elements were not removed from the end of the vector, but in the middle.  If the vector is very big (let's say 1 million elements), then removing elements can still become a bottleneck.  However, I agree than using a sort, followed by a unique is probably faster.

A: Asymptotically, your algorithm seems like the usual O(n) implementation and is therefore optimal. (Even though I didn't understand your diagonalization strategy with i and j and why you only erase, but never move elements. Your code is highly unclear.)
However, you are duplicating the STL, and a shorter version of a unique-ing loop is:
struct unique {
    template <class C>
    void operator()( C& c ) {
         c.erase( std::unique( c.begin(), c.end() ), c.end() );
    }
};

std::for_each( new_combs.begin(), new_combs.end(), unique() );

A: I agree with Luchian Grigore's answer, but you might also consider converting the whole outer vector to unordered_set, which is an O(n) operation provided hashes of sub-vectors are not too lopsided (as opposed to average O(n*log(n)) for sorting). You can even use pointers to sub-vectors in your unordered_set, to avoid unnecessary copying. This can be an important performance difference for large amounts of data.
This example illustrates the basic idea of using your own hash function and pointers (it deals with vector of strings and uses unordered_map, not unordered_set, but you should be able to modify it fairly easily to your needs).


text:
Q: Syntaxnet / Parsey McParseface declarative sentences only? I cannot seem to find detail on the the data parsey was trained on; I am assuming it was mostly, if not all, on declarative sentences. If that's true, then Syntaxnet / parsey might not be the solution for imperative sentences, such as instructional text. Is this accurate? Is there anything out there that works with imperative sentence structure?

A: It is mentioned in official docs:

The included English parser, Parsey McParseface, was trained on the
  the standard corpora of the Penn Treebank and OntoNotes, as well as
  the English Web Treebank, but these are unfortunately not freely
  available.

A: Parsey McParseface is trained on the Penn Treebank as well as the Web Treebank. The cloud parser has additional proprietary data to help cover some of the gaps.
Parsey actually does pretty well on imperatives, though I don't have actual numbers to back that up -- but if you just try things, it mostly does well in my experience. The cloud system may do a bit better than that as well. In both cases there are imperative examples in our training data.
For example:

This was the first thing I tried. Note that "try" is often a noun, so there's some ambiguity for it to figure out, and it gets it right.


text:
Q: HTML meta tag for Windows Phone "website pin to start" I'm developing website and I would like to know if it's possible to set shortcut icon for website (when you pin website to start screen on Windows phone mobile IE), just like on apple (apple touch icons).
I found this, but it doesn't work :(
<meta name="msapplication-TileImage" content="windows_phone_icon.png">
<meta name="msapplication-TileColor" content="#1B262B">

Thanks for your help!

A: Windows Phone now supports the msapplication meta tags, as well as browserconfig.xml and RSS feed. If you did the work for IE10 or 11, it will now work on Windows Phone as well.
The code you suggested should do the trick with the latest Windows Phone update.

A: Looks like there isn't an option as good as you typed.
I already saw many sites using a clever hack to accomplish this.
You need to provide to the user some way to know the site can be pinned.
The user needs to trigger an action to show what you want in the tile an after that he needs to invoke the ... and pin the site.
Here you can see a more elaborated post in Windows Phone Blog.

A: You might just be missing the self closing part in your tags:
<meta name="msapplication-TileImage" content="windows_phone_icon.png" />
<meta name="msapplication-TileColor" content="#1B262B" />


text:
Q: Display results on keyup event and values inside form how to? How do i display the output on keyup event rather than on submit and also the values inside the input fields?
I tried readonly <input  id="result" name="totalamount" value="" readonly/>but its not working. can someone helo?
Here is thew complete codes

<form id="myForm">
    <input id="actualprice" type="number" placeholder="Actual Price">
    <input id="discount" type="number" placeholder="Discount">
    <input id="shipping" type="number" placeholder="Shipping">
    <input  id="result" name="totalamount" value="" readonly/>

    <input type="submit" value="Submit">
</form>

A: Use keyup event for input and you are using same id result for an input and h3. I've changed the id of h3 to result2.

$('input').on('keyup input', function () {
  var actualprice = Number($("#actualprice").val().trim());
  var discount = Number($("#discount").val().trim());
  var shipping = Number($("#shipping").val().trim());

  var discountRate = (100 - discount) / 100;
  var result = (actualprice * discountRate) + shipping;

  $("#result").val("Result :" + result.toFixed(2));
});

<form id="myForm">
    <input id="actualprice" type="number" placeholder="Actual Price">
    <input id="discount" type="number" placeholder="Discount">
    <input id="shipping" type="number" placeholder="Shipping">
    <input id="result" name="totalamount" value="" readonly />

    <input type="submit" value="Submit">
</form>


text:
Q: How to bind variable to a HTML tag in SQL? How to bind variable to a HTML tag in SQL?
SET @body ='
File loaded successfully at Getdate()
'

How to concatenate this variable: Getdate() to the existing the HTML Tag?

A: You need to convert the date to a string and concat it:
SET @body ='
File loaded successfully at ' + convert(nvarchar(max), GETDATE(), 0) + '
'


text:
Q: Explain the Open-E technology stack I wonder how the Open-E stack is built. I was not able find this information on their website or on other sites.
Is it an application that is installed on top of Linux or BSD or does it run on bare metal? Are they using publically available drivers?

A: It's described as a "storage OS", and the system requirements only talks about hardware, not any already-installed OS; I think it's safe to assume it runs on bare metal.

A: As Massimo states it's bare-metal. The manual showing this is only a couple of clicks from your link (products, dss lite, manual).

A: After doing some reading on it, I found a document that describes how to log into "the linux console". This strongly suggests that the foundation for this product is some kind of Linux, very probably heavily modified. This is not something you layer on top of an existing Linux build, though. This is something you install as a stand-alone product on bare metal. It is possible that it would work in a VM, but I don't really see the benefits of doing so.


text:
Q: The CAMERA_BUTTON intent cannot be caught by receiver
Possible Duplicate:
Android: How to listen to camera capture in Broadcastreceiver

I want to awake my app by one key pressing. But I found it's not easy to implement on Android.
I am trying to capture camera key and then  launch my app. BUT the onReceive() function is not called after camera key pressing.
Here is what in manifest.xml
<reciever android:enabled="true"  android:name=".SaveUKeyCapture">
    <intent-filter android:priority = "10000">
    <action android:name = "android.intent.action.CAMERA_BUTTON"/>
    <action android:name = "android.intent.action.SEARCH_LONG_PRESS" />
    <!-- <category android:name="android.intent.category.DEFAULT" />-->
    </intent-filter>
</reciever>

<uses-permission android:name="android.permission.CAMERA"/>

Here is the code
public class SaveUKeyCapture extends BroadcastReceiver{
    @Override

public void onReceive(Context context, Intent intent){
    Toast.makeText(context, "intent received", Toast.LENGTH_LONG);
}
}

Any suggestion?


text:
Q: "Chop lines" in `less` isn't working I'm doing:
less -S my_database_dump.sql

In order to see the files with the lines chopped (i.e. line wrapping.) But it's not working, the lines aren't being wrapped and I need to scroll horizontally to see the entire line. What can I do?

A: Try this:
fold -w $COLUMNS my_database_dump.sql | less

$COLUMNS is set to the terminal width by the shell. You can try other widths depending on your needs, of course. If you're running this in a script you may not have either $COLUMNS or $LINES defined - in that case you can use tput lines instead.
If you really want lines chopped (in this example, keep the first 80 chars) instead do this:
cut -c -80 my_database_dump.sql | less

A: "chop" means truncate (discard remainder of line) not fold (put remainder at start of next line).
The documented behaviour of the -S option to less is to do the opposite of what you describe.

       -S or --chop-long-lines
              Causes lines longer than the screen width to be  chopped  rather
              than  folded.   That  is, the remainder of a long line is simply
              discarded.  The default is to fold long lines; that is,  display
              the remainder on the next line.

(I think of -S as meaning "Scroll Sideways to See end of line")
Try omitting the -S option.

$ wc longlines.txt
      9     128     726 longlines.txt

$ less longlines.txt
WHAN that Aprille with his shoures soote The droghte of Marche hath perced to th
e roote,
And bathed every veyne in swich licour, Of which vertu engendred is the flour;
Whan Zephirus eek with his swete breeth Inspired hath in every holt and heeth
The tendre croppes, and the yonge sonne Hath in the Ram his halfe cours y-ronne,
And smale fowles maken melodye, That slepen al the night with open ye,
So priketh hem nature in hir corages: Than longen folk to goon on pilgrimages,
And palmers for to seken straunge strondes, To ferne halwes, couthe in sondry lo
ndes;
And specially, from every shires ende Of Engelond, to Caunterbury they wende,
The holy blisful martir for to seke, That hem hath holpen, whan that they were se
ke.
longlines.txt (END)

$ less -S longlines.txt
WHAN that Aprille with his shoures soote The droghte of Marche hath perced to th
And bathed every veyne in swich licour, Of which vertu engendred is the flour;
Whan Zephirus eek with his swete breeth Inspired hath in every holt and heeth
The tendre croppes, and the yonge sonne Hath in the Ram his halfe cours y-ronne,
And smale fowles maken melodye, That slepen al the night with open ye,
So priketh hem nature in hir corages: Than longen folk to goon on pilgrimages,
And palmers for to seken straunge strondes, To ferne halwes, couthe in sondry lo
And specially, from every shires ende Of Engelond, to Caunterbury they wende,
The holy blisful martir for to seke, That hem hath holpen, whan that they were s
longlines.txt (END)


text:
Q: Give comparision of Nutch Vs Heritrix I want to select one of the above for building a crawling framework for specific web sites. This is not an internet-wide crawl. I am not building a search index, and rather interested in scraping specific pages from the web site.
Could somebody please detail about the pros and cons of above?
Thanks
Nayn

A: Your main task is scrape specific pages from the web site.
Nutch: Open-source web-search software, built on Lucene Java
Heritrix: is the Internet Archive's open-source, extensible, web-scale, archival-quality web crawler project
So I think Heritrix is much better than Nutch for your project.
Learning a framework/library is a valuable exercise. But it takes some time. Since you task is not very complex one, sometimes it would be less painful to write a simple crawler from the scratch in Java


text:
Q: How to set the overall background color behind the view in React-Native Is there a way to set the overall backgroundColor behind the view being rendered in React Native? For example if I style my view with marginTop: 30 then there is a blank whitespace above the view. I'm wondering if there is a way to alter this background color?
renderStoriesListView() {
if (this.state.dataSource.getRowCount() === 0) {
  return (
    <Loading>top stories</Loading>
  )
} else {
  return (
    <View style={{marginTop: 30, backgroundColor: 'black'}}>
    <RefreshableListView
      dataSource={this.state.dataSource}
      renderRow={this.renderStory}
      loadData={this.loadTopStories}
      refreshDescription="Refreshing top stories"
      refreshingIndictatorComponent={<Refreshing />}

    /></View>
  )
}
},
  render() {
return this.renderStoriesListView()
}
})

A: Try this...
<View style={{backgroundColor: 'black'}}>
<View style={{marginTop: 30}}>
<RefreshableListView
  dataSource={this.state.dataSource}
  renderRow={this.renderStory}
  loadData={this.loadTopStories}
  refreshDescription="Refreshing top stories"
  refreshingIndictatorComponent={<Refreshing />}

/></View></View>


text:
Q: Java SplashScreen.getSplashScreen() returns null Trying to get a SplashScreen working in Java; unfortunately without any success.
I have read many threads about it but almost all of them are pretty old.
I have set up a maven project and was following the Sun/Oracle Tutorial about the SplashScreen.
I am using the maven-jar-plugin to create my manifest.mf file. In there I specified the main class and the image file as shown in the tutorial.
Extract of my pom.xml file
<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-jar-plugin</artifactId>
            <version>3.2.0</version>
            <configuration>
                <archive>
                    <manifestFile>src/main/resources/META-INF/MANIFEST.MF</manifestFile>
                </archive>
            </configuration>
        </plugin>
    </plugins>
</build>

My manifest.mf file contains the following two additional lines:
Main-Class: com.mycompany.splashscreen.MySplashScreen
SplashScreen-Image: images/java-duke-logo.jpg

I copied the image in src/main/resources/images followed maven standard directory recommendation.
Nevertheless, the following line:
final SplashScreen splash = SplashScreen.getSplashScreen();

always returns null!
In the generated jar file the image was put in the package "images".
Kindly asking for a lead to get it work. Thanks.
(My working environment: MacOSX 10.13.6, jdk16, NetBeans 12.3)

A: I've managed to make it work by editing the original project, using the following directory structure:
└───misc-SplashDemoProject
    │   pom.xml
    │
    └───src
        └───main
            ├───java
            │   └───com
            │       └───mycompany
            │           └───splashscreen
            │                   SplashDemo.java
            │
            └───resources
                ├───images
                │       splash.gif
                │
                └───META-INF
                        MANIFEST.MF

pom.xml:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">

  <modelVersion>4.0.0</modelVersion>
  <groupId>com.mycompany</groupId>
  <artifactId>spashscreen</artifactId>
  <version>0.1.0-SNAPSHOT</version>

  <build>
    <plugins>
      <!-- Java 9 or later
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.8.0</version>
        <configuration>
          <release>16</release>
        </configuration>
      </plugin>
      -->
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-jar-plugin</artifactId>
        <version>3.2.0</version>
        <configuration>
          <archive>
            <manifest>
              <mainClass>com.mycompany.splashscreen.SplashDemo</mainClass>
            </manifest>
            <manifestFile>src/main/resources/META-INF/MANIFEST.MF</manifestFile>
          </archive>
        </configuration>
      </plugin>
    </plugins>
  </build>
</project>

MANIFEST.MF:
Manifest-Version: 1.0
X-COMMENT: Main-Class will be added automatically by build
Codebase: *.oracle.com
Permissions: sandbox
Application-Name: Splash Demo
SplashScreen-Image: images/splash.gif

I've edited SplashDemo.java by replacing:
package misc;

with:
package com.mycompany.splashscreen;

Running:
mvn clean install

Creates the executable .jar file in misc-SplashDemoProject/target


text:
Q: Call COM DLL functions from ASP.NET project as specific user I am trying to call an old VB6 dll (no source code available) from an ASP.NET project. The dll connects to a server using windows authentication, so I need to call functions as a specific user, not NETWORKSERVICE as it is now.
This would preferably be determined at call time, not load time because I am impersonating the remote user and would like for this to be the user calling the functions, not the application user and not NETWORKSERVICE as it is now.
So, theres the browser running as USER, connecting to the application impersonating USER, calling the dll as USER, but the dll is trying to connect to a remote server as NETWORKSERVICE, not USER.
Is it possible to make this dll connect to the remote server as USER? Or, if nothing else, connect as the application user?
Edit:
Impersonation is done in code by calling Impersonate() on the remote user's WindowsIdentity. The company I work for has a custom SecurityPrincipal and SecurityIdentity so it's kind of weird how I have to go about getting the WindowsIdentity (it's a little more in depth than User.Identity), but I have used this method before successfully and have verified that System.Security.Principal.WindowsIdentity.GetCurrent().Name
 is the correct user during the impersonation.

A: I would first try to find out how the DLL is connecting as a different user (Process Explorer can help with this).  Is it possible that the DLL is communicating with a service (or some other process) which is running on the box which is logged in as NETWORKSERVICE?  If so, you can change that service to run as a different user.  Just grasping at straws, hope you figure it out!

A: I did eventually find the problem (which just lead to other problems, but anyway) it turned out to be I was missing an AspCompat="true" on my page. Actually the problem was that I was using a "Handler" and not a "Page". Handlers do not have the STA abilities that Pages have. What was happening was every time I tried to access the COM component, there would be a thread switch (impersonation lost) since the application is running in an MTA and the COM component must run in an STA.


text:
Q: Constructing a RatingBar using images loaded from the web I have a form which I'm dynamically generating from data I receive from a web service. This web service provides images which need to be used in the creation of input elements. I'm having difficuly in setting the progressDrawable of a RatingBar. Though XML I'm able to apply a custom image using the following as the progressDrawable:
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:id="@+android:id/background" android:drawable="@drawable/custom_star" />
    <item android:id="@+android:id/secondaryProgress" android:drawable="@drawable/custom_star" />
    <item android:id="@+android:id/progress" android:drawable="@drawable/custom_star" />
</layer-list>

where custom_star is a simple .png image, and with @android:style/Widget.RatingBar as the RatingBar style. This works fine:

but I'm wanting to change custom_star dynamically.
In code, I have tried setting the progress drawable using a bitmap directly:
Drawable d = new BitmapDrawable(getResources(), downloadedImage);
ratingBar.setProgressDrawable(d);

and also by constructing a layer-list:
LayerDrawable layerDrawable = new LayerDrawable(new Drawable[] {
    getResources().getDrawable(R.drawable.custom_star),
    getResources().getDrawable(R.drawable.custom_star),
    getResources().getDrawable(R.drawable.custom_star)
});

layerDrawable.setId(0, android.R.id.background);
layerDrawable.setId(1, android.R.id.secondaryProgress);
layerDrawable.setId(2, android.R.id.progress);

ratingBar.setProgressDrawable(layerDrawable);

Neither works for me; both result in the custom_star drawable appearing once, stretched by the dimensions of the RatingBar:

Any ideas?
Update:
Luksprog's answer below has made an improvement, but I'm still having a couple of issues. Now, the star drawable is not stretched and the value can be set by touch, but it appears as so with 3/5 selected:

and 5/5 selected:

I believe the scaling of the images can be fixed with a few tweaks, but annoyingly the secondaryProgress drawable doesn't seem to be set - the drawable used for the greyed out not-selected stars. Without that, it's not very usable.

A:
Any ideas?

When using the default progressDrawable or a progressDrawable set through a theme all will be ok as in the constructor for the RatingBar(its superclass ProgressBar to be more precise) widget a method will be called to "make tiles" from that drawable. When using the setProgressDrawable method this doesn't happen and if you pass a simple BitmapDrawable or a LayerDrawable(with simple BitmapDrawables) that Drawable will simply be stretched to cover the widget's background area(what you see know).
In order to make it work you would need to manually do what the RatingBar does at start, create the tiles along with the ClipDrawables that it uses. I've written a method for this, following the source code of the ProgressBar widget:
private Drawable buildRatingBarDrawables(Bitmap[] images) {
    final int[] requiredIds = { android.R.id.background,
            android.R.id.secondaryProgress, android.R.id.progress };
    final float[] roundedCorners = new float[] { 5, 5, 5, 5, 5, 5, 5, 5 };
    Drawable[] pieces = new Drawable[3];
    for (int i = 0; i < 3; i++) {
        ShapeDrawable sd = new ShapeDrawable(new RoundRectShape(
                roundedCorners, null, null));
        BitmapShader bitmapShader = new BitmapShader(images[i],
                Shader.TileMode.REPEAT, Shader.TileMode.CLAMP);
        sd.getPaint().setShader(bitmapShader);
        ClipDrawable cd = new ClipDrawable(sd, Gravity.LEFT,
                ClipDrawable.HORIZONTAL);
        if (i == 0) {
            pieces[i] = sd;
        } else {
            pieces[i] = cd;
        }
    }
    LayerDrawable ld = new LayerDrawable(pieces);
    for (int i = 0; i < 3; i++) {
        ld.setId(i, requiredIds[i]);
    }
    return ld;
}

Then you would use the LayerDrawable returned by this method with the setProgressDrawable method. The RatingBar set its width multiplying the width of one of the state bitmaps with the number of stars, so in order to show the right amount of stars this has to be calculated as well.

A: Your ids are wrong, you have to set
@android:id/background
@android:id/secondaryProgress
@android:id/progress
You can also define a drawable in xml containing your customization
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:id="@+android:id/background"
          android:drawable="@drawable/star_empty" />
    <item android:id="@+android:id/secondaryProgress"
          android:drawable="@drawable/star_empty" />
    <item android:id="@+android:id/progress"
          android:drawable="@drawable/star_full" />
</layer-list>

And you can use setMax on the RatingBar object to set the maximum amount of stars that can be displayed

A: It's much easier with such solution:
RatingBar ratingBar = new RatingBar(new ContextThemeWrapper(context, R.style.AppTheme_RatingBar), null, 0);


text:
Q: Why doesnt this next line run? The point of this program is to ensure valid input of two integers between 0 to 2 with a space in between (and strictly nothing else), and then to assign the result of these two integers to variables. For some reason this isn't allowed.
Very basic typecasting has me confused. The print statement %i and %i never runs! I can't see why, even though I've put braces around the part that has "success" labelled. I've tried quite a few things.
#include <stdio.h>
#include <string.h>

int main(void)
{
    int row, column;
    char buffer[100];

    }

    printf("enter 2 values of row | column format \n");

    fgets(buffer,100,stdin);
    sscanf(buffer,"%c %c",&row, &column);
    printf("%i %i", row,column);

// only accepts integers between 0 and 2 inclusive

    if ((((int)row >=48) && ((int)row <= 50 )) && ((int)column >= 48) && ((int)column <= 50))
        {

        printf("success\n");
        printf("%i and %i", atoi(row), atoi(column));

        }

    else
        printf("fail\n");

    return 0;
}

A: Good that OP it trying to validate input.

To accept 2 int:
char dummy;  // Used to detect text after the 2 digits
if (sscanf(buffer,"%d %d %c", &row, &column, &dummy) != 2) {
  puts("Input is not 2 ints");
}

Then test the range
if (row < 0 || row > 2 || column < 0 || column > 2) {
  puts("Outside 0 to 2 range");
}

Additional code needed to detect out-of-range text for an int.  Something like the below which limits input to 1 digit each for the int and records the scan offset between the two int to insure some white-space.
int n1, n2;
if (sscanf(buffer,"%1d%n %n%1d %c", &row, &n1, &n2, &column, &dummy) != 2 || n1 == n2) {
  puts("Input is not 2 ints");
}

Save time
Enable all compiler warnings.  A good compiler will complain about sscanf(buffer,"%c %c",&row, &column); - "%c" expects an char *, not int *.

A: Move away from the scanf() family of functions. They are the cause of so many SO questions...
The following should be simple to understand. When you wake up I'd be happy to elaborate on anything you might find perplexing.
#include <stdio.h>
#include <string.h>

int main( void ) {
    printf("enter 2 values of row | column format \n");

    char buf[ 100 ];
    fgets( buf, 100, stdin );

    if( buf[3] == '\n' // fgets leaves LF in the buffer
    &&  ('0' <= buf[0] && buf[0] <= '2' )   // limit ASCII digit
    &&  buf[1] == ' '                       // single space between
    &&  ('0' <= buf[2] && buf[2] <= '2' )   // limit ASCII digit
    ) {
        int row = buf[0] - '0', col = buf[2] - '0';
        printf( "success\n%i and %i", row, col );
    } else
        puts( "fail" );

    return 0;
}


text:
Q: How can I get item by composite key? const dynamoDB = new AWS.DynamoDB.DocumentClient();
    var params: any = {};
    params.TableName = 'StockDailyCandles';
    var key = { 'symbol': 'AAPL', 'datetime': '640590008898' }; // example timestamp
    params.Key = key;

    var x = await dynamoDB.get(params).promise();
    return (x.Item ? true : false);

The composite key for the table is  symbol, and "datetime"(which is simply a timestamp). Both columns are set as strings in dynamodb.
The error im receiving is : The provided key element does not match the schema

A: Try it more like this:
const AWS = require("aws-sdk");

AWS.config.update({ region: "us-west-2" });

const documentClient = new AWS.DynamoDB.DocumentClient();

async function getItem() {
  const params = {
    TableName: "RetailDatabase",
    Key: {
      pk: "jim.bob@somewhere.com",
      sk: "metadata",
    },
  };

  const response = await documentClient.get(params).promise();
  return response;
}

getItem()
  .then((data) =>
    console.log("GetItem succeeded:", JSON.stringify(data, null, 2))
  )
  .catch((error) => console.error(JSON.stringify(error, null, 2)));


text:
Q: Does there exist and open set $U$ such that $A⊆U$ and $μ(U∖A)<ϵ$? Let $(X,\mathcal{M},\mu)$ be a measure space. Take $\epsilon > 0$ and $A \in \mathcal{M}$.
Is it in general true that there exist and open set $U$ such that $A \subseteq U$ and $\mu(U \setminus A)<\epsilon$  ?
If it is, I would also be grateful for a hint on how to prove this.
I need only the case when $X=\mathbb{R^n}$, $\mathcal{M} = \mathcal{B}(\mathbb{R^n})$, and $\mu$ is the Lebesgue measure. But I would be interested in a more general result, if there is one.
Thank you in advance!

A: On an arbitrary set $X$, the concept of "open set" is not defined.  In order to talk about open sets, you need $X$ to be a topological space.
A very common general setting is the following: Let $X$ be a locally compact Hausdorff space, $\mathcal{M} \supset \mathcal{B}(X)$ a $\sigma$-algebra containing the Borel sets, and $\mu$ a Borel measure on $\mathcal{M}$.  Your question amounts to asking whether or not the measure $\mu$ is "outer regular."  In general, no, an arbitrary Borel measure on $X$ need not be outer regular.
However, it is true that the Lebesgue measure on $\mathbb{R}^n$ is outer regular.  Here's a hint:
If you're defining Lebesgue measure as
$$\mu(A) = \inf\{\sum_{n=1}^\infty |I_n|\colon\, A \subset \bigcup_{n=1}^\infty I_n\},$$
where the $I_n$ are open intervals (rectangles), then you should think about using the definition of "infimum."


text:
Q: How to protect app hosted on Google Cloud Run? I'm looking into building a Cloud Run based API that requires authentication. Is it possible to invoke it only if the request meets some security checks for example:

*

*Query string passes my function (eg. param X has value of Y)

or

*

*Authorization header value passes my function (JWT verification)

I'm afraid that if I run those checks after invocation, someone can DDoS my API and I will be the one to pay the bill.

A: You can use IAM authentication and require a valid and authorized authentication to access the service. You have example here. All the not authorized traffic is filter by Google (Google Front end (or GFE) layer)
You can also deploy an API Gateway (or a Cloud Endpoint, the feature are very similar) and accept an API key. It's not recommended but in some situation it's better than nothing. I wrote an article on that. You will pay the number of requests on API Gateway (good or not), but your service is protected and the valid requests processed.
You can also try a new feature for Cloud Run: IAP (Identity Aware Proxy). You need to deploy a Load Balancer and to plug IAP on it. With a Load balancer you can also deploy Cloud Armor on it (a WAF) and then prevent your service against attacks.

A: You can use ESPv2 https://cloud.google.com/endpoints/docs/openapi/get-started-cloud-run#migrating_to.
You can add API key as well as JWT auth easily with firebase.


text:
Q: Store tag input values in a single column into database using Laravel8 I Have the following form with a tag input.
<form id="filialeform" action="filiales" enctype="multipart/form-data">
  {{ csrf_field() }}
  <input type="hidden" id="id_hidden" name="id" />

    Filiale
    <input type="text" class="form-control" name="filiale" id="filiale" placeholder="Filiale">

    Adm_Email
    <input data-role="tagsinput" type="text" name="adm_email" id="adm_email">

    <input type="hidden" name="action" id="action" />
    <input type="hidden" name="hidden_id" id="hidden_id" />
    <input type="submit" name="action_button" id="action_button" class="btn btn-warning" value="Enregistrer" />

</form>

And I have the following database table :
 public function up()
    {
        Schema::create('filiales', function (Blueprint $table) {

            $table->increments('id_filiale');
            $table->string('filiale',80);
            $table->string('adm_email',500);
            $table->integer('actif');
            $table->timestamps();
        });
    }

I'mtrying to store data into database,so that the values entered in the input tag are stored in the adm_email column of the table separated with gamma.
So I'm trying the following code :
 public function store(Request $request)
    {

        $input = $request->all();
        $tags = explode(",", $request->adm_email);
        $form_data = array(
             'filiale'     =>  $request->filiale,
             'adm_email'    =>   $tags

                    );

         Filiale::create($form_data);

     return response()->json(['success' => 'Data Added successfully.']);
    }

But I'm getting the following error :
message: "Array to string conversion"

I don't know how can I realize that . If you have any idea please help.

A: Go to Model/Filiale.php and add this:
protected $casts = [
    'adm_email' => 'array',
];

Model make the conversion to and from array automatically.

A: In this line :
$tags = explode(",", $request->adm_email);

the explode function takes a string ($request->adm_email in this case) and converts it into an array, so when you then try and store it :
'adm_email'    =>   $tags

it fails because you cannot store an array, as it stands, in the database. Instead you would convert it to json, using :
'adm_email'    =>   json_encode($tags)

and then convert it from json using :
json_decode()

when you retrieve it from the database and wish to do something with it.


text:
Q: Creating credit memo does not change order grand total? I have added extra fee in the checkout page and save it to the database but when I go to credit memos the extra fee is shown in Credit memo totals but the grand total is not updated

This is my config.xml file
 <blocks>
      <adminhtml>
         <rewrite>
            <sales_order_creditmemo_totals>My_Module_Block_Adminhtml_Sales_Order_Creditmemo_Totals</sales_order_creditmemo_totals>
         </rewrite>
      </adminhtml>
    </blocks>

A: Check this module on github by Adam Moss. I have used the creditmemoSaveBefore() method in observer for the same solution.
(Use your extra charge fee variable at the place of $depositAmount)
https://github.com/adampmoss/magento-deposit-total/blob/master/app/code/local/Creare/Deposit/Model/Observer.php
Code:
class Creare_Deposit_Model_Observer {

    /* ... */

    public function creditmemoSaveBefore(Varien_Event_Observer $observer)
    {
        $post_data = Mage::app()->getRequest()->getPost();
        $creditmemo = $observer->getEvent()->getCreditmemo();
        $deposit_amount = $post_data['creditmemo']['deposit_amount'];
        if ($deposit_amount > 0)
        {
            $depositAmount = $creditmemo->getDepositAmount();
            $baseDepositAmount = $creditmemo->getDepositAmount();
            // Adjust Grand Total to reflect Deposit refund
            $creditmemo->setGrandTotal($creditmemo->getGrandTotal()-($depositAmount-$deposit_amount));
            $creditmemo->setBaseGrandTotal($creditmemo->getBaseGrandTotal()-($baseDepositAmount-$deposit_amount));
            // Set Deposit Total to actual refund amount
            $creditmemo->setDepositAmount($deposit_amount);
            $creditmemo->setBaseDepositAmount($deposit_amount);
        }
        return $this;
    }

    /* ... */
}


text:
Q: How can I replace CloudBlockBlob.OpenWriteAsync() in the Azure.Storage.Blobs v12 SDK? We have been using the older package Microsoft.Azure.Storage.Blob, and now we are moving to a newer Azure.Storage.Blobs v12.13.1. And thus need to replace a number of older methods we used.
But the CloudBlockBlob.OpenWriteAsync() I cannot find a good replacement for, in the new SDK (they seem to promise some alternatives - but still none has been provided so far).
Any suggestions on how to replace this method with the new package?
Here is our original code:
    private readonly CloudBlobContainer _container;

    public async Task<(string, int)> StoreCsvCollectionAsZipAsync(string zipFileName, IEnumerable<(string, IEnumerable<string>)> csvCollection)
    {
        var blob = _container.GetBlockBlobReference(zipFileName);
        await blob.DeleteIfExistsAsync();
        var maxRowCount = 0;

        const int bufferCapacityLines = 100;
        var bufferLinesCount = 0;
        var rowsBuffer = new StringBuilder();

        await using (var uploadStream = await blob.OpenWriteAsync())
        {
            using (var zipArchive = new ZipArchive(uploadStream, ZipArchiveMode.Create))
            {
                foreach (var (tableName, csvRows) in csvCollection)
                {
                    var rowCount = 0;
                    var zipArchiveEntry = zipArchive.CreateEntry(tableName);
                    await using var innerFile = zipArchiveEntry.Open();
                    foreach (var csvRow in csvRows)
                    {
                       ...
                    }

                    if (rowsBuffer.Length > 0)
                    {
                        var finalBytes = Encoding.UTF8.GetBytes(rowsBuffer.ToString());
                        await innerFile.WriteAsync(finalBytes);

                        rowsBuffer.Clear();
                    }

                    if (maxRowCount < rowCount) maxRowCount = rowCount;
                }
            }
        }

        var uri = GetSharedAccessUri(zipFileName);

        return (uri?.ToString() ?? "", maxRowCount);
    }

As the data could be large enough we do need to keep it as a stream.

A: The solution seems to be very simple and like this:
...
   var blob= _container.GetBlobClient(zipFileName);
   await blob.DeleteIfExistsAsync();
   await using (var uploadStream = await blob.OpenWriteAsync(true))
            {
...


text:
Q: Steam - location and game censorship From what I could read Steam offers differing versions of the games. For example non-censored US Fallout and non-US censored Fallout. I would like to go with the genuine versions. What do I need to do to get the right version? Do I just need to manually change "download location" in the Steam settings to one of the US locations? I can also see that there is a "Country: xxx" in account settings. Does it affect it?

A: Changing download location may work. But if you really want to make sure you can find someone in the country that has the version you want to gift you the game. Or you could just create a new account and choose the country you want during setup and then just gift the game to yourself.


text:
Q: How to check if file is still being copied in bash? How to check if file is still being copied in bash?
How to check the progress of copy operation in bash?
Thank you!
P.S. I'm copying a file via Ctrl+C - Ctrl-V, not over the  Bash.

A: What about md5sum?
Check current file:
$ md5sum bigfile.img
cd573cfaace07e7949bc0c46028904ff  bigfile.img`

Start copy and check during copy process:
$ cp bigfile.img /tmp/
$ md5sum /tmp/bigfile.img
8e516a451c4b3c440d7bf9aebc5f3639  /tmp/bigfile.img

And check after copy finished:
$ md5sum /tmp/bigfile.img
cd573cfaace07e7949bc0c46028904ff  /tmp/bigfile.img

Then you can use something like:
S_SUM=$(md5sum bigfile.img | cut -d " " -f 1)
D_SUM=$(md5sum /tmp/bigfile.img | cut -d " " -f 1)

And compare two $SUM variables in some while true; do loop.
Another way - using cmp and exit code:
$ cmp -b bigfile.img /tmp/bigfile.img; echo $?
0

$ cmp -b bigfile.img /tmp/qtsingleapp-homese-8faf-3e8-lockfile &> /dev/null; echo $?
1

A: Easiest way for this - just compare md5sum of files or file sizes like that
#!/bin/sh
SOURCE_SIZE=$(stat -c%s source_file)
DEST_SIZE=$(stat -c%s destination_file)
if [[ "$SOURCE_SIZE" -eq "$DEST_SIZE" ]]; then
    echo '..........'
fi

A: function check
{
oldsize=`wc -c <"$f"`
sleep 1
newsize=`wc -c <"$f"`

while [ "$oldsize" -lt "$newsize" ]
do
 echo "The file is growing... "
oldsize=`wc -c <"$f"`
sleep 1
newsize=`wc -c <"$f"`
done

if [ "$oldsize" -eq "$newsize" ]
then
   echo "The copying is done!"
fi
}


text:
Q: List of subfolders with 2 ghost entries how can I avoid them? With a bat file I sorted the subfolders list in a Directory but what are the 2 folders named "." 1 dot and ".." 2 dots ?  actually they are not present in windows explorer and most of all how I can avoid to show them in the list ?
@echo off
setlocal EnableExtensions EnableDelayedExpansion
> ".\Utils\Check last modified Profile.txt" (
    for /F "delims=" %%D in ('
    dir %APPDATA%\Mozilla\Firefox\Profiles\  /A /all-D /TW /A:D /O:-DE
') do (
    rem print each item:
       echo %%~D %
      )
)
endlocal

image here > https://imgur.com/8XyQk6q

A: . is the current directory. .. is it's parent directory.
Explorer hides them.
Dir C:\windows\.\.\..

A: dir %APPDATA%\Mozilla\Firefox\Profiles\  /A /all-D /TW /A:D /O:-DE ^|findstr /v /e /L /c:"."

worked for me.
The dir output is sent to findstr which allows through lines which do not (/v) end (/e) with the literal (/L) string "."
Directories cannot be created that end with .
I believe I do not need to comment further on the attributes-selection specification.
The ^ is required to have the pipe applied to the dir command, not the for.
I'll make no further comment on the attributes-selection specified.

A: I have decided to post this because the existing answers appear to be using the same crazy and incorrect options for the Dir command. The following examples use the appropriate findstr.exe method of eliminating the . and .. directory entries from your listing, sorted according to most recently modified to least recent. I have included the full path to findstr.exe to eliminate the possibility of %PATH% and/or %PATHEXT% modifications from not being able to locate it.
If you wanted the same output format, then this should work for you:
@For /F "Tokens=1*Delims=:" %%G In ('"Dir "%AppData%\Mozilla\Firefox\Profiles" /AD/O-DE 2>NUL|%SystemRoot%\System32\findstr.exe /ELNV ".""')Do @Echo(%%H

If you don't need the empty lines then, this should omit those for you:
@For /F "Delims=" %%G In ('"Dir "%AppData%\Mozilla\Firefox\Profiles" /AD/O-DE 2>NUL|%SystemRoot%\System32\findstr.exe /ELV ".""')Do @Echo %%G

And if you only needed the directory name lines, then perhaps this will satisfy you:
@For /F EOL^=^ Delims^= %%G In ('"Dir "%AppData%\Mozilla\Firefox\Profiles" /AD/O-DE 2>NUL|%SystemRoot%\System32\findstr.exe /ELV ".""')Do @Echo %%G

A: You can use and add this switch /B
@echo off
@for /F "delims=" %%D in ('
    dir %APPDATA%\Mozilla\Firefox\Profiles\ /A /all-D /TW /A:D /O:-DE /B
') do (
    echo %%~D
    )


text:
Q: WPF/C# Updating (and disposing of) Bitmap/BitmapSource in ValueChanged event? I have a small image editing program that opens an image and does fancy stuff to it. In this case, I'm trying to adjust the brightness of the pixels. The problem isn't getting the pixels right, its disposing the Bitmap/BitmapSources being created in the ValueChanged event for my slider.
So basically the user will click a button and it will open up a new window with a slider. This new window makes a copy of the original bitmap for later use.
When the slider's value changes, it will create a new Bitmap from the original with the corresponding brightness increase, create a new BitmapSource from this, and update the image control's source. Even though I'm using a 'using' statement, I still get an "out of memory" exception after sliding for so long.
Any idea why this is? Is there a better workaround that can achieve the same thing? I have included the code below:
using Imagin.Slideshow;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace Imagin
{
    /// <summary>
    /// Interaction logic for BrightnessWindow.xaml
    /// </summary>
    public partial class BrightnessWindow : Window
    {

        public int Increase;

        private System.Drawing.Bitmap Bitmap;
        private System.Drawing.Bitmap NewBitmap;

        private MainWindow ParentWindow;

        public BrightnessWindow(MainWindow m)
        {

            InitializeComponent();

            this.ParentWindow = m;

            this.Bitmap = (System.Drawing.Bitmap)this.ParentWindow.Document.Bitmap.Clone();

        }

        private void slider1_ValueChanged(object sender, RoutedEventArgs e)
        {

            using (System.Drawing.Bitmap b = (System.Drawing.Bitmap)this.ParentWindow.Document.Bitmap.Clone(new RectangleF() { Width = (int)this.ParentWindow.Document.Bitmap.Width, Height = (int)this.ParentWindow.Document.Bitmap.Height, X = 0, Y = 0 }, this.ParentWindow.Document.Bitmap.PixelFormat))
            {
                this.ParentWindow.SetPixels(b, AdjustmentTypes.Brightness, Convert.ToInt32(this.slider1.Value));
                BitmapSource m = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(b.GetHbitmap(), IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions());
                this.ParentWindow.image1.Source = m;
                this.NewBitmap = (System.Drawing.Bitmap)b.Clone();
            }

        }

        private void applyButton_Click(object sender, RoutedEventArgs e)
        {
            if (this.NewBitmap != null)
            {
                this.ParentWindow.Document.Bitmap = this.NewBitmap;
            }
            this.Close();
        }

        private void cancelButton_Click(object sender, RoutedEventArgs e)
        {
            this.ParentWindow.Document.Refresh();

            this.Close();
        }
    }
}

Another thing I was wondering is if there is a better way to alter the MainWindow's controls without having to pass it as a parameter, or is this the preferred approach for that kind of thing? Thanks!

A: http://msdn.microsoft.com/en-us/library/1dz311e4%28v=vs.110%29.aspx
Every time you use bitmap.GetHbitmap you create a new instance of a gdibitmap. Per the msdn link, "You are responsible for calling the GDI DeleteObject method to free the memory used by the GDI bitmap object. For more information about GDI bitmaps, see Bitmaps in the Windows GDI documentation."
I'd pull that guy out to a variable and call deleteobject on it when you're done with it, otherwise you're just creating n gdibitmaps where n = number of times you move the slider and never disposing of them.
Edit: Highlighting the line:
//Somewhere in the class
[System.Runtime.InteropServices.DllImport("gdi32.dll")]
public static extern bool DeleteObject(IntPtr hObject);

    private void slider1_ValueChanged(object sender, RoutedEventArgs e)
    {

        using (System.Drawing.Bitmap b = (System.Drawing.Bitmap)this.ParentWindow.Document.Bitmap.Clone(new RectangleF() { Width = (int)this.ParentWindow.Document.Bitmap.Width, Height = (int)this.ParentWindow.Document.Bitmap.Height, X = 0, Y = 0 }, this.ParentWindow.Document.Bitmap.PixelFormat))
        {
            this.ParentWindow.SetPixels(b, AdjustmentTypes.Brightness, Convert.ToInt32(this.slider1.Value));
            IntPtr hbitmap = b.GetHbitmap(); //create variable so we don't orphan the object
            BitmapSource m = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(hbitmap, IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions()); //use variable
            this.ParentWindow.image1.Source = m;
            this.NewBitmap = (System.Drawing.Bitmap)b.Clone();
            DeleteObject(hbitmap); //delete gdi object
        }

    }


text:
Q: Is zookeeper required for partitions on single machine? If single machine contains 4 partitions against same topic. I believe this will be treated as cluster and i need zookeeper to manage the partitions.?

A: Zookeeper is always needed for having Apache Kafka working even if you have a single machine with only one Apache Kafka instance.