text:
Q: jquery ui datepicker give focus to the input without loading the calendar again in IE? I know that jquery ui datepicker loses focus if the date is selected with a mouse. I want to able to give focus to that input field. So i did something like this
    $("#patientDob").live("click", function() {
              $("#patientDob").datepicker({
            onSelect: function() {
                this.focus();
            // selecting a date moves the page, so remove the href attribute
                $(".ui-datepicker a").removeAttr("href");

        },

                        changeMonth: true,
                        changeYear: true,
                        duration: 'fast',
                        showOn: 'focus'
    }).focus();
});

This does gives the focus to the input field, but in IE it keeps on loading the calendar again. It does not do that in firefox or chrome. How can i be able to give focus to the input field without loading the calendar again and again in IE?
Also, if i make a input field readonly and after selecting the date in IE the field loses focus and if i try to press backspace it takes me to the previously visited page.
any help is appreciated!

A: My solution uses the beforeShow event to cancel the show for IE (since it seems to work okay without the hack in Chrome and Firefox). The onSelect and onClose set a flag before returning focus to the input box. See my full write-up to also send blur and change events if you need those.
$("input.dateInput").datepicker({
   /* fix buggy IE focus functionality */
   fixFocusIE: false,

   onSelect: function(dateText, inst) {
       this.fixFocusIE = true;
       $(this).focus();
   },
   onClose: function(dateText, inst) {
       this.fixFocusIE = true;
       this.focus();
   },
   beforeShow: function(input, inst) {
       var result = $.browser.msie ? !this.fixFocusIE : true;
       this.fixFocusIE = false;
       return result;
   }
});

A: I had the same problem as you. To solve it I override the following methods of datepicker:
$.datepicker._attachments = function(input, inst) {
    var appendText = $.datepicker._get(inst, "appendText");
    var isRTL = $.datepicker._get(inst, "isRTL");

    if (inst.append) {
        inst.append.remove();
    }
    if (appendText) {
        inst.append = $('' + appendText + "");
        input[isRTL ? "before" : "after"](inst.append);
    }
    input.unbind("focus", $.datepicker._showDatepicker);
    if (inst.trigger) {
        inst.trigger.remove();
    }
    var showOn = $.datepicker._get(inst, "showOn");
    if (showOn == "focus" || showOn == "both") {
        input.focus($.datepicker._showDatepicker);
    }
    if (showOn == "button" || showOn == "both") {
        var buttonText = $.datepicker._get(inst, "buttonText");
        var buttonImage = $.datepicker._get(inst, "buttonImage");
        inst.trigger = $($.datepicker._get(inst,"buttonImageOnly") ? $("")
                .addClass($.datepicker._triggerClass).attr({
                    src : buttonImage,
                    alt : buttonText,
                    title : buttonText
                })
                : $('<button type="button"></button>')
                .addClass($.datepicker._triggerClass)
                .html('ui-button'));
        input[isRTL ? "before" : "after"](inst.trigger);
        inst.trigger.click(function() {
            if ($.datepicker._datepickerShowing
                    && $.datepicker._lastInput == input[0]) {
                $.datepicker._hideDatepicker();
            } else {
                $.datepicker._showDatepicker(input[0]);
            }
            return false;
        });

        input.bind('focus', function(e) {
            if (!$.datepicker._datepickerShowing) {
                inst.trigger.trigger('click');
            }
        });

        input.bind('click', function(e) {
            input.trigger('focus');
        });
    }
};

$.datepicker._selectDate = function(id, dateStr) {
    var target = $(id);
    var inst = $.datepicker._getInst(target[0]);
    dateStr = (dateStr != null ? dateStr : $.datepicker._formatDate(inst));
    if (inst.input) {
        inst.input.val(dateStr);
    }
    $.datepicker._updateAlternate(inst);
    var onSelect = $.datepicker._get(inst, "onSelect");
    if (onSelect) {
        onSelect.apply((inst.input ? inst.input[0]
        : null), [ dateStr, inst ]);
    } else {
        if (inst.input) {
            inst.input.trigger("change");
        }
    }
    if (inst.inline) {
        $.datepicker._updateDatepicker(inst);
    } else {
        if ($.datepicker._datepickerShowing) {
            inst.input.select();
        }
        setTimeout("$.datepicker._hideDatepicker()", 10);

        $.datepicker._lastInput = inst.input[0];
        $.datepicker._lastInput = null;
    }
};

Check if it works for you...

A: call datepicker at document.ready event


text:
Q: Как написать что функция равна нулю?
на картинке код на с++(с лева), а нужно переписать на с#
переписываю что у меня написано в коде:
 public virtual kyzov CreateKuzov()
    {
        return "0";
    }
    public virtual dvizh CreateDvygun()
    {
        return 0;
    }

A: Компилятор C# не может преобразовать строку или число в kyzov/dvizh.
Попробуйте вернуть null.
Соответственно, далее в коде нужно скорректировать условия проверки, если таковые имеются.
Также можно добавить неявный оператор преобразования в kyzov и dvizh.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to include "leaflet.css" in a React app with webpack? I using the survivejs.com site as a template to build a map based React app with webpack. For the map i am using leaflet but i can't find a way to add the leaflet.css. Without this the map tiles are displayed in the wrong order.
I have tried adding the leaflet.css to the App.jsx file using this
 require('leaflet/dist/leaflet.css');

but get the following error
ERROR in ./~/leaflet/dist/leaflet.css
Module parse failed: myApp/node_modules/leaflet/dist/leaflet.css Unexpected token (3:0)
You may need an appropriate loader to handle this file type.

If I had access to the index.html i could add it there but i with webpack, i'm unclear how to do this?

A: In my applications that use webpack (via create-react-app) I add the following line to the top of my css file relevant for maps:
/* map.css */

@import '~leaflet/dist/leaflet.css';

For example, this file could be map.css. I also put any custom map css styles in this file.
Then in my javascript / jsx file that uses the Map Component, I import this css file:
// map.js

import './map.css'

A: Webpack can't parse CSS without some help from a loader.  The most commonly used CSS loader is webpack/css-loader.
I disagree with the answer from Lakshman Diwaakar in that I think it is extremely beneficial to import component specific CSS files within the JSX of that component, as it allows all the relevant code for that component to live in one place.  If I remove the component, then that CSS is no longer part of any build.  If I want to re-use a component then the CSS is right there to go with it.

A: This code worked for me.
1/ Import leaflet.css directly from leaflet (located inside of node_modules)
2/ Add useEffect, where replace map marker icons (by default markers were not visible, after leaflet.css import)
3/ Render any leaflet components

import * as React from "react";
import { Map, TileLayer, Marker, Popup } from "react-leaflet-universal";
import "leaflet/dist/leaflet.css";

export default () => {
  React.useEffect(() => {
    const L = require("leaflet");

    delete L.Icon.Default.prototype._getIconUrl;

    L.Icon.Default.mergeOptions({
      iconRetinaUrl: require("leaflet/dist/images/marker-icon-2x.png"),
      iconUrl: require("leaflet/dist/images/marker-icon.png"),
      shadowUrl: require("leaflet/dist/images/marker-shadow.png")
    });
  }, []);

  return (
    <Map center={[51.505, -0.09]} zoom={13} style={{ height: "100vh" }}>
      <TileLayer
        attribution='&copy OpenStreetMap contributors'
        url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
      />
      <Marker position={[51.505, -0.09]}>
        <Popup>
          A pretty CSS3 popup.
 Easily customizable.
        </Popup>
      </Marker>
    </Map>
  );
};

A: I solved it by simply importing the CSS like this:
import 'leaflet/dist/leaflet.css';

A: OK So i got help from Juho Vepsäläinen from survivejs on this. HIs advice was to
To make it find Leaflet CSS, you should make sure to include the path to leaflet/dist/leaflet.css at your webpack configuration. You likely have a style path setting (PATHS.style) there if you have been following the material. Having something along path.resolve(__dirname, 'node_modules/leaflet/dist/leaflet.css') should do the trick.
I followed his advice and added the following to webpack.config file:
style: [
   path.join(__dirname, 'app', 'main.css'),
   path.resolve(__dirname, 'node_modules/leaflet/dist/leaflet.css')
],

but i also needed to add a file loader later on
module: {
  loaders: [
   {test: /\.(png|jpg)$/, loader: "file-loader?name=images/[name].[ext]"}
]
}

A: I have worked with leaflet and adding the leaflet to the index.html worked correctly. Usually, you dont add CSS files in JSX. All styling and external libraries are added in the index.html.
In my case it is index.jade. Implemented the open street map using leaflet and reactJS.

A: This code works for me.
I use react + tailwind.css
You need to import
**"leaflet/dist/leaflet.css"**

and add this class
**".leaflet-container"  :**

in file index.css
//index.css
@import url("leaflet/dist/leaflet.css");`enter code here`

  .leaflet-container {
    width: 100%;
    height: 100vh;
  }


text:
Q: Issue with Express sessions and fs module app.post('/register', express.BodyParser(), function (req, res){

   var newu = new UserModel({});

   newu.user = req.body.nuser;
   newu.pass = req.body.npass;
   newu.mail = req.body.nmail;

   var pathu = __dirname + '/users/' + req.body.nuser;

   newu.save(function (err, newu){

       req.session.user = new.user;

       if(err) throw err;

       fs.mkdir(pathu, function (err){

           if (err) throw err;

        });

   });

   res.redirect('/home);

});

Always when the fs.mkdir is executed, I lose all the current Express' sessions, is there any way to execute fs.mkdir and keep all the Express' sessions?

A: Not sure how it's causing your symptoms, but this line:
req.session.user = new.user;

should likely be:
req.session.user = newu.user;

UPDATE
The root of the problem is that creating the directory is triggering nodemon to restart the app and the default in-memory session store loses all sessions when that occurs.  The fix is to use a persistent session store like Redis via connect-redis.


text:
Q: Putting MySQL database info into an HTML table with for loop I need to put 10 albums from a database into an HTML table for school and I thought it could work using a couple of for loops like this:
<!DOCTYPE html>

    <meta charset="UTF-8">
    <title>Album cover from Database</title>
    <meta name="description" content="" />
    <link rel="stylesheet" href="" type="text/css" />

<?php

$servername = "localhost";
$username = "root";
$password = "";
$dbname = "album_list";

$conn = mysqli_connect($servername, $username, $password, $dbname);
if (!$conn) {
    die("error:  " . mysqli_connect_error());
}

$sql = "SELECT * FROM albums";

$albumOne = $albumTwo = $albumThree = $albumFour = $albumFive = $albumSix = $albumSeven = $albumEight = $albumNine = $albumTen = [];
$albumList = [$albumOne, $albumTwo, $albumThree, $albumFour, $albumFive, $albumSix, $albumSeven, $albumEight, $albumNine, $albumTen];
$data_values = ["albumcover", "id", "artist", "albumname", "releasedate", "tracknumber", "genre", "detail", "edit"];
$data_names = ["", "#", "Artiest", "Album", "Jaar", "Nummers", "Genre", "Detail", "Edit"];
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
    while ($row = mysqli_fetch_assoc($result)) {
        for ($i = 0; $i < 10; $i++) {
            for ($ii = 0; $ii < 9; $ii++) {
                $albumList[$i][] = $row[$data_values[$ii]];
            }
        }
    }
}

?>

        <?php
        foreach ($data_names as $name) {
            echo "$name	";
        }
        ?>

    <?php
    for ($i = 0; $i < 10; $i++) {
        $oddOrNot = "";
        if ($i % 2 == 0) {
            $oddOrNot = "even";
        } else {
            $oddOrNot = "oneven";
        }
        echo "
";
        for ($ii = 0; $ii < 9; $ii++) {
            if ($ii == 0) {
                echo "	";
            } else if ($ii == 7) {
                echo "Detail	";
            } else if ($ii == 8) {
                echo "Edit	";
            } else {
                echo "" . $albumList[$i][$ii] . "	";
            }
        }
        echo "
";
    }
    ?>

But this only results in the same album being outputted ten times.
Even if I manually type in all the the data_values instead of the second for loop it still only puts out the same album ten times.
I don't really know what I'm doing wrong as I'm only a beginner.


text:
Q: Cannot figure out the issue with this simple Angular contoller I am new to AngularJS and have a problem with a simple controller. Can anyone help me with that? I don't understand why the SimpleController does not work here!!!
I need the input of the text box be shown after the field as shown by {{name}}.
And basically it should produce a list of customers retrieved from SimpleController' where this list should be filtered bynameand ordered bybudget`...
But it does not!
Here is the Html and JS code:

       <title>My Angular with Simple Controller</title>

        Name:

        <input type="text" ng-model="name" /> {{name}}

 Looping with ng-repeat & SimpleController

                 {{cust.name}} - {{cust.city}} - {{cust.budget}}

the scenario works fine without the use of controller ( by using only ng-init)

A: Works fine when angular module is added.
var myApp = angular.module('myApp',[]);

Fiddle


text:
Q: Custom label inside if not working I have used custom label inside if in vf page its not working....
{!IF(ISNULL(cases.Account.mobile), '{!$Label.Rf_Label_No}', cases.Account.mobile)}

Getting same as Output:#{$Label.Rf_Label_No}

A: {!IF(ISNULL(cases.Account.mobile), $Label.Rf_Label_No, cases.Account.mobile)}

'' has to be used with when you want to print a string.
{} has to be used when you start a code.
If your case you are already inside a code block. So you need not to add {} or ''


text:
Q: Ember Template Compiler I am new to ember.js and javascript frontend MVCs.
I am running into:
Cannot call 'compile' without the template compiler loaded
https://github.com/emberjs/ember.js/issues/10265
So I added:
app.import('bower_components/ember/ember-template-compiler.js');

to the top level of my project directory in the Brocfile.js.
ember build
Future versions of Ember CLI will not support v0.10.33. Please update to Node 0.12 or io.js.
version: 0.2.5

A new version of ember-cli is available (0.2.6). To install it, type ember update.
Could not find watchman, falling back to NodeWatcher for file system events.
Visit http://www.ember-cli.com/#watchman for more info.
Building..
controllers/application.js: line 1, col 16, 'Ember' is not defined.

1 error

===== 1 JSHint Error

Warning: ignoring input sourcemap for bower_components/ember/ember-template-compiler.js because ENOENT, no such file or directory 'proj/tmp/tree_merger-tmp_dest_dir-HJiSoIdK.tmp/bower_components/ember/ember-template-compiler.map'

Is there a separate build step that I am missing to create the template compiler map as the last warning fails create the necessary source map?


text:
Q: Angular translation function gets called infinitely I have a function which translates text, it's hooked on all of the text and looks like this
$rootScope.getWord = function (key) {
  if (angular.isDefined(Language.dict[key])) {
    return Language.dict[key];
  }
  return key;
};

This is how it's hooked up in a view:

{{getWord('Name')}}

The problem is it's calling getWord infinite times, even if there's only one instance of getWord per view it still goes into a loop.
The language can be changed anytime.
What am I doing wrong and what's the way to fix it?

A: The binding you use ({{getWord('Name')}}) is being evaluated in every single iteration of the digest loop. Multiply this by the amount of getWord calls ona  page...
To prevent this, use a "one-time binding":

{{::getWord('Name')}}

An expression that starts with :: is considered a one-time expression.
  One-time expressions will stop recalculating once they are stable, which happens after the first digest if the expression result is a non-undefined value.

Since you want to be able to re-bind your texts, you're going to have to do something differently:

{{translated.Name}}

Then, in your controller, you will have to fill a $scope.translated object with all your translations.
The function that gets the translations can be triggered again, should the language change. Something like:
$scope.translate = function(keys){
    someTranslationWebService.get(keys, function(response){
        $scope.translated = response;
    });
};

Where keys can be an array like:
['Name', 'CompanyName', 'Address']

response should be an object like:
{
    "Name": "Recipient's name",
    "CompanyName": "Company name",
    "Address": "Delivery address"
}

Another option altogether would be to use the "angular-translate" library

A: Try to use filter instead, for example

{{ Name | customFilter}}

angular.module('yourApp')
  .filter('customFilter', ['Language', function(Language) {
    return function(key) {
      return Language.dict[key] || key;
    };
  }]);

A: You can try
 var Language = {dict: {Name: 'Name 1'}};
    $scope.visited = [];
    $rootScope.getWord = function(key) {
        if (angular.isDefined(Language.dict[key])) {
            $scope.visited[key] = Language.dict[key];
            return Language.dict[key];
        }
        $scope.visited[key] = key;
        return key;
    };

And
{{visited['Name']?visited['Name']:getWord('Name')}}

Just clear out visited object when language changes.


text:
Q: including XML file in another XML file + XML schema validation I have four three xml files and one xsd file.
This is file videodes.xml:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE videodes [
<!ENTITY dvds   SYSTEM "./dvds.xml">
<!ENTITY movies SYSTEM "./movies.xml">
]>
<videodes xsi:noNamespaceSchemaLocation="src/videodes.xsd" xmlns="" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
  &dvds;
  &movies;
</videodes>

This is file dvds.xml (in the same directory):
<?xml version="1.0" encoding="UTF-8"?>

<dvds>
    <dvd id="1">
        <title>The lord of the rings</title>
        <type>Original</type>
        <content>
            <movie movie_id="1"/>
            <movie movie_id="2"/>
            <movie movie_id="3"/>
        </content>
    </dvd>

    <dvd id="2">
        <title>Inception</title>
        <type>Original</type>
        <content>
            <movie movie_id="3"/>
        </content>
    </dvd>
</dvds>

And this is file movies.xml (also in the same directory):
<?xml version="1.0" encoding="UTF-8"?>

<movies>
    <movie id="1">
        <name>Inception</name>
        <director>Christopher Nolan</director>
        <year>2010</year>
        <country>USA</country>
        <actors>
            <actor>Ellen Page</actor>
        </actors>
        <genres>
            <genre>Thriller</genre>
        </genres>
    </movie>

    <movie id="2">
        <name>Two towers</name>
        <director>Peter Jackson</director>
        <year>2003</year>
        <country>USA</country>
        <actors>
        </actors>
        <genres>
            <genre>Action</genre>
            <genre>Fantasy</genre>
        </genres>
    </movie>

    <movie id="3">
        <name>Return of the king</name>
    </movie>
</movies>

You can see that I wrote an XML schema for the "main" file (videodes.xml). I think the schema is not important so I'm not posting it here. The thing is that when I put dvds.xml and movies.xml in videodes.xml, it is valid (at least that's what NetBeans is saying). But I want to have dvds and movies stored separately (not in the same file). So I created dvds.xml and movies.xml and included them in videodes.xml. But when I valid the videodes.xml file now, netbeans says it is not valid file. It looks like the files declared in doctype aren't even being included in videodes.xml.
What am I doing wrong ? Am I including it wrong ? Did I declare the doctype wrong ?
Thanks for any answers in advance. And sorry for any grammar mistakes in my English.


text:
Q: Local variable might be referenced before assignment This working function will receive a dictionary that will proceed with uploading or download files based on the transfer_type value. But currently my IDE is displaying the warningLocal variable  might be referenced before assignment when i'm using it to execute  the subprocess.run stage.
My question is, should i accept the sugestion of declating as a global variable inside the function ( global cmd ) or should I ignore this suggestion?
def scp_transfer(data):

    host = data['host']
    remote = data['remote']
    local = data['local']
    transfer_type = data['transfer_type']

    if transfer_type == 'download':
        cmd = 'scp -qr %s:%s %s' % (host, remote, local)
    if transfer_type == 'upload':
        cmd = 'scp -qr %s %s:%s' % (local, host, remote)

    run = subprocess.run(cmd, shell=True, stdout=subprocess.PIPE)
    try:
        run.check_returncode()
    except subprocess.CalledProcessError as e:
        print(e.output)
    else:
        print(run.stdout.decode('utf-8'))

A: I would avoid declaring it as a global. You could declare it within the function:
cmd = None
if transfer_type == 'download':
    cmd = 'scp -qr %s:%s %s' % (host, remote, local)
if transfer_type == 'upload':
    cmd = 'scp -qr %s %s:%s' % (local, host, remote)

This could still cause issues when you try to run the cmd though. Instead, you should raise an exception if transfer_type doesn't match anything.
if transfer_type == 'download':
    cmd = 'scp -qr %s:%s %s' % (host, remote, local)
elif transfer_type == 'upload':
    cmd = 'scp -qr %s %s:%s' % (local, host, remote)
else:
    raise ValueError('Unexpected transfer type: %s' % transfer_type)

In any case, I would always pay attention to the warning.


text:
Q: How can I block incoming calls from a particular phone number on an Ubuntu phone? I have a Meizu Ubuntu phone, and I am getting repeated incoming calls from the same number.
I may be being stupid, but I have been unable to find a way of blocking those calls.
Is this possible?

A: F-Call is available now that does call filtering but installation is through terminal.


text:
Q: Using JSoup, can you get the position/index of a node in the html? Once JSoup has parsed an html String, can you go from the Node object to the start/end String indexes?
I think this isn't possible. But perhaps someone has tried editing JSoup to expose this information?
Or has another solution to matching Nodes onto Strings?
Thanks, Dan

A: I guess the only position you can get from jsoup are elementSiblingIndex and siblingIndex. Possible you can calculate something with them, but not shure if that's a good idea.
Can you give some more information about what you want to do? Maybe there's another solution for your problem.


text:
Q: How to show "no results found" in the search result is empty? I have a simple SQL search and show result script.
Did it with the help of stackoverflow members.
I want to show "No results found: if the search result is empty.
I am a beginner in  coding , if anyone can help me in this , it will be great.
Script is installed in http://http://klkerala.tk/pincode.php
The search result have the table's header visible , even its empty.
I want to hide it and display "no results found" instead....
Thanks in advance
    <?php
    require_once("perpage.php");
    require_once("dbcontroller.php");
    $db_handle = new DBController();

    $name = "";
    $code = "";

    $queryCondition = "";
    if(!empty($_POST["search"])) {
        foreach($_POST["search"] as $k=>$v){
            if(!empty($v)) {

                $queryCases = array("name","code");
                if(in_array($k,$queryCases)) {
                    if(!empty($queryCondition)) {
                        $queryCondition .= " AND ";
                    } else {
                        $queryCondition .= " WHERE ";
                    }
                }
                switch($k) {
                    case "name":
                        $name = $v;
                        $queryCondition .= "name LIKE '" . $v . "%'";
                        break;
                    case "code":
                        $code = $v;
                        $queryCondition .= "code LIKE '" . $v . "%'";
                        break;
                }
            }
        }
    }
    $orderby = " ORDER BY id desc";
    $sql = "SELECT * FROM pincodes " . $queryCondition;
    $href = 'pincode.php';

    $perPage = 20;
    $page = 1;
    if(isset($_POST['page'])){
        $page = $_POST['page'];
    }
    $start = ($page-1)*$perPage;
    if($start < 0) $start = 0;

    $query =  $sql . $orderby .  " limit " . $start . "," . $perPage;
    $result = $db_handle->runQuery($query);

    if(!empty($result)) {
        $result["perpage"] = showperpage($sql, $perPage, $href);
    }
?>

    <title>PHP CRUD with Search and Pagination</title>
    <link href="style.css" type="text/css" rel="stylesheet" />

            <form name="frmSearch" method="post" action="pincode.php">

<input type="text" placeholder="PIN CODE" name="search[name]" class="demoInputBox" value="<?php echo $name; ?>"  />or<input type="text" placeholder="Location" name="search[code]" class="demoInputBox" value="<?php echo $code; ?>" /><input type="submit" name="go" class="btnSearch" value="Search"><input type="reset" class="btnSearch" value="Reset" onclick="window.location='pincode.php'">

          PIN CODE
          Location
          City
                    State

                    <?php
                        foreach($result as $k=>$v) {
                        if(is_numeric($k)) {
                    ?>

                    <?php echo $result[$k]["name"]; ?>
          <?php echo $result[$k]["code"]; ?>
                    <?php echo $result[$k]["category"]; ?>
                    <?php echo $result[$k]["price"]; ?>

                    <?php
                        }
                    }
                    if(isset($result["perpage"])) {
                    ?>

                     <?php echo $result["perpage"]; ?>

                    <?php } ?>

            </form>

A: You can use empty to check if $result has any results or not.
<?php
if (empty($result)) {
   echo "
No results matched the query
\n";
} else {
?>

    ...

<?php
}
?>

A: You can use PHP's empty() function to check if it's empty:
if(empty($result)) {
    echo "No results found";
} else {
    // display your table
}

empty()will return true when empty and false when set.


text:
Q: How to get the user activity using tweetsharp library? I am creating a demo application using wpf with tweetsharp library and I need to get the user acitvity such as TweetDeck activity.
How can we achieve this task?
Please help me.
Any help will be appreciated.

A: You should use below line of code for getting the twitter activity for tweetsharp  library with the help of site stream.
public void Can_stream_from_user_stream()
        {
            const int maxStreamEvents = 5;

            var block = new AutoResetEvent(false);
            var count = 0;

            var service = GetAuthenticatedService();

            service.StreamUser((streamEvent, response) =>
            {
                if (streamEvent is TwitterUserStreamEnd)
                {
                    block.Set();
                }

                if (response.StatusCode == 0)
                {
                    if (streamEvent is TwitterUserStreamFriends)
                    {
                        var friends = (TwitterUserStreamFriends)streamEvent;
                        Assert.IsNotNull(friends);
                        Assert.IsNotNull(friends.RawSource);
                        Assert.IsTrue(friends.Ids.Any());
                    }

                    if (streamEvent is TwitterUserStreamEvent)
                    {
                        var @event = (TwitterUserStreamEvent)streamEvent;
                        Assert.IsNotNull(@event);
                        Assert.IsNotNull(@event.TargetObject);
                        Assert.IsNotNull(@event.RawSource);
                    }

                    if (streamEvent is TwitterUserStreamStatus)
                    {
                        var tweet = ((TwitterUserStreamStatus)streamEvent).Status;
                        Assert.IsNotNull(tweet);
                        Assert.IsNotNull(tweet.Id);
                        Assert.IsNotNull(tweet.User);
                        Assert.IsNotNull(tweet.RawSource);
                        Assert.IsNotNull(tweet.User.ScreenName);
                    }

                    if (streamEvent is TwitterUserStreamDirectMessage)
                    {
                        var dm = ((TwitterUserStreamDirectMessage)streamEvent).DirectMessage;
                        Assert.IsNotNull(dm);
                        Assert.IsNotNull(dm.Id);
                        Assert.IsNotNull(dm.Sender);
                        Assert.IsNotNull(dm.Recipient);
                        Assert.IsNotNull(dm.RawSource);
                    }

                    if (streamEvent is TwitterUserStreamDeleteStatus)
                    {
                        var deleted = (TwitterUserStreamDeleteStatus)streamEvent;
                        Assert.IsNotNull(deleted);
                        Assert.IsTrue(deleted.StatusId > 0);
                        Assert.IsTrue(deleted.UserId > 0);
                    }

                    if (streamEvent is TwitterUserStreamDeleteDirectMessage)
                    {
                        var deleted = (TwitterUserStreamDeleteDirectMessage)streamEvent;
                        Assert.IsNotNull(deleted);
                        Assert.IsTrue(deleted.DirectMessageId > 0);
                        Assert.IsTrue(deleted.UserId > 0);
                    }
                    count++;
                    if (count == maxStreamEvents)
                    {
                        block.Set();
                    }
                }
                else
                {
                    Assert.Ignore("Stream responsed with status code: {0}", response.StatusCode);
                }
            });

            block.WaitOne();
            service.CancelStreaming();
        }

above line of code I am getting from this Link


text:
Q: Include another field in the select statement which must not be part of the distinct How can I include another column in the select statement without making it part of the distinct? I tried to set another column name before the distinct but that did not work.
SELECT  distinct nm.LeadConsumerId, nm.LeadMetaInfoId

  FROM [MyDatabase].[dbo].[LeadConsumer] as lc
  inner join [dbo].[LeadNMConsumer] as nm on lc.ID = nm.LeadConsumerId
  inner join [dbo].BrokerHistories as his on nm.LeadConsumerId = his.LeadConsumerId
  where (his.EventType = 0 Or his.EventType = 1)
  AND his.EventDate >= Convert(datetime, '2016-05-01') AND his.EventDate <= Convert(datetime, '2016-05-31')

A: You could use ROW_NUMBER:
WITH CTE AS(
    SELECT
        nm.LeadConsumerId,
        nm.LeadMetaInfoId,
        -- other columns you want
        ROW_NUMBER()OVER (PARTITION BY nm.LeadConsumerId,   nm.LeadMetaInfoId ORDER BY (SELECT NULL))
    FROM [MyDatabase].[dbo].[LeadConsumer] AS lc
    INNER JOIN [dbo].[LeadNMConsumer] AS nm
        ON lc.ID = nm.LeadConsumerId
    INNER JOIN [dbo].BrokerHistories AS his
        ON nm.LeadConsumerId = his.LeadConsumerId
    WHERE
        (his.EventType = 0 OR his.EventType = 1)
        AND his.EventDate >= CONVERT(datetime, '2016-05-01')
        AND his.EventDate <= CONVERT(datetime, '2016-05-31')
)
SELECT
    --list all columns you want
FROM CTE
WHERE rn = 1

Replace (SELECT NULL) from the ORDER BY clause as preferred.


text:
Q: C/C++: is GOTO faster than WHILE and FOR? I know, that everybody hates GOTO and nobody recommends it. But that's not the point. I just want to know, which code is the fastest:

*

*the goto loop
int i=3;
loop:
printf("something");
if(--i) goto loop;

*the while loop
int i=3;
while(i--) {
    printf("something");
}

*the for loop
for(int i=3; i; i--) {
    printf("something");
}

A: The only time I've seen the argument made for goto was in one of W. Richard Stevens' articles or books. His point was that in a very time-critical section of code (I believe his example was the network stack), having nested if/else blocks with related error-handling code could be redone using goto in a way that made a valuable difference.
Personally, I'm not good enough a programmer to argue with Stevens' work, so I won't try. goto can be useful for performance-related issues, but the limits of when that is so are fairly strict.

A: Write short programs, then do this:
gcc -S -O2 p1.c
gcc -S -O2 p2.c
gcc -S -O2 p3.c

Analyze the output and see if there's any difference. Be sure to introduce some level of unpredictability such that the compiler doesn't optimize the program away to nothing.
Compilers do a great job of optimizing these trivial concerns. I'd suggest not to worry about it, and instead focus on what makes you more productive as a programmer.
Speed and efficiency is a great thing to worry about it, but 99% of the time that involves using proper data structures and algorithms... not worrying about whether a for is faster than a while or a goto, etc.

A: It is probably both compiler, optimiser and architecture specific.
For example the code if(--i) goto loop; is a conditional test followed by an unconditional branch.  A compiler might simply generate corresponding code or it might be smart enough (though a compiler that did not have at least that much smarts may not be worth much), to generate a single conditional branch instruction.  while(i--) on the other hand is already a conditional branch at the source level, so translation to a conditional branch at the machine level may be more likley regardless of the sophistication of the compiler implementation or optimiser.
In the end, the difference is likley to be minute and only relevant if a great many iterations are required, and the way you should answer this question is to build the code for the specific target and compiler (and compiler settings) of interest,  and either inspect the resultant machine level code or directly measure execution time.
In your examples the printf() in the loop will dominate any timing in any case; something simpler in the loop would make observations of the differences easier.  I would suggest an empty loop, and then declaring i volatile to prevent the loop being optimised to nothing.

A: Generally speaking, for and while loops get compiled to the same thing as goto, so it usually won't make a difference. If you have your doubts, you can feel free to try all three and see which takes longer. Odds are you'll be unable to measure a difference, even if you loop a billion times.
If you look at this answer, you'll see that the compiler can generate exactly the same code for for, while, and goto (only in this case there was no condition).

A: As long as you're generating the same flow of control as a normal loop, pretty nearly any decent compiler can and will produce the same code whether you use for, while, etc. for it.
You can gain something from using goto, but usually only if you're generating a flow of control that a normal loop simply can't (at least cleanly). A typical example is jumping into the middle of a loop to get a loop and a half construct, which most languages' normal loop statements (including C's) don't provide cleanly.

A: There is should not be any significant difference between all the loops and the goto. Except the idea, that compiler more probably will not try to optimize the GOTO-things at all.
And there is not a lot of sense trying to optimize compiler-generated stuff in loops. It's more sense to optimize the code inside the loop, or reduce the number of iterations or so on.

A: I think there will be some code after compiler under nornal condition.
In fact I think goto is very convenient  sometimes, although it is hard to read.

A: On Linux, I compiled the code below into assembly using both g++ and clang++. For more information on how I did that, see here. (Short version: g++ -S -O3 filename.cpp clang++ -S -O3 filename.cpp, and some assembly comments you'll see below to help me out.)
Conclusion/TL;DR at the bottom.

First, I compared label: and goto vs. do {} while. You can't compare a for () {} loop with this (in good faith), because a for loop always evaluates the condition first. This time around, the condition is evaluated only after the loop code has been executed once.
#include <iostream>

void testGoto()
{
  __asm("//startTest");
  int i = 0;
  loop:
  std::cout << i;
  ++i;
  if (i < 100)
  {
    goto loop;
  }
  __asm("//endTest");
}

#include <iostream>

void testDoWhile()
{
  __asm("//startTest");
  int i = 0;
  do
  {
    std::cout << i;
    ++i;
  }
  while (i < 100);
  __asm("//endTest");
}

In both cases, the assembly is the exact same regardless of goto or do {} while, per compiler:
g++:
    xorl    %ebx, %ebx
    leaq    _ZSt4cout(%rip), %rbp
    .p2align 4,,10
    .p2align 3
.L2:
    movl    %ebx, %esi
    movq    %rbp, %rdi
    addl    $1, %ebx
    call    _ZNSolsEi@PLT
    cmpl    $100, %ebx
    jne .L2

clang++:
    xorl    %ebx, %ebx
    .p2align    4, 0x90
.LBB0_1:                                # =>This Inner Loop Header: Depth=1
    movl    $_ZSt4cout, %edi
    movl    %ebx, %esi
    callq   _ZNSolsEi
    addl    $1, %ebx
    cmpl    $100, %ebx
    jne .LBB0_1
# %bb.2:

Then I compared label: and goto vs. while {} vs. for () {}. This time around, the condition is evaluated before the loop code has been executed even once.
For goto, I had to invert the condition, at least for the first time. I saw two ways of implementing it, so I tried both ways.
#include <iostream>

void testGoto1()
{
  __asm("//startTest");
  int i = 0;
  loop:
  if (i >= 100)
  {
    goto exitLoop;
  }
  std::cout << i;
  ++i;
  goto loop;
  exitLoop:
  __asm("//endTest");
}

#include <iostream>

void testGoto2()
{
  __asm("//startTest");
  int i = 0;
  if (i >= 100)
  {
    goto exitLoop;
  }
  loop:
  std::cout << i;
  ++i;
  if (i < 100)
  {
    goto loop;
  }
  exitLoop:
  __asm("//endTest");
}

#include <iostream>

void testWhile()
{
  __asm("//startTest");
  int i = 0;
  while (i < 100)
  {
    std::cout << i;
    ++i;
  }
  __asm("//endTest");
}

#include <iostream>

void testFor()
{
  __asm("//startTest");
  for (int i = 0; i < 100; ++i)
  {
    std::cout << i;
  }
  __asm("//endTest");
}

As above, in all four cases, the assembly is the exact same regardless of goto 1 or 2, while {}, or for () {}, per compiler, with just 1 tiny exception for g++ that may be meaningless:
g++:
    xorl    %ebx, %ebx
    leaq    _ZSt4cout(%rip), %rbp
    .p2align 4,,10
    .p2align 3
.L2:
    movl    %ebx, %esi
    movq    %rbp, %rdi
    addl    $1, %ebx
    call    _ZNSolsEi@PLT
    cmpl    $100, %ebx
    jne .L2

Exception for g++: at the end of the goto2 assembly, the assembly added:
.L3:
    endbr64

(I presume this extra label was optimized out of the goto 1's assembly.) I would assume that this is completely insignificant though.
clang++:
    xorl    %ebx, %ebx
    .p2align    4, 0x90
.LBB0_1:                                # =>This Inner Loop Header: Depth=1
    movl    $_ZSt4cout, %edi
    movl    %ebx, %esi
    callq   _ZNSolsEi
    addl    $1, %ebx
    cmpl    $100, %ebx
    jne .LBB0_1
# %bb.2:

In conclusion/TL;DR: No, there does not appear to be any difference whatsoever between any of the possible equivalent arrangements of label: and goto, do {} while, while {}, and for () {}, at least on Linux using g++ 9.3.0 and clang++ 10.0.0.
Note that I did not test break and continue here; however, given that the assembly code generated for each of the 4 in any scenario was the same, I can only presume that they would be the exact same for break and continue, especially since the assembly is using labels and jumps for every scenario.
To ensure correct results, I was very meticulous in my process and also used Visual Studio Code's compare files feature.

A: There are several niche verticals where goto is still commonly used as a standard practice, by some very very smart folks and there is no bias against goto in those settings.  I used to work at a simulations focused company where all local fortran code had tons of gotos, the team was super smart, and the software worked near flawlessly.
So, we can leave the merit of goto aside, and if the question merely is to compare the loops, then we do so by profiling and/or comparing the assembly code.  That said however, the question includes statements like printf etc.  You can't really have a discussion about loop control logic optimization when doing that. Also, as others have pointed out, the given loops will all generate VERY similar machine codes.
All conditional branches are considered "taken" (true) in pipelined processor architectures anyway until decode phase, in addition to small loops being usually expanded to be loopless.  So, in line with Harper's point above, it is unrealistic for goto to have any advantage whatsoever in simple loop control (just as for or while don't have an advantage over each other).  GOTO makes sense usually in multiple nested loops or multiple nested ifs, when adding the additional condition checked by goto into EACH of the nested loops or nested ifs is suboptimal.
When optimizing a search kind of operation in a simple loop, using a sentinal is sometimes more effective than anything else.  Essentially, by adding a dummy value at the end of the array, you can avoid checking for two conditions (end of array and value found) to be just one condition (value found), and that saves on cmp operations internally.  I am unaware if compilers automatically do that or not.

A: goto Loop:
start_Chicken:
{
    ++x;
    if (x >= loops)
        goto end_Chicken;
}
goto start_Chicken;

end_Chicken:
x = 0;

for Loop:
for (int i = 0; i < loops; i++)
{

}

while Loop:
while (z <= loops)
{

    ++z;
}
z = 0;

Image from results
While loop in any situation with more mixed tests had as minimal but still better results.


text:
Q: Finding the area enclosed by $px^4+qxy+ry^2+sy+t=0$ When $px^4+qxy+ry^2+sy+t=0\ (p,q,r,s,t\in\mathbb R)$ represents a simple closed curve on the $xy$ plane, can we represent the area enclosed by this curve by $p,q,r,s,t$? If yes, then how?
Example 1 : $2x^4-2xy+y^2+6y+5=0$ represents a simple closed curve. (see here)
Example 2 : $2x^4-2xy-y^2+6y+5=0$ does not represent a simple closed curve. (see here)

A: The case $ax^4-by^2\pm\ldots=0$ with $a,b>0$ is an open curve pretty much for the same reason that $ax^2-by^2\pm\ldots=0$ is an open curve as well, called hyperbola. Then all you have to do is compute
$y_{_{1,2}}(x)=\dfrac{-(s+qx)\pm\sqrt{(s+qx)^2-4r(t+px)^4}}{2r}$ , the area being $\displaystyle\int_v^w|y_{_1}(x)-y_{_2}(x)|~dx=$
$=\displaystyle\frac1r\int_v^w\sqrt{(s+qx)^2-4r(t+px)^4}~dx$, where v and w are the left-most and right-most values
of x, i.e., the extrema of $x(y)$, which are to be found amongst the roots of $x'(y)=0$. Granted, this type of integral does not usually possess a closed form expression, and even the exact values of v or w are hard to come by.


text:
Q: Kamon MDC propagation doesn't work I am trying to do MDC propagation with Kamon like shown in this documentation But it does not seem to work like they say
Play framework - 2.5

kamon-core - 0.6.2

kamon-play-25 - 0.6.2

My logback pattern:
<pattern>%d{HH:mm:ss.SSS} [%thread] [%level] [%traceToken]- %logger{36}\(%L\) %X{X-ApplicationId} - %message%n%xException</pattern>

I have created a filter:

class AccessLoggingFilter @Inject() (implicit val mat: Materializer, ec: ExecutionContext) extends Filter with LazyLogging {
val ApplicationIdKey = AvailableToMdc("X-ApplicationId")
def apply(next: (RequestHeader) => Future[Result])(request: RequestHeader): Future[Result] = {
TraceLocal.storeForMdc("X-ApplicationId", request.id.toString)
logger.error("first Location")
withMdc {
  logger.error("Second location")
  next(request)
}}}

And added it like so:
class MyFilters @Inject() (accessLoggingFilter: AccessLoggingFilter) extends DefaultHttpFilters(accessLoggingFilter)

Now when i do an http call to the server i get the following output:

c.v.i.utils.AccessLoggingFilter(24)  - first Location
c.v.i.utils.AccessLoggingFilter(26) 1 - Second location

And all log prints afterwards do not show the '1' X-ApplicationId
Cant figure out what i am doing wrong.

A: Here a complete(almost) example:
build.sbt:
name := "kamon-play-example"

version := "1.0"

scalaVersion := "2.11.7"

val kamonVersion = "0.6.2"

val resolutionRepos = Seq("Kamon Repository Snapshots" at "http://snapshots.kamon.io")

val dependencies = Seq(
  "io.kamon"    %% "kamon-play-25"        % kamonVersion,
  "io.kamon"    %% "kamon-log-reporter"   % kamonVersion
)

lazy val root = (project in file(".")).enablePlugins(PlayScala)
                                      .settings(resolvers ++= resolutionRepos)
                                      .settings(libraryDependencies ++= dependencies)

basic filter:
class TraceLocalFilter @Inject() (implicit val mat: Materializer, ec: ExecutionContext) extends Filter {
  val logger = Logger(this.getClass)
  val TraceLocalStorageKey = "MyTraceLocalStorageKey"

  val userAgentHeader = "User-Agent"

  //this value will be available in the MDC at the moment to call  to Logger.*()s
  val UserAgentHeaderAvailableToMDC = AvailableToMdc(userAgentHeader)

  override def apply(next: (RequestHeader) ⇒ Future[Result])(header: RequestHeader): Future[Result] = {

    def onResult(result:Result) = {
      val traceLocalContainer = TraceLocal.retrieve(TraceLocalKey).getOrElse(TraceLocalContainer("unknown","unknown"))
      result.withHeaders(TraceLocalStorageKey -> traceLocalContainer.traceToken)
    }

    //update the TraceLocalStorage
    TraceLocal.store(TraceLocalKey)(TraceLocalContainer(header.headers.get(TraceLocalStorageKey).getOrElse("unknown"), "unknown"))
    TraceLocal.store(UserAgentHeaderAvailableToMDC)(header.headers.get(userAgentHeader).getOrElse("unknown"))

    //call the action
    next(header).map(onResult)
  }
}

we need add the filter:
class Filters @Inject() (traceLocalFilter: TraceLocalFilter)  extends HttpFilters {
  val filters = Seq(traceLocalFilter)
}

a really simple controller and action:
class KamonPlayExample @Inject() (kamon: Kamon) extends Controller {

  def sayHello = Action.async {
    Future {
      logger.info("Say hello to Kamon")
      Ok("Say hello to Kamon")
    }
  }
}

in logback.xml add the following pattern:
    <pattern>%date{HH:mm:ss.SSS} %-5level [%traceToken][%X{User-Agent}] [%thread] %logger{55} - %msg%n</pattern>

add the sbt-aspectj-runner plugin in order to run the application with Aspectjweaver in DEV mode:
addSbtPlugin("io.kamon" % "aspectj-play-runner" % "0.1.3")

run the application with aspectj-runner:run and make some curls:
  curl -i -H 'X-Trace-Token:kamon-test' -H 'User-Agent:Super-User-Agent' -X GET "http://localhost:9000/helloKamon"

  curl -i -H 'X-Trace-Token:kamon-test'-X GET "http://localhost:9000/helloKamon"

in the console:
15:09:16.027 INFO  [kamon-test][Super-User-Agent] [application-akka.actor.default-dispatcher-8] controllers.KamonPlayExample - Say hello to Kamon

15:09:24.034 INFO  [kamon-test][curl/7.47.1] [application-akka.actor.default-dispatcher-8] controllers.KamonPlayExample - Say hello to Kamon

hope you help.


text:
Q: Java -- How to create a 2d ArrayList of objects from a custom class for an (x,y) coordinate text-game map I'm a beginner in the world of java for android (and java in general) and am trying to make an interactive fiction game app to improve my abilities. I have already made this game in python, and am simply trying to convert to java, but I'm running into a lot of difficulties.
This biggest problem I've had so far is creating the world map. In python, I simply made a variable that contained an 8x4 list of lists with object variables denoting specific rooms in the game world, and zeroes representing places the player could not go, like so (this is only part of the map):
worldMap = [[0, 0, othDorm, 0, 0],
        [0, 0, darkForest, 0, 0],
        [0, observatory, forkPath, resHall, 0],

This essentially created an coordinate plane. Then within my 'Player' class, I had variables that gave his x and y coordinate, and his current position by indexing his location on the world map, like so:
class player:
def __init__(self, name, ycoord, xcoord):
    self.name = name
    self.xcoord = xcoord
    self.ycoord = ycoord
    self.mapposi = worldMap[ycoord][xcoord]

Finally, the player could enter a command to 'move' north, south, east, west, and the player coordinates would update by adding 1 to the appropriate x/y, placing him in a new room.
However, java seems a lot stricter about it's data types, and I've been having trouble converting this system. First I tried to make an ArrayList, but I guess I can't have an integer and object datatype within the same list? Then I tried to make an ArrayList of objects, and where null values would replace the 0 values. To do this I used the code:
    public static Object worldMap[][] = new Object[8][4];
    worldMap[0][0] = mainGate;

where worldMap would become my x/y grid filled with objects from my custom made "Room" class, and "mainGate" being a Room at position 0, 0. This allowed me to compile, but when I checked the player's location at [0][0], Java returned a value of "com.weebly.fishopolis.adesaw.Room@9676a63", which is obviously not what I wanted. I also tried to use Player.mapposi.name to produce the name, but it seems my variables weren't inherited and got a "could not resolve symbol" error. I also tried to make an ArrayList<Room>[][], but I got a "generic array" error going that route.
At this point I really have no idea how to move forward, and I'm starting to think I'm missing a really easy solution I'm just not aware of, because this was so simple in python yet seems so complicated in Java. My end goal here is to be able to call up the game players position in the world, and be able to access the object at that index and all its variables. For example in python, I could do something like
Player.mapposi.name
Player.mapposi.roomitems

and that would return me the name and room items of the object variable at whatever x/y index the player was currently in.
As I said, I'm very new with Java, so any explanations/tips would be really appreciated. And I hope that I gave you enough code to understand what I'm trying to do, but if not just ask and I'll add whatever else is needed


text:
Q: Cannot include std::thread header in wxWidgets application I have the following code:
#include "wx\wx.h"

class BClient : public wxApp
{
   virtual bool OnInit();
   virtual int  OnQuit();
};

IMPLEMENT_APP(BClient)

bool BClient::OnInit()
{

    return true;
}

int BClient::OnQuit()
{

    return 0;
}

As soon I try to add the line
#include <thread>

I receive this errors:

Error 10  error C2347: '__w64' : can not be used with type '__w64
  unsigned __int64'
Error 12  error C2143: syntax error : missing ';' before ','
Error 13  error C2059: syntax error : ','

The errors refer to this file: c:\program files (x86)\microsoft visual studio 12.0\vc\include\concrt.h
So, for some reason, wxwidgets and std::thread doesn't mix together.
Can someone explain to me why this is happening and is there a workaround for this issue ?
Thanks.

A: Something is wrong with your MSVS installation. Here, adding #include <thread> line either before or after #include <wx/wx.h> one works without any problems.
Also, on a completely unrelated note, there is no OnQuit() in the base class, only OnExit().


text:
Q: How to calculate volume of a 3D object in Postgresql? I'm quite new to PostgreSQL and I'm trying to calculate the volume of a 3D object with the shape of a rectangle.
Here's the table with the values:
CREATE TABLE warehousethree(
 name character varying(100) NOT NULL,
 wid serial NOT NULL,
 CONSTRAINT warehousethree_pk PRIMARY KEY (wid));

SELECT AddGeometryColumn('warehousethree', 'location', '3785', 'POLYHEDRALSURFACE', 3)

INSERT INTO warehousethree (name, location, wid)
values
('Helianthus Italy', ST_GEOMFROMTEXT('POLYHEDRALSURFACE(((43450771 11890747 0,43450755 11892667 0,43449727 11892882 0,43449688 11890994 0,43450771 11890747 0)),((43450771 11890747 500,43450755 11892667 500,43449727 11892882 500,43449688 11890994 500,43450771 11890747 500)),((43450771 11890747 0,43450755 11892667 0,43450755 11892667 500,43450771 11890747 500,43450771 11890747 0)),((43450755 11892667 0,43449727 11892882 0,43449727 11892882 500,43450755 11892667 500, 43450755 11892667 0)),((43449727 11892882 0,43449688 11890994 0,43449688 11890994 500,43449727 11892882 500,43449727 11892882 0)),((43449688 11890994 0,43450771 11890747 0,43450771 11890747 500, 43449688 11890994 500, 43449688 11890994 0)))', 3785), 1)

So far I've tried to combine the ST_Volume with ST_MakeSolid to calculate the volume but I get an error saying there's a problem with the syntax at the bracket following ST_Volume. I've tried some other ones which returned errors saying the functions didn't exit. Here is my query:
SELECT name ST_Volume(ST_MakeSolid(location)) as ware_solid_vol
FROM warehousethree

Any ideas about the correct syntax for this query will be greatly appreciated! Thank you.

A: Both ST_Volume and ST_MakeSolid are provided by the postgis_sfcgal extension which is not necessarily installed by default with postgis. You need to install it by typing in the following command from your operating system shell.
psql -d mydatabase -c 'create extension postgis_sfcgal';

Once it has been installed on your database your query should change to
SELECT ST_Volume(ST_MakeSolid(location)) as ware_solid_vol
 FROM warehousethree

Note that I have rubbed out 'name' from the query.


text:
Q: Angular.js problems with small numbers and scientific notation in input fields I'm having troubles displaying and editing small numbers in an input field using Angular.js v1.3.14.
I've attempted to use a directive to prevent the number from displaying in scientific notation. example: 0.00000005 instead of 5e-8.
I get an error message from the directive because the datatype returned is a string and not a number.
This is the error message I receive: Error: [ngModel:numfmt] Expected '0.00000005' to be a number
HTML:

    <input type="number" ng-model="myNum" />

    <input decimal type="number" ng-model="myNum" />

JavaScript:
angular
    .module('myApp', [])
    .controller('myCtrl', function($scope) {
        $scope.myNum = 0.00000005;
    })
    .directive('decimal', function()
    {
        return {
            require: 'ngModel',
            link: function(scope, element, attrs, ngModelController) {

                ngModelController.$formatters.push(function(data)
                {
                    var newData = data.toFixed != null ? data.toFixed(8) : data;

                    console.log('data', data, newData);
                    //convert data from model format to view format
                    return newData; //converted
                });

            }
        };
    });

jsFiddle: http://jsfiddle.net/joelnet/u277z929
note: Ideally I would prefer to use type="number" and not type="text" for the input field.
How can I force the input field to display ONLY decimal and not the scientific notation?
EDIT: The reason I prefer to use type="number" is because (1) the field is a number type. (2) this brings up the number pad on mobile. (3) I can use the min, max fields. (4) The $scope.$watch only fires when the number is valid. (5) it's cleaner.
EDIT2: It appears FireFox displays correctly (and doesn't need the directive example: http://jsfiddle.net/joelnet/u277z929/7), while Chrome and Internet Explorer display the number as scientific notation. Both of the input fields should display the number as decimal and never as scientific notation.

A: The AngularJS documentation for input[number] specifically says:

The model must always be of type number otherwise Angular will throw an error. Be aware that a string containing a number is not enough. See the numfmt error docs for more information and an example of how to convert your model if necessary.

You can read more information on the numfmt error documentation.
As far as I can tell, there is no way to do this while specifying type="number". The last item that must go through the $formatters array must return a number, not a string.
If you change to type="text", your code will work fine:
<input decimal type="text" ng-model="myNum" />

What is your motivation for using type=number? If you're looking to only allow numerical entry, you can use pattern or a directive to create that behaviour.

A: I'm afraid that you can't change the displayed format of the input type="number".
There are plenty  libraries for formatting scientific notations into javascript, but what are you trying to do you will have to create a directive.
Using two inputs, and one of them visible which displays the non-scientific notation and is bind to the normal number-input. I don't know if this is cleaner enough for you requirement. Here i made you an example

A: Based on your fiddle, you can have an <input type="number"> field that validates on 0.00000005 by making these changes:
<input decimal type="number" ng-model="myNum" step="any" />

and
return Number(newData); //converted

See: http://jsfiddle.net/u277z929/6/


text:
Q: Question about how foreign key data is stored in SQL I know this is ultra-basic, but it's an assumption I've always held and would like to validate that it's true (in general, with the details specific to various implementations)
Let's say  I have a table that has a text column "Fruit".  In that column only one of four values ever appears:  Pear, Apple, Banana, and Strawberry.  I have a million rows.
Instead of repeating that data (on average) a quarter million times each, if I extract it into a another table that has a Fruit column and just those four rows, and then make the original column a foreign key, does it save space?
I assume that the four fruit names are stored only once, and that the million rows now have pointers or indexes or some kind of reference into the second table.
If my row values are longer than short fruit names I assume the savings/optimization is even larger.

A: That is correct.
You should have
table fruits
id   name
1    Pear
2    Apple
3    Banana
4    Strawberry

Where ID is a primary key.
In your second table you will use just the id of this table. That will save you physical space and will make your select statements work faster.
Besides, this structure would make it very easy for you to add new fruits.

A:
Instead of repeating that data (on average) a quarter million times
  each, if I extract it into a another table that has a Fruit column and
  just those four rows, and then make the original column a foreign key,
  does it save space?

No if the "Fruit" is the PRIMARY KEY of the "lookup" table, so it must also be the FOREIGN KEY in the "large" table.
However if you make a small surrogate PRIMARY KEY (such as integer "id") in the "lookup" table and than use that as the FOREIGN KEY in the "large" table, you'll save space.

A: At first yes it will save space because int - 4 bytes, TINYINT - 1 byte. Secondly, searching by this field with TYPE INT will be faster than by VARCHAR. In addition to this, you can use ENUM if your data doesn't change in future. With enum you will get the same maybe faster result than with secondary table and you will avoid additional join.

A: Normalization is not just about space, it's often about redundancy and modelling the data behavior and also about updating just one row for a change - and reducing the scope of locks by updating only the minimal amount of data.

A: The data types of the fields on both sides of a foreign key relationship have to be identical.
If the parent table's key field is (say) varchar(20), then the foreign key fields in the dependent table will also have to be varchar(20). Which means, yes, you'd have to have X million rows of 'Apple' and 'Pear' and 'Banana' repeating in each table which has a foreign key pointing back at the fruit table.
Generally it's more efficient to use numeric fields as keys (int, bigint), as those can have comparisons done with very few CPU instructions (generally a direct one cpu instruction comparison is possible). Strings, on the other hand, require loops and comparatively expensive setups. So yes, you'd be better off to store the fruit names in a table somewhere, and use their associated numeric ID fields as the foreign key.
Of course, you should benchmark both setups. These are just general rules of thumbs, and your specific requirements/setup may actually work faster with the strings-as-key version.

A: Sadly, you assume wrong: the values are physically stored repeatedly for each referencing table. Some SQL products do store the value just once but most don't, notably the more popular ones which are based on contiguous storage on disk.
This is the reason end users feel the need to implement their own points in the guise of use integer 'surrogate keys'. A system surrogate would be preferable e.g. wouldn't be visible to users, in the same way an index's 'values' are maintained by the system and cannot be manipulated directly by users. The problem with rolling your own is they become part of the logical model.


text:
Q: How do i apply changes made to path variable after changing it? In my .bat file, I used the code:
setx /m path "%PATH%;%~dp0" %~dp0

to add the current directory of the .bat file to the system path.
But I can't use the cmd to run phantomjs.exe (in the same directory) until I go into my system settings and edit the path variable. I do not actually make any changes, just click edit then ok to apply the change.
What do I need to add to the script to allow me to run phantomjs.exe without the need of going into system settings?
EDIT: The laptop I'm using is a 32bit operating system and the change is not applied. I tested it on a 64bit operating system using the code setx /m path %PATH%%~dp0 and the change is applied straight away without having to open the path variable.
How can i make this work for a 32bit operating system?

A: Use set and setx. Setx is for future windows and set for current window. Mix and match how you want.


text:
Q: linux bash - sed > grep > mail (not working in sh) This is working ok from command line:
sed -n -e '/^2014-06-17/,/^2014-06-18/p' /var/log/tomcat7/catalina.out |         grep -i '===============================\|ACTION URL=\|user-agent=\|RemoteAddr=\|exception\|at \|caused by' |         mail mymail@mydomain.com -s "[mydomain.com.crons] logsWatch - tomcat7/catalina.out - 06-17"

but when I execute it inside a .sh sends me an empty body message.
Full code:
#!/bin/bash

year=`date --date='1 days ago' +%Y`
monthName=`date --date='1 days ago' +%b`
month=`date --date='1 days ago' +%m`
day=`date --date='1 days ago' +%_d`
today=`date +%_d`
hour=`date --date='1 hour ago' +%H`

echo "logsWatch - catalina.out - ${month}-${day}"
echo "logsWatch - catalina.out - ${month}-${day}" > logsWatch.txt
echo "========================" >> logsWatch.txt
echo "===============================\|ACTION URL=\|user-agent=\|RemoteAddr=\|exception\|at \|caused by" >> logsWatch.txt
echo "" >> logsWatch.txt
echo "sed -n -e '/^${year}-${month}-${day}/,/^${year}-${month}-${today}/p' /var/log/tomcat7/catalina.out | \
        grep -i '===============================\|ACTION URL=\|user-agent=\|RemoteAddr=\|exception\|at \|caused by' | \
        mail mymail@mydomain.com -s \"[mydomain.com.crons] logsWatch - tomcat7/catalina.out - ${month}-${day}\""

sed -n -e '/^${year}-${month}-${day}/,/^${year}-${month}-${today}/p' /var/log/tomcat7/catalina.out | \
        grep -i '===============================\|ACTION URL=\|user-agent=\|RemoteAddr=\|exception\|at \|caused by' | \
        mail mymail@mydomain.com -s "[mydomain.com.crons] logsWatch - tomcat7/catalina.out - ${month}-${day}"


text:
Q: Serial voting rep calculation bug I was visiting my profile. I noticed a -43 change on my reputation tab header. Confused as to why I would lose that much reputation as I haven't done much the past few days, I clicked it. To my surprise, someone decided to serially downvote me for reasons unbenounced to me. Thankfully, the system reverted these votes and put my rep back to "normal".
However, my reputation tab appears to have miscalculated the delta since I last checked. All that was new since I last checked was a downvote on a question (-1), a serial downvote spree (-42), and a serial downvote reversal (+42). For some reason, the tab shows -43 instead of the actual delta of -1. I'm guessing this is a bug, but if it is status-bydesign, please explain why.


text:
Q: Restrict autocompletion with HLS and vscode Autocompletion in the Haskell Language Server (with VScode) gives suggestions before a single character in the next word is typed (starts with !!) and adds often non-sense text. How can the useful auto-completion function be limited to start only after say 2 or 3 characers are typed?
I tried
"editor.acceptSuggestionOnCommitCharacter": false,
in the settings, but it did not produce the desired effect.
Addition: could somebody start a Haskell-Language-Server tag?


text:
Q: Commonly used metrics to compare two Young measures Let $\Omega\subset \mathbb{R}^n$ be a bounded open set, $K\subset \mathbb{R}^d$ be a compact set, and $M_1(K)$ be the set of probability measures on $K$. Then  a Young measure is defined as a $\textrm{weak}^*$ measurable map:
$$
\nu:x\in \Omega\mapsto \nu(x)\in M_1(K).
$$
Now I want to compare two Young measures $\nu$ and $\mu$. However, since there are many distances defined on $M_1(K)$, I am not sure what is the most commonly used metric for Young measures. Is the choice of metric  problem dependent?
In particular, I am interested in the case where $K$ is not finite. Since if $K$ is a finite set with cardinality $N$, then I can identify $M_1(K)$ as the probability simplex in $\mathbb{R}^N$, and hence view $\nu$ as a function
$$
\nu:x\in \Omega\to \nu(x)\in \mathbb{R}^N,
$$
and use the metric $\|\nu-\mu\|=\sup_{x\in \Omega}\|\nu(x)-\mu(x)\|_{\mathbb{R}^N}$, where $\|\cdot\|_{\mathbb{R}^N}$ denotes the Euclidean norm on $\mathbb{R}^N$.

I found in the literature that one can use the norm
$\|\nu\|_{\textrm{TV}}=\sup_{x\in \Omega}|\nu(x)|_{\textrm{TV}}$, where $|\cdot|_{\textrm{TV}}$ denotes the total variation norm of a probability measure. However,  the TV norm seems to be too strong for my application. In particular, $(M_1(K),|\cdot|_{\textrm{TV}})$ is not separable if $K$ is uncountable, so it is not easy to approximate $M_1(K)$ by a finite dimensional sub-manifold and obtain convergence in $\|\cdot\|_{\textrm{TV}}$-norm.


text:
Q: How can I align the itemize with its title? I want to align the list of items with its title, all start from the left margin of the page. For decreasing the space between the items, I have used "compactitem" package. But the result is like this:
Name list

*

*item 1

*item 2

*item 3

But I want the bullets align with title "Name list" (i,e with no indent). I used \noindent for each item but it doesn't change. How can I do it?

A: This is a solution using the enumitem package instead of paralist. Its wide option is made for that:
\documentclass[12pt, a4paper]{article}
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage{lmodern}
\usepackage{enumitem}

\begin{document}

Here's a compact itemize environment with bullets aligned with the left margin:

\noindent
\begin{itemize}[wide, nosep, labelindent = 0pt, topsep = 1ex]
\item[\textbf{Name list}]
\item A first item
\item A second item
\item Another item
\end{itemize}
Text text text text text text text text text text text text text text text text text text text text text text text text text.

\end{document}


text:
Q: Responsive Design + RESS techniques I am wondering if something similar to this can be easily done in if/else PHP or Javascript. I have read about the usual ress techniques and I am trying to find a solution that doesn't rely on device detection like WURFL. Maybe what I am looking for is called "conditional loading"?
My goal is to only load the appropriate markup based on screen width exactly like a media query. For instance, I could create a full nav for larger screens and a simple more mobile friendly nav for smaller devices/screens. This would save tons of bandwidth and make the site truly flexible.  Thanks for your input!
{ if < 768 }
some code here {html, php, etc}
{ / if}
{ if > 768 }
some code here {html, php, etc}
{ / if}

A: You can use element.clientWidth for device-width and window.screen.width. Another approach would be window.matchMedia, which is available in fairly every browser.

A: There are a few ways that these designs can be made. Javascript and php can both be used but will have their querks.
You said that you didn't want to do user agent testing, so that rules out PHP. You could use php to check the user agent by doing $_SERVER['HTTP_USER_AGENT'] and testing for IPhone etc. if you wanted to and then show the content that you wanted within a conditional statement.
Javascript can be used to test for the screen size by using
window.screen.availWidth AND window.availHeight
This will return the available height for the browser that can be occupied by your web browser. For the full resolution use window.screen.width AND window.screen.height
This works on most browsers but comes with one issue. Depending on the pixel depth ratio you may not be able to return the ACTUAL screen resolution. For instance I use a mac that has a retina screen. The javascript listed above shows that my screen width and height is 1280x800 when in fact its 2560x1600 or 2x the return value. You could fix this though by testing for apple products with retina screens and multiplying by two. That said though, his pixel depth doesn't affect the proportions of the objects on the website, it just makes images and video that aren't hidpi look blurry or pixelated.
Hope this helps.


text:
Q: Is there a term for contemporary words that historically described a state of affairs that's no longer the case? The example in question: the term "chemist" has been used to describe pharmacists since the middle ages, because in the middle ages and perhaps until a century or so ago, the pharmacist literally was the chemist who synthesized the substances you purchased from him. This is no longer the case in any way at all, and yet the term remains in common use to refer to pharmacists.
I can't think of any other distinct examples off the top of my head. "Sinister", maybe? It used to literally described left-handed people because the association between left-handedness and evil was so strong as to be built into the language, and of course, since that association has largely disappeared, the word now only invokes its abstract meaning of "evil".
Edit: so, it seems like the phenomenon in question is kind of like the verbal equivalent of a skeuomorph. I wonder if there's a term for that specifically, but I don't see it mentioned in any of the number of similar threads.


text:
Q: How can I assign value into difference parameter from the same time in SQL Server? How can I assign value into difference parameter from the same time in SQL Server?
Example:
I have table that has columns age, name, address. How can I assign those values into the declared parameters @age int, @name varchar(max) and @address varchar(max)?
I wrote the following code, but it's not working
set @age = age,
set @name = name,
set @address = address
from [dbo].[test]

A: I don't know which DMBS you are using, but in mysql you can do this:
select @name := name, @age := age from dbo.test

Of course it will only store the field of the last row matched, so you will need to use an appropriate where clause to choose the row you are interested in.
You can also use the set command, but you will need a separate query for each field you want set:
set @name = (select name from dbo.test limit 1)
set @age = (select age from dbo.test limit 1)

A: SELECT @age = age,@name = name,@address = address FROM [dbo].[test]

A: SELECT @age = age,
       @name = name,
       @address = address
FROM dbo.test
WHERE primarykey = somevalue


text:
Q: XR device (Oculus) starts unpaired in Unity's new input system I've set up actions in Unity's new input system and added corresponding bindings for both keyboard and XR (Oculus Rift). When I enter play mode, the keyboard-based action correctly fires, but the button clicks from the Rift controller do not.
Viewing the Input Debug panel, I see that User #0 is showing a control scheme of Keyboard/Mouse and that the Rift is not listed as a Paired Device:

InputUser.PerformPairingWithDevice appears in the Input docs, but given that I'm just doing a local single-player experience, it makes me think that I'm missing an easier way to set this up. Is there a way to alter the default user paired input to include the Rift?


text:
Q: $.getJSON returned selected item I'm creating a kind of API system like any social network :D
Basically, i created a php page that call with $getJSON method:
This is getuser.php
<?

include 'config.php'; connect();

$get = trim(strip_tags($_GET['id']));

$sql = "SELECT username,id,avatar FROM utenti WHERE id = $get ";
$result = mysql_query($sql);

while ($row = mysql_fetch_array($result,MYSQL_ASSOC))
{
        $row_set[] = $row;
}
echo json_encode($row_set);

?>

(example id=2)
[{"username":"Firefoxer","id":"2","avatar":"account\/firefoxer\/pic.jpg"}]

And .js function
$.getJSON('getuser.php', {
    id: user
}, function (data) {
    callback = data.avatar
});
alert(callback);

Question is... why it returns undefined object every time ? Code seems right, any ideas ?

A: i am not sure but try to set header as JSON object before your echo like below:
header('Content-type: application/json');
echo json_encode($row_set);

A: Since you are getting array of objects, you have to mention the index for data.
ie data[0].avatar
$.getJSON( 'getuser.php',{ id: user }, function(data) {
   callback = data[0].avatar
   alert(callback);
});

A: You can only access the data after the callback function has been executed:
$.getJSON( 'getuser.php',{ id: user }, function(data) {
    // now it's available
    console.log(data);
});
// now it's not

This is called asynchronous programming, do a search here on SO if this is a new concept for you.


text:
Q: Batch file for loop including too many files I am using a batch file to compress files in separate archives using 7-zip. The batch file contains this line:
FOR %%A IN (*.xls) DO "c:\program files\7-zip\7z.exe" u -mx9 -m0=lzma2:d16m "%%~nA.7z" "%%A"

Unfortunately, due to the nature of CMD, it this line compresses both *.xls files and *.xlsx files which i don't intent.
How do i get it to ignore *.xlsx-files?

A: All you need to do is to test what the file extension is
for %%A in (*.xls) do if /i "%%~xA"==".xls" (
    "c:\program files\7-zip\7z.exe" u -mx9 -m0=lzma2:d16m "%%~nA.7z" "%%A"
)


text:
Q: Oracle nvl function not working as expected I want to convert null values to ' '. But when I use this code I got null values as 'NULL':
SELECT NVL(column_a, ' ') FROM table_a

A: If your GUI displays "NULL" for those values, it is the GUI setting, not Oracle value. Set it to something else (e.g. nothing, in your case).


text:
Q: set the value of struct property in different Viewcontrollers in ios swift I have used struct to set constant.I have maxTextLength in integer form I have to set different values for different controller like one for 300 and another 1000.Here is my code
    struct Validations {
    static let maxAudioRecSec:Int = 150
    static var maxTextLength = 300 // Default value
    }
    SecondVC :ViewController {
    override func viewDidLoad () {
          Validations.maxTextLength = 1000
    }
   }

So value changed inside SecondVC is retain inside that controller only that is 1000.If I access this value inside another controller should be default 300.

A: You must use like below, don't use static variable for maxTextLength.
struct Validations {
    static let maxAudioRecSec:Int = 150
    var maxTextLength = 300 // Default value
 }

Now in any ViewController you must use like below.
class SecondVC :ViewController {
var validations = Validations() // create Validations struct object
    override func viewDidLoad () {
          validations.maxTextLength = 1000 // use like this
    }
   }

Any doubt plz comment.


text:
Q: Yii2-user Dektrium - Registration Controller not exists error when i override I encountered a strange issue today with Yii2.
I am using yii2-user extension and i have overridden the RegistrationController in my app folder to add few more features.
The thing is its working fine in my XAMPP but not in the server (Cent OS).
Im getting the below error.
**ReflectionException

Class app\controllers\user\RegistrationController does not exist**

My config is...
    'modules' => [
    'user' => [
            'class' => 'dektrium\user\Module',
            'layout'=>'@app/views/layouts/main.php',
            'mailer' => [
                'viewPath' => '@app/views/mail',
            ],
            'modelMap' => [
                'User' => 'app\models\User',
                'RegistrationForm' => 'app\models\RegistrationForm',
                'Profile' => 'app\models\Profile',
            ],
            'controllerMap' => [
                'registration' => 'app\controllers\user\RegistrationController',
                'security' => [ 'class' => 'dektrium\user\controllers\SecurityController', 'layout' => '@app/views/layouts/login', ],
            ],
    ],
],

My new controller file is...
namespace app\controllers\user;
use Yii;
use app\models\RegistrationForm;
use dektrium\user\controllers\RegistrationController as BaseRegistrationController;
use yii\filters\AccessControl;

class RegistrationController extends BaseRegistrationController
{
.......
}

Can anyone please let me know what im doing wrong?
Thanks in advance!

A: The app\controller..... filname  don't exist   or don't match cause lower/uppercase difference between OS
 the problem is related to the fact unix is case sensitive and windows not .. check for you class/filename    if you have a lowercase (typically  ath the begin  of camel case)


text:
Q: Zend Framework Error: Failed opening required 'Zend/Application.php' I get the following error when I try to run the project created by Zend Framework. Its looking for Zend/Application.php and that is available in the directory that is in my include_path. I do have read permissions on the directory.

PHP Fatal error:  require_once() [function.require]:
  Failed opening required 'Zend/Application.php'
  (include_path='/var/www/vhosts/moderncloud.net/om/library:.:/var/www/vhosts/moderncloud.net/om
  /library:') in /var/www/vhosts/moderncloud.net/om/public/index.php on
  line 24

<?php

// Define path to application directory
//defined('APPLICATION_PATH')
//    || define('APPLICATION_PATH', realpath(dirname(__FILE__) . '/../application'));

defined('APPLICATION_PATH')
    || define('APPLICATION_PATH', dirname(__FILE__) . '/../application');

// Define application environment
defined('APPLICATION_ENV')
    || define('APPLICATION_ENV', (getenv('APPLICATION_ENV') ? getenv('APPLICATION_ENV') : 'production'));

// Ensure library/ is on include_path
set_include_path(implode(PATH_SEPARATOR, array(
    ('/var/www/vhosts/moderncloud.net/om/library'),
    get_include_path(),
)));

/** Zend_Application */
require_once 'Zend/Application.php';

// Create application, bootstrap, and run
$application = new Zend_Application(
    APPLICATION_ENV,
    APPLICATION_PATH . '/configs/application.ini'
);
$application->bootstrap()
            ->run();

SOLUTION:

I found it myself today. Its a problem with the option
  "php_admin_value open_basedir" in my httpd configuration. I set it to
  none and it started working. Alternatively, I guess I can append the Zend library
  directory to the open_basedir option in my web server configuration instead of setting it to none.

A: Can you try replacing:

set_include_path(implode(PATH_SEPARATOR, array(
    ('/var/www/vhosts/moderncloud.net/om/library'),
    get_include_path(),
)));

with

$siteRootDir = dirname($_SERVER['DOCUMENT_ROOT']);

set_include_path(
    $siteRootDir . '/library' . PATH_SEPARATOR
    . $siteRootDir . '/application' . PATH_SEPARATOR
    . get_include_path()
);

Hope it works for you

A: If possible, remove the existing zend framework installation and install ZF using PEAR. It will be easier to update later on:
 pear channel-discover zend.googlecode.com/svn
 pear install zend/zend

It will also use PEAR's include_path, so it should solve your problem.
If you can't use pear, try to use relative path with your include path:
 // Ensure library/ is on include_path
set_include_path(implode(PATH_SEPARATOR, array(
    realpath(APPLICATION_PATH . '/../library'),
    get_include_path(),
)));

A: This problem generated due to :

*

*Inside Public folder in index.php file.

or

*Inside library folder :- Just check in library folder there is a folder of Zend present in library folder or not.If not present zend folder then download from zend framework and save in library folder.

=> In index.php copy the following code and replace it.

<?php

 // Define path to application directory

 defined('APPLICATION_PATH')
|| define('APPLICATION_PATH', realpath(dirname(__FILE__) . '/application'));

 // Define application environment
 defined('APPLICATION_ENV')
 || define('APPLICATION_ENV', (getenv('APPLICATION_ENV') ? getenv('APPLICATION_ENV') : 'production'));

 // Ensure library/ is on include_path
 set_include_path(implode(PATH_SEPARATOR, array(
 realpath(APPLICATION_PATH . '/../library'),
 get_include_path(),
 )));

  /** Zend_Application */
  //require_once 'Zend/Application.php';
  require_once 'library/Zend/Application.php';

  // Create application, bootstrap, and run
 $application = new Zend_Application(
 APPLICATION_ENV,
 APPLICATION_PATH . '/configs/application.ini'
      );
                                                                                $application->bootstrap()
        ->run();


text:
Q: Generating dartboard shapefiles using ArcGIS Desktop I am attempting to generate a polygon 'dartboard' shapefile. Radially, there should be a circle from 0 to 20 km, an annulus from 20 km to 30 km, and an annulus from 30 km to 80 km. These three concentric shapes are divided into 8 segments to yield 24 sectors.
Within ArcGIS Desktop , within a new shapefile, I have generated three overlapping circles, with the same origin. However, I do not know how to take these multiple features and convert them into a single feature set (e.g. separate outer ring, middle ring, and inner circle).
I have attempted to use the Overlay tools in ArcToolbox but to no effect.
Equally, I have no idea, once that is done, how to divide this shape up into 45 degree sectors.

A: This ArcUser article may point you in the right direction.  The final output is a ring map, which seems similar to the "dartboard" you are trying to achieve. It has a download link to a Ring Map toolbox and practice datasets.
After further digging, How to implement ringmaps in ArcGIS? references the same ArcUser article.

A: I would build the dartboard with a projected coordinate system, perhaps azimuthal equidistant with its defining parameter set to use the center point. Buffer it to form the three rings you need.
To create the 45 degree X that you need, use the Create Fishnet tool. You'll need to set the origin to the lower left of your area of interest, so something like (-100 km,-100 km) or if the coordinate system units are meters, (-100000 m, -100000 m). Use the Y Axis coordinates to set the 45 degree angle that you need like (0,0). Then you can either set the number of rows and columns to zeroes and set the upper right corner, or define the upper right corner of the grid.
Note: I have not tried this. Thinking about it further, you may need to experiment with the start point in order to have the fishnet cover the buffered rings.

A: Clipping the circles can be done using the editing tools. First, select the innermost circle and click the 'clip' command under the 'Editor' menu. Then select the middle circle (which will now actually be an annulus) and click the 'clip' command again.
For the sectors, you should first make a new shapefile of 8 isosceles triangles radiating out from the center point. You can then intersect the triangles with the annuli to arrive at your final shapes.
The coordinates for the points of your first triangle (clockwise from north) will be:
x_1 = x_circle_center (x-coordinate of the center of the circles)
y_1 = y_circle_center
x_2 = (x_circle_center + cos(0 * pi / 180) * length)
y_2 = (y_circle_center + sin(0 * pi / 180) * length)
x_3 = (x_circle_center + cos(45 * pi / 180) * length)
y_3 = (y_circle_center + sin(45 * pi / 180) * length)

For the second triangle you will use 45 and 90 in place of 0 and 45, and so on.
The length that you use must go sufficiently past the outside of the outer annulus so that the shortest leg of the triangle does not cut into it. Just use something like 1.5 times the longest radius (in your example, 1.5 * 80 km = 120 km), which will be way more than enough.
All of this can be implemented in Python using arcpy geometries, but you can also do this manually using the editing tools in ArcMap. Just calculate the coordinates for your triangles and enter them into the Edit Sketch Properties window.
And be sure to use a projected coordinate system for this (not latitude and longitude). If you want to be very accurate with your angles and distances, you could reconstruct your circles and create your triangles in an azimuthal equidistant projection centered on the circle center. Depending on your needs, that might not be necessary.


text:
Q: How to get the autocomplition working correctly for inherited methods in PhpStorm? There are two classes defined as follows:
class Foo
{
    private $aaa;
    public function setAaa(Aaa $aaa): self
    {
        $this->aaa = $aaa;
        return $this;
    }
}

class Bar extends Foo
{
    private $bbb;
    public function setBbb(Bbb $bbb): self
    {
        $this->bbb = $bbb;
        return $this;
    }
}

So here "fluent" setters are used. But PhpStorm seems to ignore this and displays a warning:
$bar = (new Bar())
    ->setAaa(new Aaa())
    ->setAaa(new Bbb())
;

Method 'setBbb' not found in ...\Foo

Is there a way to get the autocompletion working as expected ins such cases?

A: First of all -- fix your code sample -- make it real and not some PHP-looking chunk of text.

*

*class Bar extends -- extends what?

*what is setAaa() method?

*what is setBbb() method? Your code sample does not have it.

Anyway ... as for the actual question, after making all the changes so it looks like real PHP code...
Use PHPDoc and ensure that it says @return $this. Right now it interprets self in : self part as specific class (which is Foo) ... and setPropertyBbb() is obviously NOT available in Foo class. By specifying @return $this you make it fluent in IDE eyes.
<?php

class Foo
{
    private $aaa;

    /**
     * My super method
     *
     * @param Aaa $aaa
     * @return $this
     */
    public function setPropertyAaa(Aaa $aaa): self
    {
        $this->aaa = $aaa;
        return $this;
    }
}

class Bar extends Foo
{
    private $bbb;
    public function setPropertyBbb(Bbb $bbb): self
    {
        $this->bbb = $bbb;
        return $this;
    }
}

$bar = (new Bar())
    ->setPropertyAaa(new Aaa())
    ->setPropertyBbb(new Bbb())
;


text:
Q: How to randomly generate random numbers in one of two intervals in Python I want to generate random numbers from two different ranges [0, 0.3) and [0.7, 1) in python.
numpy.random.uniform has the option of generating only from one particular interval.

A: I assume you want to choose an interval with probability weighted by its size, then sample uniformly from the chosen interval. In that case, the following Python code will do this:
import random

# Define the intervals.  They should be disjoint.
intervals=[[0, 0.05], [0.7, 1]]
# Choose one number uniformly inside the set
random.uniform(*random.choices(intervals,
   weights=[r[1]-r[0] for r in intervals])[0])

import numpy

# Generate a NumPy array of given size
size=1000
numpy.asarray([ \
    random.uniform(*random.choices(intervals,
        weights=[r[1]-r[0] for r in intervals])[0]) \
    for i in range(1000)])

Note that the intervals you give, [[0, 0.3], [0.7, 1]], appear to be arbitrary; this solution works for any number of disjoint intervals, and it samples uniformly at random from the union of those intervals.

A: How about this one?
first_interval = np.array([0, 0.3])
second_interval = np.array([0.7, 1])

total_length = np.ptp(first_interval)+np.ptp(second_interval)
n = 100
numbers = np.random.random(n)*total_length
numbers += first_interval.min()
numbers[numbers > first_interval.max()] += second_interval.min()-first_interval.max()

A: Refer to this thread hope it solves your query.
But the answer is as follows :
def random_of_ranges(*ranges):
  all_ranges = sum(ranges, [])
  return random.choice(all_ranges)
print(random_of_ranges(range(65, 90), range(97, 122)))

click here

A: You can just concatenate random numbers from those two intervals.
import numpy as np

rng = np.random.default_rng(12345)
a = rng.uniform(0, 0.3,1000)
b = rng.uniform(0.7, 1,1000)

my_rnd = np.concatenate([a, b])

These look fairly uniform across the two intervals.


text:
Q: How do notifications work with Mailboxer gem? I'm trying to figure out how to setup a notifications system using Mailboxer.
I've already used it to setup an in-site messaging system so that users can message each other. Now I'd like to use it to send notifications from the site, to notify users of changes in their reputation points or remind them of actions they must complete. Something like Facebook or Stackoverflow's dropdown notification menus.
As an example, it might contain these types of notices:

*

*User gets some points for performing an action:

*

*"You received 50 points for helping #{user.name} with #{request.title}.

*A reminder that the user must perform an action:

*

*"You must review #{user.name}'s help with #{request.title}!

*Will link to a page to complete that action.

*User receives a reply to a message they sent:

*

*"You've received a message from #{sender.name}"

*Will link to the message.

Here are some details:

*

*I don't want all notifications to send an email. Most will only need to be seen in the notifications menu. Is there an option in Mailboxer to control what is emailed, or would I have to bypass Mailboxer's mailers?

*I'll want to format each type of notification differently in the dropdown. Add a specific glyphicon to each for example. Could I use the notification type field for this (using it to set a conditional)? How does type work? Can I just set it to a string, such as "reputation", depending on the notification?

*Objects can be passed to the notify method. I'm confused about the purpose of this. How can that object be used? What objects would I want to send?

Feel free to leave some general info on Mailboxer notifications rather than specifically answering everything.
I've had pretty bad luck finding documentation for the notifications features, so would appreciate it if someone with some Mailboxer knowledge could chime in on this. Thanks in advance.

A: This is an late answer but just in case someone came upon this question like me, this is what I ended up doing.
There is an user identities method defined as https://github.com/mailboxer/mailboxer#user-identities
If it returns an email, an email will be sent. If it returns nil, no email will be sent.
There is a notify method in mailboxer, and you can use it to send notifications as,
alice.notify("Hi","Bob has just viewed your profile!")

And in mailboxer_email, check if the object is a notification or not.If it is, do not send an email.
def mailboxer_email(object)

    if object.class==Mailboxer::Notification
      return nil
    else
      email
    end
 end

You can defined more complex logic here such as disable email for certain type of users, etc.


text:
Q: Attrubute error, z3 has no attribute Ints I am doing symbolic execution in Python using the z3 module. At some part of the code, exec is being used to invoke calling z3 function. The code snippet is as follows:
def can_be_satisfied(n):
 path = get_path(n)
 my_names, path =to_single_assignment(path)
 s1 = "%s = z3.Ints('%s')" % (', '.join(my_names), ' '.join(my_names))
 exec(s1, globals(), locals())
 s = z3.Solver()
 s2 = 's.add(%s)' % (', '.join([tosrc(i) for i in path]))
 print(s2)
 exec(s2, globals(), locals())
 if s.check() == z3.sat:
    print("sat:", s.model())
    return True
 else:
    return False

As I saw in the documentation of z3 module for Python (http://www.cs.tau.ac.il/~msagiv/courses/asv/z3py/guide-examples.htm), it contains the attribute 'Ints'. However, after the execution of the program, the following error is generated by the snippet:
File "code/symbolic_concolic_egt/symbolic/symbolic.py", line 69, in can_be_satisfied
    exec(s1, globals(), locals())
File "<string>", line 1, in <module>
AttributeError: module 'z3' has no attribute 'Ints'

Any suggestion on how to solve this problem is welcomed.
Thank you in advance

A: For me, the problem was with conflicting packages.
I had z3 and z3-solver both installed.
After removing z3 package I was able to use z3 without issues.


text:
Q: extjs-adding a record to a store does not reflect on the grid hi i have grid with store and i add record dynamically to the store for most times the data being added to the store gets reflected on the grid but sometimes the record dont seem to get reflected on the grid..please help me solve this problem
var entityGrid = new Ext.grid.EditorGridPanel({

    ddGroup           : 'gridDDGroup',
    layout            : 'fit',
    store             : gridStore,
    closable          : true,
    enableDragDrop    : true,
    enableColumnMove  : false,
    enableColumnResize: true,
    columnLines       : true,
    stripeRows        : true,
    colModel          : new Ext.grid.ColumnModel({
        columns:cols
    }),
    expandable        : true,
    autoExpandColumn  : 'name',
    tbar              : gridToolBar,
    view              : new Ext.grid.GridView({
        enableRowBody : true,
        ignoreAdd     : true,
        deferEmptyText: false,
        emptyText     : 'No Record found.',
        getRowClass   : function(record, rowIndex, rp, ds){}
    }),
    id                : id,
    selModel          : new Ext.grid.RowSelectionModel({
        singleSelect  : true
    })

var store =new Ext.data.JsonStore({
    fields : [
        {
            name : 'name',
            mapping : 'name'
        }, {
            name : 'displayName',
            mapping : 'displayName'
        }
    ],
    root : masterData.
})

A: I am not sure it makes a difference but this code always worked for me:
var r = new store.recordType({ field1: '1', field2: '2' });
r.commit();
store.add(r);
store.commitChanges();
grid.store.sort('field1', 'ASC');

Try adding commitChanges() and refreshing.

A: I'm not sure if you're still plagued by this problem, but I found the code at:
http://www.sencha.com/forum/showthread.php?141982-commitChanges-and-rejectChanges-for-the-Store-in-ExtJS-4
to be very useful as things changed moving to EXTJS-4.   Which version of EXTJS are you using?  Since you're using an EditorGridPanel, I'm guessing it's ExtJS 3.  If you'd like, I can contribute a code fragment that uses the above architecture successfully to update a record on a grid.


text:
Q: Wordpress plugin: session based form processed after shortcode generation I wrote a Wordpress plugin enabling the embedding of a form inside a post / page using a shortcode.
I use php sessions for this form.
One of the uses is to store a token, generated when the form is displayed, and then compared to the value of an hidden field of the form, also set when the form is displayed.
This way, if the submitted value of the hidden field is the same as the token's stored value in the session, I know that this is the form that was generated by my plugin and further validation takes place.
The token is generated when I create the form, when the function called by 'add_shortcode' is run. At this time its value is stored both in the session array and as the value of the form's hidden field.
The problem is that it looks like the token stored in the session is overwritten before it is compared to the hidden fields value, in other words it looks like the generation of the form (and the token) happens before the form logic (included at 'init').
Here are the relevant parts of my code:
main-plugin-file.php:
// Sessions
function init_sessions() {
    if (!session_id()) {
        session_start();
    }
}
add_action('init', 'init_sessions');

// Formlogic
add_action('init', 'include_formlogic');

function include_formlogic()
{
    include_once 'formlogic.php'; // comparing $_SESSION['token'] and $_POST['token']
}

// Shortcode
add_shortcode('display_form', 'display_form');

function display_form()
{
    return getForm();
}

formlogic.php:
// generate unique token
function generateToken()
{
    $token = uniqid(rand(), true);
    $_SESSION['token'] = $token;
    return $token;
}

// Generate form
function getForm()
{
    $token = generateToken();
    // Checking the form
    if (checkForm()) {
        // Get variables to be included in the form
        getVariables();
        // Start with the output buffering
        ob_start();
        include 'form-template.php';
        $output = ob_get_clean();
    } else {
        // Alternative html in case of error
        $output = 'Error';
    }
    return $output;
}

// Comparing $_SESSION['token'] and $_POST['token'] to see if we go further:
if ($_SESSION['DRAFS_token'] === $_POST['token']) {
    // Validate the form and process it
} else {
    // Display the form along with the errors
}