text:
Q: How to tile matplotlib figures evenly on screen? Does matplotlib offer a feature to spread multiple figures evenly on the screen? Or does anyone know of a toolbox that is able to achieve this? I'm getting tired of doing this by hand.
import matplotlib.pyplot as plt
for i in range(5):
    plt.figure()
plt.show()

This creates five figures that are staying on top of each other. To check what is on figure 1, I have to move the other 4 figures to the side.
On MacOS, I could use the Ctrl+↓ shortcut just to get a glimpse on all the figures. Alternatively, I could write the plots to files and inspect the images in a gallery. But I wondered if there is a custom window manager for matplotlib out there that possibly offers some more flexibility.
In Matlab, I got used to tools such as spreadfigure or autoArrangeFigures.

A: You can control the position of the plot window using the figure manager like so:
import matplotlib.pyplot as plt

start_x, start_y, dx, dy = (0, 0, 640, 550)
for i in range(5):
    if i%3 == 0:
        x = start_x
        y = start_y  + (dy * (i//3) )
    plt.figure()
    mngr = plt.get_current_fig_manager()
    mngr.window.setGeometry(x, y, dx, dy)
    x += dx
plt.show()

This will result in five graphs shown beside each other like so:

Hopefully, this is what you're looking for!

A: It appears that matplotlib does not offer such a feature out-of-the-box. In addition, there is no "backend-agnostic" way to control the figure geometry, as discussed here.
I therefore wrote tile_figures() to implement this mini-feature extending Anwarvic's suggestion by some tiling logic and a simple backend abstraction. It currently supports only Qt- or Tk-backends, but it certainly can be extended to other backends as well.
Happy tiling!

Usage
tile_figures(cols=3, rows=2, screen_rect=None, tile_offsets=None)

# You may have to adjust the available screen area and a tile offset
# for nice results. This works well for my MacOS.
tile_figure(screen_rect=(0,22,1440,740), tile_offsets=(0,22))

# Run a test with 10 figures. Note that you cannot switch the backend dynamically.
# It's best to set mpl.use(<backend>) at the very beginning of your script.
# https://matplotlib.org/faq/usage_faq.html#what-is-a-backend
test(n_figs=10, backend="Qt5Agg", screen_rect=(0,22,1440,750), tile_offsets=(0,22))

Result

Implementation
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt

def screen_geometry(monitor=0):
    try:
        from screeninfo import get_monitors
        sizes = [(s.x, s.y, s.width, s.height) for s in get_monitors()]
        return sizes[monitor]
    except ModuleNotFoundError:
        default = (0, 0, 900, 600)
        print("screen_geometry: module screeninfo is no available.")
        print("Returning default: %s" % (default,))
        return default

def set_figure_geometry(fig, backend, x, y, w, h):
    if backend in ("Qt5Agg", "Qt4Agg"):
        fig.canvas.manager.window.setGeometry(x, y, w, h)
        #fig.canvas.manager.window.statusBar().setVisible(False)
        #fig.canvas.toolbar.setVisible(True)
    elif backend in ("TkAgg",):
        fig.canvas.manager.window.wm_geometry("%dx%d+%d+%d" % (w,h,x,y))
    else:
        print("This backend is not supported yet.")
        print("Set the backend with matplotlib.use(<name>).")
        return

def tile_figures(cols=3, rows=2, screen_rect=None, tile_offsets=None):
    """
    Tile figures. If more than cols*rows figures are present, cols and
    rows are adjusted. For now, a Qt- or Tk-backend is required.

        import matplotlib
        matplotlib.use('Qt5Agg')
        matplotlib.use('TkAgg')

    Arguments:
        cols, rows:     Number of cols, rows shown. Will be adjusted if the
                        number of figures is larger than cols*rows.
        screen_rect:    A 4-tuple specifying the geometry (x,y,w,h) of the
                        screen area used for tiling (in pixels). If None, the
                        system's screen is queried using the screeninfo module.
        tile_offsets:   A 2-tuple specifying the offsets in x- and y- direction.
                        Can be used to compensate the title bar height.
    """
    assert(isinstance(cols, int) and cols>0)
    assert(isinstance(rows, int) and rows>0)
    assert(screen_rect is None or len(screen_rect)==4)
    backend = mpl.get_backend()
    if screen_rect is None:
        screen_rect = screen_geometry()
    if tile_offsets is None:
        tile_offsets = (0,0)
    sx, sy, sw, sh = screen_rect
    sx += tile_offsets[0]
    sy += tile_offsets[1]
    fig_ids = plt.get_fignums()
    # Adjust tiles if necessary.
    tile_aspect = cols/rows
    while len(fig_ids) > cols*rows:
        cols += 1
        rows = max(np.round(cols/tile_aspect), rows)
    # Apply geometry per figure.
    w = int(sw/cols)
    h = int(sh/rows)
    for i, num in enumerate(fig_ids):
        fig = plt.figure(num)
        x = (i%cols) *(w+tile_offsets[0])+sx
        y = (i//cols)*(h+tile_offsets[1])+sy
        set_figure_geometry(fig, backend, x, y, w, h)

def test(n_figs=10, backend="Qt5Agg", **kwargs):
    mpl.use(backend)
    plt.close("all")
    for i in range(n_figs):
        plt.figure()
    tile_figures(**kwargs)
    plt.show()

The tile-offset in y-direction is best chosen as the height of the title bar. On my MacOS it is 22. This value can be queried programmatically using for example Qt.
from PyQt5 import QtWidgets as qtw
enum = qtw.QStyle.PM_TitleBarHeight
style = qtw.QApplication.style()
tile_offset_y = style.pixelMetric(enum)


text:
Q: Where should I write the script that fills new data in my updated schema? I am working on a web app that already has a schema in place (aka in prod) with a certain number of tables (A, B, C...).
Table A has an attribute that corresponds to an enum from table B. Problem is that I can have only one item of that enum list in my dedicated column in table A. But I want my objects from table A to have many of them. So I created a join table A_B and a has_many through association with my table B.
The first consequence is that I need to fill my join table with data from the previous schema architecture. To be clearer, they were objects from table A that were associated with one element of the table B enum. I need to report these simple relationships (only one element from enum list in table B is associated with table A objects) in my newly created join table.
Here's the type of things I'd like to do:
list_of_ids = []
Model_A.where(attribute: 0).each { |r| list_of_ids << r.id }

a.each { |el| A_B.create(tableA_id: el, tableB_id: 0) }

Where should I write and execute these lines of code that will update my data ?

A: As stated in my comments, I would put this "data-update" logic in the same migration file of the join table creation.
Why in a migration file?

*

*the data conversion needs to be done only once, AFTER you created the join table and BEFORE you remove the column which holds the foreign key. If you do this data conversion after the column removal, you will get an error saying that your code is trying to access column that does not exist anymore.

*the migration is responsible for changing the DB structure AND for the data integrity.

Why not a rake task?

*

*rake tasks are meant to be run several times, not only once. The usual tasks are "send_emails", "update_expiration_dates", "compute_cache", "close_inactive_users_account", etc.

*the data you have before your conversion has_many -> HABTM have to be updated to follow the new structure. the rake task could not be ran, and then your data would not be updated, therefore you would loose the association between your models (removing the foreign_key column before running the rake task would make you loose this data).

*your data-conversion logic must happen after the migration creating the join table and BEFORE the migration removing the foreign key's column. There are clear way to say to your rails app: "do this migration, then stop, run this task, then do this migration". It will run the migrations consecutively. If you have these 2 migrations pending, they will be run at once unless you specify otherwise (which is not common at all), and then you rake task will be useless because it relies on the fact that the foreign key column still exists.

A: In addition to MrYoshiji's answer (too long for comments):
Migrations are intended for one-off changes to both database schemas and the data therein. The official guide mentions this, too.
In your case, populating the join table is an appropriate thing to do in a migration. Otherwise data would be left in an invalid or incorrect state vis-a-vis the schema and model changes you have made. Running migrations is a typical step in deploying a Rails app. Since you probably do not want to deploy without updating the data, having it as part of a migration is a great solution. In contrast, if you created a custom rake task to update the data then you would need to remember to run it manually after deploying or add it as a deployment step, neither of which is a very good option.

redpajama_set_name: RedPajamaStackExchange


text:
Q: subsetting data frame by row index Why is my last step converting the data frame to a vector? I want to keep the first 6000 observations in the data frame key.
  set.seed(1)
  key <- data.frame(matrix(NA, nrow = 10000, ncol = 1))
  names(key) <- "ID"
  key$ID <- replicate(10000,
                      rawToChar(as.raw(sample(c(48:57,65:90,97:122), 8, replace=T))))
  key <- unique(key)  # still a data frame
  key <- key[1:6000,] # no longer a data frame

A:  key1 <- key[1:6000,,drop=F] #should prevent the data.frame from converting to a vector.

According to the documentation of ?Extract.data.frame

drop:  logical.  If 'TRUE' the result is coerced to the lowest
            possible dimension.  The default is to drop if only one
            column is left, but not to drop if only one row is left.

Or, you could use subset, but usually, this is a bit slower.  Here the row.names are numbers from 1 to 10000
 key2 <- subset(key, as.numeric(rownames(key)) <6000)

 is.data.frame(key2)
 #[1] TRUE

because,
 ## S3 method for class 'data.frame'
 subset(x, subset, select, drop = FALSE, ...) #by default it uses drop=F

A: It's being coerced to a vector basically because it can be and that's the default coercion when there's only 1 element. R is trying to be "helpful".
This will keep it as a dataframe:
set.seed(1)
key <- data.frame(matrix(NA, nrow = 10000, ncol = 1))
names(key) <- "ID"
key$ID <- replicate(10000,
                      rawToChar(as.raw(sample(c(48:57,65:90,97:122), 8, replace=T))))
key <- unique(key)
key <- as.data.frame(key[1:6000,]) # still a data frame


text:
Q: T-SQL/MS SQL SERVER UPDATE USING CASE I have table which contains the following columns empid, month, year, day1, day2, day3, day4...........day31.
I have written a SP to update the attendance every day, once the employee log-in.
CREATE PROC PROC_Attendance_update @empid INT, @day INT, @month INT, @year INT

AS

BEGIN

DECLARE @sql_text VARCHAR(8000)

SET @sql_Text = 'UPDATE tblattendance SET DAY'+CONVERT(VARCHAR(2),@day)+'=''P'' WHERE empid = '+CONVERT(VARCHAR(4), @empid)+'  AND month = '+CONVERT(VARCHAR(4), @month)+' AND Year ='+CONVERT(VARCHAR(4), @year)

EXEC(@sql_text)

END

But, I don't want it to be in dynamic sql. I want to re-write it to standard T-sQL code.
I tried by it didn't work.
CREATE PROC PROC_Attendance_update @empid INT, @day INT, @month INT, @year INT

AS

BEGIN

UPDATE tblattendance SET CASE   WHEN @day=1 THEN DAY1 = 'P'

                WHEN @day=2 THEN DAY2 = 'P'

                .

                .

                WHEN @day=31 THEN DAY31 = 'P'

              END

WHERE empid = @empid AND MONTH = @month AND Year = @Year
END

Can anyone help on this?

A: IF @day = 1
    UPDATE tblattendance
    SET DAY1 = 'P'
    WHERE empid = @empid
    AND MONTH = @month AND Year = @Year
ELSE IF @day = 2
    UPDATE tblattendance
    SET DAY2 = 'P'
    WHERE empid = @empid
    AND MONTH = @month AND Year = @Year
ELSE IF @day = 3
    UPDATE tblattendance
    SET DAY3 = 'P'
    WHERE empid = @empid
    AND MONTH = @month AND Year = @Year
--...

Or better yet, change your table schema to empid, month, year, day, attendance. (Or even empid, date, attendance.) This way, you will have one row per day, and queries against the table (no, not just this one) become much easier to manage.


text:
Q: How can I use List(Of ) as MethodParameters in ObjectDataProvider? (WPF) I have an Object 'ArticleMasterData' and a list with instances of this Object. To show it in the XamDataGrid I have to convert it to a DataTable, which i do with 'ListToDataTable'. First off the VB Code for it:
Private Function ListToDataTable(Of T)(ByVal AccessDataList As IList(Of T)) As DataTable
    Dim table As New DataTable
    Dim fields() As FieldInfo = GetType(T).GetFields

    For Each field As FieldInfo In fields
        table.Columns.Add(field.Name, field.FieldType)
    Next
    For Each item As T In AccessDataList
        Dim row As DataRow = table.NewRow
        For Each field As FieldInfo In fields
            row(field.Name) = field.GetValue(item)
        Next
        table.Rows.Add(row)
    Next
    Return table
End Function

I need now the list(Of ArticleMasterData) as MethodParamter:
<Window.Resources>
    <ObjectDataProvider x:Key="odpImport"
                        ObjectType="{x:Type local:ArticleMasterData}"
                        MethodName="ListToDataTable"
                        >
        <ObjectDataProvider.MethodParameters>

        </ObjectDataProvider.MethodParameters>
    </ObjectDataProvider>
</Window.Resources>

How can I do this? I didn't find anything in the Documentation or on google, so I appreciate any help! Thank you.


text:
Q: How to affect 2 in directories column for a file ( ls command) I'm looking how to affect the value 2 in directories  column inside the ls command for a file.
Actually the value is 1.
I tried to creat a symbolic link but its still 1

A:
I tried to creat a symbolic link but its still 1

You need a hardlink instead (i.e. ln without -s). That number is the count of references to the inode and a symbolic link doesn't increase it.


text:
Q: Wordpress Bootstrap dropdown not working after moving to another server I've got webpage based on wordpress (uses bootstrap3 template) which I recently moved on another server. Since then dropdown menu is not working. It may be that I've forgotten some css or js files, but console is not saying anything.
Thanks

A: The console says there's an error in your main.js at line 3, try to fix it as it might be breaking other Javascripts in your page.

A: Your box-slider-fade.jquery.min.js script cannot be found (404 error).
Check if this file is present in your theme library/js/effects/ directory.

A: Actually, your dropdown toggles miss the data-toggle attributes which is required by Bootstrap : http://getbootstrap.com/components/#navbar
Jednotky


text:
Q: Format a pc with a GRUB error i have a pc with a grub error {caused by deleting ubuntu partition in XP dual boot}
i would like to format the hard disk and install a new OS [chromium]
i do not have either the ubuntu or the XP installation drives
although i do have the chromium bootable drive
when i try to boot from the chrome bootable USB its says "your system is repairing itself" and restarts. this keeps happening over and over again.
i just want to format my HDD completely and start over with chromium (i have no important data on the HDD)

A: Go and download a live boot-able ISO of "Gparted" and delete all of your partitions on your hard drive, then try to run the installer for Chromium.


text:
Q: Error in converting the json value using JQuery I am trying to get the value from the serverside but i can't get it..Here, i am trying to convert the json data using JSON.parse(); but it is not working in jQuery... i don't know how to solve this...
    $(document).ready(function() {
            $.ajax({
                url:'http://newslet.comxa.com/NewsRecord.php' ,
                    dataType:'json',
                success:function(output_string) {
                    temp=JSON.parse(output_string);
                for(var i=0;i<temp.length;i++)
                {
                     $('#level').append('
Title         :'+temp[i].Title+'
Source     :'+temp[i].Source+'
Category :'+temp[i].Category+'

');
                 }
                }
             });
        });

i get this output when i am running these path 'http://newslet.comxa.com/NewsRecord.php'..
[{"Id":"2","Date":"","Title":"Hitachi Data Systems bets big on analytics","Source":"TOI","Category":"Corporate","links":"http:\/\/timesofindia.indiatimes.com\/tech\/tech-news\/software-services\/Hitachi-Data-Systems-bets-big-on-analytics\/articleshow\/26542988.cms?"},{"Id":"3","Date":"","Title":"British bike company Triumph drives into India","Source":"TOI","Category":"Industry","links":"http:\/\/timesofindia.indiatimes.com\/business\/india-business\/British-bike-company-Triumph-drives-into-India\/articleshow\/26542881.cms"}]

A: you need to stringify first json result.
var json = JSON.stringify([{"Id":"2","Date":"","Title":"Hitachi Data Systems bets big on analytics","Source":"TOI","Category":"Corporate","links":"http:\/\/timesofindia.indiatimes.com\/tech\/tech-news\/software-services\/Hitachi-Data-Systems-bets-big-on-analytics\/articleshow\/26542988.cms?"},{"Id":"3","Date":"","Title":"British bike company Triumph drives into India","Source":"TOI","Category":"Industry","links":"http:\/\/timesofindia.indiatimes.com\/business\/india-business\/British-bike-company-Triumph-drives-into-India\/articleshow\/26542881.cms"}]);

var temp = JSON.parse(json);

A: Your string already is a valid json so there isnt any need to use
JSON.parse(output_string);

Check this fiddle  http://jsfiddle.net/uDr6t/


text:
Q: Mongo / Express Query Nested _id from query string Using: node/express/mongodb/mongoose
With the setup listed above, I have created my schema and model and can query as needed. What I'm wondering how to do though is, pass the express request.query object to Model.find() in mongoose to match and query the _id of a nested document. In this instance, the query may look something like:
http://domain.com/api/object._id=57902aeec07ffa2290f179fe

Where object is a nested object that exists elsewhere in the database. I can easily query other fields. _id is the only one giving an issue. It returns an empty array of matches.
Can this be done?
This is an example and not the ACTUAL schema but this gets the point across..
let Category = mongoose.Schema({
    name: String
})

let Product = mongoose.Schema({
    name: String,
    description:String,
    category:Category
})

// sample category..
{
    _id:ObjectId("1234567890"),
    name: 'Sample Category'
}

// sample product
{
    _id:ObjectId("0987654321"),
    name:'Sample Product',
    description:'Sample Product Description',
    category: {
        _id:ObjectId("1234567890"),
        name: 'Sample Category'
    }
}

So, what I'm looking for is... if I have the following in express..
app.get('/products',function(req,res,next){
    let query = req.query
    ProductModel.find(query).exec(function(err,docs){
        res.json(docs)
    })
})

This would allow me to specify anything I want in the query parameters as a query. So I could..
http://domain.com/api/products?name=String
http://domain.com/api/products?description=String
http://domain.com/api/products?category.name=String

I can query by category.name like this, but I can't do:
http://domain.com/api/products?category._id=1234567890

This returns an empty array

A: Change your query to http://domain.com/api/object/57902aeec07ffa2290f179fe and try
app.get('/api/object/:_id', function(req, res) {

    // req._id is Mongo Document Id
    // change MyModel to your model name
    MyModel.findOne( {'_id' : req._id }, function(err, doc){
        // do smth with this document
        console.log(doc);
    });

});

or try this one
http://domain.com/api/object?id=57902aeec07ffa2290f179fe
app.get('/api/object', function(req, res) {
    var id = req.param('id');
    MyModel.findOne( {'_id' : id }, function(err, doc){
        console.log(doc);
    });
})

*

*First of all increase your skills in getting URL and POST Parameters by this article.

*Read official Express 4.x API Documentation

A: Never mind I feel ridiculous. It works just as I posted above.. after I fixed an error in my schema.


text:
Q: C# split string array to Excel I have a previous question similar to this but I am still frozen on the actual solution. I am sending rows of text from dynamic textboxes to Excel, this information comes from a database. Within the rows I am sending "txtProductNameBundle" and on occasion a "product description"("txtProductDesc") row that will have to split and would need to be in place under the "txtProductNameBundle" in Excel, it could be 1 row or up to 6. I have my for loops that successfully send all of the rows (without Product Description) exactly where I need them. Here is the problem, I know how to perform a "split string" with the "txtProductDesc" as this text can be rather long and even send it to Excel but I am clueless on how to add a loop to place it after the "product name". The Excel sheet is a template so rows have to be inserted for as many rows of information that will be sent.
    int StartBundleRow = 11;  // row 11 is where I start to insert the dynamic controls
    string rowIndent = "        ";  // adds spaces to the beginning of the text
    string DescriptionSplit = frmProposal.ProdDesc.Text;

    for (int BndlRow = 0; BndlRow < bundleRows; BndlRow++)
        {
            worksheet.Rows[StartBundleRow].Insert();
            worksheet.Rows[StartBundleRow].Font.Size = 14; //********Excel formatting*********
            worksheet.Cells[StartBundleRow, "E"].Font.Bold = true;
            worksheet.Rows[StartBundleRow].Interior.Color = ColorTranslator.ToOle(Color.White);
            worksheet.Columns["A"].Interior.Color = ColorTranslator.ToOle((Color)cc.ConvertFromString("#808080"));
            worksheet.Columns["J:XFD"].Interior.Color = ColorTranslator.ToOle((Color)cc.ConvertFromString("#808080"));
            worksheet.Rows[StartBundleRow].HorizontalAlignment = XlHAlign.xlHAlignLeft;
            worksheet.Cells[StartBundleRow, "C"].Interior.Color = ColorTranslator.ToOle((Color)cc.ConvertFromString("#49176D"));
            worksheet.Cells[StartBundleRow, "D"].value = srcBundlePanel.Controls["txtQtyBundle" + BndlRow].Text;
          //(product name below)
            worksheet.Cells[StartBundleRow, "E"].value = srcBundlePanel.Controls["txtProductNameBundle" + BndlRow].Text;
         //(this is where I need to insert the split string of product description)
            worksheet.Cells[StartBundleRow, "F"].value = srcBundlePanel.Controls["txtListPriceBundle" + BndlRow].Text;
            worksheet.Cells[StartBundleRow, "G"].value = srcBundlePanel.Controls["txtMaxDiscountBundle" + BndlRow].Text;
            worksheet.Cells[StartBundleRow++,"H"].value = srcBundlePanel.Controls["txtProposedPriceBundle" + BndlRow].Text;
        }
    ** BELOW IS MY SAMPLE STAND ALONE CODE FOR SPLITTING THE STRING INTO 3 ROWS **
    worksheet.Cells[11, "E"].Value = rowIndent + DescriptionSplit.Substring(0, DescriptionSplit.IndexOf("|")).Trim();
    worksheet.Cells[12, "E"].Value = rowIndent + DescriptionSplit.Substring(DescriptionSplit.IndexOf("|") + 1,
      DescriptionSplit.IndexOf("|")).Trim();
    worksheet.Cells[13, "E"].Value = rowIndent + DescriptionSplit.Substring(DescriptionSplit.LastIndexOf("|") + 1,
      DescriptionSplit.Length - DescriptionSplit.LastIndexOf("|") - 1).Trim();

A: The split of the description string can be made simpler provided that each part is separated by a pipe char.
string[] descriptionParts = DescriptionSplit.Split('|');

To insert the rows you can use a simple for loop:
for(int i = 0; i < descriptionParts.Length; i++)
{
    worksheet.Cells[StartBundleRow + i, "E"].Value =
        rowIndent + descriptionParts[i].Trim();
}

You probably also want to replace the last line with below code to adjust the row offset for the next bundle based on number of rows used for the description:
worksheet.Cells[StartBundleRow,"H"].value =
    srcBundlePanel.Controls["txtProposedPriceBundle" + BndlRow].Text;
StartBundleRow += descriptionParts.Length;


text:
Q: Initialize a multiple levels hash in rails So I have some codes look like the following:
@foo ||= {}
@foo[:bar] ||= {}
@foo[:bar][:baz] ||= {}

I am not concerning the performance, but the cleanness. Is there a more beautiful way or better way to do so?

A: {:bar => {:baz => {}}}.merge(@foo)

A: I think what you have is a good, terse way of writing the code, but below is another way I thought of to do the same thing. It'll still do the job, if you'd prefer to be more verbose:
if @foo.nil?
    @foo = { :bar => { :baz => {} } }
else if @foo[:bar].nil?
    @foo[:bar] = { :baz => {} }
else if @foo[:bar][:baz].nil?
    @foo[:bar][:baz] = {}
end

or
if !@foo
    @foo = { :bar => { :baz => {} } }
else if !@foo[:bar]
    @foo[:bar] = { :baz => {} }
else if !@foo[:bar][:baz]
    @foo[:bar][:baz] = {}
end


text:
Q: Using text-overflow: ellipses in an HTML table I must be missing something here, but why isn't my text-overflow: ellipses rule working correctly here?
Fiddle: https://jsfiddle.net/sgj9rv5r/
td {
    white-space: nowrap;
    width: 50px;
    overflow: hidden;
    text-overflow: ellipsis;
}

      This content should shorten to ellipses after the 50px width has been reached.

A: Using max-width as suggested by Michael Coker solves this problem.


text:
Q: iOS spotlight or settings icon is necessary? My app needs to compatible with iPhone & iPad and based on iOS 6.0.
I want to know if i don't set spotlight icons or settings icons,what will be displayed? blank or use app icon instead?

A: Spotlight search icons are not required. Even if you don't provide them, your app icon will be used in the search results.
Using spotlight icons is recommended by apple in case you want to make sure they appear properly on all device types.
You can find additional info here.


text:
Q: Generate a list of a given length with fake elements. Django I'm developing my app with django and in one of my views I have a given number (nbr). I would like to know if it is possible to generate a list of length 'nbr', filled with 'nbr' fake elements.
Thank you

A: You mean something like:
new_list = [None]*nbr

This idiom is mostly used for immutable objects.  For mutable objects, typically
new_list = [ mutable_object_factory() for _ in range(nbr) ]

is used (unless you really know what you're doing :)

A: You mean something like this?
[fake_element for n in xrange(nbr)]

A: Assuming the random elements are stored in a list called choices, you can use random.choice
In [1]: choices = ['a', 'b', 'c']

In [2]: myList = [random.choice(choices) for x in xrange(10)]

In [3]: myList
Out[3]: ['b', 'b', 'c', 'b', 'c', 'a', 'a', 'a', 'b', 'a']


text:
Q: Can't create In-App Purchase Review Screenshot by API I am trying to create an In-App Purchase Review Screenshot to create a new In-App Purchase by API.
I'm following Apple's guide, but am stuck at step : "Make an image reservation with POST /v1/inAppPurchaseAppStoreReviewScreenshots (Create an In-App Purchase Review Screenshot)."
Payload example :
{
    "data": {
        "type": "inAppPurchaseAppStoreReviewScreenshots",
        "attributes": {
            "fileName": "my-screenshot.jpg",
            "fileSize": "45482"
        },
        "relationships": {
            "inAppPurchaseV2": {
                "data": {
                    "id": "1651010682",
                    "type": "inAppPurchases"
                }
            }
        }
    }
}

I always get error 409.
Exception = Client error: `POST https://api.appstoreconnect.apple.com/v1/inAppPurchaseAppStoreReviewScreenshots` resulted in a `409 Conflict` response:
{
  "errors" : [ {
    "id" : "7c813a34-37a6-49e7-be5f-699236659d0e",
    "status" : "409",
    "code" : "ENTITY_ERROR.A (truncated...)

I tried to remove V2 from inAppPurchaseV2 in relationships, but get the same error.
Has anyone succeeded by any chance?

A: I found the cause of the problem, it's because I was passing a string on "fileSize". By removing the quotes everything works!


text:
Q: Rselenium xpath not able to save response I'm trying to get the stocks from https://www.vinmonopolet.no/
for example this wine https://www.vinmonopolet.no/vmp/Land/Chile/Gato-Negro-Cabernet-Sauvignon-2017/p/295301
Using Rselenium
library('RSelenium')
    rD=rsDriver()
    remDr =rD[["client"]]
    remDr$navigate("https://www.vinmonopolet.no/vmp/Land/Chile/Gato-Negro-Cabernet-Sauvignon-2017/p/295301")
    webElement = remDr$findElement('xpath', '//*[@id="product_2953010"]/span[2]')
    webElement$clickElement()

It will render Response
But how to store it?
Full XML

A: Maybe be rvest is what you are looking for?
library(rvest, tidyverse)

url <- "https://www.vinmonopolet.no/vmp/Land/Chile/Gato-Negro-Cabernet-Sauvignon-2017/p/295301"

page <- read_html(url)
stock <- page %>%
  html_nodes(".product-stock-status div") %>%
  html_text()

stock.df <- data.frame(url,stock)

To extract the number use
stock.df <- stock.df %>%
  mutate(stock=as.numeric(gsub(".*?([0-9]+).*", "\\1", stock)))

A: Got it to work just sending the right plain request no need of R
https://www.vinmonopolet.no/vmp/store-pickup/1101/pointOfServices?locationQuery=0661&cartPage=false&entryNumber=0&CSRFToken=718228c1-1dc1-41cd-a35e-23197bed7b0c


text:
Q: Iphone cannot receive push notification I used Javapns to push notification to iphone, when i run the test applicaiton fist time, iPhone can receive the notification, but when i tried agian, no notication will be recieveed, about 20-40 minutes after i receive the notification, i tried again, then i received it, doese any limitatoin on appler server that i can only send the notifiction after special interval?

A: JavaPNS was recently updated to 2.0, and fixed ALL reported issues up to the release date.  I believe it fixes the issue you are reporting, as the problem being described seems to be caused by an un-closed or un-timed-out connection.


text:
Q: Write a nested cell array to an Excel file I have a variable with nested cells:
hello =
    '8'     {1x3 cell}    {1x3 cell}
    '22'    {1x3 cell}    {1x3 cell}
    '97'    {1x3 cell}    {1x3 cell}

How do I write this into a single Excel file using MATLAB, e.g. xlswrite('file',hello)?

A: Just looked into it after a while. Here is my solution with a sample problem.
clear all; clc ;
d = {{'Number'},{'Class A'},{'class B'};{'007'},{'Test One'},{'Test Two'}};
for i = 1:size(d,1)
for j = 1:size(d,2)

    if iscell(d(i,j))

        d(i,j) = d{i,j};

    end
end

end
xlswrite('FileAddress',d);


text:
Q: Using PhpStorm XAMPP when opening file it is using port 63442 and rather than default port, how can I change it? I have Windows 10, using XAMPP local host and PhpStorm as IDE.
When I open show the php file in browser, it shows a weird URL like:
http://localhost:63342/index.php/index.php?_ijt=k1qvpci720mq530tq6le3f4djb

instead of
http://localhost/projectfolder/index.php

I have the following settings:

I have changed these settings to show my project folder and vice versa, but the results are the same.
How do I fix that?

A: Navigate to File | Settings | Build, Execution, Deployment | Deployment, define a new web-server and select Use as Default. The entry should be in bold instead of regular.


text:
Q: How to solve "Transform AWS::Include failed with: The specified S3 object's content should be valid Yaml/JSON" in SAM template I'm trying to include an OpenApi specification into my AWS::Serverless::Api DefinitionBody like so:
  MyApi:
    Type: "AWS::Serverless::Api"
    Properties:
      StageName: 'dev'
      Domain:
        DomainName: 'mydomain.com'
        CertificateArn: 'my-arn'
        EndpointConfiguration: REGIONAL
        Route53:
          HostedZoneId: 'HOSTEDZONEID'
        BasePath:
          - /api
      DefinitionBody:
        'Fn::Transform':
          Name: 'AWS::Include'
          Parameters:
            Location: !Sub 'open-api.yml'

I used Fn:Transform to ensure that my shorthand notation is evaluated. I'm using some AWS API Gateway extensions in my open-api.yml like below:
        ...
        x-amazon-apigateway-integration:
            uri: !Sub 'arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/arn:aws:lambda:${AWS::Region}:${AWS::AccountId}:function:${FunctionName}/invocations'
            responses:
                default:
                    statusCode: "200"
            passthroughBehavior: "when_no_templates"
            httpMethod: "GET"
            type: "aws_proxy"

When I run sam deploy --debug I get the following error:

Transform AWS::Include failed with: The specified S3 object's content should be valid Yaml/JSON

A: You are getting this error because you are using shorthand notation in YAML snippets. Shorthand notations for YAML snippets included via AWS::Include transform is not support at the time of this writing.
That means, instead of this:
uri: !Sub 'arn:aws:apigateway:${AWS::Region}:lambda:path/2015-03-31/functions/arn:aws:lambda:${AWS::Region}:${AWS::AccountId}:function:${FunctionName}/invocations'

you have to do this instead:
uri:
  Fn::Sub:
     - 'arn:aws:apigateway:${AWSRegion}:lambda:path/2015-03-31/functions/${FunctionArn}/invocations'
     - AWSRegion:
           Ref: AWS::Region
       AWSAccountId:
           Ref: AWS::AccountId
       FunctionArn:
           Fn::GetAtt: [UserServicesFunction, Arn]

See AWS::Include transform for more info.


text:
Q: How to restart network services on Sierra? On FreeBSD/Linux, it is possible to restart network services by restarting a daemon.
Is there something similar in macOS Sierra?

A: You can tear down and start up the network interface using:
sudo ifconfig en0 down
sudo ifconfig en0 up

A: Network interfaces can also be Disabled & Enabled in System Preferences‑Network.

A: The restarts Wi-Fi without sudo. Does anyone know how to do this with a single command?
networksetup -setairportpower en0 off
networksetup -setairportpower en0 on


text:
Q: OSMnx downloaded unexpected edges of a river network, how to fix this? I'm using OSMnx (0.15.1) to extract a network of rivers. Using the code below I expected to download a river network with only the central way of the river, see Fig. 1, which is obtained using QuickOSM plugin in QGIS with the tag "waterway=river":

Fig. 1 with QuickOSM
When using OSMnx, the most part of the network within this river catchment seems to be correctly presented as the central way of the river. However, at this particular lat-long point (51.062981, 13.270961), the OSMnx tool downloaded the edges of the riverbank as well (Fig. 2, grey lines). For some river sections (bottom right), the edges of the riverbank were downloaded instead of the central way of the river. Where is the problem and how can I fix this?
The OSM tag "waterway"~"river" was used as a filter. A reproducible example:
import osmnx as ox

"""
A simple attempt to download a river network from a point with OSMnx.
"""
# Get a river network and plot it with all edge intersections.
point = 51.062981, 13.270961 # lat, long
G = ox.graph_from_point(point,
                        dist=1000,
                        custom_filter='["waterway"~"river"]')
fig, ax = ox.plot_graph(G, node_color='r')

Fig. 2 with OSMnx

A: Your filter '["waterway"~"river"]' matches both "river" and "riverbank", hence you're getting river banks in your graph. Instead, use = to just match "river":
G = ox.graph_from_point(point, dist=1000, custom_filter='["waterway"="river"]')


text:
Q: Windows 10 showing "ghost" Drive Letters Yesterday I had to reset (PSU switch off-wait-on) my Computer, when i started it again it ran a disk check and installed the cumulative update released a few days ago.
Now its showing two drive letters for every disk, The "normal" ones for the Volumes C, D and T and the strange ones, E,G,I-L. As you can see on the Screenshot

four of them are in a Software-RAID-0, their Volume has the letter D, but every single disk now has an "own" letter, The System Disk even has three Letters.
I already:

*

*rebooted

*plugged it out, waited 5 minutes and plugged it back in

*deleted the HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Explorer\Desktop\NameSpace\DelegateFolders\{F5FB2C77-0E2F-4A16-A381-3E560C68BC83} Key

but nothing worked.
My Guess is that some weird bug makes windows assign Letters to hidden partitions, cause the System Disk has three letters; C=System, E=maybe msftres, F=EFI, the other ones got two.
I'm running Windows 10 Enterprise x64.
Any Idea what I could do? (except for re-install Windows or restoring a Backup)

A: Today I formatted my System Disk and reinstalled Windows, a few hours later the "ghostletters" (My guess was right, they were assigned to the efi boot and msftres partitions) were back.
I don't know why this happens yet, but I've found a Solution: ext2fsd, an ext2/3/4 file system driver for Windows with a built-in drive letter manager. A few clicks later, everything was fine again, even after a reboot.


text:
Q: Is there a way to do some pre-process/post-process every time I call a function in python I have a number of calls I need to make to functions imported from a package (the package is a shared object file). However I need to do some pre-process / post - process step every time I make a call to a function from this package. Something like this:
import xyz

prepare()
xyz.foo(<args>)
done()

prepare()
xyz.bar(<args>)
done()

prepare()
xyz.foobar()
done()

Is there some way I can ask python to always invoke prepare() before I call a function from xyz module. And also to invoke done() after the call is complete?
Writing prepare and done through my whole code seems redundant and messy. Appreciate your help!

A: This is typically done with a context manager.
import contextlib

@contextlib.contextmanager
def with_preparation():
    prepare()
    yield
    done()

with preparation():
    xyz.foo(<args>)

with preparation():
    xyz.bar(<args>)

with preparation():
    xyz.foobar()

preparation defines a function that returns a context manager. The with statement works by invoking the context manager's __enter__ method, then executing the body, then ensuring that the context manager's __exit__ method is invoked before moving on (whether due to an exception being raised or the body completing normally).
contextlib.contextmanager provides a simple way to define a context manager using a generator function, rather than making you define a class with explicit __enter__ and __exit__ methods.

You mentioned you need this for every function in a particular module. Without exact details about the module, this may not be entirely correct, but you  might be able to build up on it.
class XYZWrapper:
    def __getattr__(self, name):
        # Intentionally let an AttributeError propagate upwards
        f = getattr(xyz, name)
        def _(self, *args, **kwargs):
            prepare()
            return f(*args, **kwargs)
            done()
        setattr(XYZWrapper, name, _)
        return _

prepared = XYZWrapper()

prepared.foo(<args>)
prepared.bar(<args>)
prepared.foobar()

In short, any attribute access on the XYZWrapper instance tries to find an identical attribute on the xyz module, and if successful, defines a wrapper that calls prepare() and done() as needed and patches the XYZWrapper instance with the new wrapper.

A: To extend @chepner's excellent answer, you can define your own class and use its __getattr__ function to create a function that wraps the actual module's function with your pre- and post-processing functions:
import typing
import xyz

def XYZWrapper():
    def __init__(self, pre, post):
        self.pre = pre
        self.post = post

    def __getattr__(self, a):
        func = getattr(xyz, a)
        if isinstance(func, typing.Callable):
            def wrapper(*args, **kwargs):
                self.pre()
                func(*args, **kwargs)
                self.post()
            return wrapper
        raise TypeError(f"'{type(func)}' object is not callable")

To use it, do
xyz = XYZWrapper(prepare, done)
xyz.foo(<args>)
...

Note that if you want to overwrite the xyz variable, you will need to put the wrapper class in a separate file.


text:
Q: Rendering XML in Angular 2+ I've been reading other posts similar to this issue but im still unable to render my xml properly in my app.
I've used the following to get my xml ready:
  const parser = new DOMParser();
  const xml = parser.parseFromString(response, 'application/xml');
  this.questionSet = xml.documentElement;

  console.log(this.questionSet);

This is what is in the console:

How can i now render this in the HTML?
Im currently trying this:

But its just printing: [object Element]
Any help would be great, thanks

A: Angular security Blocks dynamic rendering of HTML and other scripts. You need to bypass them using DOM Sanitizer.
Read more here  : Angular Security
DO below changes in your code :

// in your component.ts file

//import this
import { DomSanitizer } from '@angular/platform-browser';

// in constructor create object

constructor(
...
private sanitizer: DomSanitizer

...
){

}

someMethod(){

  const parser = new DOMParser();
  const xml = parser.parseFromString(response, 'application/xml');
  this.questionSet = xml.documentElement;
  console.log(this.questionSet);

 this.htmlData = this.sanitizer.bypassSecurityTrustHtml( this.questionSet); // this line bypasses angular scurity

}

Here is the StackBlitz working Demo

A: Try to put innerHtml property between brackets:

.


text:
Q: PBS commands return wrong output or not output at all I have run the following lines from the terminal, one by one:
#!/bin/bash
#PBS -S /bin/bash
#PBS -lnodes=1:ppn=8
#PBS -lwalltime=48:00:00
echo $PBS_O_WORKDIR
cd $PBS_O_WORKDIR
cat $PBS_NODEFILE

Line echo $PBS_O_WORKDIR returns an empty line.
cd $PBS_O_WORKDIR returns the home directory instead of the directory I was launching the command from.
Line cat $PBS_NODEFILE is simple hanging, without doing anything.
This used always to work, do you have any idea about what's going on?
An additional note. When trying to submit the following script with qsub, it simply hangs, alternating between status R and Q.
#!/bin/bash
#PBS -N test
#PBS -l select=1:ncpus=1
echo "Hi"
date
echo "############################"
env
echo "############################"
echo "bye"
exit 0

A: I don't know what PBS is, but it sounds like the environment variables aren't set.
So, on that assuption

*

*When you echo with no arguments, it will simply output an empty line.

*When you cd with no arguments, it defaults to $HOME

*When you cat with no arguments, it waits for information on stdin (which will create the illusion that it hangs, as ti will keep on waiting forever)

So, the question becomes: when is those variables supposed to be set?
So, until env | awk -F= '$1 ~ /^PBS_O_(WORKDIR|NODEFILE)$/' outputs anything, the commands don't have an argument to pass and the result you experience is expected.


text:
Q: Accessing Windows harddrive wrecked with viruses, trojans, etc using Linux I am in possession of a windows harddrive that was recently infected and as a new user to Linux, I wish to salvage as much data as possible from the harddrive. A few questions though.

*

*Can the viruses affect my Linux installation in any way?

*What is the best way to salvage as much information as possible whilst ensuring the files I am attempting to save are not infected and that do not infect my installation of Linux?

Appreciate any other advise and tips.

A: The former, no, Viruses are usually OS specific, thought there have been a few multiplatform ones as of late
Imaging before  recovery is often a good idea, in case something went wrong.
As for salvaging information, run an antivirus or three on it before mounting it on a linux livec for actual salvage to make sure the contents of the drive get cleaned up first- I'd recommend running multiple livecd AV distros --- MS has one in system sweeper , and there's a few more - for example avira.Clean out the disc first before you do anything, and what you salvage SHOULD be virus free.


text:
Q: Assigning variable to result of formula in EPPlus I have an Excel file that contains lots of data, and I'm making a program that reads the excel file, does some statistics, and prints the findings in console.
I need to count the occurrences of a specific string, in a specific column, and save the result to a variable in code.
I've thought of using excel's COUNTIF() formula, but it seems like I have to put the formula in a cell, to read the result, and therefore cant just assign a variable to it's result.
How can I do the same thing as COUNTIF() without modifying the file?


text:
Q: Python 3 sorting "TypeError: 'NoneType' object is not iterable" When sorting in Python 3, I get:
TypeError: 'NoneType' object is not iterable

Here is my code:
for f in self.db[key].sort():
  yield f

I have confirmed none of the items in my list are None.

A: The reason for this is simple, Python3 provides two methods and you're using the wrong one,

*

*sorted(foo) returns a copy sorted, uses core sorted().

*.sort() sorts the stuff in place, returns None

You need to call sorted(foo) instead. For more information see the docs on Sorting HOW TO


text:
Q: Error: argument 1 is not a vector I am following the Rhea script for analysis of microbial sequencing data. The last command gives me the error saying that "

argument 1 is not a vector

although I've closely followed the script.
Find my sessions info attached below.
`R version 3.4.0 (2017-04-21) -- "You Stupid Darkness"
 Copyright (C) 2017 The R Foundation for Statistical Computing
 Platform: x86_64-w64-mingw32/x64 (64-bit)

R is free software and comes with ABSOLUTELY NO WARRANTY.
You are welcome to redistribute it under certain conditions.
Type 'license()' or 'licence()' for distribution details.

R is a collaborative project with many contributors.
Type 'contributors()' for more information and
'citation()' on how to cite R or R packages in publications.

Type 'demo()' for some demos, 'help()' for on-line help, or
'help.start()' for an HTML browser interface to help.
Type 'q()' to quit R.

> setwd("C:/Users/Jonas/Desktop/Bielefeld")
> file_name<- "C:/Users/Jonas/Desktop/Bielefeld/OTUs_Table-norm.tab"
> Species.richness <- function(x)
+ {
+
+     count=sum(x[x>0.5]^0)
+     return(count)
+ }
> Shannon.entropy <- function(x)
+ {
+     total=sum(x)
+     se=-sum(x[x>0]/total*log(x[x>0]/total))
+     return(se)
+ }
> Shannon.effective <- function(x)
+ {
+     total=sum(x)
+     se=round(exp(-sum(x[x>0]/total*log(x[x>0]/total))),digits =2)
+     return(se)
+ }
> Simpson.concentration <- function(x)
+ {
+     total=sum(x)
+     si=sum((x[x>0]/total)^2)
+     return(si)
+ }
> Simpson.effective <- function(x)
+ {
+     total=sum(x)
+     si=round(1/sum((x[x>0]/total)^2),digits =2)
+     return(si)
+ }
> otu_table <- read.table (file_name,
+                          check.names = FALSE,
+                          header=TRUE,
+                          dec=".",
+                          sep = "\t",
+                          row.names = 1)
> otu_table <- otu_table[!apply(is.na(otu_table) | otu_table=="",1,all),]
>
> my_otu_table <- otu_table[,order(names(otu_table))]
Error in order(names(otu_table)) : argument 1 is not a vector
> my_otu_table <-data.frame(t(my_otu_table))
Error in t(my_otu_table) : object 'my_otu_table' not found`

'> str(otu_table)
'data.frame':   166 obs. of  1 variable:
$ Sample1: int  102243 48415 5602 9142 1560 1099 1153 1088 1891 414 ...
> otu_table <- otu_table[!apply(is.na(otu_table) | otu_table=="",1,all),]
>
> str(otu_table)
 int [1:166] 102243 48415 5602 9142 1560 1099 1153 1088 1891 414 ...
>

> otu_table[!is.na(otu_table)]
[1] 102243  48415   5602   9142   1560   1099   1153   1088   1891    414
526    504    612    795    568
 [16]    459    680    212    207    265    156    149    149    228    327
212    114    666    296    751
 [31]     37    272    220    851    126    162    250    122    124    431
118    221    141    153     83
 [46]     51    149    256    166    120    158     11    116     84    291
130    371    138    129     58
 [61]     98    176     86     69    192     27     59     31     61     35
58    110     46    105    153
 [76]     87      6    119     31    100     84     61      9     60    201
101     68      4    439     46
 [91]     59     35     61     97     11     16    167    101     46    127
16    101    144      8     65
[106]     55     51     39     48      6     93      2      2     37     24
15     15     24     52      3
[121]      2      2     27     13      2      2    131     10     32      5
49     41      2     56     83
[136]      2     11     77     75     20      5     33     95     57      4
7     24     57     27     19
[151]     55      2      4    693     15      2      3     12     19      8
4    108     72     12      5
[166]      2
> my_otu_table <- otu_table[order(names(otu_table))]
Error in order(names(otu_table)) : argument 1 is not a vector
> my_otu_table <-data.frame(t(my_otu_table))
Error in t(my_otu_table) : object 'my_otu_table' not found'


text:
Q: OpenSSL PHP extension not loaded despite uncommenting it in php.ini I removed the (;) before extension=php_openssl.dll in the php.ini file. I verified that textension_dir = "ext" and I checked that openssl is already there.
When I ran "php -m" it showed me that openssl as one of the loaded modules but this test returns the error (extension_loaded = false)
 if (!extension_loaded('openssl')){
        Errors::$errors[] = array(
            'title' => "OpenSSL Extension not loaded",
            'message' => "Laravel requires OpenSSL PHP Extension"
        );}

in c:/windows there is no php.ini file


text:
Q: object instance's properties crushed by another instance I am kind of new to node.js/javascript, and come from C# world : probably my problem is about transposing C# habits to javascript...
I created a small node.js app to reproduce the problem I run into.
In the app, two 'Kid' are created. Each of them graps a balloon, and makes it bounce with more or less power (parameter). When the balloon stops boucing, we get a log from an event fired..
The problem I have is that the first instanciated kid seems to be crushed by the last one. The crush seems to happen on a call to the 'bounce' function.
Here is the log sequence i am expecting:

*

*Mike arrived in the garden. The kid wants to play with a balloon....

*Elia arrived in the garden. The kid wants to play with a balloon....

*Ensure that Mike's name is Mike...

*Ensure that Elia's name is Elia...

*Mike just got a balloon and wrote his/her name on it !

*Mike makes the balloon bounce (force 10) !

*Elia just got a balloon and wrote his/her name on it !

*Elia makes the balloon bounce (force 4) !

*Elia's balloon has stopped bouncing... The name written on it is Elia.

  10.Mike's balloon has stopped bouncing... The name written on it is Mike.

Here is the log sequence i get:

*

*Mike arrived in the garden. The kid wants to play with a balloon....

*Elia arrived in the garden. The kid wants to play with a balloon....

*Ensure that Mike's name is Mike...

*Ensure that Elia's name is Elia...

*Elia just got a balloon and wrote his/her name on it !

*Elia makes the balloon bounce (force 10) !

*Elia just got a balloon and wrote his/her name on it !

*Elia makes the balloon bounce (force 4) !

*Elia's balloon has stopped bouncing... The name written on it is Elia.

  10.Elia's balloon has stopped bouncing... The name written on it is Elia.

The three files composing the app.
app.js
const Kid = require('./kid.js');

var mike = new Kid('Mike');
var elia = new Kid('Elia');

console.log(`Ensure that Mike's name is ${mike.name}...`);
console.log(`Ensure that Elia's name is ${elia.name}...`);

mike.bounce(10);
elia.bounce(4);

kid.js
const Balloon = require('./balloon.js');
var self;

function Kid(name){
    self=this;
    this.name=name;

    console.log(`${this.name} arrived in the garden. The kid wants to play with a balloon....`);
}

Kid.prototype.bounce = function(force1To10) {
    var balloon = new Balloon(self.name);
    balloon.bounce(force1To10);
    balloon.on('balloonStopped',(kidnameWrittenOnIt)=>{
        console.log(`${self.name}'s balloon has stopped bouncing... The name written on it is ${kidnameWrittenOnIt}.`);
    });
};

module.exports=Kid;

balloon.js
const timers = require("timers");
var inherits = require('util').inherits;
var EventEmitter = require('events').EventEmitter;
var self;

function Balloon(kidName) {
    self = this;
    this.kidName = kidName;

    this.bounce = function(kidsPower1To10){
        console.log(`${self.kidName} makes the balloon bounce (force ${kidsPower1To10}) !`);
        timers.setTimeout(() => {
            self.emit('balloonStopped',self.kidName);
        }, kidsPower1To10*1000);
    }

    console.log(`${this.kidName} just got a balloon and wrote his/her name on it !`);
}

inherits(Balloon, EventEmitter);
module.exports = Balloon;

To execute:
node app.js

Thanks by advance for any useful information !

A: Indeed the problem is in the bounce method. You reference a global self variable which will reference the second person. So if you call bounce on the first person, it will still reference the second in there.
The solution is to use this directly instead of self, or to define self in each method:
function Kid(name){
    this.name=name;

    console.log(`${this.name} arrived in the garden. The kid wants to play with a balloon....`);
}

Kid.prototype.bounce = function(force1To10) {
    var balloon = new Balloon(this.name);
    balloon.bounce(force1To10);
    balloon.on('balloonStopped',(kidnameWrittenOnIt)=>{
        console.log(`${this.name}'s balloon has stopped bouncing... The name written on it is ${kidnameWrittenOnIt}.`);
    });
};

Now you still have to take care that when you reference the bounce method, you make sure this is correctly bound. This will be the case when you do call mike.bounce(10) or elia.bounce(2), but there are pitfalls when you start assigning the bounce method to another variable and call that other variable. In that case this will be undefined.
Class notation
You can also code the above with the class syntax:
class Kid {
    constructor(name) {
        this.name=name;
        console.log(`${this.name} arrived in the garden. The kid wants to play with a balloon....`);
    }
    bounce(force1To10) {
        var balloon = new Balloon(this.name);
        balloon.bounce(force1To10);
        balloon.on('balloonStopped',(kidnameWrittenOnIt)=>{
            console.log(`${this.name}'s balloon has stopped bouncing... The name written on it is ${kidnameWrittenOnIt}.`);
        });
    }
}


text:
Q: Finite Cyclic group isomorphic to C
If $G$ is a cyclic group and $|G|=n$ ($n\in \Bbb Z_{\ge 1}$), then $G\cong C_n$.

Why does this statement not hold in both directions, i.e an if and only if statement?

A: That statement (very obviously) holds in both directions. Sometimes, when the converse is glaringly obvious, the 'only if' is not written.


text:
Q: Get Bokeh dropdown value without interaction Below is the code for a small working example of a Bokeh dashboard.
When you make a selection in the first dropdown menu, the second one is updated dynamically and the chart is updated with a new source. This works for options A1/A2 because the data arrays are the same length.
Once you select option B1 in the first dropdown, the second dropdown changes to B2.
But the source update doesn't happen because you cant get the Yselector.value.
How can you retrieve the Yselector.value without using Bokeh's on_change method and pass it to a function like source_selector?
import numpy as np
import pandas as pd
from bokeh.models import ColumnDataSource
from bokeh.models.widgets import Tabs, Select
from bokeh.layouts import column, row, Spacer
from bokeh.io import curdoc
from bokeh.plotting import figure, curdoc, show

#Plotting points on initial chart.
df_AB = pd.DataFrame(np.random.randint(0,100,size=(500, 2)), columns=list('XY'), index=[str(i) for i in range(1,500+1)])
pointchart=figure(plot_width=800, plot_height=700, tools=['lasso_select','box_select','wheel_zoom'],title="Point scatter")
pointchart_source= ColumnDataSource(df_AB[["X","Y"]])
pointchart.circle("X","Y",source=pointchart_source)

#Dropdown X
selectoroptions=['','Series A1', 'Series A2','Series B1','Series B2']
Xselector = Select(title="Dropdown X:", value="", options=selectoroptions)

#Dropdown Y
selectoroptions=['','Series A1', 'Series A2','Series B1','Series B2']
Yselector = Select(title="Dropdown Y:", value="", options=selectoroptions)

#Will list multiple sources to feed the chart based on dropdown selection.
def source_selector(selection):
    if selection=='Series A1':
        newvalues= pd.Series(list(np.random.randint(100, size=500)),name="")
    elif selection=='Series A2':
        newvalues= pd.Series(list(np.random.randint(200, size=500)),name="")
    elif selection=='Series B1':
        newvalues= pd.Series(list(np.random.randint(20, size=20)),name="")
    elif selection=='Series B2':
        newvalues= pd.Series(list(np.random.randint(10, size=20)),name="")
    return newvalues

#Once dropdown X seelction is made, the options of dropdown Y will dynamically change.
#Data used for X axis is updated.
def X_switch_selection_and_source(attr, old, new):
    if new == '':
        pointchart_source.data = ColumnDataSource(df_AB[["X","Y"]]).data

    #Other dropdown changed dynamically
    elif new=='Series A1':
        Yselector.options=['Series A2']

    elif new=='Series A2':
        Yselector.options=['Series A1']

    elif new=='Series B1':
        Yselector.options=['Series B2']

    elif new=='Series B2':
        Yselector.options=['Series B1']

    #Updating source based on this dropdown's selection/ X values.
    new_x_values=source_selector(new)

    #Issue is right here. This line will only work if y is the same length as new x.
    new_y_values=list(pointchart_source.data["Y"])

    #If the lenghths are different I want to update the source for y by getting the y dropdown value.
    if len(new_x_values)!= len(new_y_values):
        new_y_values=source_selector(Yselector.value) # Does not get the dynamically changed value in the Y dropdown.

    sourcedf=pd.DataFrame({"X":new_x_values,"Y":new_y_values})
    pointchart_source.data=  ColumnDataSource(sourcedf).data

Xselector.on_change("value", X_switch_selection_and_source)

#Show
layout=row(column(Xselector,Yselector, Spacer(width=400, height=500)),pointchart)
curdoc().add_root(layout)
!powershell -command {'bokeh serve --show Bokeh_dropdown_helped_v2.ipynb'}

My goal is for the user to be able to make selections from the dropdowns and for the other dropdown to show only the appropriate selections based on the first selection.
The data used for the axis' will be updated based on the selections.
Thank you for any advice.

A: Change the Select widget values instead of its options. If you change the options, you must make sure that its value is one of the options.
elif new=='Series A1':
    Yselector.value='Series A2'

elif new=='Series A2':
    Yselector.value='Series A1'

elif new=='Series B1':
    Yselector.value='Series B2'

elif new=='Series B2':
    Yselector.value='Series B1'


text:
Q: How do I get an extension to open automatically as soon as a new tab is opened? Here's the code to the popup.jsx file and the background index.js file. For starters, I'm just working with a simple alert. the way I've gone with the working is that the background makes note of any new tabs using chrome.tabs.onCreated() and sends a message to the popup once so,
the issue I feel I'm facing is that the popup isnt receiving the message sent by the background file. please help out if you can, this is the link to the Github repo.https://github.com/Brihadeeshrk/extension
popup.jsx
chrome.runtime.onMessage.addListener((req) => {
    console.log("message: "+req.message)
    if(req.type === 'newTabCreated') {
      alert("new tab")
    }
    return true
  })

background.js
chrome.tabs.onCreated.addListener(function() {
    console.log('new tab created')
    chrome.runtime.sendMessage({
        type: "newTabCreated",
        message: "new tab created121"
    }, function() {
        console.log("message sent")
    })
})


text:
Q: " multiple active partitions " ERROR I am trying to install ubuntu 11.10 from a bootable usb but when i boot from usb the " multiple active partitions " error show up and automatically boots in windows 7. PLEASE HELP! Thank you.

A: write image with last version of ultraiso. i had this problem with every ubuntu release. unetbootin didn't help, only the latest versions of ultraiso at the moment.


text:
Q: Determining Complex Functions If we have some $h:\mathbb{C}\rightarrow \mathbb{C},$ such that h is defined to be $h(z)= x^3y^2+ix^2y^3, \text{where} \space z=x+iy,$ find all set of complex numbers where $h $ is differentiable.
So what I have done so far was to check using Cauchy - Riemann equations, and for the second part of the Cauchy - Riemann, when I checked $u_y=-v_x,$ this holds iff $x=0$, or $y =0.$ Then does this mean that it works for all complex numbers having $x=0, \text{or}\space  y = 0? $ I would appreciate the help, with this problem.

A: Yes. Since the functions $u_x$, $u_y$, $v_x$, and $v_y$ are continuous, $h$ is differentiable at those points which are solution of the Cauchy-Riemann equations and only at those points. So, $h'(z)$ exists if and only if $\operatorname{Re}z=0$ or $\operatorname{Im}z=0$.


text:
Q: Disabling an element in selenium webdriver I am trying to count the number of rows in an HTML table using Selenium webdriver (Java.). The functionality is as below:
Text is iteratively entered into a search box from CSV file. Once, first text is entered and search results are displayed in HTML table, I have to count the rows in that HTML table.
The issue I am facing is that for every search text, the count of number of rows in HTML table displays same. I suspect that the rows are counted before the HTML table is refreshed for every search text and hence the count remains the same as the first text every time.
I guess the HTML table should be refreshed every time new text is entered in search box and then rows in table should be counted.
Can anyone suggest the possible solution to this issue?
Can I temporarily disable the HTML element of webpage till the new text from CSV file is entered?

A: As you cannot post your code
There is was a way but i am not how feasible it is for your problem
this can be achieved using java script
you can disable any element Using java script
Refer this for disabling
http://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_select_disabled2
1) using javascript executor you can execute it in selenium.
If  First method is failing to do so
try
2)Execute your javascript first then run your selenium code means make your selenium method depends on the javascript method.
Let me know if this works out.


text:
Q: Accessing docker containers by hostname when running through Vagrant on Windows I am running docker on Ubuntu system within Vagrant VM (VirtualBox) on Windows 7. Everything is working fine, I am successfully setting up several containers through docker-compose. Containers can reach themselves by logical hostnames mapping service names from docker-compose file.
Is there any way to be able to reach containers by those logical hostnames not only from within containers themselves, but also from:

*

*host running docker daemon

*Vagrant's VM host (my windows running all of this)

In this way I wouldn't have to maintain separate configs for the app executed directly from top-level windows host and target container-inteded config.
In short: 'ping mongo' reaches the host only when run from inside docker container. I would love to set it up so it would work from the ubuntu host and top-level windows host...
My Vagrantfile:
# -*- mode: ruby -*-
# vi: set ft=ruby :

Vagrant.configure(2) do |config|
  config.vm.box = "ubuntu/trusty64"
  if (/cygwin|mswin|mingw|bccwin|wince|emx/ =~ RUBY_PLATFORM) != nil
    config.vm.synced_folder ".", "/vagrant", mount_options: ["dmode=700,fmode=600"]
    # find out a way to move this to environment variables...
    # this is to speed up maven builds on vagrant box by reusing host maven repository
    config.vm.synced_folder "c:\\Users\\woci\\.m2\\repository ", "/home/vagrant/.m2/repository", mount_options: ["dmode=700,fmode=600"]
    # to provide access to configuration
    config.vm.synced_folder "d:\\data\\dev\\pro\\pro-lab\\pro-lab-config", "/pro_config", mount_options: ["dmode=700,fmode=600"]
  end
#  else
#    config.vm.synced_folder ".", "/vagrant"
#    config.vm.synced_folder "c:\\Users\\woci\\.m2\\repository ", "/extrepo"
#  end
  config.vm.provider "virtualbox" do |v|
    v.memory = 4096
  end
  config.vm.define :dev do |dev|
    dev.vm.network "private_network", ip: "10.100.198.200"
    dev.vm.provision :shell, path: "bootstrap.sh"
    dev.vm.provision :shell,
      inline: 'PYTHONUNBUFFERED=1 ansible-playbook \
        /vagrant/ansible/dev.yml -c local'
  end
  if Vagrant.has_plugin?("vagrant-cachier")
    config.cache.scope = :box
  end
end

docker-compose.yml
services:

  configserver:
    build: ./config-server
    image: pro-lab/config-server
    volumes:
      - /pro_config:/config
    ports:
      - "8888:8888"

  attachment-manager:
    build: ./attachment-manager
    image: pro-lab/attachment-manager
    ports:
      - "8080:8080"

  mongo:
    image: mongo
    ports:
      - "27017:27017"

  redis:
    image: redis
    ports:
      - "6379:6379"

  datadog:
    image: datadog/docker-dd-agent:latest
    environment:
      API_KEY: ...
    volumes:
      - /var/run/docker.sock:/var/run/docker.sock
      - /proc/:/host/proc/:ro
      - /sys/fs/cgroup/:/host/sys/fs/cgroup:ro
      - /vagrant/docker/dd-agent/conf/:/conf.d/:ro
      - /vagrant/:/vagrant/


text:
Q: Convergence functions Let X be a nonempty set. I define a  convergence function on X to be a partial function from the set of all sequences in X, to X, that satisfies the five additional conditions:

*

*Every constant sequence is assigned that constant.

*If a sequence converges, so does any sequence obtained from altering, inserting, or deleting finitely many terms, and to the same value.

*If a sequence converges, every subsequence converges to the same value.

*If two sequences have the same convergence value, any weave of them also converges to the same value

*This is the most complicated property. Let $(a_m)_n$ be a double sequence where every $(a_m)$ converges. And suppose the resulting sequence of convergence values also converges, say to $L$. Then there is a sequence, where the $n$-th element is in the $n$-th sequence, that converges to $L$.

The question I am trying to find out, as an independent scholar, is this: Does every convergence function on a set induce a topology such that every sequence that converges in the topological sense to a value $L$, also converges under $f$ to $L$? I have tried proving it, but I am completely stuck. Any help would be much appreciated.

A: Yes.
A set $H$ will be closed iff it is closed under taking limit (of sequences within $H$). All you have to prove that any intersection and any finite union of closed sets is again closed.
Then define the open sets as complements of closed sets.

Note that the topology obtained this way is $T_1$: one point sets are closed by criterium 1.
Now if $x_n$ converges to $L$ according to our limit function $f$, and $U\ni L$ is any open set, then its complement, $U^\complement$ is closed, but cannot contain an infinite subsequence of $x_n$ as it doesn't contain $L$ but is closed under limit.
On the other hand, if $x_n$ converges to $L$ in the topology, then -eliminating constant subsequences- we can reduce it to the case when $x_n\ne L$ for all $n$.

Then consider $G:=\{x_n\,\mid\, n\in\Bbb N\}$. We claim that $G$ is not closed: its complement contains $L$ and if that were open, that would contain some $x_n$ because of the definition of limit.
So, by definition of the topology, $G$ is not closed under limit, moreover by the same reasoning, $L$ must be in the closure of $G$, i.e. there is at least a subsequence $(x_{n_k})_k$ that converge to $L$, according to $f$.
Now cut the original sequence $(x_n)$ into ${\bf A}_0:=(x_{n_k})_k$ and the rest, say $(x_{m_k})_k$ (So that $\{n_k\mid k\in\Bbb N\}\,\cup\,\{m_k\mid k\in\Bbb N\}\,=\,\Bbb N$, and repeat all with $(x_{m_k})_k$ which still converges to $L$ in topology. This yields a next subsequence ${\bf A}_1$ which already converges to $L$ according to $f$. Repeat it until all elements $x_n$ are used up (either for finite or infinite many times), then apply condition 4. or 5.


text:
Q: CSS class under # selector I am trying to apply a style to a specific item of a CSS menu.  The CSS menu has a

So all of the items in the .css file are #cssmenu li ul { etc.  However, I want to apply a style to the headers of the menu, so I am trying to add:

Menu Header

When I try to add styles to my .css using .header class, the styles do not appear to be being applied.  Do I need to be nesting the class CSS, like #cssmenu .header or something?
EDIT:
Here is the CSS:
#cssmenu {
    background-color: #FFFFCC;
    clear: both;
    display: inline;
    float: left;
    list-style: none;
    overflow: hidden;
    text-align: center;
    text-transform: uppercase;
    width: 100%;
}
#cssmenu li {
    display: inline-block;
}
#cssmenu li a {
    display: inline-block;
}
#cssmenu li ul {
    /*margin-top: 0px; submenu location relative to bottom of parent */
    display: none;
}
#cssmenu li:hover ul {
    display: block;
    position: absolute;
}
#cssmenu li ul li a {
    width: 200px;
}
#cssmenu li:hover > a {
    background: #99CC99; /* parent background when hovering over child */
/* shadow around parent when hover */
    box-shadow: 5px 5px 25px #000;
    -moz-box-shadow: 5px 5px 25px #000;
    -webkit-box-shadow: 5px 5px 25px #000;

    /*border-radius: 10px;
    -moz-border-radius: 10px;
    -webkit-border-radius: 10px;*/
}
#cssmenu li a {
    color: #000;
    font-weight: bold;
    text-decoration: none;
    padding: 12px;
}
#cssmenu li a:hover {
    background-color: #99CC99;
    padding: 12px 12px 11px 12px; /* link background when hover over link */
}
#cssmenu li ul {
    background: rgba(255,255,255,0.9); /* child menu background w/ transparency */
    padding: 10px 5px;

    box-shadow: 5px 5px 25px #BBB;
    -moz-box-shadow: 5px 5px 25px #BBB;
    -webkit-box-shadow: 5px 5px 25px #BBB;

    border-radius: 0px 15px 15px 15px;
    -moz-border-radius: 0px 15px 15px 15px;
    -webkit-border-radius: 0px 5px 5px 5px;
}
/* display sub-menu as list */
#cssmenu li ul li {
    display: block;
    text-align: left;
}
#cssmenu li ul li a, #nav li ul li a:hover {
    background: transparent;
    color: #000;
    width: 180px;
    font-size: 0.95em;
    font-weight: normal;
}
#cssmenu li ul li a:hover {
    /*text-decoration: underline;*/
    box-shadow: none;
    -moz-box-shadow: none;
    -webkit-box-shadow: none;
    border-radius: 0;
    -moz-border-radius: 0;
    -webkit-border-radius: 0;
}
#cssmenu .menuheader {
    color: #bbb;
}

And the HTML:

Store

Essential Oil Blends

      ....

.....

A: #cssmenu .header should work.
Check this example I created: http://jsfiddle.net/74JQQ/2/
Here is a simple reference regarding CSS selectors:
# is used for id's while . is for classes (which you already know).
A space between selections mean you are looking at all descendant elements.
A > symbol means you are looking only at direct children elements.
Example:

Header1

Header2

    Footer

#cssmenu .header will select the two

.header will select the two

#cssmenu > .header will not select anything since there is no element with the class "header" that is a direct child of #cssmenu.
#cssmenu a will select all 3  elements.
#cssmenu > a will only select the last  element (which reads Footer).

A: Maybe this works
#cssmenu:nth-child(1){
/* Here the style you want to add */
}

As it should give to the first child of the element with id="cssmenu" the style you define.


text:
Q: Unable to resolve service for type xxx.'Infrastructure' while attempting to activate 'xxx.Infrastructure.TagRepository' I am getting the below error. I am using .Net Core web API.

An unhandled exception occurred while processing the request.
  InvalidOperationException: Unable to resolve service for type 'xxx.Infrastructure.Data.xxxContext' while attempting to activate 'xxx.Infrastructure.Repository.TagRepository'.

Api Controller
namespace xxx.API.Controllers
{
    [Route("api/Default")]
    [ApiController]
    public class DefaultController:ControllerBase
    {
         private ITagRepository _tagRepository;
        public DefaultController(ITagRepository tagRepository)
    {
         _tagRepository = tagRepository;
    }

    [HttpGet]
    public string GetAllUserInfo()
    {
        try
        {
            var Tags = _tagRepository.GetAllTagsByInstanceId("");
            if (Tags == null)
            {
                Tags = new List<TagEntity>();
            }
            return Tags.ToString();
        }
        catch (Exception ex)
        {
            return null;
        }
    }
}

Startup.cs
public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    // This method gets called by the runtime. Use this method to add services to the container.
    public void ConfigureServices(IServiceCollection services)
    {
        services.AddMvc().AddControllersAsServices();
        services.AddSingleton<ModulePermissionHelper>();
        services.AddScoped<ITagRepository, TagRepository>();
        services.AddScoped<ITagModuleRepository, TagModuleRepository>();
    }

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseHsts();
        }

        app.UseHttpsRedirection();
        app.UseMvc();
    }
}

ITagRepository
public interface ITagRepository
{
    List<TagEntity> GetAllTagsByInstanceId(string instanceId);
}

A: Based on the exception message and the shown startup, the DI container is unaware of the required dependency in order to properly activate the desired type.
You need to register the DbContext with its associated configurations during startup
public void ConfigureServices(IServiceCollection services) {
    services.AddMvc().AddControllersAsServices();
    services.AddSingleton<ModulePermissionHelper>();
    services.AddScoped<ITagRepository, TagRepository>();
    services.AddScoped<ITagModuleRepository, TagModuleRepository>();

    //..
    services.AddDbContext<xxxContext>(options => ...);
}

Documentation: Using DbContext with dependency injection


text:
Q: MBP: would 4k external display work as retina when resolution scaled to 1080p? I'm looking to buy an external display but can't wrap my head around one thing: does 4k monitor behaves like retina (in other fonts looks sharper, etc.) if scaled to smaller resolution e.g. 1080p?
Or would it just work like a regular 1080p display?
Sorry if that sounds awkward. My concern if there is a visual difference between 4k with 1080p vs 1080p with 1080p resolution.

A: On macOS you have both choices when connecting such a 4k monitor:
You can choose to have it run at a real 1080p resolution, where the signal sent to the monitor is really 1080p. In essence the image displayed on the 4k monitor would then be visually the same as had you bought a 1080p monitor of the same physical size.
You can also choose (which is most probably what you want) to have it run scaled to "Looks like 1080p". This means that the signal sent to the monitor is really a 4k signal, but user interface elements are scaled to be the same physical size as if you had been running 1080p. This ensures that the system is usable without requiring extraordinarily good eye sight. Note that this means that text is really drawn at the large resolution, which ensures crisp and sharp text, which is easier to read. Images and video are also displayed at a larger resolution (if available), which means you get better picture quality on the 4k monitor compared to a 1080p monitor.
In addition to the two scenarios outlined in your question and above, you also have the third option of running the monitor in a 4k non-scaled resolution. This means that you'll have a very large amount of screen real estate (i.e. room for lots of windows, content, etc.) - but everything will be 4 times smaller physical size - so this is usually only a good choice if you buy a really large monitor (like for example when using a 50 inch TV as a monitor).

A: A 4K display scaling to 1K would display each 1K 'logical' pixel using a 2x2 'real' pixel block. So it will look like a 1K display, possibly with slightly more noticeable pixels.
Apple's Retina system works similarly, except that each pixel in that block can be different. This gives you the scaling of objects at a more comfortable "1K" size, but with the higher definition of 4K.
If you buy a 4K display, any Mac can use it as a 'Retina' display, as the scaling is done on the computer. I don't think it should affect your purchase decision.


text:
Q: Using `process.emit('info')` as opposed to `process.emit('warning')` It appears to be common practice for libraries to use
const err = new Error('some warning');
process.emit('warning', err);

so that the user-land library can log the error or handle the error, their way.
However, I am wondering, is there a convention for handling info level messages instead of warning level messages.
Might it be
process.emit('message',msg) // no that's reserved for IPC messages

what about
process.emit('info', msg);

anybody know?


text:
Q: d3js How to make Grids as `dotted` or `dashed`? I have made a simple line chart. I have added the grids to the axis but I would like to keep them as dotted or dashed so how can I do that?

 var margin = {top: 20, right: 100, bottom: 30, left: 100},
    width = 960 - margin.left - margin.right,
    height = 500 - margin.top - margin.bottom;

var dataset = [
  {x: 0, y: 5},
  {x: 1, y: 8},
  {x: 2, y: 13},
  {x: 3, y: 12},
  {x: 4, y: 16},
  {x: 5, y: 21},
  {x: 6, y: 18},
  {x: 7, y: 23},
  {x: 8, y: 24},
  {x: 9, y: 28},
  {x: 10, y: 35},
  {x: 11, y: 30},
  {x: 12, y: 32},
  {x: 13, y: 36},
  {x: 14, y: 40},
  {x: 15, y: 38},
];

var xScale = d3.scale.linear()
    .domain([0, d3.max(dataset, function(d){ return d.x; })])
    .range([0, width]);

var yScale = d3.scale.linear()
    .domain([0, d3.max(dataset, function(d){ return d.y; })])
    .range([height, 0]);

var xAxis = d3.svg.axis()
    .scale(xScale)
    .orient("bottom")
    .innerTickSize(-height)
    .outerTickSize(0)
    .tickPadding(10);

var yAxis = d3.svg.axis()
    .scale(yScale)
    .orient("left")
    .innerTickSize(-width)
    .outerTickSize(0)
    .tickPadding(10);

var line = d3.svg.line()
    .x(function(d) { return xScale(d.x); })
    .y(function(d) { return yScale(d.y); });

var svg = d3.select("body").append("svg")
    .attr("width", width + margin.left + margin.right)
    .attr("height", height + margin.top + margin.bottom)
  .append("g")
    .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

  svg.append("g")
      .attr("class", "x axis")
      .attr("transform", "translate(0," + height + ")")
      .call(xAxis)

  svg.append("g")
      .attr("class", "y axis")
      .call(yAxis)

  svg.append("path")
      .data([dataset])
      .attr("class", "line")
      .attr("d", line);
.axis path,
  .axis line{
    fill: none;
    stroke: black;
  }

  .line{
    fill: none;
    stroke: blue;
    stroke-width: 2px;
  }

  .tick text{
    font-size: 12px;
  }

  .tick line{
    opacity: 0.2;
  }
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>

A: You can use a property of the svg elements called stroke-dasharray.
Each time you have to set an style, use the .style() method
svg.append("path")
  .data([dataset])
  .attr("class", "line")
  .style("stroke-dasharray", "5 5")
  .attr("d", line);

It applies also for the axis
svg.append("g")
  .attr("class", "x axis")
  .attr("transform", "translate(0," + height + ")")
  .style("stroke-dasharray", "5 5")
  .call(xAxis)

svg.append("g")
  .attr("class", "y axis")
  .call(yAxis)
  .style("stroke-dasharray", "5 5")

Look here to see more properties or this jsFiddle
If you want to set only for the internal grid, then you can do it using pure css
.tick line{
    opacity: 0.2;
    stroke-dasharray: 5 5;
}

A: Set it using CSS and only apply it to line elements that are children of tick classed g:
.tick line{
  opacity: 0.2;
  stroke-dasharray: 5,5;
}

Example:

 var margin = {top: 20, right: 100, bottom: 30, left: 100},
    width = 960 - margin.left - margin.right,
    height = 500 - margin.top - margin.bottom;

var dataset = [
  {x: 0, y: 5},
  {x: 1, y: 8},
  {x: 2, y: 13},
  {x: 3, y: 12},
  {x: 4, y: 16},
  {x: 5, y: 21},
  {x: 6, y: 18},
  {x: 7, y: 23},
  {x: 8, y: 24},
  {x: 9, y: 28},
  {x: 10, y: 35},
  {x: 11, y: 30},
  {x: 12, y: 32},
  {x: 13, y: 36},
  {x: 14, y: 40},
  {x: 15, y: 38},
];

var xScale = d3.scale.linear()
    .domain([0, d3.max(dataset, function(d){ return d.x; })])
    .range([0, width]);

var yScale = d3.scale.linear()
    .domain([0, d3.max(dataset, function(d){ return d.y; })])
    .range([height, 0]);

var xAxis = d3.svg.axis()
    .scale(xScale)
    .orient("bottom")
    .innerTickSize(-height)
    .outerTickSize(0)
    .tickPadding(10);

var yAxis = d3.svg.axis()
    .scale(yScale)
    .orient("left")
    .innerTickSize(-width)
    .outerTickSize(0)
    .tickPadding(10);

var line = d3.svg.line()
    .x(function(d) { return xScale(d.x); })
    .y(function(d) { return yScale(d.y); });

var svg = d3.select("body").append("svg")
    .attr("width", width + margin.left + margin.right)
    .attr("height", height + margin.top + margin.bottom)
  .append("g")
    .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

  svg.append("g")
      .attr("class", "x axis")
      .attr("transform", "translate(0," + height + ")")
      .call(xAxis)

  svg.append("g")
      .attr("class", "y axis")
      .call(yAxis)

  svg.append("path")
      .data([dataset])
      .attr("class", "line")
      .attr("d", line);
.axis path,
  .axis line{
    fill: none;
    stroke: black;
  }

  .line{
    fill: none;
    stroke: blue;
    stroke-width: 2px;
  }

  .tick text{
    font-size: 12px;
  }

  .tick line{
    opacity: 0.2;
    stroke-dasharray: 5,5;
  }

<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>


text:
Q: Limit data in Flask Restless how can I limit amout of rows/objects returning by calling an endpoint?
http://localhost:8111/api/food_order?q={"filters":
[{"name":"user_id","op":"==","val":1188},
{"name":"date","op":">","val":"2018-05-01"}]}

I need only last 6 rows from this query. Thanks

A: well I figured that out. Hope that will help some1 :D
http://localhost:8111/api/food_order?q={"limit":6,"filters":
[{"name":"user_id","op":"==","val":1188},
{"name":"date","op":">","val":"2018-05-01"}]}

so its  simply "limit": 6  inside q param


text:
Q: Flutter Pageview swipe change background image with animation I working on a project where I have a Stack widget with a Container which has an image(this is the background of the app):
//Background image:
          Container(
            decoration: BoxDecoration(
              image: DecorationImage(
                image: AssetImage(background),
                fit: BoxFit.fill,
              ),
            ),
          ),

and a PageView widget that contains the page of the app.
How do I do that when the widget changes page, then the AssetImage(background) change the image with a faded animation?
Currently in the PageViews widget onPageChanged section I can change the background with multiple setStates:
onPageChanged: (index) {
              if (index == 0) {
                setState(() {
                  pageName = "Home";
                  background =
                      "lib/assets/Backgrounds/gradient_background_6.jpg";
                });
              } else if (index == 1) {
                setState(() {
                  pageName = "Coupons";
                  background =
                      "lib/assets/Backgrounds/gradient_background_5.jpg";
                });
              } else if (index == 2) {
                setState(() {
                  pageName = "Forum";
                  background =
                      "lib/assets/Backgrounds/gradient_background_4.jpg";
                });
              }
            },

but with this solution the background image just change without any animation. What is the best why to change image with faded, or any other animation?

A: use AnimatedOpacity for fade effect on background image, also you can fast or slow fade control with duration properties i already use in it
Output:-

Code:-
import 'package:flutter/material.dart';

class PageViewExample extends StatefulWidget {
  const PageViewExample({Key? key}) : super(key: key);

  @override
  State<PageViewExample> createState() => _PageViewExampleState();
}

class _PageViewExampleState extends State<PageViewExample>
    with SingleTickerProviderStateMixin {
  int currentIndex = 0;
  String background = "https://picsum.photos/id/237/200/300";

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: PageView.builder(
        onPageChanged: (index) => setState(() {
          currentIndex = index;
          currentIndex == 1
              ? background = "https://picsum.photos/id/238/200/300"
              : currentIndex == 2
                  ? background = "https://picsum.photos/id/239/200/300"
                  : background = "https://picsum.photos/id/237/200/300";
        }),
        physics: const ClampingScrollPhysics(),
        itemCount: 3,
        itemBuilder: (context, index) {
          return AnimatedOpacity(
            duration: const Duration(seconds: 2),
            opacity: currentIndex == index ? 1.0 : 0.1,
            child: Container(
              decoration: BoxDecoration(
                image: DecorationImage(
                  image: NetworkImage(background),
                  fit: BoxFit.fill,
                ),
              ),
            ),
          );
        },
      ),
    );
  }
}

A: Maybe you can use SwitchAnimation, but you need a key you can use the index like a "key" this is a example
import 'package:flutter/material.dart';

class Examp extends StatelessWidget {
  const Examp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body:
       AnimatedSwitcher(
        key: index,
        duration: const Duration(milliseconds: 700),
        child: Container(
            decoration: BoxDecoration(
              image: DecorationImage(
                image: AssetImage(background),
                fit: BoxFit.fill,
              ),
            ),
          ),

        ),
    );
  }
}

Tell if this code worked for you


text:
Q: Is it possible to find cloudfront distributions from Origin via AWS CLI? I've multiple Cloudfront distributions pointing to a single S3 Bucket to create different URLs. Now when I deploy it is difficult to clear cache of all the buckets manually one by one. So I thought there should be an option from where I can find all the ids and clear the cache but all I could find was
aws cloudfront  get-distribution-config
--id <value>
[--cli-input-json <value>]
[--generate-cli-skeleton <value>]

Where id takes the id of cloudfront distribution itself which I want to find out.
I can't use this as well as I don't want to clear cache of all the distributions
aws cloudfront list-distributions
[--max-items <value>]
[--cli-input-json <value>]
[--starting-token <value>]
[--page-size <value>]
[--generate-cli-skeleton <value>]

I'm trying to find something like but so far this doesn't seem to be the right approach
aws cloudfront --origing <value>

A: You can use the query argument to fetch only Ids
aws cloudfront list-distributions --query "DistributionList.Items[*].Origins.Items[*].Id" --output text

S3-test1.example.com
S3-Website-test2.example.com.s3-website-us-west-1.amazonaws.com

then you can filter the list using grep
aws cloudfront list-distributions --query "DistributionList.Items[*].Origins.Items[*].Id" --output text | grep test2

S3-test1.example.com

You can return multiple values using query argument
aws cloudfront list-distributions --query "DistributionList.Items[*].Origins.Items[*].{id:Id,name:DomainName}" --output text

S3-test1.example.com  test1.example.com.s3.amazonaws.com
S3-Website-test2.example.com.s3-website-us-west-1.amazonaws.com test2.example.com.s3-website-us-west-1.amazonaws.com

A: https://stackoverflow.com/a/64264887/5773416
While this solution is not exactly what I wanted it helped me to find the exact answer. I'm posting my answer which finally helped me achieve this.
aws cloudfront list-distributions --query "DistributionList.Items[*].{id:Id,origin:Origins.Items[0].Id}[?origin=='S3-BUCKET_NAME'].id" --output text

Which will give a result like this
EXXXXXXXXXXX1 EXXXXXXXXXXX2

and in order to clear the cache of multiple distributions
for id in $(aws cloudfront list-distributions --query "DistributionList.Items[*].{id:Id,origin:Origins.Items[0].Id}[?origin=='S3-BUCKET_NAME'].id" --output text);do aws cloudfront create-invalidation --distribution-id $id --paths "/*";done;

A: You can get a list of CloudFront distributions id's, domain, certificate source, and origin using this python script
#!/usr/bin/env python
import boto3
cf = boto3.client('cloudfront') # Create CloudFront client
print("\nCloudFront Distributions:\n")  # List distributions
distributions=cf.list_distributions()
if distributions['DistributionList']['Quantity'] > 0:
  for distribution in distributions['DistributionList']['Items']:
    print("Domain: " + distribution['DomainName'])
    print("Distribution Id: " + distribution['Id'])
    print("Certificate Source: " + distribution['ViewerCertificate']['CertificateSource'])
    for name in distribution['Origins']['Items']:
        print ("origin:" + name['DomainName'])
    if (distribution['ViewerCertificate']['CertificateSource'] == "acm"):
      print("Certificate: " + distribution['ViewerCertificate']['Certificate'])
    print("")
else:
  print("Error - No CloudFront Distributions Detected.")

A: While Ritik Patni's answer was closest to what I needed, I had interpreted the following to mean that I could substitute the bucket name and filter out the CF distribution I was looking for:
[?origin=='S3-BUCKET_NAME']

I did not find this to be the case, as when I created the resource in TF, I used a different name than the bucket name to distinguish between variables. In my case, Origins.Items[0].Id was staticsite_s3_bucket, which differed from the name of the s3 bucket, dev-it-static-site-mvp. So an empty-set was returned.
I was doing this inside of Jenkins, and had a little difficulty with the console output looking like it was misinterpreting quotes, so I'm posting the sh script taken out of the pipeline here, in case the actual implementation can help anyone. Note that Jenkins may not be behaving as it would out-of-the-box. The solution worked in Cloudbees Jenkins Enterprise v 2.249.3.1-rolling.
Also of interest is that I'm referencing the domain name of the s3 bucket to match to the bucket name. AFAIK, this is a safe assumption with buckets not configured with static website hosting. But your mileage may vary.
sh '''#!/bin/sh
set -e
set -x

bucket_name="${ENVIRONMENT}-it-${APP_NAME}"
aws s3 ls ${bucket_name}
aws cloudfront list-distributions

echo "Getting CF distributions matching ${bucket_name} ?"
distributions=$(aws cloudfront list-distributions --query "DistributionList.Items[*].{id:Id,origin_domain:Origins.Items[0].DomainName}[?starts_with(origin_domain,'${bucket_name}.')].id" --output text)
echo ${distributions}
for id in "${distributions}"; do aws cloudfront create-invalidation --distribution-id $id --paths "/*";done;

'''

Finally, I also wanted to point out that this URL was very conveniently useful for me to figure out what I was doing incorrectly: https://jmespath.org/. I was able to paste the raw contents of aws cloudfront list-distributions and poke around at it until I figured out why I was getting an empty return.


text:
Q: load an xml asset in actionscript without events I am trying to read an XML asset in actionscript. The examples that I find online all seem to be event driven:
http://www.leebrimelow.com/actionscript-3-quicktip-6-loading-xml/
This seems really heavy-handed for a simple file read. Is there a way that I can do this without breaking up my logic into multiple functions?

A: If it is by any chance Adobe AIR AS3 you are executing and xml file resides on hard drive then you can call FileStream.open function to open file synchronously and load data.
var fileStream:FileStream = new FileStream();
fileStream.open(File.applicationDirectory.resolvePath("abc.xml"), FileMode.READ);
var fileContents:String = fileStream.readUTFBytes(fileStream.bytesAvailable);
var theXML:XML = new XML(fileContents);

If it's not an AIR and/or you need to load data from network, then you will need to relay on URLLoader and event handling as explained in the URL you provided.


text:
Q: SQL 'LIKE' query using '%' where the search criteria contains '%' I have an SQL query as below.
Select * from table
where name like '%' + search_criteria + '%'

If search_criteria = 'abc', it will return data containing xxxabcxxxx which is fine.
But if my search_criteria = 'abc%', it will still return data containing xxxabcxxx, which should not be the case.
How do I handle this situation?

A: To escape a character in sql you can use !:

EXAMPLE - USING ESCAPE CHARACTERS
It is important to understand how to "Escape Characters" when pattern matching. These examples deal specifically with escaping characters in Oracle.
Let's say you wanted to search for a % or a _ character in the SQL LIKE condition. You can do this using an Escape character.
Please note that you can only define an escape character as a single character (length of 1).
For example:
SELECT *
FROM suppliers
WHERE supplier_name LIKE '!%' escape '!';

This SQL LIKE condition example identifies the ! character as an escape character. This statement will return all suppliers whose name is %.
Here is another more complicated example using escape characters in the SQL LIKE condition.
SELECT *
FROM suppliers
WHERE supplier_name LIKE 'H%!%' escape '!';

This SQL LIKE condition example returns all suppliers whose name starts with H and ends in %. For example, it would return a value such as 'Hello%'.
You can also use the escape character with the _ character in the SQL LIKE condition.
For example:
SELECT *
FROM suppliers
WHERE supplier_name LIKE 'H%!_' escape '!';

This SQL LIKE condition example returns all suppliers whose name starts with H and ends in _ . For example, it would return a value such as 'Hello_'.

Reference: sql/like

A: If you want a % symbol in search_criteria to be treated as a literal character rather than as a wildcard, escape it to [%]
... where name like '%' + replace(search_criteria, '%', '[%]') + '%'

A: Select * from table where name like search_criteria

if you are expecting the user to add their own wildcards...

A: You need to escape it: on many databases this is done by preceding it with backslash, \%.
So abc becomes abc\%.
Your programming language will have a database-specific function to do this for you. For example, PHP has mysql_escape_string() for the MySQL database.

A: Use an escape clause:
select *
  from (select '123abc456' AS result from dual
        union all
        select '123abc%456' AS result from dual
       )
  WHERE result LIKE '%abc\%%' escape '\'

Result
123abc%456

You can set your escape character to whatever you want. In this case, the default '\'. The escaped '\%' becomes a literal, the second '%' is not escaped, so again wild card.
See List of special characters for SQL LIKE clause

A: The easiest solution is to dispense with "like" altogether:
Select *
from table
where charindex(search_criteria, name) > 0

I prefer charindex over like.  Historically, it had better performance, but I'm not sure if it makes much of difference now.

A: Escape the percent sign \% to make it part of your comparison value.

A: May be this one help :)
DECLARE @SearchCriteria VARCHAR(25)
SET  @SearchCriteria = 'employee'
IF CHARINDEX('%', @SearchCriteria) = 0
BEGIN
SET @SearchCriteria = '%' + @SearchCriteria + '%'
END
SELECT *
FROM Employee
WHERE Name LIKE @SearchCriteria


text:
Q: Access Denied to "Documents and Settings" on Vista Please help me before I defenestrate my computer!
I'm trying to browse to folder "c:/Documents and settings" on my MS Vista-machine and I keep getting an access denied window. Where do I change the settings so that I can access all folders on my computer.
Facts: I'm the administrator and only user on this computer, and I have turned user account control off.
Have searched superuser for a solution, but in my agitated state I may well have missed the answer.
Thanks folks!

A: You can't open "Documents and settings" in Vista. In fact it doesn't exist anymore. It's just a pointer to the new location which you will find under c:\users.

A: The folders \Documents and Settings is a junction (pointer) to the \Users directory. In fact, if you look in your user directory itself (\Users\username) you'll see that there are quite a few folders like Application Data and Local Settings that you can't open.
These folder junctions are to hand hold poorly written programs that hard code paths in their program (like always assuming the Program Files folder will be Program Files when in fact, in a different language it can be something else entirely! If you install a German copy of Windows it will be Programme).
Hopefully, if you turned off UAC just for trying to browse this folder, you'll see that it won't let you in at all (since it's just there for legacy purposes) you'll turn UAC back on, otherwise you're running almost as insecure as XP is.