text:
Q: Magento product images new option Hey guys, how do i add one more option to product image list? like Exclude & Remove checkboxes

A: @vrnet
You were almost there...
In addition, you would need to update:

*

*/js/mage/adminhtml/products.js (ton of changes). Basically you would need to add code for JSON to handle your new field. I needed to add a second label on my end and ended up copyPasting label code and changing the variable names to match the code variable. Should be pretty straight forward.

*(line 66) Mage_Catalog_Model_Resource_Eav_Mysql4_Product_Attribute_Backend_Media class, you would need to add your new column so that it would be loaded back from the DB.
If you have any questions, drop me an email

A: I'm trying to code the same feature. Did you have an answer ?
The idea is to add a "Use as page" checkbox for each image in the image gallery. The goal being to make a JS carousel with all picture checked as "Use as page".
I have a few things done but I cannot update data in the database.
--> So my question is : how to update data in the database and retrieve it in the checkbox (0 or 1 depending on the checkbox) ?
Thanks all for your very precious help.

Here is what I've done (1.4.1.0) :
1- Update table catalog_product_entity_media_gallery_value
Added a new field (which name is "page") :

*

*page      tinyint(4)          UNSIGNED    No      0

2- Made the following changes to class Mage_Catalog_Model_Product_Attribute_Backend_Media
Line 49 :
from
$localAttributes = array('label', 'position', 'disabled');

to
$localAttributes = array('label', 'position', 'disabled', 'page');

Line 223 :
from
$data['disabled'] = (int) $image['disabled'];

to
$data['disabled'] = (int) $image['disabled'];
$data['page'] = (int) $image['page'];

Line 301
from
$mediaGalleryData['images'][] = array(
    'file'     => $fileName,
    'position' => $position,
    'label'    => '',
    'disabled' => (int) $exclude
);

to
$mediaGalleryData['images'][] = array(
    'file'     => $fileName,
    'position' => $position,
    'label'    => '',
    'disabled' => (int) $exclude,
    'page' => (int) $exclude,
);

Line 328
from
$fieldsMap = array(
    'label'    => 'label',
    'position' => 'position',
    'disabled' => 'disabled',
    'exclude'  => 'disabled',
);

to
$fieldsMap = array(
    'label'    => 'label',
    'position' => 'position',
    'disabled' => 'disabled',
    'exclude'  => 'disabled',
    'page'  => 'disabled',
);

3- Made the following changes to template adminhtml/default/default/template/catalog/product/helper/gallery.phtml
Line 64
from
    <?php echo Mage::helper('catalog')->__('Exclude') ?>

to
    <?php echo Mage::helper('catalog')->__('Exclude') ?>
    <?php echo Mage::helper('catalog')->__('Is Page') ?>

Line 77
from
<input type="checkbox" <?php if($_block->getElement()->getReadonly()):?> disabled="disabled"<?php endif;?> onclick="<?php echo $_block->getJsObjectName(); ?>.updateImage('__file__')" />

to
<input type="checkbox" <?php if($_block->getElement()->getReadonly()):?> disabled="disabled"<?php endif;?> onclick="<?php echo $_block->getJsObjectName(); ?>.updateImage('__file__')" />
<input type="checkbox" <?php if($_block->getElement()->getReadonly()):?> disabled="disabled"<?php endif;?> onclick="<?php echo $_block->getJsObjectName(); ?>.updateImage('__file__')" />

Line 105
from

to
            <input type="hidden" />
            <input type="hidden" />


text:
Q: cannot download an image from server with authentication using c# in wpf am using following code to download image from server but failed.
am using server authentication please help
  private BitmapImage getimage (string uri)
    {

        var webRequest = WebRequest.Create(uri);//making a variable webrequest,
        webRequest.Credentials = new NetworkCredential("user", "password");//credential is using for authentication
        using (var webResponse = webRequest.GetResponse())//use for stucking problem of button
        {
            using (var responseStream = webResponse.GetResponseStream())
            {
                BitmapImage img = new BitmapImage();
                img.BeginInit();
                img.StreamSource = responseStream;
                img.EndInit();
                return img;

            }
        }

    }

A: The problem is that you are closing the response stream before the image is completely downloaded. In order to ensure that it is completely downloaded, you can copy it to an intermediate MemoryStream. Moreover, you will have to set the BitmapCacheOption.OnLoad flag if you want to close the stream immediately after EndInit. See the Remarks section in BitmapImage.StreamSource .
using (var webResponse = webRequest.GetResponse())
using (var responseStream = webResponse.GetResponseStream())
using (var memoryStream = new MemoryStream())
{
    responseStream.CopyTo(memoryStream);
    BitmapImage img = new BitmapImage();
    img.BeginInit();
    img.CacheOption = BitmapCacheOption.OnLoad;
    img.StreamSource = memoryStream;
    img.EndInit();
    return img;
}

Alternatively you could delay the closing of the WebResponse until the image has been download completely. BitmapImage provides the DownloadCompleted and DownloadFailed event handlers for purposes like that. Note that closing the WebResponse also closes the response stream.
var webResponse = webRequest.GetResponse();
var img = new BitmapImage();
img.DownloadCompleted += (o, e) => webResponse.Close();
img.DownloadFailed += (o, e) => webResponse.Close();
img.BeginInit();
img.StreamSource = webResponse.GetResponseStream();
img.EndInit();
return img;

redpajama_set_name: RedPajamaStackExchange


text:
Q: inconsistent behavior from BigDecimal and MathContext I am Seeing some strange behavior from BigDecimal
When I do division using mathContext the output is different than when I do the division by directly providing the scale and rounding mode
Here is an example that I think should provide the same output
public static void main(String...args){
    MathContext mc = new MathContext(3,RoundingMode.HALF_UP);
    BigDecimal four = new BigDecimal(4);
    BigDecimal three = new BigDecimal(3);
    System.out.println(four.divide(three,3,RoundingMode.HALF_UP));
    System.out.println(four.divide(three,mc));
}

Output:
1.333
1.33

It appears that the scale is treated differently when using MathContext. Or I dont understand when to use which.

A: The divide method of BigDecimal lets you specify the scale of the result, which loosely speaking is number of decimal places.  scale = 3 means that a number will be expressed with 3 decimal places.  A negative scale indicates the number of insignificant zeroes at the end of a whole number - so for example to round to the nearest 1000, you can specify scale = -3.
four.divide(three,3,RoundingMode.HALF_UP);  // scale = 3, so round to 3 decimal places

But a MathContext is different.  It lets you specify precision - that is, the number of significant digits.  This is different from scale.
MathContext mc = new MathContext(3,RoundingMode.HALF_UP);
four.divide(three, mc); // precision = 3, so round to 3 significant figures


text:
Q: MongoDB OR query in PHP What is the correct code to compare username and experience using OR?
$regex = new MongoRegex("/".$name."*/i");
$regex2 = new MongoRegex("/".$comm."*/i");

$where = array('$in' => array('username' => array($regex),'experience' => array($regex2)));
$cursor = $collection->find($where)->limit($limit)->skip($skip);

A: What do you want with an $in operator in the context of two regular expressions? Makes zero sense....look at the $or operator instead.


text:
Q: Woocommerce Save Order button is not working for two orders
I received two orders and order status is automatically set to on hold.
When the order was ready to deliver, I tried to change the order status to Pending Payment (as you see in the picture) but unfortunately the Save Order button is not working and it is not doing anything. I don't have any problem for the other orders. I have processed more than 100 orders without any problem. I couldn't find any difference between these orders and others that don't have any problem.
I found that I can change the order status to processing, on-hold or complete from the bulk edit (see below picture) but there is no Pending Payment option in bulk edit.

Do you have any idea?

A: Finally, I found the problem.
The problem was because of the value with more than 1 decimal place in QTY field.

A: @Majid Nasirinejad
I guess you are using the plug-in WooCommerce Advanced Quantity.
I had the same issue and just found its cause.
Under "Edit Product" in the "Product data" section under 'WooCommerce Advanced Quantity' you can set "Minimum" and "Step" among others.
If in the 'Edit Order' page you edit the quantity and put any value outside those you defined in "Minimum" and "Step" etc., the "Update Button" will stop responding.
Solution:
e.g. Product C:
Weight (kg): 1
Minimum: 0.25
Step: 0.25
In this case, values allowed would be 0.25 - 0.50 - 0.75 - 1.00 - 1.25 etc.
if you put a value not covered by your settings, e.g. 0.4 or 1.17 your "Update Button" will not work.


text:
Q: Connecting mysql to visual studio I have a MYSQL database and I wish to connect it to my visual basic application running in visual studio. I know the code once it is connected however I am not sure on how to initially connect it up to visual studio.
I have done it once before using MYSQL-Connector however I cant seem to be able to run the connector.
I am also using a uni-server controller to run the database too

A: First of all, download the MySQL to vb.net or Visual Studio connector and install.
Go to the solution explorer and right click on the reference > add reference > com (search for myql.dll file) > ok
You are good to go but you can also decide to create a module like this to make connecting to the database easier:
  Public Sub dbconnect()

    Try
        Dim connString As String = "server=localhost; uid=root; pwd=; database=databasename"
        conn = New MySqlConnection(connString)
        conn.Open()
    Catch ex As Exception
        'MsgBox(ex.Message)
        MsgBox("Please make sure your database properly configured", MsgBoxStyle.Information, "Database Connection Error")
    End Try

End Sub

With this, whenever you want to connect to the database, just call the Sub dbconnect.


text:
Q: JS object properties undefined after I've used JSON.parse(), and properties have no invalid characters? Here is my code from Google Scripts:
var request =
UrlFetchApp.fetch('https://api.example.com/v2/directory/myuserid.json?
key=myapikey');
Logger.log(request); // see below
JSON.parse(request);
Logger.log(request); // see below
Logger.log(request["meta"]); // undefined
var meta = "meta";
Logger.log(request.meta); // undefined

When I log request before and after it's parsed, I get the following:
{"meta":{"requests":67,"timestamp":1497800064,"status":200,"message":"Request successful","method_id":1201,"method":{}},"data":{"full_name":"my name","given_name":"given name","last_name":"last name","user_id":"user id","department":"eng","common_names":["first last"],"email_addresses":[],"offices":[],"telephone_numbers":[],"homepage":""}}

This only seems to be happening with this particular API that I am using.


text:
Q: Java code, ASCII art, switch statements/structure, enter a character and then print it on the screen This is what I am asked of in my lab:

*

*Create a new class called ASCIIArt inside of your lab 4 project.
2. Before getting started, I want you to decide on 5 characters you would like to turn into
ASCII art. Choose any 5 you can find on the keyboard (excluding the examples below and function keys like Enter, Backspace, F1, Esc...) and think about how you can make them into ASCII art.
3. Back to the code, tell the user what characters you can turn into art for them, and then ask the user what character they would like to see turned into ASCII Art.
4. Using a switch statement/structure, you should implement the large versions of all 5 characters you have chosen.
5. If the user enters in an invalid character (not one of the 5 you choose) tell them that they made an invalid choice (hint: use the default case in your switch statement)
6. Make sure you have comments throughout your program (including your header comment at the beginning of your program).

Here is what I have
import java.util.Scanner;
public class ASCIIArt {
    public static void main(String[] args) {
        Scanner keyboard = new Scanner(System.in);
        System.out.println("Chose a letter to print: E, T, F, Z, I.");
        int ASCIIArt = keyboard.nextInt();
        switch (ASCIIArt) {
            case 'E': {
                System.out.println("*****");
                System.out.println("*    ");
                System.out.println("*****");
                System.out.println("*    ");
                System.out.println("*****");
                break;
            }
            case 'T': {
                System.out.println("*****");
                System.out.println("  *  ");
                System.out.println("  *  ");
                System.out.println("  *  ");
                System.out.println("  *  ");
                break;
            }
            case 'F': {
                System.out.println("*****");
                System.out.println("*    ");
                System.out.println("*****");
                System.out.println("*    ");
                System.out.println("*    ");
                break;
            }
            case 'Z': {
                System.out.println("*****");
                System.out.println("   * ");
                System.out.println("  *  ");
                System.out.println(" *   ");
                System.out.println("*****");
                break;
            }
            case 'I': {
                System.out.println("*****");
                System.out.println("  *  ");
                System.out.println("  *  ");
                System.out.println("  *  ");
                System.out.println("*****");
                break;
            }
        }
    }
}

Where did I messed up and somehow I cannot add default meaning at the end. ECLIPSE says its undefined.

A: import java.io.IOException;
import java.util.Scanner;

public class ASCIIArt {
    public static void main(String[] args) throws IOException {

        while (true)
        {
            Scanner keyboard = new Scanner(System.in);

            System.out.println("Chose a letter to print: E, T, F, Z, I.");

            String asciiString = keyboard.next();

            switch (asciiString.charAt(0)) {

                case 'E': {
                    System.out.println("*****");
                    System.out.println("*    ");
                    System.out.println("*****");
                    System.out.println("*    ");
                    System.out.println("*****");
                    break;
                }
                case 'T': {
                    System.out.println("*****");
                    System.out.println("  *  ");
                    System.out.println("  *  ");
                    System.out.println("  *  ");
                    System.out.println("  *  ");
                    break;
                }
                case 'F': {
                    System.out.println("*****");
                    System.out.println("*    ");
                    System.out.println("*****");
                    System.out.println("*    ");
                    System.out.println("*    ");
                    break;
                }
                case 'Z': {
                    System.out.println("*****");
                    System.out.println("   * ");
                    System.out.println("  *  ");
                    System.out.println(" *   ");
                    System.out.println("*****");
                    break;
                }
                case 'I': {
                    System.out.println("*****");
                    System.out.println("  *  ");
                    System.out.println("  *  ");
                    System.out.println("  *  ");
                    System.out.println("*****");
                    break;
                }
                default:
                {
                    System.out.println("Invalid char - press anykey");
                    System.in.read();
                }
            }
        }

    }

    public static void functionDumpText() throws IOException
    {

    }
}

A: import java.io.IOException;
import java.util.Scanner;

public class ASCIIArt {
    public static void main(String[] args) throws IOException {

        functionDumpText();
    }

    public static void functionDumpText() throws IOException
    {
        Scanner keyboard = new Scanner(System.in);

        System.out.println("Chose a letter to print: E, T, F, Z, I.");

        String asciiString = keyboard.next();

        switch (asciiString.charAt(0)) {

            case 'E': {
                System.out.println("*****");
                System.out.println("*    ");
                System.out.println("*****");
                System.out.println("*    ");
                System.out.println("*****");
                break;
            }
            case 'T': {
                System.out.println("*****");
                System.out.println("  *  ");
                System.out.println("  *  ");
                System.out.println("  *  ");
                System.out.println("  *  ");
                break;
            }
            case 'F': {
                System.out.println("*****");
                System.out.println("*    ");
                System.out.println("*****");
                System.out.println("*    ");
                System.out.println("*    ");
                break;
            }
            case 'Z': {
                System.out.println("*****");
                System.out.println("   * ");
                System.out.println("  *  ");
                System.out.println(" *   ");
                System.out.println("*****");
                break;
            }
            case 'I': {
                System.out.println("*****");
                System.out.println("  *  ");
                System.out.println("  *  ");
                System.out.println("  *  ");
                System.out.println("*****");
                break;
            }
            default:
            {
                System.out.println("Invalid char - press anykey");
                System.in.read();

                functionDumpText();
            }
        }
    }
}


text:
Q: How to setup monodoc to work with transifex.com? monodoc is the only C# system, which work on mono on linux. Sandcastle fails - https://github.com/ArsenShnurkov/sandcastle-tools/issues/1
The goal is to get multilanguage HTML documentation for API.
How to setup development with monodoc and transefix.com (which is opensource translation platform) for hello-world project?

A: Interesting question;  The best course of action would be to extract the strings from the various XML nodes (those inside Docs/) and put them on a .po file, translate that, and then produce a translated version out of it.


text:
Q: Select from json column There is a task to obtain most ordered products from orders table for given period of time. Table have JSON column called details and ordered products IDs are stored there:
{
    products: [
        {
            id: 1,
            quantity: 2,
        },
        {
            id: 6,
            quantity: 1
        }
    ]
}

Currently, I'm solving it this way, which kind of inefficient:
Order::whereBetween('created_at', $period)
    ->get('details->products as details')
    ->flatMap(fn ($order) => $order->details)
    ->groupBy('id')
    ->map(fn ($products) => $products->sum('quantity'));

The result contains pairs, where key - product id, and value total count from orders:
[
    1 => 2,
    6 => 1,
];

Is it possible to query product id and quantity directly?


text:
Q: PowerShell: Display the differences in permissions between folders and their parents I'm hoping to come up with a script that can walk a directory tree on a Windows server and show me a tree that only includes directories whose permissions are different from it's parent (or sub) directory.  I want to produce an easily understandable report that can help me quickly audit the permissions of a folder structure.
Here's what I've got so far:
DIR "Z:\FileShare" -directory -recurse | GET-ACL | where {$_.AreAccessRulesProtected -eq $true} | select path, accessToString | format-list  |out-file c:\permissions.txt

This produces a usable set of data as is but it's a bit bulky.
What I don't know is how to have it filter out redundant text, namely lines like "BUILTIN\Administrators Allow  FullControl" and instead only show me the delta.  Human readable psudo-code might be "if this ACL line can be found in the immediate parent directory, don't show it here."

A: I tested this with a few folders setting up different ACLs with my own user and it seem to be working but I haven't tested enough to be sure. Basically, the script will loop through directories and add the ACLs to a dictionary where the Keys are each IdentityReference and the Values are the properties from the ACLs which you're interested on (FileSystemRights and AccessControlType) in addition to the folder's absolute path. While enumerating the directories, each object will be compared against the stored values using the Compare-Acl function which only returns $true if the object is different.
using namespace System.Collections
using namespace System.Collections.Generic

$map = [Dictionary[string, ArrayList]]::new()

$outObj = {
    [pscustomobject]@{
        AbsolutePath      = $dir.FullName
        FileSystemRights  = $acl.FileSystemRights
        IdentityReference = $acl.IdentityReference
        AccessControlType = $acl.AccessControlType
    }
}

function Compare-Acl {
param(
    [object[]]$Reference,
    [object]$Difference
)
    foreach($ref in $Reference)
    {
        $fsRights = $ref.FileSystemRights -eq $Difference.FileSystemRights
        $actRef = $ref.AccessControlType -eq $Difference.AccessControlType
        if($fsRights -and $actRef)
        {
            return $false
        }
    }
    $true
}

foreach($dir in Get-ChildItem Z:\FileShare -Directory -Recurse)
{
    foreach($acl in (Get-Acl $dir.FullName | Where-Object AreAccessRulesProtected).Access)
    {
        if($thisKey = $map[$acl.IdentityReference])
        {
            $obj = & $outObj
            if(Compare-Acl -Reference $thisKey -Difference $obj)
            {
                $null = $thisKey.Add($obj)
            }
            continue
        }
        $obj = & $outObj
        $null = $map.Add($acl.IdentityReference, [object[]]$obj)
    }
}

$map.Keys.ForEach({ $map[$_] })| Export-Csv path\to\acls.csv -NoTypeInformation


text:
Q: Problem with the definition of sample function (realization). Suppose our sample space is $\Omega = \{H,T\}$ and we have two random variables $X_1 , X_2$ such that $X_1(H) = 1,X_1(T) = 2$ and $X_2(H) = 3,X_2(T) = 4$. If we define stochastic process $S = \{X_1,X_2\}$ is $\{1, 4\}$ a realization of $S$ or only sets $\{1, 3\},\{2, 4\}$ are possible realization of process $S$? I though a realization means a sequence of sampling from each random variable in a process but reading this sample function definition (also page 9)  seems i was totally wrong and $\{1, 4\}$ cant be realization of $S$ because realization is  defined for a fixed $\omega \in \Omega$ and in the case of $\{1, 4\}$ the first outcome is $H$ and the second outcome is $T$.

A: If $\omega=H$ then $X_1=1$ and $X_2=3$, and similarly if $\omega=T$ then $X_1=2$ and $X_2=4$. So indeed the only realizations of $S$ are $\{1,3\}$ and $\{2,4\}$.


text:
Q: How to validate a string is JSON or not in Java? I've already said, my question is different...question is already asked   here, but i want a predefined method in java which checksgiven string is json format or not.
if there is no predefined method then at least tell a code which checks JSON Format or not, without  using try catch block..
Thanks in advance...

A: Use JSONObject's constructor from a String
    try {
        JSONObject o = new JSONObject(yourString);
    } catch (JSONException e) {
        LOGGER.error("No valid json");
    }

A: public boolean isValidJson(String jsonStr) {
    Object json = new JSONTokener(jsonStr)).nextValue();
    if (json instanceof JSONObject || json instanceof JSONArray) {
      return true;
    } else {
      return false;
    }
}

Just pass any string in this function.

A: import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
/**
         *
         * @param inputJosn
         * @return
         * @throws IOException
         * @throws JsonParseException
         * @throws JsonProcessingException
         */
        private static boolean isJsonValid(String inputJosn) throws JsonParseException, IOException  {
            ObjectMapper mapper = new ObjectMapper();
            mapper.enable(DeserializationFeature.FAIL_ON_READING_DUP_TREE_KEY);
            JsonFactory factory = mapper.getFactory();
            JsonParser parser = factory.createParser(inputJosn);
            JsonNode jsonObj = mapper.readTree(parser);
            System.out.println(jsonObj.toString());

            return true;
        }


text:
Q: How to change search model for using one field I have CRUD generated bu Gii. By default, the search in app use one field for each table column. How should i change my search model, for make search in all columns via alone field?
That's my model:
class UserSearch extends User
{
    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['id', 'status', 'created_at', 'updated_at'], 'integer'],
            [['username', 'auth_key', 'password_hash', 'password_reset_token', 'email'], 'safe'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function scenarios()
    {
        // bypass scenarios() implementation in the parent class
        return Model::scenarios();
    }

    /**
     * Creates data provider instance with search query applied
     *
     * @param array $params
     *
     * @return ActiveDataProvider
     */
    public function search($params)
    {
        $query = User::find();

        $dataProvider = new ActiveDataProvider([
            'query' => $query,
        ]);

        $this->load($params);

        if (!$this->validate()) {
            // uncomment the following line if you do not want to any records when validation fails
            // $query->where('0=1');
            return $dataProvider;
        }

        $query->andFilterWhere([
            'id' => $this->id,
            'status' => $this->status,
            'created_at' => $this->created_at,
            'updated_at' => $this->updated_at,
        ]);

        $query->andFilterWhere(['like', 'username', $this->username])
            ->andFilterWhere(['like', 'auth_key', $this->auth_key])
            ->andFilterWhere(['like', 'password_hash', $this->password_hash])
            ->andFilterWhere(['like', 'password_reset_token', $this->password_reset_token])
            ->andFilterWhere(['like', 'email', $this->email]);

        return $dataProvider;
    }
}

A: This is how I do it:
 public function search($params)
    {
        ..............................
        if($this->keyword) {
            if(preg_match("/[A-Za-z]+/", $this->keyword) == true) {
                $query->andFilterWhere(['like', 'LOWER(CONCAT(name, age, WHATEVERFIELDS)), ', strtolower($this->keyword)]);
            } else {
                $query->andFilterWhere(['id' => $this->keyword]);
            }
        }

keyword is not actually a column in the db it is just a variable I attached to the search model. If the keyword is numeric I consider it an ID, you can ignore this part if you want. Otherwise I concat some fields and search in the result.  You can also not concat the fields and just add a condition for each field, up to you.
You can see the full file at: https://github.com/Mihai-P/yii2-core/blob/master/models/ContactSearch.php


text:
Q: Scroll to anchor after all async data and images are loaded I have one problem with my app. App aggregates some event list - each evant consist from several sections (description, speakers, location etc.). On main page I have event list (images, + some links). When I click on image - app is switching to event details (it's different route, controller and view). Now everything is ok. But I would like when user clicks link named "location" on event list main page - app should not only redirect to event details view but after that scroll down to section named location.
We used:
$document.scrollTo(document.getElementById('my_id'), 70);

Well - it worked, but some data in event details controller are loaded from firebase in async way - so id works, but after data is loaded (and images) - scroll position stays the same, but page content moves down (since data is loaded) and everything ends up with wrong scroll position.
So we wrapped this with:
$timeout(function() {
           $document.scrollTo(document.getElementById('my_id'), 70);
}, 1000);

And it helps - indeed scroll mechanism waits 1 sec and after all data is loaded and images are loaded - app scrolls down and scroll is at good position.
Beside fact that is in our opinion rather poor solution - it even sometimes fail - especially when there is slow network and data and images are loaded longer than 1sec. Of corse we can set timeout to 2sec - but problem remains the same.
Is there any chance to somehow bind (or broadcst and then bind) to event after all async data is loaded and also all images loaded and rendered? I tried every solution found (anchorScroll, jquery img load, broadcast event after all firebase element fetched and countinuus scroll after each event) in the internet but no luck.

A: One possible solution is to create an attribute directive that would
watch loaded attribute on scope and scroll content to the
element with this directive. You can switch $scope.loaded when you know
that everything was loaded. You can access element and scope in directive's link function. So you can do $document.scrollTo(element, 70); inside.
angular.module('app').directive('scrollTo', function($document) {
  return {
    restrict: 'A',
    link: function (scope, element, attrs) {
      scope.$watch('loaded', function() {
        $document.scrollTo(element, 70);
      });
    }
  };
});

Also you can use resolve property in your route to wait until everything is loaded before you render this page. In this case you can be sure that you scroll to right position


text:
Q: Sincronização automatica de base de dados no MySQL Bom dia, tenho uma base de dados MySQL local onde a disponibilidade é  de 24h, no entanto possuo outra base de dados em outro local que fica disponível por algumas horas, enfim... Eu quero sincronizar duas bases de dados idênticas automaticamente quando ambas estiverem disponíveis, com o detalhe de que alterações são efetuadas nas duas bases de dados! Existe algum método que faça isto?

A: O que você quer é uma replicação de dados MASTER-MASTER.
Tem um passo-a-passo no link http://blog.websolute.com.br/como-configurar-replicacao-multi-master-para-mysql-no-jelastic/
O processo é até simples mas requer atenção ao definir o offset do autoincrement.


text:
Q: Past perfect and simple perfect difference This is an excerpt from a newspaper.
In September 2014 the Delhi high court had restrained the institute from using words like......
Why are we using "had" here.. Can we use past indefinite?

A: The past perfect is used when there are two different times in the past that are relevant: the time the speaker is focussing on, and the earlier time when the action took place.
The example says that the writer is focussing on a time after September 2014 (but before the present) and talking about some that happened earlier than that time.
It is usually possible to substitute a simple past, but it changes the meaning, in that it does not focus attention on a time in the past the way the past perfect does.


text:
Q: How much memory is given each program when compiled/how is more memory allocated to a program? From my understanding, when a program compiles, the OS doesn't know how much memory the program will use, so does it just give it an arbitrary amount of memory, say, 200 MB? But if it does, won't really small programs be using too much unnecessary space?
If this is the case, then what happens if a program needs more than 200MB of memory? How does it allocate more space for a program? I'm looking at this image

So if a program runs out of memory, it must expand up, but won't there be another program above this one?


text:
Q: Constraint Layout Vertical Align Center - Two Child Views I have two TextViews, one above the other. I would like the vertical middle of the two TextViews to be at the same position as the vertical middle of the ImageView. (This is so, regardless of the amount of text that may go into either TextView, everything will always look neat, vertically.)
I created what I need perfectly using two LinearLayouts (as the space above the title is the same as the space beneath the description):

But Android Studio was unable to covert it to ConstraintLayout successfully, as it just dumped the TextViews at the bottom of the layout. I've played with a lot of attributes, but could not quite arrive at the desired layout.
My question is similar to this one, except that I am trying to center_vertical align a pair of views rather than a single one - which means I have no view edge to align to the centre of the ImageView/container.
Is it possible to achieve what I'm after with ConstraintLayout? (I expect I may be able to do it with a single RelativeLayout, but I would like to use the layout_constraintDimensionRatio attribute on my ImageView which presumably leave me needing to use ConstraintLayout.)
In case it helps, here's the code for my aforementioned LinearLayout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="horizontal">

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="@dimen/resources_list_image_size"
        android:layout_height="@dimen/resources_list_image_size"
        android:layout_marginEnd="@dimen/activity_horizontal_margin"
        android:layout_marginRight="@dimen/activity_horizontal_margin"
        android:layout_gravity="center_vertical"
        android:contentDescription="@string/resource_image"
        android:scaleType="centerCrop"/>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center_vertical"
        android:orientation="vertical">

        <TextView
            android:id="@+id/textViewTitle"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textAppearance="@style/MyTextAppearanceMedium"
            tools:text="Title" />

        <TextView
            android:id="@+id/textViewDescription"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textAppearance="@style/MyTextAppearanceSmall"
            tools:text="Description" />

    </LinearLayout>

</LinearLayout>

Update: Solution
Thanks to Ben P's answer, this is my final code:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <!-- Add guideline to align imageView to. -->
    <androidx.constraintlayout.widget.Guideline
        android:id="@+id/guideline"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        app:layout_constraintGuide_percent="0.3" />

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:contentDescription="@string/resource_image"
        android:scaleType="centerCrop"
        app:layout_constraintDimensionRatio="H,1:1"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintEnd_toStartOf="@id/guideline"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"/>

    <TextView
        android:id="@+id/textViewTitle"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="@dimen/activity_horizontal_margin"
        android:layout_marginLeft="@dimen/activity_horizontal_margin"
        app:layout_constraintBottom_toTopOf="@id/textViewDescription"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toEndOf="@id/imageView"
        app:layout_constraintTop_toTopOf="parent"
        android:textAppearance="@style/MyTextAppearanceMedium"
        app:fontFamily="@font/roboto_slab_regular"
        app:layout_constraintVertical_chainStyle="packed"
        tools:text="@string/enter_title_colon" />

    <TextView
        android:id="@+id/textViewDescription"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="@dimen/activity_horizontal_margin"
        android:layout_marginLeft="@dimen/activity_horizontal_margin"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toEndOf="@id/imageView"
        app:layout_constraintTop_toBottomOf="@id/textViewTitle"
        app:fontFamily="@font/roboto_slab_light"
        android:textAppearance="@style/MyTextAppearanceSmall"
        tools:text="Description" />

</androidx.constraintlayout.widget.ConstraintLayout>

A: It sounds like you could solve this problem by using a packed chain anchored to the top and bottom of the ImageView. You'll also need to use horizontal bias and a constrained width in order to get wrapping to work correctly.
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <View
        android:id="@+id/anchor"
        android:layout_width="80dp"
        android:layout_height="80dp"
        android:layout_margin="64dp"
        android:background="#caf"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintTop_toTopOf="parent"/>

    <TextView
        android:id="@+id/one"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintVertical_chainStyle="packed"
        app:layout_constraintHorizontal_bias="0"
        app:layout_constrainedWidth="true"
        app:layout_constraintTop_toTopOf="@id/anchor"
        app:layout_constraintStart_toEndOf="@id/anchor"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintBottom_toTopOf="@id/two"/>

    <TextView
        android:id="@+id/two"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_constraintHorizontal_bias="0"
        app:layout_constrainedWidth="true"
        app:layout_constraintTop_toBottomOf="@id/one"
        app:layout_constraintStart_toEndOf="@id/anchor"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintBottom_toBottomOf="@id/anchor"/>

</androidx.constraintlayout.widget.ConstraintLayout>

The important attributes here are:

*

*app:layout_constraintVertical_chainStyle="packed" on the first view, which causes the two textviews to stack right on top of each other

*app:layout_constraintHorizontal_bias="0" on both views, which means that when the text is not long enough to reach the edge of the screen it will stick to the edge of the anchor view

*app:layout_constrainedWidth="true" on both views, which prevents the textview from ever being wider than its constraints, and so the text wraps to a new line

A: If you want to use ConstraintLayout you could use something like this:
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="200dp"
        android:layout_height="200dp"
        android:contentDescription="description"
        android:scaleType="centerCrop"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

    <LinearLayout
        android:id="@+id/linearLayout"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        app:layout_constraintBottom_toBottomOf="@+id/imageView"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toEndOf="@+id/imageView"
        app:layout_constraintTop_toTopOf="@+id/imageView">

        <TextView
            android:id="@+id/textViewTitle"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            tools:text="Title" />

        <TextView
            android:id="@+id/textViewDescription"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            tools:text="Description" />

    </LinearLayout>

</androidx.constraintlayout.widget.ConstraintLayout>

A: You can use this layout:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:app="http://schemas.android.com/apk/res-auto"
  xmlns:tools="http://schemas.android.com/tools"
  android:layout_width="match_parent"
  android:layout_height="match_parent">

<TextView
    android:id="@+id/textView2"
    android:layout_width="0dp"
    android:layout_height="0dp"
    android:background="@color/colorAccent"
    android:text="I am 5% of the screen height"
    app:layout_constraintBottom_toTopOf="@+id/textView3"
    app:layout_constraintEnd_toEndOf="@+id/textView3"
    app:layout_constraintHeight_percent="0.05"
    app:layout_constraintHorizontal_bias="1.0"
    app:layout_constraintStart_toStartOf="@+id/textView3"
    app:layout_constraintTop_toTopOf="@+id/imageView2" />

<TextView
    android:id="@+id/textView3"
    android:layout_width="0dp"
    android:layout_height="0dp"
    app:layout_constraintHeight_percent="0.15"
    android:layout_marginStart="8dp"
    android:layout_marginEnd="8dp"
    android:background="@color/colorPrimary"
    android:text="I am 15% of the screen height (And the image is 20% screen size in height) "
    app:layout_constraintBottom_toBottomOf="@+id/imageView2"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toEndOf="@+id/imageView2"
    app:layout_constraintTop_toBottomOf="@+id/textView2" />

<ImageView
    android:id="@+id/imageView2"
    android:layout_width="0dp"
    android:layout_height="0dp"
    app:layout_constraintHeight_percent="0.20"
    app:layout_constraintDimensionRatio="1:1"
    android:scaleType="fitXY"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent"
    app:srcCompat="@drawable/rose" />

</android.support.constraint.ConstraintLayout>

It will look like this:

One important thing about this layout:
You can control your aspect ratio (for the image) with app:layout_constraintDimensionRatio="x:y" and by passing "1:1" make it square
And by the way - I am using support library for no reason on this example, you can use androidx


text:
Q: Count Number and Track IP Address of Software Installation We have developed a windows application. To distribute it, we put it on different software distributor website and My organization wants me to track IP, Location and count number of downloads of the software. I put some script to track this on our main product website but as I told that we are distributing this software through different vendors well so my question is how to track these ("Software which is downloaded by third party website") downloads. Is there any way to put some tracking code inside the software (in xml or any other format). The application is developed in c# on .Net framework.

A: You can add a code to do this in your C# application but you have to ask the users if they wants to participate in this feedback feature. you will need a server to hold the logs or use a ready made analytics if you use .net https://developers.google.com/api-client-library/dotnet/apis/analytics/v3


text:
Q: How would you define a type in typescript that's both an object and a function at the same time? After reading this answer to the question How is jQuery's $ a function and an object?, it got me thinking. How would you define this kind of type in typescript?
In regular JS this is completely valid:
var f = function() { alert('yo'); }
f.foo = "bar";

alert(f.foo); // alerts "bar"
f();          // alerts "yo"

However in typescript, f.foo would throw an error, Property 'foo' does not exist on type '() => void'.
While you could achieve a similar result using bracket notation:
var f = function() { alert('yo'); }
f['foo'] = "bar";

alert(f['foo']); // alerts "bar"
f();          // alerts "yo"

This would entirely bypass the type system, and there for the type safety, of typescript.
Is there a way of implementing this type of functionality without violating the type safety of typescript?

A: You can define this kind of type by specifying an invocation signature on an interface:
interface MyFoo {
    (): void;
    foo: string;
}

And you can initialize the object by casting the function to any before assigning it to the variable:
let f: MyFoo = function() { alert('yo'); } as any;
f.foo = 'bar';
x();

Playground link

As an aside, the JQueryStatic type (which is the type of the $ variable) is defined similarly in the JQuery defintions:
interface JQueryStatic<TElement extends Node = HTMLElement> {
    ...
    Deferred: JQuery.DeferredStatic;
    ...
    (html: JQuery.htmlString, ownerDocument_attributes: Document | JQuery.PlainObject): JQuery<TElement>;
    ...
    (selector: JQuery.Selector, context: Element | Document | JQuery | undefined): JQuery<TElement>;

(Can't put the links inline, so here they are)

*

*interface start

*Deferred property

*First invokable signature
However, this doesn't really help, as your question is also how to initialize a variable with this type. The JQuery library doesn't have that problem, because it isn't written in Typescript.

A: You can use & to define a variable with multiple types. It's called an "Intersection Type". More informations in the official docs.
Here's how to use it in your example :
let f: Function & {foo?: String} = function() { alert('yo'); }
f.foo = "bar";

alert(f.foo); // alerts "bar"
f();          // alerts "yo"

Playground Link
Here, the type of f is Function & {foo?: String} because it's both a Function, and also {foo?: String}. The ? is required here, as you initialize it as only a Function, and only then you assign a value to foo.
You can see in the Playground that the code compiles, and even gives the same JavaScript code you started with, validating that this is the correct syntax.


text:
Q: Can not compute reject rate in InfluxDB I have 2 measurements OK and ERROR. I would like to compute an reject/error rate using this formula:
                      count(OK)
error rate = ------------------------
             count(OK) + count(ERROR)

It would be nice to have a continuous query which recalculate error rate every time a new series appears in OK or ERROR measurements.
How is it possible to do it in InfluxDB?


text:
Q: Primefaces dataTable Sorting does not seem to work I am having difficulties sorting a dynamic dataTable
dataTable
<h:form prependId="false" id="Main_Form">
    <p:dataTable id="dataTable" var="c" value="#{databaseSearch.customerList}"
        paginator="true" rows="10" paginatorAlwaysVisible="false"
        paginatorTemplate="Page {CurrentPageReport}  {FirstPageLink} {PreviousPageLink} {PageLinks} {NextPageLink} {LastPageLink}  Rows per page {RowsPerPageDropdown}"
        rowsPerPageTemplate="5,10,15,30" draggableColumns="True">
        <p:column sortBy="#{c.machine}" headerText="Machine">
            <h:outputText value="#{c.machine}" />
        </p:column>
        <p:column sortBy="#{c.company}" headerText="Company">
            <h:outputText value="#{c.company}" />
        </p:column>
        <p:column sortBy="#{c.contact}" headerText="Contact">
            <h:outputText value="#{c.contact}" />
        </p:column>
        <p:column sortBy="#{c.phone}" headerText="Phone">
            <h:outputText value="#{c.phone}" />
        </p:column>
        <p:column sortBy="#{c.email}" headerText="Email">
            <h:outputText value="#{c.email}" />
        </p:column>
        <p:column exportable="false" headerText="Modify">
            <center>
                <p:commandButton id="basic" value="Update"
                    action="#{updateEntry.setMachine(c.machine)}"
                    oncomplete="dlg1.show();"
                    styleClass="ui-Machinebutton" update=":Update_Entry"/>
                <p:tooltip for="basic" value="Update/Delete Database Entry"
                    showEffect="fade" hideEffect="fade" />
            </center>
        </p:column>
    </p:dataTable>
</h:form>

I am using a @SessionScoped bean where databaseSearch.customerList would query the database and populate the dataTable. When I click on the column name to sort, the sort arrow mark changes but the table contents do not sort.
I am using PF 3.4.2

A: If you are querying your database in your getCustomerList method in every request this will not work. You may try with a local variable
public class DatabaseSearch{

    private List<C> customerList;

    public List<C> getCustomerList () {
        if (customerList == null)
            customerList = dao.getcustomerList();
        return customerList ;
    }
}


text:
Q: Question on $\varepsilon$-$\delta$ proof for $\lim_{x \to 0} x^2\sin\left(\frac{1}{x}\right)=0$ I'm trying to understand the $\varepsilon$-$\delta$ proof for
$$\lim_{x \to 0} x^2\sin\left(\frac{1}{x}\right)=0$$
We have to find $\varepsilon>0$ and $\delta>0$ such that
$$
\left|x^2\sin\left(\frac{1}{x}\right)\right| < \varepsilon \tag{1}\label{eq1}
$$
and
$$
|x|<\delta \tag{2}\label{eq2}
$$
My work:
We know
$$
\begin{aligned}
\left|\sin\left(\frac{1}{x}\right)\right| &\leq 1 \\
\implies \left|x^2\sin\left(\frac{1}{x}\right)\right| &\leq |x^2| \\
\end{aligned}
$$
$$
\therefore \text{ } \left|x^2\sin\left(\frac{1}{x}\right)\right| < \delta^2 \tag{3}\label{eq3}
$$
For $0<\delta<1$, we have
$$
\begin{aligned}
\delta^2 &< \delta \\
\implies \left|x^2\sin\left(\frac{1}{x}\right)\right| &< \delta
\end{aligned}
$$
and hence we can choose any $\delta$, such that $0 < \delta \leq \varepsilon$. So far so good.
But, for $\delta \geq 1$, we have
$$
\delta^2 \geq \delta
$$
The range of value for $\delta$ in this case that I can think of such that $\eqref{eq1}$ and $\eqref{eq3}$ could be reconciled is
$$
\left|x^2\sin\left(\frac{1}{x}\right)\right| < \delta \leq \varepsilon
$$
But when I check on a graphing tool, regardless of whether $\delta$ is $<1$ or $\geq 1$, $0<\delta\leq\varepsilon$ holds.
What am I doing wrong?

EDIT:
Since $0<\delta\leq\varepsilon$ and from $\eqref{eq2}$, we get
$$
|x|<\delta \leq\varepsilon
\implies |x|^2 < \delta^2 \leq \varepsilon^2
$$
So, since
$$
\left|x^2\sin\left(\frac{1}{x}\right)\right| \leq |x^2| \\
\implies \left|x^2\sin\left(\frac{1}{x}\right)\right| < \delta ^2 \leq \varepsilon^2
$$
So, can we now say $\delta \leq \varepsilon$, regardless of values that either take?

A: In $\DeclareMathOperator{\epsilon}{\varepsilon}\epsilon$-$\delta$ proofs, $\delta$ is allowed to depend on $\epsilon$, but not vice versa. In your example, if $\epsilon\le1$, then we can set $\delta=\epsilon$, and things work out nicely. Often, weird things can happen for large values of $\epsilon$, and so as a kind of 'safety-net' we require that $\delta$ be at most a specific number. Here, we can set
$$
\delta=\min\left(\epsilon,1\right)
$$
and things work out nicely. It also helps to work backwards. We need
$$
\left|x^2\sin\left(\frac{1}{x}\right)\right|<\epsilon
$$
or
$$
\left|x^2\right|\left|\sin\left(\frac{1}{x}\right)\right|<\epsilon \, .
$$
Now, if we can make $|x^2|$ be smaller than $\epsilon$, then it will be certainly be the case that $|x^2|\left|\sin(1/x)\right|$ will be smaller than $\epsilon$, as $|\sin(1/x)|\le1$. Moreover, if $|x|<1$, then $|x^2|<|x|$. So if $|x|<\epsilon$ and $|x|<1$, then $|x^2|<|x|<\epsilon$, which is what we need. So let $\delta=\min(\epsilon,1)$, which guarantees that $|x|<1$ and $|x|<\epsilon$.

A: You're almost there, and there are several ways to finish up. One thing you could do is what @Tito Eliatron suggests in his comment (this might be the most elegant way):
Let $\epsilon > 0$, set $\delta = \sqrt{\epsilon}$. Then, for $|x|<\delta$ we have
\begin{equation}
\left|x^2 \sin{\left(\frac{1}{x}\right)}\right| \leq |x|^2 < \delta^2 = \sqrt{\epsilon}^2 = \epsilon.
\end{equation}
But there is another way to "fix" your argument. As you have noted, if $\epsilon \leq 1$, you can choose $\delta = \epsilon$ and use the fact that in this case we have $\delta^2 \leq \delta$, and do the same thing as above. Then we deal with the case $\epsilon > 1$ separately. In this case, we can choose $\delta = 1$, and we have for $|x| < \delta:$
\begin{equation}
\left|x^2 \sin{\left(\frac{1}{x}\right)}\right| \leq |x|^2 < \delta^2 = 1^2 = 1 < \epsilon.
\end{equation}
Thus, we can set $\delta = \min{(\epsilon, 1)}$ and obtain the same result. I think Tito's suggestion is more beautiful since it avoids different cases, but both methods are valid.


text:
Q: How to show the uniqueness of the solution of the time dependent linear system in $\mathbb{R}^n$? Consider the time dependent linear system in $\mathbb{R}^n$:
$$
\dot{x} = Ax + b(t),
$$
where $b: \mathbb{R}^n \rightarrow \mathbb{R}^n$ is continuous.
Prove that
$$
x(t) = e^{At}x_0 + \int_0^t e^{A(t-s)}b(s)d(s), \tag{1}
$$
for $t \in \mathbb{R}$ is the unique solution satisfying the initial condition $x(0) = x_0$.
My try:
I tried to take the derivative with respect to Leibniz rule to show that $(1)$ satisfies the systems of differential equation.
$$
\dot{x}(t) = Ae^{At}x_0 +\frac{ \mathrm{d}}{\mathrm{d}t}\bigg(\int_0^t e^{A(t-s)}b(s)d(s)\bigg)
$$
Also, I have no idea how to prove uniqueness.

A: If there were two solutions with the same $x_0$, then their difference $h$ would satisfy $$\dot{h}=Ah,\quad h(0)=0,$$ equivalent to $$h(t)=\int_0^tAh$$
Since this is reminiscent of Banach's theorem, let $Ty(t):=\int_0^tAy$. Then $$\|T(u-v)\|=\sup_t|\int_0^t A(u-v)| \le \|A\|\|u-v\|\int_0^t1\le\|A\||t|\|u-v\|$$ where $\|u\|$ is the sup-norm. So for $t$ small enough, the mapping $T$ is a contraction mapping and has a unique fixed point. In fact, clearly, this is zero, i.e. $h=0$.


text:
Q: rails angular js subdomain I am new to angular js and I want request the server which is already implemented with subdomain for api part . I am facing issues when I want request the server api part from angular js . I tried like the following
1st case:

@service = $resource('/api.lvh.me/properties/:property_id/rates/:id',{})

2nd case:

@service = $resource('/api.lvh.me/properties/:property_id/rates/:id.json',{})

3rd case:

@service = $resource('http://api.lvh.me:3000/properties/:property_id/rates/:id.json',{})

no one is working for me , but when I tried the following its working fine
 @service = $resource('/properties/:property_id/rates/:id.json',{})

In this case its hitting the normal controllers(not the api part/controllers) and I had to manage json type requests and rendering data accordingly , but I dont recommend this as I have already built the api part with sub domain constraint in rails , I want to go with this .
my routes defined like the following
 namespace :api, defaults: {format: 'json'} , :path => '' , :constraints => {:subdomain => 'api'} do
  ....
 end

Can anyone please help how to request the api part on the server .
Thanks ,

A: finally I fixed it by using rack-cors gem , I configured middileware as they suggested in application.rb file and changed my routing way like the following
$resource('http://api.lvh.me:3000/properties/:property_id/rates/:id',{})

Hope it helps for someone.


text:
Q: SQL performance issues with remote query across linked server This sproc
create proc dbo.Get_Accounts as
begin
  declare @current_date datetime
  set @current_date = dbo.fn_currdate()

  select [fields]
  into dbo.current_accounts
  from linkedserver.database.dbo.accounts
  where date = @current_date
end

continually fails after 10 minutes with the following error message:

Server: Msg 7399, Level 16, State 1, Line 1 OLE DB provider 'SQLOLEDB'
  reported an error. Execution terminated by the provider because a
  resource limit was reached. [OLE/DB provider returned message: Timeout
  expired] OLE DB error trace [OLE/DB Provider 'SQLOLEDB'
  ICommandText::Execute returned 0x80040e31: Execution terminated by the
  provider because a resource limit was reached.].

However, when I run the same query from the same database (not on the remote one) in an interactive query window with the date hard-coded:
  select [fields]
  into dbo.current_accounts
  from linkedserver.database.dbo.accounts
  where date = '1/20/2012'

It returns in 30 seconds.
The local server is SQLSERVER 2008, the remote is SQLSERVER 2000.
We have done the following to no avail:

*

*Recreated the stored proc.

*sp_recompile on the stored proc

*update statistics on dbo.accounts

*dropped and recreated the indexes on dbo.accounts

*dropped the index on dbo.accounts and try

*DBCC FREEPROCCACHE & DBCC DROPCLEANBUFFERS on both local and remote servers

*Rebooted the remote server (not an easy option on the local one)

Questions

*

*Can anyone explain this bizarre behavior?

*Any suggestions on other options for correcting it?

A: I have two ideas that might help. I'm also going to tell you that I've had mixed to bad luck with performance running queries against linked servers. So my first recommendation is to avoid it if you can.
My first idea is to install the stored procedure into the SQL Server 2000 box, having it reference the local server. You can then execute the stored procedure remotely.
exec linkedserver.database.dbo.Get_Accounts

If you can go this route, it should improve performance tremendously.
My second idea is to get at the estimated query plan when running the stored procedure. Is it showing you what is taking so much time? One potential problem is that the account you are using on the linked server might not have enough authority to get at the table statistics (you need more authority for the linked server than you do for the local server). And that can make queries unbelievably slow. You can read more about that particular problem here.

A: What happens when you try this (i.e. explicitly indicate what should be run on the remote server)?:
select [fields]
into dbo.current_accounts
from OPENQUERY(linkedserver, 'SELECT [fields] FROM database.dbo.accounts where date = ''1/20/2012''');

I suspect in your case above SQL Server is just pulling the whole table from the remote server then running the query locally (I have seen this happen many times in the past). I prefer to be explicit (either by using OPENQUERY or by creating a SP on the remote server) so there is no chance of confusion.

A: You can turn on trace flag 7300 which might give you a more detailed error message
How many rows does a representative query return? How fast/reliable is the network connection between the two servers?
It's possible that a large dataset is taking too long to transfer (on top of the actual query time).  You could raise the timeout value.
You can try to reconfigure the timeout setting as follows:
Set the remote login timeout to 300 seconds:
sp_configure 'remote login timeout', 300
go
reconfigure with override
go

Set the remote query timeout to 0 (infinite wait):
sp_configure 'remote query timeout', 0
go
reconfigure with override
go

Update: SQL Server 2012 SP1 onwards: users with SELECT permission will be able to access DBCC SHOW_STATISTICS which will improve read only performance on linked servers. Ref: https://msdn.microsoft.com/en-us/library/ms174384(v=sql.110).aspx
Update:  You are correct in saying it's not the size of data or connection speed.  It rang a bell in my foggy memory and I remembered where I had seen it: Slow in the Application, Fast in SSMS?(An Issue With Linked Servers). It's not parameter sniffing, it is the statistics themselves that are missing (due to permissions), causing a bad query plan to be used:

You can see that the estimates are different. When I ran as sysadmin,
  the estimate was 1 row, which is a correct number, since there are no
  Orders in Northwind where the order ID exceeds 20000. But when I ran
  as a plain user, the estimate was 249 rows. We recognize this
  particular number as 30 % of 830 orders, or the estimate for an
  inequality operation when the optimizer has no information.
  Previously, this was due to an unknown variable value, but in this
  case there is no variable that can be unknown. No, it is the
  statistics themselves that are missing.
As long as a query accesses only tables in the local server, the
  optimizer can always access the statistics for all tables in the
  query; there are no extra permission checks. But this is different
  with tables on a linked server. When SQL Server accesses a linked
  server, there is no secret protocol that is only used for inter-server
  communication. No, instead SQL Server uses the standard OLE DB
  interface for linked servers, be other SQL Server instances, Oracle,
  text files or your home-brewed data source, and connects just like any
  other user. Exactly how statistics is retrieved depends on the data
  source and the OLE DB provider in question. In this case, the provider
  is SQL Server Native Client which retrieves the statistics in two
  steps. (You can see this by running Profiler against the remote
  server). First the provider runs the procedure
  sp_table_statistics2_rowset which returns information about which
  column statistics there are, as well as their cardinality and their
  density information. In the second step, the provider runs DBCC
  SHOW_STATISTICS, a command that returns the full distribution
  statistics. (We will look closer at this command later in this
  article.) Here is the catch: to run DBCC SHOW_STATISTICS, you must be
  member of the server role sysadmin or any of the database roles
  db_owner or db_ddladmin.
And this is why I got different results. When running as sysadmin I
  got the full distribution statistics which indicated that there are no
  rows with order ID > 20000, and the estimate was one row. (Recall that
  the optimizer never assumes zero rows from statistics.) But when
  running as the plain user, DBCC SHOW_STATISTICS failed with a
  permission error. This error was not propagated, but instead the
  optimizer accepted that there were no statistics and used default
  assumptions. Since it did get cardinality information, it learnt that
  the remote table has 830 rows, whence the estimate of 249 rows.
Whenever you encounter a performance problem where a query that
  includes access to a linked server is slow in the application, but it
  runs fast when you test it from SSMS, you should always investigate if
  insufficient permissions on the remote database could be the cause.
  (Keep in mind that the access to the linked server may not be overt in
  the query, but could be hidden in a view.) If you determine that
  permissions on the remote database is the problem, what actions could
  you take?

*

*You can add the users to the role db_ddladmin, but since this gives them right to add and drop tables, this is not recommendable.

*By default, when a users connect to a remote server they connect as themselves, but you can set up a login mapping with
  sp_addlinkedsrvlogin, so that users map to a proxy account that has
  membership in db_ddladmin. Note that this proxy account must be an SQL
  login, so this is not an option if the remote server does not have SQL
  authentication enabled. This solution too is somewhat dubious from a
  security perspective, although its better the previous suggestion.

*In some cases you can rewrite the query with OPENQUERY to force evaluation on the remote server. This can be particularly useful, if
  the query includes several remote tables. (But it can also backfire,
  because the optimizer now gets even less statistics information from
  the remote server.)

*You could of course use the full battery of hints and plan guides to get the plan you want.

*Finally, you should ask yourself whether that linked-server access is needed. Maybe the databases could be on the same server? Could data
  be replicated? Some other solution?

A: As this is a ressource issue , the memory pool outside SQL server used to load external drivers and the CLR might be close to its limit. The default is 256MB. To get around this I suggest that you go to SQL server configuration manager, advanced tab and add the -g option to the end of the startup parameters.i.e ;-g1024 then restart the SQL Server service. I usually do  this as we use a high number of linked server.
http://msdn.microsoft.com/en-us/library/ms190737.aspx


text:
Q: Image picker and firebase plugins supporting iOS, android and web I want to migrate my existing flutter application to web. But while migrating app to web,I am facing issues regarding some plugins(i.e firebase and image picker) as that supports only iOS and android but not web. Is there any plugin or work around which supports all of the above platforms (i.e. iOS, android and web)? Is there any work around for this.

A: This seems to be highly specific to the plugins that you are using.  It looks like there is some amount of discussion about how to proceed in order to make the plugins searchable by the platform that they support (web/android/ios/desktop) as well as creating a pubspec.yaml format to load specific plugins depending on the platform being used. (the schema is discussed here (by user amirh)
Depending on what functionality that you're trying to get, there are some workarounds for auth and firestore web.  There are some discussions here about various methods to get around this issue.  HOWEVER....
... the flutter team has been very clear that there is still a long way to go for web development.  They have indicated that the current version of flutter is still in beta, and not ready for production, and that flutter plugins are not ready for web use.
So, workarounds exist, but they are highly specific (like fp_auth for firebase authorization, and unofficial firebase sdks)


text:
Q: Run NUnit 2.5.5 tests in Gallio 3.1 I'm trying to get Gallio running some existing NUnit tests but they're not showing in Gallio.  The assembly loads into Gallio fine and I can run them fine via Resharper within the VS IDE.
I created a really simple NUnit test in VS and this also doesn't show so I know it's not something weird in my existing tests.
Any ideas?

A: Current version of Gallio (3.1 build 397) only supports NUnit up to 2.5.2.
But if you drop in the new 2.5.5 assemblies into C:\Program Files (x86)\Gallio\bin\NUnit\v2.5 and update Gallio.NUnitAdapter25.plugin with the new version numbers you should be good to go.

A: As Carl said, Gallio v3.1 only supports NUnit up to v2.5.2. I suggest you use Gallio v3.2 instead. It's still in beta but is very stable already. You may want to try the latest daily build.
UPDATE1: Gallio v3.2 now RC
UPDATE2: There is breaking change in the test model of NUnit v2.5.4. The Gallio NUnit adapter has been updated accordingly. You might want to use Gallio 3.2 build 520 or later.

A: Just a shot in the dark--are your text fixtures public?


text:
Q: Sleepless Mac although disabled PowerNap I have got a late 2012 Mac Mini.
I like that, when I put my mac to sleep, it sleeps but, my Mac, since I bought it, even if I put in sleep mode it keep working.
For example tonight I heard it working while I was sleeping (Mac is 1,5m from my pillow!) and this morning, looking at the console, it keep doing
29/10/15 06:29:21,285 secd[332]:  SOSEngineCreateMessage_locked 0tO+TZaAgGvPu3zt06Cf+Hoxvo:xvJCfnGe/EQhMHiLAfw7g6Yo9H error in send: Error Domain=com.apple.security.sos.error Code=1032 "peer: dpTJSdz3zg6x6mbOpQZb5DX0Hx not found" UserInfo={NSDescription=peer: dpTJSdz3zg6x6mbOpQZb5DX0Hx not found}
29/10/15 06:29:21,286 secd[332]:  SOSEngineCreateMessage_locked 0tO+TZaAgGvPu3zt06Cf+Hoxvo:0FMuFyL3Yys/PPBGTitpl03kvm error in send: Error Domain=com.apple.security.sos.error Code=1032 "peer: dpTJSdz3zg6x6mbOpQZb5DX0Hx not found" UserInfo={NSDescription=peer: dpTJSdz3zg6x6mbOpQZb5DX0Hx not found}
29/10/15 06:29:21,296 secd[332]:  SOSEngineCreateMessage_locked 0tO+TZaAgGvPu3zt06Cf+Hoxvo:eF41woRcEPyTixrXTfYoNNOsKv error in send: Error Domain=com.apple.security.sos.error Code=1032 "peer: dpTJSdz3zg6x6mbOpQZb5DX0Hx not found" UserInfo={NSDescription=peer: dpTJSdz3zg6x6mbOpQZb5DX0Hx not found}
29/10/15 06:29:21,299 secd[332]:  SOSEngineCreateMessage_locked 0tO+TZaAgGvPu3zt06Cf+Hoxvo:CZlGqQrp/9K9fhZ2TgH6qtffzQ error in send: Error Domain=com.apple.security.sos.error Code=1032 "peer: dpTJSdz3zg6x6mbOpQZb5DX0Hx not found" UserInfo={NSDescription=peer: dpTJSdz3zg6x6mbOpQZb5DX0Hx not found}
29/10/15 06:29:21,300 secd[332]:  SOSEngineCreateMessage_locked 0tO+TZaAgGvPu3zt06Cf+Hoxvo:by7oZw3Sw4DkHN7ijdFdsqVbeg error in send: Error Domain=com.apple.security.sos.error Code=1032 "peer: dpTJSdz3zg6x6mbOpQZb5DX0Hx not found" UserInfo={NSDescription=peer: dpTJSdz3zg6x6mbOpQZb5DX0Hx not found}
29/10/15 06:29:21,300 secd[332]:  __SOSCCProcessSyncWithAllPeers_Server_block_invoke sync with all peers failed: Error Domain=com.apple.security.sos.error Code=1032 "peer: dpTJSdz3zg6x6mbOpQZb5DX0Hx not found" UserInfo={NSDescription=peer: dpTJSdz3zg6x6mbOpQZb5DX0Hx not found}
29/10/15 06:29:21,356 CloudKeychainProxy[341]:  __39-[UbiqitousKVSProxy doSyncWithAllPeers]_block_invoke_2 <UBK-s-pC---> syncWithAllPeers (null), rescheduling timer
29/10/15 06:29:36,622 secd[332]:  SOSEngineCreateMessage_locked 0tO+TZaAgGvPu3zt06Cf+Hoxvo:xvJCfnGe/EQhMHiLAfw7g6Yo9H error in send: Error Domain=com.apple.security.sos.error Code=1032 "peer: dpTJSdz3zg6x6mbOpQZb5DX0Hx not found" UserInfo={NSDescription=peer: dpTJSdz3zg6x6mbOpQZb5DX0Hx not found}
29/10/15 06:29:36,624 secd[332]:  SOSEngineCreateMessage_locked 0tO+TZaAgGvPu3zt06Cf+Hoxvo:0FMuFyL3Yys/PPBGTitpl03kvm error in send: Error Domain=com.apple.security.sos.error Code=1032 "peer: dpTJSdz3zg6x6mbOpQZb5DX0Hx not found" UserInfo={NSDescription=peer: dpTJSdz3zg6x6mbOpQZb5DX0Hx not found}
29/10/15 06:29:36,634 secd[332]:  SOSEngineCreateMessage_locked 0tO+TZaAgGvPu3zt06Cf+Hoxvo:eF41woRcEPyTixrXTfYoNNOsKv error in send: Error Domain=com.apple.security.sos.error Code=1032 "peer: dpTJSdz3zg6x6mbOpQZb5DX0Hx not found" UserInfo={NSDescription=peer: dpTJSdz3zg6x6mbOpQZb5DX0Hx not found}
29/10/15 06:29:36,637 secd[332]:  SOSEngineCreateMessage_locked 0tO+TZaAgGvPu3zt06Cf+Hoxvo:CZlGqQrp/9K9fhZ2TgH6qtffzQ error in send: Error Domain=com.apple.security.sos.error Code=1032 "peer: dpTJSdz3zg6x6mbOpQZb5DX0Hx not found" UserInfo={NSDescription=peer: dpTJSdz3zg6x6mbOpQZb5DX0Hx not found}
29/10/15 06:29:36,638 secd[332]:  SOSEngineCreateMessage_locked 0tO+TZaAgGvPu3zt06Cf+Hoxvo:by7oZw3Sw4DkHN7ijdFdsqVbeg error in send: Error Domain=com.apple.security.sos.error Code=1032 "peer: dpTJSdz3zg6x6mbOpQZb5DX0Hx not found" UserInfo={NSDescription=peer: dpTJSdz3zg6x6mbOpQZb5DX0Hx not found}
29/10/15 06:29:36,639 secd[332]:  __SOSCCProcessSyncWithAllPeers_Server_block_invoke sync with all peers failed: Error Domain=com.apple.security.sos.error Code=1032 "peer: dpTJSdz3zg6x6mbOpQZb5DX0Hx not found" UserInfo={NSDescription=peer: dpTJSdz3zg6x6mbOpQZb5DX0Hx not found}
29/10/15 06:29:36,673 CloudKeychainProxy[341]:  __39-[UbiqitousKVSProxy doSyncWithAllPeers]_block_invoke_2 <UBK-s-pC---> syncWithAllPeers (null), rescheduling timer

all night long.
I tried disabling PowerNap but that the result!
Is there a way to put Mac really in standby mode? (turning it off is not standby!!)

A: Perhaps something else on your network is pinging it, causing it to wake up. Does turning off "Wake for Wi-Fi network access" in Energy Saver preferences help (if it was on already)?

A: It might be due to the new "Power Nap" feature that allows your Mac to check a few things while asleep. To disable this for while you're on battery and/or adapter power head to System Preferences > Energy Saver.


text:
Q: Image of parallelogram $f(A)$ Let $f:\mathbb{R}^2\to \mathbb{R}^2$ be function $f(x,y)=(\frac{1}{2}x+y,x-2y)$. Find a image of set $A\subset\mathbb{R}^2$ bounded with lines $x-2y=0, x-2y+2=0, x+2y-2=0, x+2y-3=0.$
Set $A$ is parallelogram with vertices $(1,\frac{1}{2}), (\frac{3}{2},\frac{3}{4}), (\frac{1}{2},\frac{5}{4}), (0,1)$.
What is $f(A)$?
Any help is welcome. Thanks in advance.

A: Just plug in the coordinates. So $$(1,{1\over 2}) \longmapsto (1,0)$$
$$({3\over 2},{1\over 4}) \longmapsto ({3\over 2},0)$$
$$({1\over 2},{5\over 4}) \longmapsto ({3\over 2},-1)$$
$$(0,1) \longmapsto (1,-2)$$
Now calculate the line betwen $(1,0),$ and $({3\over 2},0)$ and so on.

A: Your function $f$ is clearly a linear function. If you check the determinant of the matrix ($\frac 12\cdot -2 - 1\cdot 1$) you find that it is non-zero so the linear function is one-to-one. That means that lines segments map to line segments, parallel lines map to parallel lines, etc.
Thus the image of the parallelogram is another parallelogram. You can find the image parallelogram by finding the images of the vertices of the source parallelogram--these images will be the vertices of the image parallelogram.


text:
Q: Rates of change question involving water leaking out of a hemispherical tank Water is leaking out the bottom of a hemispherical tank of radius 9 feet at a rate of 4 cubic feet per hour. The tank was full at a certain time. How fast is the water level changing when its height h is 8 feet? Note: the volume of a segment of height h in a hemisphere of radius r is $$πh^2[r− \frac {h}3]$$

A: The height at time $t$ is $h$=8ft. At a very small time interval after that $t+dt$, the new height is $h-dh$. Note the minus sign, since the height decreases. The volume change is $$dv=\pi h^2\left[r− \frac {h}3\right]-\pi (h-dh)^2\left[r− \frac {h-dh}3\right]$$ The rate of change in the volume is equal to 4ft$^3$/hr=$dv/dt$. If you ignore terms in $dh^2$ and $dh^3$, which are small, you get
$$\frac{dv}{dt}=-\pi h(h-2r)\frac{dh}{dt}$$ From here
$$\frac{dh}{dt}=\frac{1}{\pi(2r-h)h}\frac{dv}{dt}$$

A: Let the level of water after 1 hour be $h$.
so change in volume in one hour is :
$π8^2[9− \frac {8}3] - πh^2[9− \frac {h}3] = 4$,  (the difference in volume of water stored in tank)
you can take positive value of $h$ after solving the above equation and your change in level is $8-h$ feet per hour.


text:
Q: Selecting readOnly textboxes with JQuery In my ASP.NET MVC project i need to select all text boxes that have attributed "readOnly" in current page and show modal Jquery dialog in keypress on the disabled text box.Any help appreciated.

A: Have you tried anything yet?..
Just to select the elements and apply a method to the keypress you could do the following:
$(":text[readonly]").keypress(function() { /*do your magic*/ });


text:
Q: Fragment shader ignores texture coordinates I am learning OpenGL through the tutorials at learnopengl.com.
I've already drawn my hand-defined 3x3 texture onto a square using 2 triangles without a shader. Using shaders, however, I don't understand this weird behavior:
The fragment shader seems to ignore texture coordinates but strangely paints my two triangles with the color of the first pixel. I tried putting garbage values into the texture coordinates and it always stays the same.
unsigned char texture_buffer[9*4] = // 3x3 texture RGBA ...
{
    255,40,100,255,  100,200,200,255,  150,150,200,255,
    100,100,150,255, 200,200,100,255,  150,200,150,255,
    150,100,100,255, 200,100,200,255,  200,150,150,255
};
float positions_texcoords[] =
{   //    x              y            z               tex coords
        0.0f,           0.0f,       0.0f,           0.0f, 0.0f,
        0.5f,           0.0f,       0.0f,           1.0f, 0.0f,
        0.0f,           0.5f,       0.0f,           0.0f, 1.0f,
        0.5f,         0.5f,       0.0f,           1.0f, 1.0f,
        0.5f,         0.0f,       0.0f,           1.0f, 0.0f,
        0.0f,         0.5f,       0.0f,           0.0f, 1.0f
};

one time draw call:
    GLuint texture = 0;
    glGenTextures(1, &texture);
    glBindTexture(GL_TEXTURE_2D, texture);
    glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, 3, 3, 0,
                 GL_RGBA, GL_UNSIGNED_BYTE, (void *)texture_buffer );
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_NEAREST);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MAG_FILTER, GL_NEAREST);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_S, GL_CLAMP);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_WRAP_T, GL_CLAMP);
    glTexEnvi(GL_TEXTURE_ENV, GL_TEXTURE_ENV_MODE, GL_REPLACE);

    unsigned int VBO, VAO;
    glGenVertexArrays(1, &VAO);
    glGenBuffers(1, &VBO);

    glBindVertexArray(VAO);
    glBindBuffer(GL_ARRAY_BUFFER, VBO);
    glBufferData(GL_ARRAY_BUFFER, sizeof(positions_texcoords),
                   positions_texcoords, GL_STATIC_DRAW);

        // position attribute
    glVertexAttribPointer(0, 3, GL_FLOAT, GL_FALSE, 5 * sizeof(float), (void*)0);
    glEnableVertexAttribArray(0);

        // texture coord attribute
    glVertexAttribPointer(1, 2, GL_FLOAT, GL_FALSE, 5 * sizeof(float), (void*)(3 * sizeof(float)));
    glEnableVertexAttribArray(1);

    glClearColor(0.3f, 0.0f, 0.1f, 0.0f);
    glClear(GL_COLOR_BUFFER_BIT);
    glBindTexture(GL_TEXTURE_2D, texture);

    glUseProgram(shader_program_id);
    glBindVertexArray(VAO);
    glDrawArrays(GL_TRIANGLES, 0, 6);

    SwapBuffers(window_dc);

vertex shader:
#version 330 core
layout (location = 0) in vec3 in_pos;
layout (location = 1) in vec2 in_tex_coord;

out vec2 out_tex_coord;

void main()
{
    gl_Position = vec4(in_pos, 1.0);
    out_tex_coord = in_tex_coord;
}

fragment shader:
#version 330 core
out vec4 FragColor;

in vec2 in_tex_coord;
uniform sampler2D in_texture;

void main()
{
    FragColor = texture(in_texture, in_tex_coord);
}

I'd appreciate any suggestions about what might be going on. Thank you.

A: The output of a shader stage is linked to the input of the next shader stage by its name (except when you use a layout qualifier). See interface matching rules between shader stages.
The name of the fragment shader input variable has to be the same as the name of the vertex shader output variable.
Since the name of the texture coordinate output in the vertex shader is out_tex_coord

out vec2 out_tex_coord;

the name of the corresponding input in the fragment shader has to be out_tex_coord, too:
in vec2 out_tex_coord;

void main()
{
    FragColor = texture(in_texture, out_tex_coord);
}


text:
Q: SQL querying a customer ID who ordered both product A and B Having a bit of trouble when trying to figure out how to return a query of a customer who ordered both A and B

What I'm looking for is  all customers who order both product A and product B

A: SELECT CustomerID
FROM table
WHERE product in ('a','b')
GROUP BY customerid
HAVING COUNT(distinct product) = 2

I don't normally post code only answers but there isn't a lot that words can add to this- the query predominantly explains itself
You can also
HAVING max(product) <> min(product)

It may be worth pointing out that in queries, the WHERE is performed, filtering to just products A and B. Then the GROUP BY is performed, grouping customer and counting the distinct number of products (or getting the min and max). Then the HAVING is performed, filtering to just those with 2 distinct products (or getting only those where MIN i.e. A, is different to MAX i.e. B)
If you'v never encountered HAVING, it is logically equivalent to:
SELECT CustomerID
FROM(
    SELECT CustomerID, COUNT(distinct product) as count_distinct_product
    FROM table
    WHERE product in ('a','b')
    GROUP BY customerid
)z
WHERE
     z.count_distinct_product = 2

In a HAVING clause you can only refer to columns that are mentioned in the group by. You can also refer to aggregate operations (such as count/min/max) on other columns not mentioned in the group by

A: I have never worked with SQLLite, but since it's specs say it is a Relational Database, it should allow the following query.
select CustomerID
  from table t
 where exists (
       select *
         from table
        where CustomerID = t.CustomerID
          and Product  = 'A'
       )
   and exists (
       select *
         from table
        where CustomerID = t.CustomerID
          and Product  = 'B'
       )

A: Select  customerid from table group by customerid having product like 'A' and product like 'B' or
you can try having count(distinct product) =2this seems to be more accurate.
The whole idea is in a group of customerid suppose 1 if I have several A's and B's count(distinct product) will give as 2 else it will be 1 so the answer is as above.

A: I'd use a correlated sub-query with a HAVING clause to scoop in both products in a single WHERE clause.
SELECT
  t.Customer
FROM
  @t AS t
WHERE
  EXISTS
    (
      SELECT
        1
      FROM
        @t AS s
      WHERE
        t.Customer = s.Customer
        AND s.Product IN ('A', 'B')
      HAVING
        COUNT(DISTINCT s.Product) = 2
    )
GROUP BY
  t.Customer;

A: Another way I just figured out was
SELECT CustomerID
FROM table
WHERE product in ('a','b')
GROUP BY customerid
HAVING sum(case product ='a' then 1 else 0 end) > 0
    and sum(case when product ='b' then 1 else 0 end) > 0


text:
Q: Add price if length is greater then 2 using jquery gform.addFilter( 'gform_product_total', function(total, formId){
    if (jQuery('li.gfield').hasClass('trustee')) {
        var trustee = (jQuery('.trustee').length > 2);
    }
    total += trusteeadd ;
    return total;
});

I am tring to add price in total if class length is greater then 2 i have used the above function but it only works for length = 3 not for 4 or 5 and so on please help how this can be done

A: I hope what you want to do is if more than 2 element have trustee class then you want them to add with trusteeadd. Try like below.
gform.addFilter( 'gform_product_total', function(total, formId){
    if (jQuery('li.gfield').hasClass('trustee')) {
        var count = jQuery('.trustee').length;
        var trusteeadd = 1 * 35;
        // add if length > 2
        total = (count > 2) ? (total + trusteeadd * (count - 2)) : total;
    }
    return total;
});


text:
Q: 1C Предприятие Друзья, жизнь заставила учить 1С и даже не 8ку, а 7ку. Никак не могу найти приличное чтиво либо видео курсы либо какой то самоучитель, попадаются либо шлак либо сразу про 8ку. Очень прошу, подскажите, где можно раздобыть материал для самообучения. Спасибо.
A: В учебном центре есть дистанционные курсы. Ну и другая информация там есть. В крайнем случае телефон там есть, может что-то посоветуют.
По 7ке сейчас довольно сложно найти что-либо, если удастся найти книжки, которые идут с коробкой (по крайней мере раньше такие давали, как минимум франчайзям), то их в принципе должно хватить для самообучения...
ЗЫ Да, халявы скорее всего не будет.
A: Скачайте ЕСИС - Единая Справочная Информационная Система.
Да сайт вот неплохой: http://help1c.com/
Вот у себя нашел: http://rusfolder.com/33179300


text:
Q: How to programmatically assign particular roles at user registration in Keycloak? When a user registers with Keycloak I want to be able to assign one of a few different roles, determined by their selections at registration, but I can't see how to achieve this - any ideas?

A: You can't do that out of the box with Keycloak but you could implement your own Authentification provider, take a look here https://keycloak.gitbooks.io/documentation/content/server_development/topics/auth-spi.html


text:
Q: Fazer multiplicação de dois números e monstrar resultado (JQUERY/JAVASCRIPT + PHP) Eu tenho 3 campos no meu formulário
CAMPO 1: que já tem um valor que puxei no meu banco de dados que é o preço o produto
Campo 2: a onde eu vou inserir um número inteiro indicando a quantidade do produto que quero adicionar
Campo 3: o total da multiplicação que sera Campo 1(preço do produto) X campo 2 (quantidade de produto)
Só que fazendo isso, o retorno do valor no meu código está me dando "NaN" e não porque?Preciso de ajuda para entender o que fiz de errado. Já passei 3 horas isso e não consigo entender.DESCONSIDERAR O CAMPO ESCRITO "VALOR VENDA EM R$" na IMAGEM
IMAGEM DE EXEMPLO

Aqui está meu condigo HTML:

                           Valor Tabelado
                           <input type="text" class="form-control" name="valor_tabela" id="valor_tabela" value="R$<?=$put['valor_tabela']?>" readonly>

                          Quantidade
                            <input type="number" class="form-control" id="qty"   name="quantidade" value="0">

                          Sub Total
                            <input type="number" class="form-control"  id="result" name="sub_total"   readonly>

JAVASCRIPT

A: Isso acontece porque o retorno da variável otherincome é um objeto e está tentando realizar uma soma com um objeto, você deve setar um valor ao input[id="valor_tabela"] e em seguida recuperar seu valor.
Por exemplo:
var otherincome = $("#valor_tabela").val(value).val()

É atribuído um valor ao input e em seguida recuperado esse valor.
Ficando algo desse tipo:

$("#calcular").click(function () {
    var value = 1467.73;
    var primaryincome = $("#qty").val();
    var otherincome = $("#valor_tabela").val(value).val();
    // Alterado o sinal de '+', para  '*'
    var totalincome = parseInt(primaryincome) * parseFloat(otherincome);
    alert(totalincome);
    $("#result").val(totalincome);
})

            Valor Tabelado
            <input type="text" class="form-control" name="valor_tabela" id="valor_tabela" value="1467.73" readonly>

            Quantidade
            <input type="number" class="form-control" id="qty"   name="quantidade" value="0">

            Sub Total</labe>
            <input type="number" class="form-control"  id="result" name="sub_total"   readonly>

        <button id="calcular">Calcular</button>


text:
Q: How to find leading number I want to write a function that identifies the leading digit of a integer number.I am confused and in lack of knowledge to write a function for this process.Can someone help me?

A: The simple, and naive, solution is to convert the number to a string, and get the first character of the string and convert it back into a number.
Another solution is to divide by ten in a loop, until the result is zero, while remembering the last digit of the number. When the result is zero, the last digit is the first digit of the whole number.

A: This can be done easily in two steps.

*

*Change the number to string.

*Return the first char of the string.

A: int num = 12345;

// left most digit:
int digit = abs(num);
while (digit > 9) {
   digit /= 10;
}

// right most digit:
int digit = abs(num) % 10;

A: If you feel more confortable by using arithmetic instead strings and loops, try this approach:
Calculate the integer part of the base 10 logarithm
Divide the source number by 10 power to the integer part of the log
{
    int value = abs(978);

    int valuelog = (int)log10(value);
    int leadingDigit = value / (pow(10,valuelog));

    printf("%d", leadingDigit);
}

Example 978:
    log10(978)->2.990; int 2
    pow(10, 2)->100
    978/100->9.78; int 9

A: #include <stdio.h>

int lead(const int number) {
    int divider = 10;
    while (number/divider) {
        divider *= 10;
    }
    return number/(divider/10);
}

main()
{
    int number = 678;
    int leadNumber = lead(number);
    printf("%d",leadNumber);
}

A: int lead_int(const int n) {
    return (abs(n) < 10) ? abs(n) : lead_int(n /10);
}

Edited after seeing comments in this post (to include abs()), And made this a one lined function.

A: you can do that by converting the integer to string and return the first character.
or you can do a simple program as below.
int a;
scanf("%d",&a);
while(a/10>0)
{
 a=a/10
}
printf("leading no. of given input is %d\n",a);


text:
Q: Reusing/Sharing of powershell remote sessions accross scripts I have a php server that generates a ps1(poweshell) script and manage remote computer. For example I have powershell script that looks like:
$ip=192.168.137.25;
$pw = convertto-securestring -AsPlainText -Force -String a
$cred = new-object -typename System.Management.Automation.PSCredential -argumentlist "$ip\admin",$pw
 $session = new-pssession $ip -credential $cred
invoke-command -session $session -scriptblock {ls}

I run this script from php by:
shell_exec("powershell.exe -ExecutionPolicy RemoteSigned -File script.ps1")

Then I need to invoke second script, and want to use session created by first script.
The question is how to leave remote session alive after first script ending.
Maybe is there other solutions like using other languages instead of php?
Thanks

A: You can reuse/share a remote powershell session between multiple scripts with a global variable.
In the first script you create a remote sessin and store it in a global variable.
$Global:session = New-PSSession -ComputerName $remoteServer -credential $credential

In all other scripts you can use Invoke-Command as follows:
Invoke-Command -Session $session -ScriptBlock {
 /* Remote code */
}

Then you can run the scripts as follows:
$scripts = "create_session.ps1; script_1.ps1; script_2.ps1";
shell_exec("powershell.exe -Command @(\"$scripts\" )");

A: If you have Powershell V3 on the managed machines, you can use Disconnected Sessions, creating the session in the first script, then explicitly disconnection from it with Disconnect-PSSession.  Then you can use Connect-PSSession in the second script to reconnect back to that same session.


text:
Q: Writing to plists located at resource folder in iPhone Any one please answer me, how to write into the plist file which is located in my resource folder. Please write an example code for me.

A: You can't. The application bundle is not writable on iPhone OS devices.

A: -(IBAction)textFieldCheck:(id) sender {
    myPrimaryinfo = [[NSMutableArray arrayWithCapacity:6]retain];
    NSArray *keys = [NSArray arrayWithObjects:@"Date",@"Time",@"Address",@"City",@"State",@"Zipcode",nil];
    [myPrimaryinfo addObject:[NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:
                                                                  [NSString stringWithFormat:@"%@",txtDate.text],
                                                                  [NSString stringWithFormat:@"%@",txtTime.text],
                                                                  [NSString stringWithFormat:@"%@",txtAddress.text],
                                                                  [NSString stringWithFormat:@"%@",txtCity.text],
                                                                  [NSString stringWithFormat:@"%@",txtState.text],
                                                                  [NSString stringWithFormat:@"%@",txtZip.text],nil]forKeys:keys]];

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSString *path = [documentsDirectory stringByAppendingPathComponent:@"myPrimaryinfo.plist"];
    [myPrimaryinfo writeToFile:path atomically:NO];
    NSLog(@"PrimaryInfo array: %@", myPrimaryinfo);
}


text:
Q: Url Connection timed out I am trying to access the url using below mentioned code
public static void main(String[] args) throws Exception {
    //CookieHandler.setDefault(new CookieManager(null,CookiePolicy.ACCEPT_ALL));
    // http://www.google.com/
    // http://finance.yahoo.com/d/quotes.csv?s=GOOG&f=g
    **URL oracle = new URL("http://finance.yahoo.com/d/quotes.csv?s=XOM+EK+JNJ+MSFT&f=snd1t1l1ohgvwdyr");
    URLConnection yc = oracle.openConnection();
    BufferedReader in = new BufferedReader(new InputStreamReader(
            yc.getInputStream()));**
    String inputLine;
    while ((inputLine = in.readLine()) != null)

        System.out.println(inputLine);
    in.close();
}

This code is working fine in my home but same code is not working in office and i am getting error like this.
Exception in thread "main" java.net.ConnectException: Connection timed out: connect
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.PlainSocketImpl.doConnect(Unknown Source)
at java.net.PlainSocketImpl.connectToAddress(Unknown Source)
at java.net.PlainSocketImpl.connect(Unknown Source)
at java.net.SocksSocketImpl.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at java.net.Socket.connect(Unknown Source)
at sun.net.NetworkClient.doConnect(Unknown Source)
at sun.net.www.http.HttpClient.openServer(Unknown Source)
at sun.net.www.http.HttpClient.openServer(Unknown Source)
at sun.net.www.http.HttpClient.<init>(Unknown Source)
at sun.net.www.http.HttpClient.New(Unknown Source)
at sun.net.www.http.HttpClient.New(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getNewHttpClient(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.plainConnect(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.connect(Unknown Source)
at sun.net.www.protocol.http.HttpURLConnection.getInputStream(Unknown Source)
at com.yahoo.Connection.main(Connection.java:21)

I am suspecting there can be firewall or proxy issue but i am not sure.
Does anyone know of way to work around this?
Thanks.

A: You're probably behind some corporate proxy.
If yes try this code to enable programmatically a proxy:
private boolean proxyEnabled = true;

public static void main(String[] args) throws Exception {
    URL oracle = new URL("http://finance.yahoo.com/d/quotes.csv?s=XOM+EK+JNJ+MSFT&f=snd1t1l1ohgvwdyr");
    URLConnection yc;
    if(proxyEnabled) {
        Proxy proxy = new Proxy(Proxy.Type.HTTP, new InetSocketAddress("my.proxy.example.com", 3128));
        yc = oracle.openConnection(proxy);
    } else {
        yc = oracle.openConnection();
    }
    BufferedReader in = new BufferedReader(new InputStreamReader(
        yc.getInputStream()));
    String inputLine;
    while ((inputLine = in.readLine()) != null)

        System.out.println(inputLine);
    in.close();
}

A: You could try setting these properties for your program. With them java should be able to use your proxy. That is, as long as you have the information on hand.
System.setProperty("http.proxyHost", "your proxyhost");
System.setProperty("http.proxyPort", "your proxyport");


text:
Q: Are meta site questions linked to each other? I do not know if this is feasible, as I do not know the current design of meta sites.  This also might have been implemented already, for all I know.
I think that without linking to SO as the ultimate source of meta information, questions with certain tags should be displayed indiscriminately across all meta sites, and belong to none in particular.  These questions would be the questions which apply to the entire SE site network, but not a particular site in general.  Questions such as general etiquette, feature requests, anything tagged with 'stackexchange' or 'stack-exchange', etc. should be spread across all meta sites.  One way to do this is to keep the question on the meta site it was originally posted in but include it in searches across any meta site.  The main reason to do this would be to try and reduce how often redundant questions are asked.  To that effect, the questions could be indexed only in the 'similar questions' section when you ask a new question.  However, I think that it wouldn't be very hard at that point to include it in searches as well.  The only alternative method I can think of would be to create a new site-wide meta questions site, which would be infinitely more cumbersome to the developers and the moderators who must migrate the questions.
Overall, I don't like posting duplicate questions, even if they are duplicates of meta questions from other sites.  I think it would be nice if all these questions with certain qualified tags were either made site-wide and inspecific to any site or at least indexed in all searches and included in the "similar questions" category (when asking a question).  Wouldn't it be ironic if somebody found a duplicate of this question from another meta site? :)

A: Something like this is planned, it's just going to be difficult to implement at first. The ideal scenario is:

*

*Stack Overflow gets its own meta site, for Stack Overflow specific issues, just like every other child meta in the network.

*Stack Exchange opens a central meta site, which propagates questions with certain tags or velocity through something similar to the community bulletin to all child meta sites.
This lets folks see their site specific topics and be alerted to posts that deal with the network at large, if they care about seeing them. Tying searches together to the central collection of faq posts may or may not be feasible, we're looking at it.
Splitting these things is the tricky part. We do have most of a plan in place which we'll share as we get closer to doing this, but I don't know when that's going to be. Right now, Internationalization is our current primary focus, so probably after that, which puts us at early next year.
That could change, though, it could be sooner. Still, it's something we're definitely planning.