Q: Confusion related to generalized linear model example I was reading this article related to generalized linear models:  http://en.wikipedia.org/wiki/Generalized_linear_models. It gave a specific example

Ordinary linear regression predicts the expected value of a given unknown quantity (the response variable, a random variable) as a linear combination of a set of observed values (predictors). This implies that a constant change in a predictor leads to a constant change in the response variable (i.e. a linear-response model). This is appropriate when the response variable has a normal distribution (intuitively, when a response variable can vary essentially indefinitely in either direction with no fixed "zero value", or more generally for any quantity that only varies by a relatively small amount, e.g. human heights).
However, these assumptions are inappropriate for many types of response variables. For example, in many cases when the response variable must be positive and can vary over a wide scale, constant input changes lead to geometrically varying rather than constantly varying output changes. As an example, a model that predicts that each increase in 10 degrees leads to 1,000 more people going to a given beach is unlikely to generalize well over both small beaches (e.g. those where the expected attendance was 50 at the lower temperature) and large beaches (e.g. those where the expected attendance was 10,000 at the lower temperature). An even worse problem is that, since the model also implies that a drop in 10 degrees leads 1,000 fewer people going to a given beach, a beach whose expected attendance was 50 at the higher temperature would now be predicted to have the impossible attendance value of -950! Logically, a more realistic model would instead predict a constant rate of increased beach attendance (e.g. an increase in 10 degrees leads to a doubling in beach attendance, and a drop in 10 degrees leads to a halving in attendance). Such a model is termed an exponential-response model (or log-linear model, since the logarithm of the response is predicted to vary linearly).

I actually didn't get the example given. For two different types of beaches, I will have two different models.
For big beach
y = 1000x

For small beach
y = 50x

So if x raises by 10, y will be impacted accordingly in the two beaches. I didn't get what they are trying to do. Any clarifications?
They have given that if they use the exponential function like $e^{Xb}$ it will solve the issue. But I don't know how. Suppose the temperature X=1, b=1 lest suppose then y = 2.7183. Now suppose the temperature is raised by let's say 10. then it will be $e^{11}$ = 5.9874e+04. The response is not doubled and they were looking something like this.
I am confused.

A: The 'geometric' change with constant input means that it will change by a constant proportion, or factor, rather than by a constant additive amount.  For example, if the old value is $y_{old}$ and $x$ goes up by 1, there will be an $\exp(\beta)$-fold change in $y$.  That is, the new $y_{new}=\exp(\beta)y_{old}$.  On the other hand, if the change were additive, it would be $y_{new}=y_{old}+\beta$ instead.  In your example, you're using the wrong value for b (presumably b1, note that you also need a b0).  Try the following (in R code, let me know if it's not transparent):
> b1 = 0.06931472   # this is the appropriate b1, not b1=1
> b0 = 1-b1         # here I make the constant
> X  = 1
> exp(b0 + b1*X)
[1] 2.718282        # this calculation gives you your original y
> X  = 11           # now we've incremented X by 10,
> exp(b0 + b1*X)
[1] 5.436564        # and y has doubled
> X  = 21           # we can go up by another 10,
> exp(b0 + b1*X)
[1] 10.87313        # and y doubles again

Here's a quick way to create your own examples:
> y1 = 2.7183           # this is the number you want y to be when X=1
> foldIncrease = 2      # this is the multiple by which you want y to go up
> y2 = y1*foldIncrease  # now we've created y_new
> xUnits = 10           # this is the number of units that X will go up to get to y_new

> b1 = (log(y2)-log(y)) / xUnits
> b1
[1] 0.06931472          # now we've calculated the appropriate b1
> b0 = log(y1)-b1
> b0
[1] 0.930692            # this gives us the appropriate value for b0

A: My less-technical explanation: Actually, you are approaching their answer. You realize that the formula for a large beach doesn't work well for a small beach, so you make a second model. But neither of these models will work well for a medium beach, so you add a third. None of these works well for a huge beach, so you add a fourth. If you get picky, you end up with models for micro, medium-large and extra-large beaches, too.
Why the proliferation of models? If you take each one and calculate the population increase from a 1-degree increase, and plot these from smallest to largest, you'll see that it's not linear. It's exponential and its slope increases as the size increases. (You see that already $50x$ versus $1000x$.)
What your quote is describing is a multiplicative model, which is based not on absolute values but percentages. Which is exactly what you were trying to do (the hard way): an $x$-percent increase at a small beach is a small number, while at a large beach it is a large number. You're just trying to imitate this percentage-based increase by using a bunch absolute-based increase models.
EDIT: Think of the combinations of action and reaction you expect to see in the world:

*

*"If temperature increases 1 degree, the number of people at this
beach will increase by approximately 100 people"

*"If the temperature increases 1 percent, the number of people at
this beach will increase by approximately 1 percent"

*"If the temperature increases by 1 degree, the number of people at
this beach will increase by approximately 1 percent"

*"If the temperature increases 1 percent, the number of people at
this beach will increase by approximately 100 people"

You are proposing that you can use #1 in any situation, but the quote is describing a situation where reality more closely resembles #2.


Q: In Python, what is the proper testing structure for packages containing packages? Which is the preferred test package structure for packages containing subpackages:
Tests in Subpackages?
a/
  __init__.py
  b.py
  c/
    __init__.py
    cc.py
    test/
      __init__.py
      test_cc.py
  d.py
  test/
    __init__.py
    test_b.py
    test_d.py

This structure suggests that each subpackage is a cohesive unit that can be tested (and possibly later released) by itself.
Subpackages in Tests?
a/
  __init__.py
  b.py
  c/
    __init__.py
    cc.py
  d.py
  test/
    __init__.py
    test_b.py
    test_c/
      __init__.py
      test_cc.py
    test_d.py

This structure does a better job of keeping the tests in one place, but makes it a little harder to run the tests for a particular subpackage.
Something else?

A: I am probably misunderstanding the question. Nevertheless, here is a go. Please, guide me to the precise question of interest by the means of comments.
Why not place the test within the modules themselves?
def main():
    pass

if __name__ == "__main__":
    main()

*

*It is idiomatic.

*It provides two different uses for every module - to be included and used by other code, or to be called directly, in which case test are run.

*Is quite handy during development. When working on a module, one usually wants to see first how the local changes are affecting the module, not that 12731 out of 13000 tests passed.

*Tests can generally be customized so that there is a test that invokes local functionality, mocking all children, and a different test to import the sub-modules usually used and do some tests that are closer to the real world use of the module. This is very handy when a sub-module is broken, but you need to work on the higher-in-the-hierarchy module.


Q: How can extract Custom Property value from lambda expression? I have the following class definition
Person.cs
class Person {

  [Column("first_name")]
  public string FirstName { get; set; }

  [Column("last_name")]
  public string LastName { get; set; }
}

I wrote an HTML Helper extension to extract the ColumnAttribute value from a given instance. However, it does not work as I expect.
Here is what I tried:
Index.cshtml
@model Person

ColumnName is @Html.ColumnNameFor( model => model.FirstName )

HtmlExtensions.cs (public static class)
public static string ColumnNameFor<T, P>(this HtmlHelper<T> helper, Expression<Func<T, P>> expression)
{
    var name = ExpressionHelper.GetExpressionText(expression);
    var metadata = ModelMetadata.FromLambdaExpression(expression, helper.ViewData);

    // this line causes a runtime error:
    //  Sequence contains no elements
    var attr = (ColumnAttribute)metadata.GetType().GetCustomAttributes(typeof(ColumnAttribute), false).First();

  return attr.Name;    // ColumnAttribute stores the value in .Name
}

For the record, I am able to extract the value using GetCustomAttributes, provided that I pass a reference to the property, which I think will make the code in the View look very different from the built in ASP MVC code for Html.TextBoxFor and Html.DisplayFor, etc.

A: Thanks to @benuto for his answer, I was able to find out how I could extract any required custom attribute or property using MemeberExpress. I wanted the answer to help others, so I made a working example. Bear in mind that you will need to check if the object does have a custom property or not, to avoid crashing when accessing FirstOrDefault().Name.
 public static string ColumnNameFor<T, P>( this HtmlHelper<T> helper,
                                           Expression<Func<T, P>> expression)
 {
      var name = ExpressionHelper.GetExpressionText(expression);

      MemberExpression me = expression.Body as MemberExpression;

      var cp = (ColumnAttribute)me
                  .Member
                  .GetCustomAttributes(typeof(ColumnAttribute), false)
                  .FirstOrDefault();

      return (cp == null) ? null : cp.Name;
 }


Q: Parsing in C# using JSON.Net (very confusing!) I want to parse the following JSON:
{"0":{"igloo_id":"0","name":"Igloo Removal","cost":"0"},"1":{"igloo_id":"1","name":"Basic Igloo","cost":"1500"},"2":{"igloo_id":"2","name":"Candy Igloo","cost":"1500"},"3":{"igloo_id":"3","name":"Deluxe Blue Igloo","cost":"4000"},"4":{"igloo_id":"4","name":"Big Candy Igloo","cost":"4000"},"5":{"igloo_id":"5","name":"Secret Stone Igloo","cost":"2000"},"6":{"igloo_id":"6","name":"Snow Igloo","cost":"1000"},"8":{"igloo_id":"8","name":"Secret Deluxe Stone Igloo","cost":"5000"},"9":{"igloo_id":"9","name":"Deluxe Snow Igloo","cost":"3000"},"10":{"igloo_id":"10","name":"Bamboo Hut","cost":"3200"},"11":{"igloo_id":"11","name":"Log Cabin","cost":"4100"},"12":{"igloo_id":"12","name":"Gym","cost":"4800"},"13":{"igloo_id":"13","name":"Split Level Igloo","cost":"4600"},"14":{"igloo_id":"14","name":"Candy Split Level Igloo","cost":"4600"},"15":{"igloo_id":"15","name":"Snowglobe","cost":"3700"},"16":{"igloo_id":"16","name":"Ice Castle","cost":"2400"},"17":{"igloo_id":"17","name":"Split Level Snow Igl","cost":"4600"},"18":{"igloo_id":"18","name":"Fish Bowl","cost":"2400"},"19":{"igloo_id":"19","name":"Tent","cost":"2700"},"20":{"igloo_id":"20","name":"Jack O' Lantern","cost":"2700"},"21":{"igloo_id":"21","name":"Backyard Igloo","cost":"4200"},"22":{"igloo_id":"22","name":"Pink Ice Palace","cost":"2400"},"23":{"igloo_id":"23","name":"Ship Igloo","cost":"4300"},"24":{"igloo_id":"24","name":"Dojo Igloo","cost":"1300"},"25":{"igloo_id":"25","name":"Gingerbread House","cost":"2100"},"26":{"igloo_id":"26","name":"Restaurant Igloo","cost":"4800"},"27":{"igloo_id":"27","name":"Tree House Igloo","cost":"4500"},"28":{"igloo_id":"28","name":"Theatre Igloo","cost":"4600"},"29":{"igloo_id":"29","name":"Circus Tent","cost":"0"},"30":{"igloo_id":"30","name":"Snowy Backyard Igloo","cost":"3000"},"31":{"igloo_id":"31","name":"Cave Igloo","cost":"1500"},"32":{"igloo_id":"32","name":"Green Clover Igloo","cost":"2050"},"33":{"igloo_id":"33","name":"Grey Ice Castle","cost":"2400"},"35":{"igloo_id":"35","name":"Cozy Cottage Igloo","cost":"2500"},"36":{"igloo_id":"36","name":"Estate Igloo","cost":"2500"},"37":{"igloo_id":"37","name":"In Half Igloo","cost":"2300"},"38":{"igloo_id":"38","name":"Shadowy Keep","cost":"2400"},"39":{"igloo_id":"39","name":"Dragon's Lair","cost":"3000"},"40":{"igloo_id":"40","name":"Mermaid Cove","cost":"3030"},"41":{"igloo_id":"41","name":"Whale's Mouth","cost":"2700"},"42":{"igloo_id":"42","name":"Trick-or-Treat Igloo","cost":"2000"},"43":{"igloo_id":"43","name":"Deluxe Gingerbread House","cost":"0"},"45":{"igloo_id":"45","name":"Invisible Snowy","cost":"0"},"46":{"igloo_id":"46","name":"Invisible Beach","cost":"0"},"47":{"igloo_id":"47","name":"Invisible Forest","cost":"0"},"48":{"igloo_id":"48","name":"Invisible Mountain","cost":"0"},"49":{"igloo_id":"49","name":"Shipwreck Igloo","cost":"900"},"50":{"igloo_id":"50","name":"Wildlife Den","cost":"900"},"51":{"igloo_id":"51","name":"Medieval Manor","cost":"1200"},"52":{"igloo_id":"52","name":"Warehouse","cost":"950"},"53":{"igloo_id":"53","name":"Pineapple Igloo","cost":"0"},"54":{"igloo_id":"54","name":"Creepy Cavern","cost":"1500"},"55":{"igloo_id":"55","name":"Frost Bite Palace","cost":"0"},"56":{"igloo_id":"56","name":"Fresh Baked Gingerbread House","cost":"2500"},"57":{"igloo_id":"57","name":"Penthouse","cost":"4000"},"58":{"igloo_id":"58","name":"VIP Penthouse","cost":"0"},"59":{"igloo_id":"59","name":"Invisible Age of Dinosaurs","cost":"0"},"60":{"igloo_id":"60","name":"Puffle Tree Fort","cost":"0"},"61":{"igloo_id":"61","name":"Secret Base","cost":"1600"},"62":{"igloo_id":"62","name":"Death Star Igloo","cost":"1000"},"63":{"igloo_id":"63","name":"Beach Party Igloo","cost":"1500"},"64":{"igloo_id":"64","name":"Gymnasium Igloo","cost":"0"},"65":{"igloo_id":"65","name":"Magical Hideout","cost":"1500"},"66":{"igloo_id":"66","name":"Eerie Castle","cost":"2000"},"67":{"igloo_id":"67","name":"Sweet Swirl Igloo","cost":"0"},"68":{"igloo_id":"68","name":"Train Station Igloo","cost":"1100"},"69":{"igloo_id":"69","name":"Main Event Igloo","cost":"1000"},"70":{"igloo_id":"70","name":"CP Airliner","cost":"1200"}}

I need a way to retrieve igloo_id, name and cost.
I've tried the following, but it's not what I want
List<Igloo> igloosList = JsonConvert.DeserializeObject<List<Igloo>>(itemJson);

This is the structure of my class
namespace Canvas
{
    public class Igloo
    {
        public int cost;
        public int igloo_id;
        public string name;

        public int Cost
        {
            get
            {
                return cost;
            }
        }

        public int Id
        {
            get
            {
                return igloo_id;
            }
        }

        public string Name
        {
            get
            {
                return name;
            }
        }
    }
}

A: Use the JsonProperty attribute :
[JsonProperty(PropertyName = "cost")]
public int Cost
    {
        get
        {
            return cost;
        }
        private set { cost = value; }
    }

    [JsonProperty(PropertyName = "igloo_id")]
    public int Id
    {
        get
        {
            return igloo_id;
        }
        private set { igloo_id = value; }
    }
    [JsonProperty(PropertyName = "name")]
    public string Name
    {
        get
        {
            return name;
        }
        private set { name = value; }
    }

Basically you need to say for each property what is the Json key that will match. Plus, you will need to have a setter for each of your property, but it can be private.

A: I'm not entirely sure I understand what you want. The code you posted generated an exception when I tried running it,

Additional information: Cannot deserialize the current JSON object (e.g. {"name":"value"}) into type 'System.Collections.Generic.List1[ConsoleApplication2.Program+Igloo]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.

It did deserialize correctly if I used:
var igloosList = JsonConvert.DeserializeObject<Dictionary<string, Igloo>>( json );

If you want to loop through it you could then use:
foreach( var igloo in igloosList.Values )


Q: How do I have a web page store changes made by javascript? I have a form on a simple web page that has a series of checkboxes.  These options represent items that may be retrieved from a database upon clicking the submit button.  In addition, there is a place to add an extra option to the page at the bottom.  Here is what I am going for:
I would like to be able to add the new option using javascript, so that it show up quickly and seamlessly to the user, rather than having to send the request back to the server and add it server-side, then have the user reload the page.  However, I also want to make sure that these added fields are preserved so that the next time I load the page, they show up.
Unfortunately, my code is proprietary, so I cannot post it here.  I hope that people can help me this some ideas without having to actually see the code.
Thanks

A: When these checkboxes are added you don't want to go the server but when user presses submit you are anyways going to server, so at that time you can persist this information about new checkboxes on server.
Another option is to call to server asynchronously using AJAX to update the server about the state change.

A: If you still want to store the changes server-side, you can do so quietly in the background.
Just use XmlHttpRequest(), together with a PHP script.

A: You can use the HTML5 local storage API to store your changes.
localStorage.setItem('favoriteflavor','vanilla');

A: If you want session related information to pass thru multiple requests, you can either put the data in a cookie, or with php you can use sessions.
http://php.net/manual/en/features.sessions.php


Q: HTML Meta and Body parts from JSON Is it possible to load html meta attributes from JSON?
for example:
<!DOCTYPE html>

<title>{{title}}</title>
<meta charset="{{charset}}">
<meta name="description" content="{{description}}">
<meta name="keywords" content="{{keywords}}">

{{H1}}

{{some_kind_of_text}}

{{some_kind_of_text2}}

A: Yes.
You can fetch data from a URL using XMLHttpRequest and then use standard DOM methods to change the content of the document.
That said, meta data is generally consumed either as the document loads (so it would be too late to change it for any practical effect by the time JS ran) or is consumed by tools that are likely to not execute JavaScript.

A: Yes as Quentin said, it is possible but any content you change with JS might not be seen by Google or other search engines.
If your purpose is to load content that needs to be read by a search engine you will want to 'build' the HTML on the server side, using a server side language like PHP for instance.


Q: How to echo the results from 2 columns within the same table - PHP I just want to echo out two columns from the same table using php.  What I have below which pulls out all the members first names:

MY DETAILS

        <?php $query = "SELECT * FROM `tblMember`";

        $result = $conn -> query($query);

        while($row = $result -> fetch_assoc())
          {
            echo $row['fldFName']."
";
          }

        $conn -> close();
        ?>

This does give the first names, but I also want the surnames to be pulled out from the same table, called fldSName. Is it a simple AND statement?

A: It is already in the results since you are using a * in the query.
echo $row['fldFName'] . ' ' . $row['fldSName'] . '
';


Q: CKEDITOR - Wordwrap seems to be posted I have a very interesting issue, using CKEDITOR. I'm doing the following:
I have an instance of CKEDITOR, and I have a form with hidden inputs. Before submitting the form, the value of CKEDITOR is entered in a hidden input field. So I have:
$('#form_hidden_input').val(CKEDITOR.instances.editor.getData());

When posting (so submitting the form, I am able, to access the value of the input with $_POST['form_hidden_input']. So far, so good. But when I now try, to insert the value I got into CKEDITOR again, it fails. What I do is
CKEDITOR.instances.editor.insertHtml('<?=$_POST['form_hidden_input'];?>');

When I echo the content of $_POST['form_hidden_input'] everything seems to be fine, but with insertHtml(), I get a "Uncaught SyntaxError: Unexpected token ILLEGAL", in Sources of of Developer Console (or when clicking on the error), the line looks like that:
CKEDITOR.instances.editor.insertHtml('
asfa

');

Be aware, that '); appears in the next line, anyway it should work, but I think, this is the only point, where the problem could appear... The question is, why is there a wordwrap, and how can I prevent that, or get it working anyway?

A: Figured out how to do it:
when I do that:
$content = $_POST['form_old_data'];
$content = str_replace("\n", "", $content);
$content = str_replace("\r", "", $content);
CKEDITOR.instances.editor.insertHtml('<?=$content;?>');

it works.


Q: How to assign a tf.keras.layers.layer to a class without initializing it? I work on a class to create all sorts of symmetric AE's. I now port this class to TF 2.0 and it is more complicated than I thought. However, I use subclassing of layers and models to achieve this. Therefore I want to group several keras layers to one keras layer. But if I want to write something like this:
def __init__(self, name, keras_layer, **kwargs):
    self.keras_layer = tf.keras.layer.Conv2D
    super(CoderLayer, self).__init__(name=name, **kwargs)

I get the following error, because tf wants to use this uninitialized layer:
TypeError: _method_wrapper() missing 1 required positional argument: 'self'

I also tried to wrap this in a list, but it did not work either.
EDIT
Here is a working minimal example and the full traceback:
import tensorflow as tf
print(tf.__version__) # 2.0.0-alpha0

class CoderLayer(tf.keras.layers.Layer):

    def __init__(self, name, keras_layer):
        self.keras_layer = keras_layer
        self.out = keras_layer(12, [3, 3])
        super(CoderLayer, self).__init__(name=name)

    def call(self, inputs):
        return self.out(inputs)

inputs = tf.keras.Input(shape=(200, 200, 3), batch_size=12)
layer = CoderLayer("minimal_example", tf.keras.layers.Conv2D)

layer(inputs)

Traceback:
Traceback (most recent call last):
  File "..\baseline_cae.py", line 24, in <module>
    layer(inputs)
  File "..\AppData\Local\Continuum\anaconda3\lib\site-packages\tensorflow\python\keras\engine\base_layer.py", line 581, in __call__
    self._clear_losses()
  File "..\AppData\Local\Continuum\anaconda3\lib\site-packages\tensorflow\python\training\tracking\base.py", line 456, in _method_wrapper
    result = method(self, *args, **kwargs)
  File "..\AppData\Local\Continuum\anaconda3\lib\site-packages\tensorflow\python\keras\engine\base_layer.py", line 818, in _clear_losses
    layer._clear_losses()
TypeError: _method_wrapper() missing 1 required positional argument: 'self'

A: The problem is with setting not instantiated class as an attribute in a subclass of tf.keras.layers.Layer. If you remove following line
self.keras_layer = keras_layer
the code would work:
import tensorflow as tf

class CoderLayer(tf.keras.layers.Layer):
    def __init__(self, name, keras_layer):
        super(CoderLayer, self).__init__(name=name)
        self.out = keras_layer(12, [3, 3])

    def call(self, inputs):
        return self.out(inputs)

inputs = tf.keras.Input(shape=(200, 200, 3), batch_size=12)
layer = CoderLayer("minimal_example", tf.keras.layers.Conv2D)
print(layer(inputs))
# Tensor("minimal_example_3/conv2d_12/BiasAdd:0", shape=(12, 198, 198, 12), dtype=float32)

It is probably a bug. This is a similar issue that had been raised (if you put your not instantiated class into list and try to __setattr__() you will get the same exception).
This could be possible workaround if you want to use multiple layers:
class CoderLayer(tf.keras.layers.Layer):
    def __init__(self, name, layername):
        super(CoderLayer, self).__init__(name=name)
        self.layer = layername
        self.out = tf.keras.layers.__dict__[layername](1, 2)

    def call(self, inputs):
        return self.out(inputs)

inputs = tf.random.normal([1, 3, 3, 1])
layer = CoderLayer("mylayer", 'Conv2D')
layer(inputs).numpy()


Q: Extract user input to python from a table created in browser? I want to create a table in a browser that's been created with python. That part can be done by using DataTable of the bokeh library. The problem is that I want to extract data from the table when a user gives his/her input in the table itself.
Any library of python I could use to do this? It would better if I could do this with bokeh though.

A: You can use BeautifulSoup it's great for parse HTML content, see this example

A: If your requirement is to create an application using Python and users will access via browser and update some data into a table?
Use Django or any web framework, basically, you are trying to build a web app!!
or
if you are looking for something else do mention your requirement thoroughly.

A: The slick grid datatable used in bokeh can be edited directly by users:
http://docs.bokeh.org/en/latest/docs/reference/models/widgets.tables.html.
Since the data for each column of a datatable can correspond to a field of a ColumnDataSource, one could create python or javascript callbacks, to detect any changes to the datavalues in the table. You can then access the updated data for your desired use case.
Here is an example using javascript callback when the data is edited. When the data is edited the updated column is printed to the browser console. Note it only detects the data as changed after you edit the value then click out of the cell.
You can do exactly the same with a python callback if you want to run outside python functions based off user input. That does require running a bokeh server to work though.
from datetime import date
from bokeh.io import output_file, show
from bokeh.layouts import widgetbox
from bokeh.models import ColumnDataSource, CustomJS
from bokeh.models.widgets import DataTable, DateFormatter, TableColumn, StringEditor

output_file("data_table.html")

data = dict(
        dates=[date(2014, 3, i+1) for i in range(10)],
        strings=['edit_this' for i in range(10)],
    )
source = ColumnDataSource(data)

columns = [
        TableColumn(field="dates", title="Date", formatter=DateFormatter()),
        TableColumn(field="strings", title="Downloads", editor=StringEditor()),
    ]

data_table = DataTable(source=source, columns=columns, width=400, height=280,
                       editable=True)

# callback code to detect user edit of table
code = """
    data = source.data
    console.log('data has been updated!')
    console.log(data['strings'])
"""

callback = CustomJS(code=code,args={'source':source})
source.js_on_change('data', callback)

show(widgetbox(data_table))

edit:
Here is a similar example using a python callback. When you edit the cell all of the cells are replaced in this example. Obviously you could do what ever you wanted this is just an illustration.
You need to set a callback on source that responds to a change in the data. Hence source.on_change('data', update). Read more
https://docs.bokeh.org/en/latest/docs/user_guide/interaction/widgets.html
from datetime import date
from bokeh.io import curdoc
from bokeh.layouts import widgetbox
from bokeh.models import ColumnDataSource
from bokeh.models.widgets import DataTable, DateFormatter, TableColumn, StringEditor

data = dict(
        dates=[date(2014, 3, i+1) for i in range(10)],
        strings=['edit_this' for i in range(10)],
    )
source = ColumnDataSource(data)

columns = [
        TableColumn(field="dates", title="Date", formatter=DateFormatter()),
        TableColumn(field="strings", title="Downloads", editor=StringEditor()),
    ]

data_table = DataTable(source=source, columns=columns, width=400, height=280,
                       editable=True)

# callback code to detect user edit of table
def update(attrname, old, new):
    data = source.data
    data['strings'] = ['you just edited the table.']*10
    source.data = data

source.on_change('data', update)

curdoc().add_root(widgetbox(data_table))


Q: (python) how can i split tuple variables? from text file, i could import the result with this code:
with open('filename.txt') as file:

    information = [tuple(line) for line in csv.reader(file)]

print(information)

result:
('   1.1   4.4   7.5   8.9  11.7  15.0  15.3  15.6  13.3  11.1   7.5   5.8        ',)

I want to split this tuple and the result has to be:
('1.1', '4.4', '7.5', '8.9', '11.7', '15.0', '15.3', '15.6', '13.3', '11.1', '7.5', '5.8')

when i use this code,
splitting = information[1].split(' ')

print(splitting)

Error happens with
AttributeError: 'tuple' object has no attribute 'split'

Are there any other methods?

A: it seems that you converted the csv into list of tuples in this line:
information = [tuple(line) for line in csv.reader(file)]

which result in:
[(//...tuple 1...//) , (//...tuple 1...//) , ...etc]

you better just concat them if you dont want nested lists:
data_list= []
for line in csv.reader(file):
    data_list += line.split()
information   = tuple(data_list)


Q: Click facebook like button and be taken to another url Is something like this possible?
I have a client launching an online magazine for his business.  He wants to add a facebook like button (for the magazine fanpage) on his current corporate site and ask users to 'like it' in order to be taken to the magazine website.  Can it be done?  Are there drawbacks to this approach?  For example, the same user will have to 'like it' every time they want to access the magazine site?
Thank you for any suggestion, I'm pretty new to facebook.

A: You can redirect a user on clicking a like button using the Javascript SDK and FB.Event.Subscribe
FB.Event.subscribe('edge.create', function(response) {

    window.parent.location = 'http://www.google.com';

});

edge.create is called when ever a user likes something on the page
response is the url that has just been liked.
If there are multiple like buttons on the page you could use an if statement with the response to make sure the page only redirects for a particular like button
Here's the full javascript code and a like button

<fb:like href="http://www.google.com" send="false" width="450" show_faces="true"></fb:like>


Q: Instantiating objects This may be a dumb question although due to my poor wording i'm having a hard time getting a good understanding from searching up on it. When instantiating an object why is the declared like so.
Object @object = new Object();
// rather than just
Object @object;

Is this simply just to call the objects constructor or is there something i'm missing?

A: Because thats the syntax to make it a new instance.


Q: Google Assistant test app unavailable in my country I've been following this tutorial on using Dialogflow and Firebase so I can control a simple website, but when trying to Talk to <app name> I receive the response

<app name> isn't available on devices set up for your language or
  country. Sorry about that.

I am located in New Zealand, but I did go into the settings for my google assistant and change the search language to English (US) and my search region to United States, although I get the same results, is there any way I can fix this or is there any way around it? Thanks

A: Following Nick Felker's comment, changing my phone's locale to English (US) enabled me to test the app. Thanks Nick!


Q: How to use the Raycaster with a CombinedCamera? I try to use a Raycaster (for selection) that works fine with a PerspectiveCamera but doesn't work with a CombinedCamera.
First it seems that CombinedCamera is not supported by the Raycaster, so among those line of three.js I add this :
if ( camera instanceof THREE.CombinedCamera ) {
    if( camera.inPerspectiveMode ) {
        camera = camera.cameraP;
    } else if ( camera.inOrthographicMode ) {
        camera = camera.cameraO;
    }
}

if ( camera instanceof THREE.PerspectiveCamera ) {

...

So as it refers to the nested camera, however that doesn't do the trick because, I believe, the nested cameras position-quaternion-rotation are not updated ??
How can I achieve this and make Raycaster work with both Ortho and Perspective modes of a CombinedCamera ?

A: The renderer needs world matrix data for the raycasting to work. Make the following modification to the CombinedCamera code:
  // Add to the .toPerspective() method:
  this.matrixWorldInverse = this.cameraP.matrixWorldInverse; //
  this.matrixWorld = this.cameraP.matrixWorld;               //

  // and to the .toOrthographic() method add:
  this.matrixWorldInverse = this.cameraO.matrixWorldInverse; //
  this.matrixWorld = this.cameraO.matrixWorld;               //

r73.


Q: Как удалить сохранённый пароль из Git Например у меня есть аккаунт на bitbucket.org. В первый раз когда я делаю git push я ввожу логин и пароль, он его запоминает. Как мне его сбросить?

A: Попробуйте просто сбросить данные о пользователе и при следующем вызове git push у вас запросит новые данные:
git config --global --unset user.password


Q: MongoDB hidden node still receiving connections I'm not sure if this question been asked before or if the following behavior of MongoDB is normal. Searching online output no results to this scenario.
Initially, we had a 3 node deployment, 1 Primary, 1 Secondary, and 1 Arbiter.
We wanted to add a ReadOnly replica to the cluster and remove the Arbiter node as well in the process. We added the following to the new node:

*

*priority: 0

*hidden: true

*votes: 1

And removed the Arbiter in the same reconfiguration process so we always have 3 voting members and it leaves us with 1 Primary and 1 Secondary and 1 ReadOnly Node.
The complete process went through smoothly, however, we still end up seeing connections to the ReadOnly replica.
But when checking via db.currentOp(), no queries show up.
Based on the documentation on MongoDB website,

Hidden members are part of a replica set but cannot become primary and are invisible to client applications.

Is there a way to investigate why there are connections coming in? And if this is normal behavior?
EDIT: (for further clarification)
Assuming the following:
MongoDB A (Primary): 192.168.1.50
MongoDB B (Secondary): 192.168.1.51
MongoDB C (Hidden): 192.168.1.52
Client A: 192.168.1.60
Client B: 192.168.1.61
In the logs, we see the following:
2018-03-12T07:19:11.607+0000 I ACCESS   [conn119719] Successfully authenticated as principal SOMEUSER on SOMEDB
2018-03-12T07:19:11.607+0000 I NETWORK  [conn119719] end connection 192.168.1.60 (2 connections now open)
2018-03-12T07:19:17.087+0000 I NETWORK  [listener] connection accepted from 192.168.1.60:47806 #119720 (3 connections now open)
2018-03-12T07:19:17.371+0000 I ACCESS   [conn119720] Successfully authenticated as principal SOMEUSER on SOMEDB

So if the other MongoDB instances were connecting, that would be fine, but my question is regarding why the clients are able to connect even when the hidden option is true and if that behavior is normal.
Thank You


Q: Modified JS file not changing Magento 2 Backend paging grid I'm currently attempting to change the "sizes.js" file using a child theme in adminhtml. This is with the "Commerce" version of Magento 2.2.5.
As we have a large number of customers and orders. What I'm trying to do is modify the paging sizes so that instead of the default "20, 30, 50, 100, 200" it uses the values "50, 100, 500, 1000, 2000". The "Custom" option is insufficient for this as this needs to be available for all users and the custom option will only allow values up to 999.
Looking into the background it would seem that the file I need to overwrite is the following one:

vendor > magento > module-ui > view > base > web > js > grid > paging > sizes.js

I've created a new theme using the vendor "TCT" and the theme "Joy". I've added a new "sizes.js" file at the location below:

app > design > adminhtml > TCT > joy > web > js > sizes.js

...containing the following code:
/**
 * Copyright Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */

/**
 * @api
 */
define([
    'ko',
    'underscore',
    'mageUtils',
    'uiElement'
], function (ko, _, utils, Element) {
    'use strict';

    return Element.extend({
        defaults: {
            template: 'ui/grid/paging/sizes',
            value: 20,
            minSize: 1,
            maxSize: 9999,
            options: {
                '50': {
                    value: 50,
                    label: 50
                },
                '100': {
                    value: 100,
                    label: 100
                },
                '500': {
                    value: 500,
                    label: 500
                },
                '1000': {
                    value: 1000,
                    label: 1000
                },
                '2000': {
                    value: 2000,
                    label: 2000
                }
            },
            statefull: {
                options: true,
                value: true
            },
            listens: {
                value: 'onValueChange',
                options: 'onSizesChange'
            }
        },

        /**
         * Initializes sizes component.
         *
         * @returns {Sizes} Chainable.
         */
        initialize: function () {
            this._super()
                .updateArray();

            return this;
        },

        /**
         * Initializes observable properties.
         *
         * @returns {Sizes} Chainable.
         */
        initObservable: function () {
            this._super()
                .track([
                    'value',
                    'editing',
                    'customVisible',
                    'customValue'
                ])
                .track({
                    optionsArray: []
                });

            this._value = ko.pureComputed({
                read: ko.getObservable(this, 'value'),

                /**
                 * Validates input field prior to updating 'value' property.
                 */
                write: function (value) {
                    value = this.normalize(value);

                    this.value = value;
                    this._value.notifySubscribers(value);
                },

                owner: this
            });

            return this;
        },

        /**
         * Starts editing of the specified size.
         *
         * @param {Number} value - Value of the size.
         * @returns {Sizes} Chainable.
         */
        edit: function (value) {
            this.editing = value;

            return this;
        },

        /**
         * Discards changes made to the currently editable size.
         *
         * @returns {Sizes} Chainable.
         */
        discardEditing: function () {
            var value = this.editing;

            if (value) {
                this.updateSize(value, value);
            }

            return this;
        },

        /**
         * Invokes 'discardEditing' and 'discardCustom' actions.
         *
         * @returns {Sizes} Chainable.
         */
        discardAll: function () {
            this.discardEditing()
                .discardCustom();

            return this;
        },

        /**
         * Returns value of the first size.
         *
         * @returns {Number}
         */
        getFirst: function () {
            return this.optionsArray[0].value;
        },

        /**
         * Returns size which matches specified value.
         *
         * @param {Number} value - Value of the item.
         * @returns {Object|Undefined}
         */
        getSize: function (value) {
            return this.options[value];
        },

        /**
         * Sets current size to the specified value.
         *
         * @param {Number} value - Value of the size.
         * @returns {Sizes} Chainable.
         */
        setSize: function (value) {
            this.value = value;

            return this;
        },

        /**
         * Adds a new value to sizes list.
         *
         * @param {Number} value - Value to be added.
         * @returns {Sizes} Chainable.
         */
        addSize: function (value) {
            var size;

            if (!this.hasSize(value)) {
                size = this.createSize(value);

                this.set('options.' + value, size);
            }

            return this;
        },

        /**
         * Removes provided value from the sizes list.
         *
         * @param {Number} value - Value to be removed.
         * @returns {Sizes} Chainable.
         */
        removeSize: function (value) {
            if (!this.hasSize(value)) {
                return this;
            }

            this.remove('options.' + value);

            if (this.isSelected(value)) {
                this.setSize(this.getFirst());
            }

            return this;
        },

        /**
         * Updates existing value to the provided one. If new value
         * is not specified, then sizes' '_value' property will be taken.
         *
         * @param {Number} value - Existing value that should be updated.
         * @param {(Number|String)} [newValue=size._value] - New size value.
         * @returns {Sizes} Chainable.
         */
        updateSize: function (value, newValue) {
            var size = this.getSize(value);

            if (!size) {
                return this;
            }

            newValue = newValue || size._value;

            if (isNaN(+newValue)) {
                this.discardEditing();

                return this;
            }

            newValue = this.normalize(newValue);

            this.remove('options.' + value)
                .addSize(newValue);

            if (this.isSelected(value)) {
                this.setSize(newValue);
            }

            return this;
        },

        /**
         * Creates new editable size instance with the provided value.
         *
         * @param {Number} value - Value of the size.
         * @returns {Object}
         */
        createSize: function (value) {
            return {
                value: value,
                label: value,
                _value: value,
                editable: true
            };
        },

        /**
         * Checks if provided value exists in the sizes list.
         *
         * @param {Number} value - Value to be checked.
         * @returns {Boolean}
         */
        hasSize: function (value) {
            return !!this.getSize(value);
        },

        /**
         * Hides and clears custom field.
         *
         * @returns {Sizes} Chainable.
         */
        discardCustom: function () {
            this.hideCustom()
                .clearCustom();

            return this;
        },

        /**
         * Shows custom field.
         *
         * @returns {Sizes} Chainable.
         */
        showCustom: function () {
            this.customVisible = true;

            return this;
        },

        /**
         * Hides custom field.
         *
         * @returns {Sizes} Chainable.
         */
        hideCustom: function () {
            this.customVisible = false;

            return this;
        },

        /**
         * Empties value of the custom field.
         *
         * @returns {Sizes} Chainable.
         */
        clearCustom: function () {
            this.customValue = '';

            return this;
        },

        /**
         * Adds a new size specified in the custom field.
         *
         * @returns {Sizes} Chainable.
         */
        applyCustom: function () {
            var value = this.customValue;

            value = this.normalize(value);

            this.addSize(value)
                .setSize(value)
                .discardCustom();

            return this;
        },

        /**
         * Checks if custom field is visible.
         *
         * @returns {Boolean}
         */
        isCustomVisible: function () {
            return this.customVisible;
        },

        /**
         * Converts provided value to a number and puts
         * it in range between 'minSize' and 'maxSize' properties.
         *
         * @param {(Number|String)} value - Value to be normalized.
         * @returns {Number}
         */
        normalize: function (value) {
            value = +value;

            if (isNaN(value)) {
                return this.getFirst();
            }

            return utils.inRange(Math.round(value), this.minSize, this.maxSize);
        },

        /**
         * Updates the array of options.
         *
         * @returns {Sizes} Chainable.
         */
        updateArray: function () {
            var array = _.values(this.options);

            this.optionsArray = _.sortBy(array, 'value');

            return this;
        },

        /**
         * Checks if provided value is in editing state.
         *
         * @param {Number} value - Value to be checked.
         * @returns {Boolean}
         */
        isEditing: function (value) {
            return this.editing === value;
        },

        /**
         * Checks if provided value is selected.
         *
         * @param {Number} value - Value to be checked.
         * @returns {Boolean}
         */
        isSelected: function (value) {
            return this.value === value;
        },

        /**
         * Listener of the 'value' property changes.
         */
        onValueChange: function () {
            this.discardAll()
                .trigger('close');
        },

        /**
         * Listener of the 'options' object changes.
         */
        onSizesChange: function () {
            this.editing = false;

            this.updateArray();
        }
    });
});

and a I've also added a "requirejs-config.js" file at the following location:
app > design > adminhtml > TCT > joy > requirejs-config.js
...containing the following code:
var config = {
  "map": {
    "*": {
      "Magento_Ui/js/grid/paging/sizes": "js/sizes"
    }
  }
};

I've cleared the caches and reloaded the admin pages but the paging grid still looks like this:

Despite the developer console appearing as follows:

It appears that the site is loading my amended "sizes.js" and not the base file but the adminhtml doesnot seem to have been amended.
I've looked at questions 161644 and 212303 but these have only gotten me this far.

A: As a stop-gap solution I have overwritten the sizes.html file at the following location:

app > design > adminhtml > TCT > Joy > web > templates > template >
  sizes.html

added the following code into a template file called sizes.html

            <button class="selectmenu-item-action" type="button" text="1000" click="setSize.bind($data, 1000)"/>

            <button class="selectmenu-item-action" type="button" text="2000" click="setSize.bind($data, 2000)"/>

So the code appears as follows:

        <input type="text" ko-value="_value" attr="id: index" autoselect/>

    <button class="selectmenu-toggle" type="button" css="_active: $collapsible.opened" toggleCollapsible>

    </button>

                    <input class="admin__control-text" type="text"
                        ko-value="$size()._value" hasFocus="isEditing($size().value)"/>
                    <button class="action-save" type="button" click="updateSize.bind($data, $size().value, false)">

                    </button>
                    <button class="action-delete" type="button" click="removeSize.bind($data, $size().value, false)">

                    </button>

                    <button class="selectmenu-item-action" type="button" text="$size().label" click="setSize.bind($data, $size().value)"/>
                    <button class="action-edit" type="button" if="$size().editable"
                        data-bind="
                            click: function () {
                                discardCustom().edit($size().value);
                            }">

                    </button>

                    <button class="selectmenu-item-action" type="button" text="1000" click="setSize.bind($data, 1000)"/>

                    <button class="selectmenu-item-action" type="button" text="2000" click="setSize.bind($data, 2000)"/>

                    <button class="selectmenu-item-action" type="button"
                       translate="'Custom'"
                       ko-visible="!isCustomVisible()"
                       data-bind="
                            click: function () {
                                $data.showCustom()
                                    .discardEditing();
                            }"/>

                    <input class="admin__control-text" type="text" ko-value="customValue" hasFocus="isCustomVisible()"/>
                    <button class="action-save" type="button" click="applyCustom">

                    </button>

I the referenced it in sizes.js with
'templates/sizes',

The admin now appears as follows and appears to work as intended

This may not be the best solution but it will suffice until I can find a better one


Q: Custom cordova plugin - Get path to file I've created a Cordova plugin for Android, and I've put a file in the src folder:
Plugin.xml
<source-file src="myfile.ext" target-dir="src/com/example"/>

I also can see (in Android Studio) that the file was succesfully added in the src folder:
android
 |-- /src
      |-- com
           |-- example
                |-- myfile.ext
                |-- MyPlugin.java

Now I need to be able to get the path to this file in MyPlugin.java, but I've no clue how to do this. Can anybody help me with this? Thanks!

A: Before you updated your question, it was correct - you should copy the asset file to "assets" not "src":
<source-file src="myfile.ext" target-dir="assets"/>

Then you can reference it via the AssetManager:
AssetManager assetManager = this.cordova.getActivity().getAssets();
InputStream inputStream = assetManager.open("myfile.ext");

In terms of "path" to the file, assets are stored in the APK differently from how your Android project is constructed, so the "path" to your file would be file:///android_asset/myfile.ext, but you most likely wouldn't actually be referencing it like this from MyPlugin.java.


Q: Detect tap touches on CALayer My setup is as follows
- UIView
    - CALayer (container)
        -CAShapeLayer
        -CAShapeLayer
        -..

And i want to detect tap touches on every shapelayer to change its color
I have put a UITapGestureRecognizer on my UIView and have the following code
CGPoint point = [self tapWithPoint:[recognizer locationInView:pieView]];

PieSliceLayer* layerThatWasTapped = (PieSliceLayer *)[_containerLayer hitTest:point];
[(PieSliceLayer *)[layerThatWasTapped modelLayer] setFillColor:UIColor.redColor];

But it seems that it only changes 1 CAShapeLayer always the first that was added.


Q: Do you need License for OS (Windows) inside Docker I am looking at creating a Docker (set) for applications that run on Windows. So, I need the Docker to have Windows OS. What license do I need for it? Or if I run the Docker on a Windows VM, does it make use of the same license from the Host?

A: The container images will use the underlying OS license. Microsoft calls it supplmental license.

You are licensed to use this Supplement in conjunction with the
  underlying host operating system software (“Host Software”) solely to
  assist running the containers feature in the Host Software. The Host
  Software license terms apply to your use of the Supplement. You may
  not use it if you do not have a license for the Host Software. You may
  use this Supplement with each validly licensed copy of the Host
  Software.


Q: Using stream_with_context as async I want to stream a file in telegram using pyrogram, but I can't do it because stream_with_context is not working asynchronously, what can I do?
How can I send a file (bytes) to the user asynchronously via flask? No matter how hard I searched, I could not find the answer to this question, there are always answers for synchronous flasks on the internet.
If I try to use flask synchronously, this time the pyrogram with telegram api starts to cause problems because this api is mainly made for async
from flask import Response

from flask import Flask, send_file
from flask import stream_with_context

app = Flask(__name__)

import asyncio
from pyrogram import Client

api_id = 000
api_hash = ""

tg = Client("aaa", api_id, api_hash)

@app.route('/bigfile')
async def bigfile():
    msg = await tg.get_messages(0674564523, 4564535254)

    async def gnn():
        async for chunk in tg.stream_media(msg):
            chnk = io.BytesIO(chunk)
            yield chnk

    return Response(
        stream_with_context(await gnn()),
        headers={
            'Content-Disposition': f'attachment; filename=asdfasdf.pdf'
        }
    )

import threading

if __name__ == '__main__':
    threading.Thread(target=app.run, daemon=True).start()
    tg.run()


Q: What is the 'area law' in the context of matrix product states? I am trying to get into the topic of matrix product states by reading this:

A practical introduction to tensor networks: Matrix product states and projected entangled pair states. R. Orús. Ann. Phys. 349, 117 (2014), arXiv:1306.2164.

There, often, the word "area-law" is mentioned, but it's not very well explained what is meant by that...
It's somehow that states in a Hilbert space are entangled with the neighbored states. (is that right?) But why? And what is meant by a local Hamiltonian?

A: The area law says that the entanglement of any part of a system with the rest of of the system scales like the boundary (the "surface area") of the region.  E.g., in a one-dimensional chain, the entanglement of a contiguous block with the rest should be bounded by a constant, and in 2D, the entanglement of e.g. a square region with the rest should scale like the linear size of this square.
The area law is a property which is proven to be satisfied by ground states of local gapped Hamiltonians in one dimension (see arXiv:0705.2024 and arXiv:1301.1162), and the corresponding statement is believed to be true in two dimensions.  However, even for systems without a gap the area law is only mildly violated (in that the entanglement does not grow like the volume).
Local Hamiltonian refers to the fact that the Hamiltonian is a sum of terms each of which only acts on a small number of closeby spins, e.g. nearest neighbors on a lattice.


Q: How to update a View without Postback in MVC3 How can I update a dropdownlist in MVC3. I want to refill it with latest data filled by some other view, but I do not want to postback the view and want to achieve it with jquery.
I have a dropdownlist like:
@Html.DropDownListFor(m => m.Department, Model.Departments)
@Html.ValidationMessageFor(m => m.Departments)
<input type="button" value="Refresh" id="btnrefresh" />

I have written jquery code to call controller's method:
 $("#btnrefresh").click(function () {
 var ref = '@Url.Action("RefreshDepartments")';
 var model = '@Model.ToJson()';
 var data = { empModel: model };
 $.getJSON(ref, data, function (result) { alert(result.message); });
        return false;
    });

And Here is the controller method:
public ActionResult RefreshDepartments(EmployeeModel empModel)
    {
        empModel.Departments = GetDepartments();
        empModel.Roles = GetRoles();
        return Json(new { message = "Updated successfully"}, JsonRequestBehavior.AllowGet);
    }

How can I update the dropdownlist with latest values on clicking "Refresh" button without any postback?
Is it a good idea to pass the model to the controller and update the model properties? What other ways are possible ?

A: It doesn't look to me like you need the model to be posted to your controller for what you're doing.  In addition, yes, you absolutely can do this with jquery!  On a side note, you could also do it with an Ajax.BeginForm() helper method, but lets deal with your jquery example.
Rather than complexify your jquery with your @Url.Action, you can simply call the path itself.
$("#btnrefresh").click(function () {
    var ref = 'ControllerName/RefreshDepartments';
    $.each(result, function (index, val) {
        $('#whateverYourRenderedDropdownListHtmlObjectis')
            .append($("<option></option>")
            .attr("value", val.Text)
            .text(val.Text));
    });
});

Now, for your controller...
public JsonResult RefreshDepartments()
{
    return Json(GetDepartments, JsonRequestBehavior.AllowGet);
}

private SelectList GetDepartments
{
    var deparments = GetDepartments;
    SelectList list = new SelectList(departments);
    return list;
}

This is an alternative to returning the model.  It allows you to manipulate the raw JSON instead.  Hope it helps!

A: You almost did it all! Why don't you send the data, I mean list, by RefreshDepartments action? You sent a message to view, so you can send the list similarly and instead of alerting the result you can fill the dropdownlist. something like this:
public ActionResult RefreshDepartments(EmployeeModel empModel)
    {
        return Json(new { departments = GetDepartments()}, JsonRequestBehavior.AllowGet);
    }

$.getJSON(ref, data, function (result) {
    $("#Department").html("");
    for (var i = 0; i < result.departments.length; i++) {
        var item = result.departments[i];
        $("#Department").append(
              $("<option></option>").val(item.Id).html(item.Name);
        );
    });
});


Q: Integral using the Substitution y = $\frac{1}{2}(\sqrt{a}x^2+\frac{\sqrt{b}}{x^2})$ Given that $\int_{-\infty}^{\infty} e^{(-\frac{1}{2}x^2)}dx = \sqrt{2\pi}$,
Find $I(a,b) = \int_{-\infty}^{\infty} e^{-\frac{1}{2}(ax^2+\frac{b}{x^2})}dx$.
The question suggests using the substitution: $$y = \frac{1}{2}(\sqrt{a}x-\frac{\sqrt{b}}{x})$$ if careful attention is paid to the limits. I'm not sure how the limits of integral changes as I can't see why the limits wouldn't remain the same using the substitution.

A: The key here is to note that this integral is improper at zero, so before performing the substitution notice the integrand is even so we may rewrite the integral as
$$I(a,b)=2\int_{0+}^\infty e^{-\frac{1}{2}(ax^2+\frac{b}{x^2})}dx$$
Let $y=\sqrt{a}x-\frac{\sqrt{b}}{x}$. Note the bounds become $-\infty$ to $\infty$, since as $x\rightarrow 0^+$, $y\rightarrow -\infty$. Also notice $y^2=ax^2+\frac{b}{x^2}-2\sqrt{ab}$, and
$$dy=\sqrt{a}+\frac{\sqrt{b}}{x^2}=\frac{\sqrt{y^2+4\sqrt{ab}}-y}{2\sqrt{b}}\sqrt{y^2+4\sqrt{ab}}\ dx$$ so the integral is
$$I(a,b)=2\int_{-\infty}^\infty e^{-\frac{1}{2}(y^2+2\sqrt{ab})}\frac{2\sqrt{b}}{\sqrt{y^2+4\sqrt{ab}}}\frac{1}{\sqrt{y^2+4\sqrt{ab}}-y}dy$$
Combining the positive and negative sides of the axis gives
$$I(a,b)=2\int_{0}^\infty e^{-\frac{1}{2}(y^2+2\sqrt{ab})}\frac{2\sqrt{b}}{\sqrt{y^2+4\sqrt{ab}}}\left(\frac{1}{\sqrt{y^2+4\sqrt{ab}}-y}+\frac{1}{\sqrt{y^2+4\sqrt{ab}}+y}\right)dy$$
$$=\frac{2}{\sqrt{a}}\int_0^\infty e^{-\frac{1}{2}(y^2+2\sqrt{ab})}dy$$
And from there you can use your identity.

A: The integrand is even, so restrict the integration range to $x\ge 0$ and introduce a factor of $2$. The only discontinuity is at $x=0$, and to the right of that $dy/dx>0$. If you're still stuck, see here.


Q: Messed up username and permission on raspberry pi, but still logged in as root through ssh I've gotten myself into a pickle, but perhaps there is still hope.
I've commented out the user "pi" while acting as root after typing the following:
  nano etc/passwd
Saved and exited. Next I literally exit terminal. Now upon opening a new terminal window I get the following message:
  I have no name!@raspberrypi ~ $
Any sudo command I type is returned with the following message:
  sudo: unknown uid #### who are you?
Thing is I still have ssh up on my macbook pro where I'm still logged in as root. Since I'm fairly new to the whole command line bit I figured I'd reach out for a bit a help.
Any ideas how to fix the pi without reinstalling??

A: This is not a huge problem, since the file can be edited like any text document.
If you are at ssh and have root privileges, just nano /etc/passwd (i feel evil typing that haha), otherwise if there is another user with root privileges (other than pi) login in as them and edit the passwd file.
If there are no other users, put your SD card in your mac and edit the file in any text editor.

A: I solved it by uncommenting the line that begins with #pi 1000 1000 (something like that) in the file passwd (access it by typing nano/etc/paswwd) by erasing the #, when I did that, everything returns to normality and I was enable to use sudo commands again.


Q: Radian Console adds random Characters as executed I am facing a problem on a Windows PC using a Radian console for R.
When I execute a line, random characters are added to the end of the line in the console.
As you can see in the image attached, there is a ") added at the end of the line when I try to execute it.
Random Characters added Image

Can somebody help?
Thanks in advance!


Q: How to sort structure C# I've got this structure:
struct kluczyk
    {
        int id;
        char litera;
    }

Making a list:
List<kluczyk> posortuj = new List<kluczyk>();
        for (int i = 0; i < 10; i++)
        {
            kluczyk temp = new kluczyk(some char here, i);
            posortuj.Add(temp);
        }

How to sort this list by litera?

A: There are very simple LINQ methods to accomplish sorting by the property of an object. One is OrderBy:
var sortedEnumerable = unsortedEnumerable.OrderBy(a => a.property);

Likewise, you can use OrderByDescending to ascertain the reverse order of the above:
var sortedEnumerable = unsortedEnumerable.OrderByDescending(a => a.property);

Note that these return a new enumerable and do not sort in place.
If you needed more complex sorting logic, or if you wanted to sort the kluczyk object itself and not any given property, you'd want to create your own object that implements IComparer and establishes less-than/equal/greater relationships between your objects.
Brad Christie included a link to List(T).Sort (IComparer<T>), which I've reproduced here unless he wants to make his own answer.


Q: How to get local language in IE-11 I am trying to get the local language in Angular in IE-11.
I set the local language in the IE-11 browser as french and then trying to get the local language from IE-11 as follows.
this.lang = window.navigator.languages ? window.navigator.languages[0] : null;
    this.lang = this.lang || window.navigator.language || window.navigator['browserLanguage'] || window.navigator['userLanguage'];

it is working fine for all browser but for IE-11 I am not getting the correct local language. it is returning me en-US every time.
can anyone help me with this how to get the correct local for IE-11 in Angular8?

A: Do you set your browser local language in Control Panel like below in win 7?

In this situation, we can get local language in IE 11 using window.navigator.browserLanguage which is "fr-FR". In other modern browsers, we can only use window.navigator.language:

In your app, you could use the code below:
var sAgent = window.navigator.userAgent;
var Idx = sAgent.indexOf("Trident");
//check if IE 11
if (Idx > 0) {
   this.lang = window.navigator.browserLanguage;
}
else {
    this.lang = window.navigator.language;
}


Q: ¿ Cómo evitar que facebook auto inicié método de compartir sin seleccionarlo previamente? Estoy utilizando el SDK de Facebook. tengo un método para compartir en cada red social disponible en el dispositivo, al momento de enviar abrir el dialogo de compartir predeterminado por el sistema, se auto ejecuta compartir con facebook sin seleccionarlo antes, cosa que no pasa con twitter. ya que al momento de seleccionar twitter va a twitter, facebook se autoselecciona y no me deja escoger otra red social.
Las redes sociales estarán disponibles dependiendo de las aplicaciones que tenga el usuario instaladas.
fragment.java
public void shareIt(View view){
        Uri bmpUri = getLocalBitmapUri(imagencompartir);
        List<Intent> targetedShareIntents = new ArrayList<Intent>();
        Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
        sharingIntent.setType("image/*");
        PackageManager pm = getActivity().getPackageManager();
        List<ResolveInfo> activityList = pm.queryIntentActivities(sharingIntent,0);
        for(final ResolveInfo app : activityList) {
            String packageName = app.activityInfo.packageName;
            Intent targetedShareIntent = new Intent(android.content.Intent.ACTION_SEND);
            targetedShareIntent.setType("text/plain");
           targetedShareIntent.setClassName(app.activityInfo.packageName, app.activityInfo.name); // add
            if(packageName.equals("com.facebook.katana") ){
            //    ((MainActivity) getActivity()).setLinkShare();
               // targetedShareIntent.putExtra(this, MyIntentService.class);
               // targetedShareIntent.putExtra(Intent.EXTRA_TITLE, titulo.getText().toString());
                setLinkShare();
            } else
            if(packageName.equals("com.twitter.android")){
                targetedShareIntent.setType("application/twitter");
                targetedShareIntent.putExtra(Intent.EXTRA_TEXT, titulo.getText().toString().trim() );
                targetedShareIntent.putExtra(Intent.EXTRA_STREAM, bmpUri);
            } else {
                targetedShareIntent.putExtra(Intent.EXTRA_TITLE, titulo.getText().toString());
                targetedShareIntent.putExtra(Intent.EXTRA_SUBJECT, titulo.getText().toString());
                targetedShareIntent.putExtra(Intent.EXTRA_TEXT, comentariocompartir.getText().toString().trim());
                targetedShareIntent.putExtra(Intent.EXTRA_STREAM, bmpUri);
            }
            targetedShareIntents.add(targetedShareIntent);
        }
        Intent chooserIntent = Intent.createChooser(targetedShareIntents.remove(0), getActivity().getString(R.string.compartir_con));

        chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, targetedShareIntents.toArray(new Parcelable[]{}));
        startActivityForResult(chooserIntent, RESULT_SHARE);

    }

Metodo compartir en Facebook
public void setLinkShare() {
    ShareLinkContent content = new ShareLinkContent.Builder()

            .setContentTitle(titulo.getText().toString().trim())
            .setImageUrl(Uri.parse("https://scontent-sin6-1.xx.fbcdn.net/t31.0-8/13403381_247495578953089_8113745370016563192_o.png"))
            .setContentDescription(comentariocompartir.getText().toString().trim())
            .setContentUrl(Uri.parse("https://www.facebook.com/"))
            .setShareHashtag(new ShareHashtag.Builder()
                    .setHashtag("#app"+" "+ "#facebook")

                    .build())
            .setQuote(titulo.getText().toString().trim())
            .build();

    shareDialog.show(content, ShareDialog.Mode.NATIVE);
}

Dependencia
compile 'com.facebook.android:facebook-android-sdk:4.+'

imagen

Como se puede ver en la imagen se auto selecciona facebook  y las otras opciones disponibles quedan abajo del dialogo de compartir


Q: Unable to make Google Analytics filter work I wish to create a custom filter on Google Analytics (GA), that would allow me to block all views except the genuine ones onto my webpage.
I want to do this because the google-analytics ID associated with my property (UA-XXXXXXXX-X) is public. Hence in theory, my analytics data is open to attack.
I was trying to follow the instructions here. As suggested I created a custom filter to exclude any hits from Hostnames other than my webpage (or any sub-webpages) - https://ishank-juneja.github.io/. In particular the steps I followed were -
New filter --> custom -->  include --> Choose filter field as Hostname
Then I entered the filter pattern as https://ishank-juneja\.github\.io/. Which I believe is the correct regex corresponding to my site URL/Hostname.
I thought this would be enough to make the filter work, however to be sure, I changed the filter type to exclude instead of include, expecting that if the configuration is correct this filter would start rejecting hits from the url https://ishank-juneja.github.io/ and any of its sub-pages.
However when I clicked the filter verification button available at the bottom of the create-filter page, I received the message-

"This filter would not have changed your data. Either the filter configuration is incorrect, or the set of sampled data is too small."

Since I am certain that all my earlier hits were from the mentioned url, it seems that the filter is not configured correctly even in the include mode.
Any help in correcting the working of the filter, so that only hits from the desired Hostname are recorded, would be appreciated.

A: Try to use this regex for hostname (without protocol and trailing slash):
ishank-juneja\.github\.io


Q: what are valid zone name or valid service name for srv records? I've been following a few guides/questions on how to use A records and SRV records to map a domain to a specific ip and port like 1.1.1.1:1889:
https://stackoverflow.com/questions/11433570/how-to-use-srv-or-any-other-record-do-redirect-a-domain
https://stackoverflow.com/questions/19015138/how-to-redirect-dns-to-different-ports
In questions like the ones above, they recommend using SRV records.  The only part I'm not clear on is how to determine the correct service name to use in my SRV record?  For example, let's say I have these records
mysql.example.com.  86400 IN A 1.1.1.1
mongo.example.com.  86400 IN A 1.1.1.1
www.example.com.  86400 IN A 1.1.1.1
mosquitto.example.com.  86400 IN A 1.1.1.1
_mysql._tcp.example.com. 86400 IN SRV 10 20 3306 mysql.example.com.
_mongo._tcp.example.com. 86400 IN SRV 10 20 27017 mongo.example.com.
_http._tcp.example.com. 86400 IN SRV 10 20 3306 www.example.com.
_mqtt._tcp.example.com. 86400 IN SRV 10 20 3306 mosquitto.example.com.

Are the _mysql, _mongo, _http and _mqtt the correct service names to use in my SRV records?  I completely guessed these service names because I wasn't able to find a website that lists all the acceptable service names that can be used.

A: First web browsers do not follow SRV records at all, so even if you can design them, they are useless.
Now given the generic process to know what goes into any record, taking SRV as an example.
IANA is the guardian of things so go to https://www.iana.org/assignments/dns-parameters/dns-parameters.xhtml#dns-parameters-4 where you can see for SRV that it is defined in RFC 2782
There it is defined as such:

Here is the format of the SRV RR, whose DNS type code is 33:
   _Service._Proto.Name TTL Class SRV Priority Weight Port Target

with then respectively:

Service
   The symbolic name of the desired service, as defined in Assigned
   Numbers [STD 2] or locally.  An underscore (_) is prepended to
   the service identifier to avoid collisions with DNS labels that
   occur in nature.

and

Proto
   The symbolic name of the desired protocol, with an underscore
   (_) prepended to prevent collisions with DNS labels that occur
   in nature.  _TCP and _UDP are at present the most useful values
   for this field, though any name defined by Assigned Numbers or
   locally may be used (as for Service).  The Proto is case
   insensitive.

[STD 2] reference is RFC 1700 but RFC 3232 obsoleted it to make a database online of possible values... which is again administered by IANA.
It is now there: https://www.iana.org/assignments/service-names-port-numbers/service-names-port-numbers.xhtml and do note that it is basically what you find in file /etc/services in any Unix box.
So taking back your examples (your port numbers are wrong in multiple SRV records depicted though):

*

*mysql is indeed defined for port 3306 so it is valid as service name and hence in an SRV record

*for port 27017, the service name is mongodb, not mongo (but do Mongo clients honor SRV records?)

*http is indeed defined for port 80 so it is a valid service name (and https for port 443)

*mqtt is defined as valid port name, for port 1883. But same question as above, do clients use SRV records at all?

Do note also that there are in the wild various SRV records not following the above. If they can be published they "work", that is nothing will prevent resolution of them at the DNS level even if they don't use a registered service name as above, as long as some application of course do read them.
For example, you can find lots of example with _sip._tls or _sipfederationtls._tcp online, which are both wrong: tls is not a valid protocol, and sipfederantiontls is not a valid service name (and is in fact too long, as https://www.rfc-editor.org/rfc/rfc6335.html#section-5.1 specifies it should be at most 15 characters long). So some tool/UI may prevent creating those records in a zonefile, and some nameservers may refuse to load them, but in most cases they will work (if applications do consume them).


Q: Doubts with Python I have a question. Here you have part of my code for a better understanding:
def client ():
    A=[]
    B = open("clientes.txt", "r")
    user = input("To begin, enter your ID number: ")
    for line in B:
        C = line.split("$")
        A.append(C)
    for i in range (len(A)):
        if A[i][0]==user:

and then I have another function, here is it:
def clientpersonalinfo ():
    A=[]
    B=[]
    C = open("accounts.txt", "r")
    D = open("clients.txt", "r")
    for line in C:
        E=line.split("$")
        A.append(E)
    for line in D:
        F=line.split("$")
        B.append(F)
    for i in range (len(A)):
        ***if user==A[i][1]:***

The question is if there is any method in which i can re-use the first input. As you see if I run this, there will be an error saying that the name "user" is not defined.
So I want to know if I can recall the user input that I first used in clients () and re-use it in my clientpersonalinfo () function.
Thanks for your help!!
Thanks to all those who helped me! Thanks a lot! :)

A: Please review the python docs on how to write functions with arguments: http://docs.python.org/tutorial/controlflow.html#defining-functions
def myFunction1():
    user = "foo"
    return user

def myFunction2(user):
    print user

user = myFunction1()
myFunction2(user)

Ideally you would organize a nice class structure, instead of using globals everywhere which I think is messy. Its a good sign that you should indeed be using a class when all of your functions end up needing to share some kind of state and you think you might need to start defining a ton of globals:
class Client(object):

    def __init__(self):
        self.userId = None

    def getClient(self):
        self.userId = raw_input("To begin, enter your ID number: ")

    def parseClientInfo(self):
        # do something with self.userId
        print self.userId

    def clientPersonalInfo(self):
        # do something with self.userId
        print self.userId

Please note that this class is a really simple example.

A: You can reuse whatever you want, you just have to store it somewhere that is visible to both funcitons. You could make a class and put the information in a field or you could return it from the function and pass it on when you call the other function. Global variables are bad style, but that's doable too.

A: To preserve the content of "user" (which would be better named "user_input" or some such), one way is to return the content of "user" along with whatever else you are returning in client(), perhaps in a tuple, and then passing it to clientpersonalinfo() as an argument, i.e. clientpersonalinfo(user).  Another way is to put the code for getting "user" higher up in the hierarchy so that user exists in the function that calls both client() and clientpersonalinfo(), and then passing it as an argument to both functions.

A: If I understand your question correctly, then I think that the best thing for you to do is to take the input call out of the first function and change the function definitions of both functions to take the user as an argument. The code would look something like:
def client(user):
    clients = []
    with open("clientes.txt",'r') as f:
        for client in f:
            clients.append(client.split('$'))
    for client in clients:
        if client[0] == user:
            ...

user = raw_input("To begin, enter your ID number: ")
client(user)

and the other would be similar. There are a couple of changes from how you handle things. It is recommended that use use the "with open" form since it handles problems better than just opening the file, for instance. Also, naming variables so that the name is relevant to what you are doing makes your code easier to read, so avoid using names like A. Finally, you should use raw_input rather than input in general. The input function evaluates what is input by the user, which means that a user could call some code which is generally not what you want. The raw_input function returns a string which contains what the user put in.


Q: automatic nomenclature breaks with subfigure I am using the method recommended in
List of symbols/abbreviations and macros
to automatically generate an entry to the nomenclature (nomencl package) when I first use a command, i.e.
\defsym{\Rn}{\mathbb{R}^n}
[...]
the first occurance $\Rn$ generates an orrurance in the nomenclature,
[...]
the second occurance $\Rn$ does not.

This works nicely, and as in the second version described in List of symbols/abbreviations and macros it also works for \section{\Rn} and in figure captions, however it fails when used in subfigures \subfigure[\Rn]{} if that is the first occurrence of the macro.
A minimum example to demonstrate the error:
\errorcontextlines2
\documentclass[paper=a4,11pt]{scrbook}
\usepackage[refpage,noprefix]{nomencl}
\usepackage{subfigure}

\makeatletter
\newcommand*{\defsym}[3][]{\def#2{%
  \ifx\protect\@unexpandable@protect
    #3%
  \else
    \nomenclature{$#3$}{#1}\gdef#2{#3}#3%
  \fi}
}
\makeatother
\makenomenclature
\begin{document}
\defsym{\MeshMacro}{{\cal M}^{\rm mac}}
% $\MeshMacro$ works nicely
\begin{figure}
\subfigure[$\MeshMacro$ goes to hell]{ }
\end{figure}
\printnomenclature
\end{document}

and the error message is
! TeX capacity exceeded, sorry [input stack size=15000].
\nomenclature ->\protect \@nomenclature

\MeshMacro ...cal M}^{\rm mac}\else \nomenclature
                                                  {${\cal M}^{\rm mac}$}{}\g...

\MeshMacro ...al M}^{\rm mac}$}{}\gdef \MeshMacro
                                                  {{\cal M}^{\rm mac}}{\cal ...
...
l.20 \subfigure[$\MeshMacro$ goes to hell]{ }

How can I avoid this problem?

A: The problem has two faces. First of all the command \MeshMacro is fragile, so it should be protected. Hence
\subfigure[$\protect\MeshMacro$ goes to hell]{ }

will do; but, since the object is typeset in a box inside a box, the usage of \MeshMacro will not be recorded in the nomenclature file.
However, the problem with the first appearance of \MeshMacro in the subfloat caption can't be solved, because it's a standard TeX feature.
On the other hand, with floating objects one is never sure where they'll fall and the first appearance might end up after the object is used in the text. My suggestion is to avoid such macros in captions.
Note that \cal and \rm are obsolete commands and you should write
\defsym{\MeshMacro}{\mathcal{M}^\mathrm{mac}}

using the "officially supported" commands. Also subfigure is obsolete, use subfig or subcaption (they have different syntax, though).


Q: Why is full-laziness a default optimization? Full laziness has been
repeatedly
demonstrated
to
cause
space
leaks.
Why is full laziness on from -O onwards?  I find myself unconvinced by the reasoning in SPJ's The Implementation of Functional Programming Languages.  The claim is that in
f = \y -> y + sqrt 4

sqrt 4 is unnecessarily repeated each time f is entered so we should float it outside the lambda.  I agree in the small, but since we've seen what problems this transformation causes in the large I don't believe it is worth it.  It seems to me that the benefits of this transformation are obtainable unilaterally** with only local code changes and programmers who want it should implement it by hand.
Can you convince me otherwise?  Is full-laziness actually really useful?  I will be especially convinced if you can provide examples which to implement by hand require multilateral cooperation or non-local transformations.
** unlike optimizations like inlining and stream fusion which to implement by hand would require multilateral cooperation between modules and non-local code changes

A: There's at least one common case where full laziness is "safe" and an optimization.
g :: Int -> Int
g z = f (z+1)
  where f 0 = 0
        f y = 1 + f (y-1)

This really means g = \z -> let {f = ...} in f (z+1) and, compiled that way, will allocate a closure for f before calling it. Obviously that's silly, and the compiler should transform the program into
g_f 0 = 0
g_f y = 1 + g_f (y-1)
g z = g_f (z+1)

where no allocation is needed to call g_f. Happily the full laziness transformation does exactly that.
Obviously programmers could refrain from making these local definitions that do not depend on the arguments of the top-level function, but such definitions are generally considered good style...
Another example:
h :: [Int] -> [Int]
h xs = map (+1) xs

In this case you can just eta reduce, but normally you can't eta reduce. And naming the function (+1) is quite ugly.


Q: pip install pods command failed in jupyter with FileNotFoundError: [Errno 2] No such file or directory: 'C:\\tmp\\sods.log' I tried installing the pods package in jupyter notebook using the below commands:
   pip install pods

   import pods

Installation failed with the following error
       ---------------------------------------------------------------------------
    FileNotFoundError                         Traceback (most recent call last)
    <ipython-input-3-c6cba4dfa9c3> in <module>
      1 get_ipython().run_line_magic('matplotlib', 'inline')
----> 2 import pods
      3 import matplotlib.pyplot as plt

~\anaconda3\lib\site-packages\pods\__init__.py in <module>
----> 1 from . import datasets
      2 from . import mocap

~\anaconda3\lib\site-packages\pods\datasets.py in <module>
     17 import logging
     18
---> 19 logging.basicConfig(
     20     level=logging.DEBUG,
     21     format="%(asctime)s %(levelname)s %(message)s",

~\anaconda3\lib\logging\__init__.py in basicConfig(**kwargs)
   1974                 mode = kwargs.pop("filemode", 'a')
   1975                 if filename:
-> 1976                     h = FileHandler(filename, mode)
   1977                 else:
   1978                     stream = kwargs.pop("stream", None)

~\anaconda3\lib\logging\__init__.py in __init__(self, filename, mode, encoding, delay)
   1141             self.stream = None
   1142         else:
-> 1143             StreamHandler.__init__(self, self._open())
   1144
   1145     def close(self):

 ~\anaconda3\lib\logging\__init__.py in _open(self)
   1170         Return the resulting stream.
   1171         """
-> 1172         return open(self.baseFilename, self.mode, encoding=self.encoding)
   1173
   1174     def emit(self, record):

 FileNotFoundError: [Errno 2] No such file or directory: 'C:\\tmp\\sods.log'

I tried to install the pods package with ! pip install pods --user command but still, the issue is the same. Could anyone give your insights for solving the issue?

A: The issue is that the path for the log file is hard coded in the source code, as can be seen on github. The path C:\\tmp does however not exist per default in windows.
Simplest solution is just to create a tmp folder on your C drive


Q: Android/XML: RelativeLayout design basically, I don't understand how to use RelativeLayout. I don't know how to design it. I always use LinearLayout with Table inside of it. Now I use RelativeLayout for my design. I want to know, how to add text "Sorry, no list available" Below is my current code of XML
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/haha"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MyHistoryList">

<TextView
    android:id="@+id/title"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:clickable="false"
    android:focusable="false"
    android:gravity="center"
    android:longClickable="false"
    android:maxLines="1"
    android:textColor="#FFFFFF"
    android:textSize="18sp"
    android:textStyle="bold" />

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

    <TableRow
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginLeft="15dp"
        android:layout_marginRight="15dp">

        <TextView
            android:id="@+id/tvSuggestion"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight=".80"
            android:gravity="start"
            android:text="Suggestion"
            android:textAllCaps="true"

android:textAppearance="@style/Base.TextAppearance.AppCompat.Medium"
            android:textColor="@color/colorAccent"
            android:textStyle="bold"
            app:fontFamily="@font/anaheim" />

        <TextView
            android:id="@+id/tvStatus"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight=".20"
            android:gravity="start"
            android:text="Status"
            android:textAllCaps="true"

android:textAppearance="@style/Base.TextAppearance.AppCompat.Medium"
            android:textColor="@color/colorAccent"
            android:textStyle="bold"
            app:fontFamily="@font/anaheim" />
    </TableRow>
</LinearLayout>

<RelativeLayout
    android:id="@+id/huhu"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.v7.widget.RecyclerView
        android:id="@+id/recylcerView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginLeft="10dp"
        android:layout_marginTop="10dp"
        android:layout_marginRight="10dp"
        android:layout_marginBottom="10dp"
        android:visibility="gone" />

    <ImageView
        android:id="@+id/imgEmpty"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:src="@drawable/empty"/>

 </RelativeLayout>
</LinearLayout>

This is how it looks like

(source: fbcdn.net)
But, I want to add text "Sorry, no list available" below of the image (marginTop = 20dp). Can anyone help?

A: <TextView
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:layout_centerHorizontal="true"
     android:layout_marginTop="20dp"
     android:layout_below="@id/imgEmpty"
     android:text="Sorry, no list available"/>

Insert it below your ImageView of RelativeLayout!

A: Replace your Relative layout with this.
    <RelativeLayout
android:id="@+id/huhu"
android:layout_width="match_parent"
android:layout_height="match_parent">

<android.support.v7.widget.RecyclerView
    android:id="@+id/recylcerView"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_marginLeft="10dp"
    android:layout_marginTop="10dp"
    android:layout_marginRight="10dp"
    android:layout_marginBottom="10dp"
    android:visibility="gone" />

<ImageView
    android:id="@+id/imgEmpty"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:gravity="center"
    android:src="@drawable/empty"/>

<TextView
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:layout_centerHorizontal="true"
     android:layout_marginTop="20dp"
     android:layout_below="@id/imgEmpty"
     android:text="Sorry, no list available"/>

A: Add this below imgEmpty. Use android:layout_below to place the text below image,android:layout_centerInParent="true" to move text to center.
 <TextView
            android:layout_marginTop="20dp"
            android:layout_centerInParent="true"
            android:text = "Sorry, no list available"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_below="@+id/imgEmpty"/>

Here the output

A: in relative layout you can use below/above to put view below/above its sibling

 <TextView
          android:id="@+id/textView"
          android:layout_width="match_parent"
          android:layout_height="wrap_content"
          android:layout_below="@+id/imgEmpty"
          android:layout_marginTop="20dp"
          android:gravity="center_horizontal"
          android:text="TextView"/>


Q: What is the difference between SBC & Development board? I was searching for an dev board with RS 232 interface and with capability to implement ethernet interface as well(either on same board or using accessory board) then I came across
Single Board Computer SBC 44B
http://www.modtronix.com/product_info.php?cPath=106_115&products_id=109
it has been designed for PIC controllers( 44pin )
Whats the difference between Single Board Computer and a Development kit? do the SBC come with ICs included inside them or the user has to buy the ICs separately..?
would this board with an accessory ethernet board fulfill my requirement..?

A: Most of the difference is Marketing.
Development boards are educational products designed to highlight the strengths of the core IC or Microcontroller they are designed around. They are rarely cheap (though the last three years has brought a lot of loss leader dev kits), and often have a lot of single purpose parts, just to show how flexible the core ICs are. They are rarely intended to be bought in bulk to be included in OEM designs. Basically "hey look at our amazing Product X, see how much stuff it can do, you should buy a bunch of it".
SBCs are full featured boards designed to be used individually or as part of a bigger product (as embedded computers). It is a product by itself.
There is much overlap between the features offered in the two. If you are going with a one off project, the only thing you need to worry about is proper documentation and ease of use, aside from if it has what you need. A dev kit or a sbc would both fill your needs.
Though I do have to say, the ""sbc"" you linked to is a VERY VERY poor and uncharacteristic example of a sbc. Almost NOTHING is included. It's really a breakout accessory board at best. And at that price... A Raspberry Pi is a 25 dollar full featured computer. A beagle Bone Black is 45 dollars and beats even that, and they both could beat top of the line 2003 computers, computers that would cost 1000+ dollars brand new.


Q: Use of function inside a for loop I am trying to call functions inside a for loop, but I am not successful.
Is it possible to call functions in Python 3.x like you call subroutines in Excel?
Here is the code I tried but I do not get any output.
def my_fun1(i):
    x=+i
    return x
def my_func2(x1)
    print(x1)

test_rng=range(124,124+100)

for i in test_rng:

    my_fun1(i)
    print(x)
    my_fun2(x)

A: Yes, it is possible but your code would not work because x inside the loop will be unknown:
for i in test_rng:
    my_fun1(i)
    print(x)
    my_fun2(x)

Possibly, you want to do something like:
for i in test_rng:
    x = my_fun1(i)
    print(x)
    my_fun2(x)

You may also want to double-check the code in my_fun1():
def my_fun1(i):
    x=+i
    return x

as the use of x=+i may suggest you are trying to do something different from x = i, which is essentially what your code is doing: x=+i -> x = (+i) -> x = i

A: Your code contains a wrong logic and I am also assuming that the variable x is globally defined. See below.
def my_fun1(i):
    x=+i#I am assuming you want this x+=i
    return x
def my_func2(x1)
    print(x1)

test_rng=range(124,124+100)

for i in test_rng:

    my_fun1(i)
    print(x)
    my_fun2(x)


Q: Python Vosk speech recognition добавление словаря Каким образом можно добавить словарь распознавающих слов в Vosk python. Мне нужно распознавать определенный, конечный набор слов/команд, а не всю речь. Подскажите как это реализовать? Я знаю что есть документация, но я не могу ничего понять от туда. Буду благодарен если опишите весь процесс пошагово.


Q: How to find columns of the partition of a master table in postgresql 9.4? In postgresql I have created a master table
CREATE TABLE IF NOT EXISTS table_master(
column_1 text NOT NULL,
column_2 text NOT NULL,
column_3 text NOT NULL
);

and a partition table based on columns: column_1, column_2
CREATE TABLE table_col1_col2 (
CONSTRAINT table_col1_col2_pk PRIMARY KEY (column_1, column_2),
CHECK ( column_1 = 'value_1' AND column_2 = 'value_2')
) INHERITS (table_master);

Is there any select query in order to get the columns of the partition (column_1, column_2)?
UPDATE
In case I know a child table, I may use the below query:
WITH table_id AS (
SELECT oid
FROM pg_class
WHERE relname = 'child_table_name'
),
con AS (
SELECT c.conname,
c.contype,
c.conkey,
c.consrc
FROM pg_constraint c INNER JOIN table_id ON c.conrelid = table_id.oid
WHERE c.contype = 'c'
)
SELECT a.attnum,
a.attname
FROM pg_attribute a INNER JOIN table_id ON a.attrelid = table_id.oid
INNER JOIN con s ON a.attnum = ANY(conkey)

FINAL QUERY
WITH table_id AS (
SELECT pg_class.oid
FROM pg_class INNER JOIN pg_inherits ON pg_class.relname::text = pg_inherits.inhrelid::regclass::text
WHERE pg_inherits.inhparent = 'master_table'::regclass
),
con AS (
SELECT c.conname,
c.contype,
c.conkey,
c.consrc
FROM pg_constraint c INNER JOIN table_id ON c.conrelid = table_id.oid
WHERE c.contype = 'c'
)
SELECT a.attnum,
a.attname
FROM pg_attribute a INNER JOIN table_id ON a.attrelid = table_id.oid
INNER JOIN con s ON a.attnum = ANY(conkey)

A: You can get columns of primary key.

This returns the names and data types of all columns of the primary
  key for the tablename table:
SELECT a.attname, format_type(a.atttypid, a.atttypmod) AS data_type
FROM   pg_index i
JOIN   pg_attribute a ON a.attrelid = i.indrelid
                     AND a.attnum = ANY(i.indkey)
WHERE  i.indrelid = 'tablename'::regclass
AND    i.indisprimary;

(source)
Here used the fact that primary key's uniqueness is handled by Postgres via index, so you can use pg_index table.


Q: Replacing the value of XML attribute I'm trying to replace the "Visible" attribute value of a Field ID=29 that is duplicated across the xml document.
An example of the xml is found below:
<Types>
    <Type ID="4">
        <Fields>
            <Field ID="29" Visible="false"/>
        </Fields>
    </Type>
    <Type ID="5">
        <Fields>
            <Field ID="29" Visible="true"/>
        </Fields>
    </Type>
    <Type ID="6">
        <Fields>
            <Field ID="29" Visible="false"/>
        </Fields>
    </Type>
</Types>

I have tried the following but with no success:
update SF
set [Static_Form_Properties].modify('replace value of (/Field[@ID=29]/@Visible)[1] with ("true")')
from wf_workflow_step_form SF

Any help would be greately appreciated.
thanks

A: It seems you cannot do an update of multiple XML node values in a single UPDATE statement, as mentioned here: How to modify multiple nodes using SQL XQuery in MS SQL 2005
In your query above I think only the first instance found will be updated.


Q: How to Filter array of objects based on a field inside one object? I have an array of this form:
[
  {
    username: '',
    id: '',
    moreInfo: {
      infoDate: ''
    }
  }
]

And I need to filter based on the infoDate, whether it's in between two specific dates.
I have a function that accepts the object, and the field to search range by and returns :
return resultDate >= fromDate && resultDate <= thruDate;

But how do I filter such array .
I tried
userData.filter(userData => functionthatFiltersDate(userData.moreInfo, {from,thru}, 'infoDate')

The functionthatFiltersDate is a function that accepts an object as input and dates to check range :
functionthatFiltersDate = (
  result,
  { fromDate, thruDate },
  fieldName
) => {
  let resultDate = result[fieldName];
  if (!isDate(resultDate)) {
    resultDate = moment(result[fieldName]).toDate();
  }
  if  (!isDate(fromDate)) {
    fromDate = moment(fromDate).toDate();
  }
  if (!isDate(thruDate)) {
    thruDate = moment(thruDate).toDate();
  }
  return resultDate >= fromDate && resultDate <= thruDate;
};

How do I filter though for an array of objects, based on another object property that's inside?
Any help  is appreciated!

A: call your function this way:
function fooBar(item ){
    // ....
    // return truthy condition
};

var result = arr.filter(fooBar);

-
Passing argument to the filter function:
const fruits = ['apple', 'banana', 'grapes', 'mango', 'orange'];

/**
 * Array filters items based on search criteria (query)
 */
const filterItems = (query) => {
  return fruits.filter((el) =>
    el.toLowerCase().indexOf(query.toLowerCase()) > -1
  );
}

console.log(filterItems('ap')); // ['apple', 'grapes']
console.log(filterItems('an')); // ['banana', 'mango', 'orange']

Source: Mozilla Docs
-
Filtering array based on nested values:
var arr = [
 {foo: 'item1', nested: {nestedFoo: 'returnThis'} },
 {foo: 'item2', nested: {nestedFoo: 'notThis'} },
];

var result = arr.filter(item => item.nested.nestedFoo == 'returnThis');
// result variable now contains an array with one object
console.log(result) // array
console.log(result[0]) // object
console.log(result[0].foo) // 'item1'

Refer to this question for explanation on how to access nested values
-
Making it more clear:
var arr = [
  {
    username: '',
    id: '',
    moreInfo: {
      infoDate: ''
    }
  },
  {
    username: '',
    id: '',
    moreInfo: {
      infoDate: ''
    }
  },
 ...
];

const filterItems = (fromDate, thruDate, fieldName) => {
  return arr.filter((item) =>
    item.moreInfo.infoDate >= fromDate && item.moreInfo.infoDate < thruDate
  );
}