text:
Q: ComboBox showing HTML as text My treecolumn has a ComboBox as the editor component. The choices in the options menu are rendered correctly with HTML, but the input box does not render HTML, it only shows the tags (See images below.)
How I can make it to also render the value as HTML?
P.S.
This solution here EXTJS 4 render HTML of a selected value in a combobox is seems like not working with extjs6 version, check here

Here's the problem place code (rendere in case depth.TypeParameter: returns text with html tags)
 {
                    xtype: 'treecolumn',
                    dataIndex: 'text',
                    text: Poly.utils.locale.Base.localeName,
                    flex: 1,
                    getEditor: function (record) {
                        return me.getController().getEditor(record);
                    },
                    renderer: function (value, meta, record) {
                        var depth = Poly.view.fluidProperties.sample.Tree.depth;
                        switch (record.getDepth()) {
                            case depth.Temperature:
                                if (Ext.isEmpty(record.get('temperature'))) {
                                    return value;
                                }
                                var text = Ext.String.format('T = {0} {1}',
                                    record.get('temperature').toFixed(2),
                                    Poly.utils.UniSum.GetUnit(me.getViewModel().get('temperatureUnitId')).name);

                                return text;
                            case depth.TypeParameter:
                                if (record.get('isNew')) {
                                    return value;
                                }
                                return Poly.enums.TypeFluidParameter.getName(record.get('fluidParameter'), record.parentNode.get('typeFluid'), true);
                        }
                        return value;
                    }
                }

Full code here
    Ext.define('Poly.view.fluidProperties.sample.Tree', {
    extend: 'Ext.tree.Panel',

    xtype: 'fluidPropertiesSampleTree',

    viewModel: {
        type: 'fluidPropertiesSampleTreeViewModel'
    },

    controller: 'fluidPropertiesSampleTreeController',

    statics: {
        /** Уровень элемента в дереве */
        depth: {
            /** Корень */
            Root: 0,
            /** Замер */
            Sample: 1,
            /** Тип среды */
            TypeFluid: 2,
            /** Параметер */
            TypeParameter: 3,
            /** Температура */
            Temperature: 4
        }
    },

    lines: false,
    rootVisible: false,
    useArrows: true,
    enableColumnHide: false,
    enableColumnResize: false,
    sortableColumns: false,

    border: true,

    viewConfig: {
        cls: 'gridActionColumnHide'
    },

    dockedItems: [
        {
            xtype: 'toolbar',
            dock: 'bottom',
            ui: 'footer',
            cls: 'transparent',
            layout: {
                type: 'hbox',
                align: 'middle',
                pack: 'center'
            },
            items: [
                {
                    xtype: 'button',
                    cls: 'pvt-chart-button',
                    text: '', // локализация в initComponent
                    flex: 2,
                    name: 'addSample',
                    margin: 2
                },
                {
                    xtype: 'button',
                    cls: 'pvt-chart-button',
                    text: '', // локализация в initComponent
                    flex: 1,
                    name: 'import',
                    disabled: true,
                    margin: 2
                },
                {
                    xtype: 'button',
                    cls: 'pvt-chart-button',
                    text: '', // локализация в initComponent
                    flex: 1,
                    name: 'export',
                    disabled: true,
                    margin: 2
                }
            ]
        }
    ],

    listeners: {
        checkchange: 'nodeCheckChange',
        edit: 'edit'
    },
    plugins: {
        ptype: 'cellediting',
        clicksToEdit: 2
    },

    bind: {
        selection: '{selectedRecord}'
    },

    initComponent: function () {
        var me = this,
            store = Ext.create('Ext.data.TreeStore', {
                root: {
                    expanded: true,
                    children: []
                }
            }),
            controller = me.getController();

        me.dockedItems[0].items[0].text = me.locale.addSample;
        me.dockedItems[0].items[1].text = me.locale.importText;
        me.dockedItems[0].items[2].text = me.locale.exportText;

        Ext.applyIf(me, {
            store: store,
            columns: [
                {
                    xtype: 'treecolumn',
                    dataIndex: 'text',
                    text: Poly.utils.locale.Base.localeName,
                    flex: 1,
                    getEditor: function (record) {
                        return me.getController().getEditor(record);
                    },
                    renderer: function (value, meta, record) {
                        var depth = Poly.view.fluidProperties.sample.Tree.depth;
                        switch (record.getDepth()) {
                            case depth.Temperature:
                                if (Ext.isEmpty(record.get('temperature'))) {
                                    return value;
                                }
                                var text = Ext.String.format('T = {0} {1}',
                                    record.get('temperature').toFixed(2),
                                    Poly.utils.UniSum.GetUnit(me.getViewModel().get('temperatureUnitId')).name);

                                return text;
                            case depth.TypeParameter:
                                if (record.get('isNew')) {
                                    return value;
                                }
                                return Poly.enums.TypeFluidParameter.getName(record.get('fluidParameter'), record.parentNode.get('typeFluid'), true);
                        }
                        return value;
                    }
                },
                {
                    width: 30,
                    xtype: 'widgetcolumn',
                    name: 'menuWidgetcolumn',
                    widget: {
                        xtype: 'button',
                        margin: '5 0 0 0',
                        arrowCls: '',
                        width: 15,
                        height: 15,
                        style: {
                            'background-color': '000000',
                            'border-color': '000000'
                        },
                        menu: {
                            xtype: 'colormenu',
                            listeners: {
                                select: function (component, color) {
                                    var button = component.up('button');

                                    button.setStyle('background-color', color);
                                }
                            }
                        }
                    },
                    onWidgetAttach: function (column, widget, record) {
                        widget.setVisible(Ext.isNumber(record.get('temperature')));
                    }
                },
                {
                    xtype: 'actioncolumn',
                    width: 25,
                    items: [
                        {
                            handler: 'removeTreeItem',
                            getClass: function (v, meta, rec) {
                                if (!rec.get('isNew')) {
                                    return 'poly-trash-icon';
                                }
                                return '';
                            },
                            getTip: function (v, meta, rec) {
                                if (!rec.get('isNew')) {
                                    return 'Delete';
                                }
                                return '';
                            }
                        }
                    ]
                }
            ]
        });

        me.getSampleNode = controller.getSampleNode;
        me.setTypeMode = Ext.bind(controller.setTypeMode, controller);

        me.callParent(arguments);
    }
});

A: Html input element can't display HTML, so you need to change template add div. Div can be shown as an overlay over input.
Best way to achieve this is by extending ComboBox:
    Ext.define('HtmlComboBox', {
    extend: 'Ext.form.field.ComboBox',
    fieldSubTpl: [ // note: {id} here is really {inputId}, but {cmpId} is available
        '<input id="{id}" data-ref="inputEl" type="{type}" {inputAttrTpl}',
            ' size="1"', // allows inputs to fully respect CSS widths across all browsers
            '<tpl if="name"> name="{name}"</tpl>',
            '<tpl if="value"> value="{[Ext.util.Format.htmlEncode(values.value)]}"</tpl>',
            '<tpl if="placeholder"> placeholder="{placeholder}"</tpl>',
            '{%if (values.maxLength !== undefined){%} maxlength="{maxLength}"{%}%}',
            '<tpl if="readOnly"> readonly="readonly"</tpl>',
            '<tpl if="disabled"> disabled="disabled"</tpl>',
            '<tpl if="tabIdx != null"> tabindex="{tabIdx}"</tpl>',
            '<tpl if="fieldStyle"> style="{fieldStyle}"</tpl>',
            '<tpl foreach="inputElAriaAttributes"> {$}="{.}"</tpl>',
        ' class="{fieldCls} {typeCls} {typeCls}-{ui} {editableCls} {inputCls}" autocomplete="off"/>',
        // overlay element to show formatted value
        '<div id="{cmpId}-overlayEl" data-ref="overlayEl"<tpl if="name"> name="{name}-overlayEl"</tpl> class="{fieldCls}-overlay {typeCls} {typeCls}-{ui} {inputCls}">{value}
',
        {
            disableFormats: true
        }
    ],
    forceSelection: true,

    childEls: [
        'overlayEl'
    ],

    setRawValue: function(value) {
        var me = this;

        // set value in overlay
        if (me.rendered) {
            me.overlayEl.update(value);
        }
        return me.callParent([value]);
    }
});

With that, some additional CSS is required:
.x-form-text-wrap {
    position: relative;
}

.x-form-field-overlay {
    background-color: #ffffff;
    position: absolute;
    top: 0;
}

Fiddle: https://fiddle.sencha.com/#fiddle/14mm

A: I suppose that your editor is combo, by default combo (as well as many other components) display HTML as plain text.
Example
I guess as workaround you could overrite combo (or any other component), i.e. change component <input> element to
. It will entail overrites of some methods (setValue() for example).


text:
Q: Error message in my controller creation, Define the key for this entity type I get the following error message when I try to add a controller for my database:
http://i.imgur.com/sYtxy3P.png
Unable to retrieve metadata for 'MvcPractise.Models.Payments'. One or more validation errors were detected during model generation.

System.Data.Entity.Edm.EdmEntityType: : EntityType 'PaymentsContext' has no key defined. Define the key for this Entity type.

Systyem.Data.Entity.Edm.EdmEntitySet:EntityType:EntitySet 'Payment' is based on the type 'Payment Context' that has no keys defined.

I am exceedingly new to Visual Studio, C# and ASP MVC.net, been following a tutorial, but slightly varying the attributes to better suit the needs for what my assignment requires.
My code looks as follows:
using System;
using System.Collections.Generic;
using System.Data;
using System.Web.Mvc;
using System.Linq;
using System.Web;
using System.Data.Entity;
using System.ComponentModel.DataAnnotations;
using MvcPractise.Models;

namespace MvcPractise.Models {

public class Payments {

    [Key]
    public String Email { get; set; }
    public String PaypalEmail { get; set; }
    public String CardHoldersName { get; set; }
    public String CardNumber { get; set; }
    public String ExpirationDate { get; set; }
    public String CardType { get; set; }

}

public class PaymentsContext : DbContext
{

    public DbSet<PaymentsContext> Payment { get; set; }

    public DbSet<Payments> Payments { get; set; }

}
}

If anyone can help, I've been searching through this site and trying many possible solutions, I'v recreated the database and rewritten the code, restarted VS, added the [Key] type as you can see in the code.

A: I believe the problem is in  your PaymentsContext class. You define a DbSet Payment property which I don't think you meant to do. The PaymentsContext class is just a derived class of DbContext and shouldn't be a property of itself. The following should fix your problem:
    public class PaymentsContext : DbContext
    {
            public DbSet<Payments> Payments { get; set; }
    }

A: Rename class Payments to class Payment.
Then your PaymentsContext should be:
public class PaymentsContext: DbContext
{
   public DbSet<Payment> Payments { get; set; }
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Summing sequences in r using data.table I am trying to sum pieces of a series using data.table in r. The idea is that I define a start index and an end index as columns in the table, then make a third column for "sum of the series between start and end indexes."
series = c(1,2,3,4,5,6)
a = data.table(start=c(1,2,3),end=c(4,5,6))
a[,S := sum(series[start:end])]
a

Expected result:
   start end  S
1:     1   4 10
2:     2   5 14
3:     3   6 18

Actual result:
Warning messages:
1: In start:end : numerical expression has 3 elements: only the first used
2: In start:end : numerical expression has 3 elements: only the first used
> a
   start end  S
1:     1   4 10
2:     2   5 10
3:     3   6 10

What am I missing here? If I just do a[,S := start+end] the code executes as one would expect.

A: An option is to loop over the 'start', 'end' columns with Map, get the sequence (:) of the corresponding elements, get the sum and unlist, the list column to assign (:=) it to a new column
a[, S := unlist(Map(function(x, y) sum(x:y), start, end))]

-output
a
#   start end  S
#1:     1   4 10
#2:     2   5 14
#3:     3   6 18

The : is not vectorized for its operands i.e. it takes just a single operand on either side, and that is the reason it showed a warning

A: Maybe you can try cumsum like below, which allows you apply vectorized operations within data.table
cs <- cumsum(series)
a[,S := cs[end]-c(0,cs)[start]]

which gives
   start end  S
1:     1   4 10
2:     2   5 14
3:     3   6 18

A: You can use the arithmetic series formula:
a[, S := (end - start + 1) * (start + end) / 2]

Gives:
   start end  S
1:     1   4 10
2:     2   5 14
3:     3   6 18

A: Your code would work if you make this a rowwise operation so each start and end represent a single value at a time.
library(data.table)
a[,S := sum(series[start:end]), 1:nrow(a)]
a

#   start end  S
#1:     1   4 10
#2:     2   5 14
#3:     3   6 18


text:
Q: PCIe x1 card in a x16 slot = computer won't turn on I have a Lenovo ThinkCentre M55 which has an x16 PCIe on the motherboard, but came with a PCIe  to PCI adapter installed. I removed the adapter so I could use my x1 PCIe wifi card, but as soon as I plug the card in, the computer refuses to turn on.
It seems as if they've made the motherboard this way intentionally. Is there some way around it?

A: The PCIe x16 slot on this computer can only be used for a graphics card.
Check the specifications:

Slot 1: Full length, full height PCI Express x16 (graphics only)
  Slot 2: Full length, full height PCI Express x1
  Slot 2: Full length, full height 32-bit PCI 2.3 (5v)
  Slot 3: Full length, full height 32-bit PCI 2.3 (5v)

This is a chipset limitation. From Intel's Q965 technical specifications:

The Intel Q965 Express chipset contains two separate, mutually exclusive graphics options. Either the GMA 3000 graphics controller (contained within the 82Q965 GMCH) is used, or a PCI Express x16 add-in card can be used. When a PCI Express x16 add-in card is installed, the GMA 3000 graphics controller is disabled.

Effectively, there's a switch inside the northbridge that connects the PCIe lanes to either the internal graphics hardware or the PCIe x16 slot. In order to allow external graphics cards to work, the slot has priority. So by putting a device in the slot, you disconnected the internal graphics, leaving you with no video device.


text:
Q: Why do the reading of local property files in JMeter require a plugin? I was earlier looking for a way to read properties from a project-local file for use in a JMeter Test Plan.
I found a plugin that allows you to do this, but I still don't understand why this functionality isn't just supported natively by the standard distribution of JMeter.  Is there a reason for this?

A: As described in the link you provide, the standard way to override properties files is to put them in user.properties.
Note you can also pass properties through command line option:

-q

as per http://jmeter.apache.org/usermanual/get-started.html#options
If that does not suit your requirement could you give more details about it ?


text:
Q: Audio tag minimal play button I would like to have a minimalistic play button, via the  tag of html5.
I've managed to strip down the play button to a bare minimum and I would like to remove the right part after the three dots, but I do not know how to do it. I'd like to strip the play button of the part indicated by the red arrow. I'm fine with the three dots that allow you to change the speed, I just need the part at the right of the dots to be minimal/disappear.

audio {
  width: 110px;
}

audio::-webkit-media-controls-volume-slider {
  display: none !important;
}

audio::-webkit-media-controls-timeline-container {
  display: none !important;
}

audio::-webkit-media-controls-time-remaining-display {
  display: none !important;
}

audio::-webkit-media-controls-timeline {
  display: none !important;
}
Text before the play button
<audio oncontextmenu="return false;" controls controlslist="nodownload" name="media">  <source src="https://www.w3schools.com/html/horse.ogg" type="audio/mpeg">
Your browser does not support the audio element.
</audio>

A: The element has a hard time getting to the max-width it needs, which is 84px (because the two desired buttons are 32px each and there is 10px of padding on left/right side of audio element), most likely because buttons are loaded and then some are hidden. You can get around the width issue with an animation on load. Make it fast enough that end-user wouldn't notice, like 0.1s - example below

audio {
  width: 110px;
  animation: audioWidth 0.1s forwards;
}

auto::-webkit-media-controls-panel {
  justify-content: center;
}

audio::-webkit-media-controls-volume-slider {
  display: none !important;
  min-width: 0;
}

audio::-webkit-media-controls-timeline-container {
  display: none !important;
  min-width: 0;
}

audio::-webkit-media-controls-time-remaining-display {
  display: none !important;
  min-width: 0;
}

audio::-webkit-media-controls-timeline {
  display: none !important;
  min-width: 0;
}

@keyframes audioWidth {
  from {
    width: 110px;
  }
  to {
    width: 84px;
  }
}
Text before the play button
<audio oncontextmenu="return false;" controls controlslist="nodownload" name="media">  <source src="https://www.w3schools.com/html/horse.ogg" type="audio/mpeg">
Your browser does not support the audio element.
</audio>


text:
Q: If one deck of 52 cards can have 52! possible arrangements, how many can you get when you have two decks? If one deck of 52 cards can have 52! possible arrangements, how many can you get when you have two decks ?

A: You have now 104 cards, but they are paired. Assuming the two decks are identical, you have $\frac {104!}{2^{52}}$ combinations. Indeed there are $104!$ possible shuffles if the two decks are different, but since they are identical, for each pair of identical cards, you can swap them and you have the same shuffle.

A: If the decks must stay separate, then you have 52! arrangements in deck 2 for each of the 52! arrangements in deck 1, so there are $52! \times 52!$ total arrangements.
If the decks are combined, you just increase the operand of the factorial to the new card count, so there are $(52 + 52)!$ total arrangements.


text:
Q: How to download a ggplotly plot with R Shiny downloadHandler? I'm making a Shiny app in R. I use plotly to make my ggplots interactive, thus I have lots of ggplotly plots in the app. I would like to be able to download each one through a button on the interface.
My download button works for normal ggplot objects but not for ggplotly objects. A simple reproducible example would be:
library(shiny)
library(ggplot2)
library(processx) # for orca()
library(plotly)

ui <- fluidPage(
  mainPanel(plotlyOutput("plot1"), downloadButton('download1', 'Download Graph'))
  )

server <- function(input,output){
  make_plot1 <- function(){
    p1 = ggplot(cars, aes(x = speed, y = dist)) + geom_point()
    return(ggplotly(p1))}

  output$plot1 <- renderPlotly({ make_plot1() })

  output$download1 <- downloadHandler(
    filename = function() {'plot1.png'},
    content = function(file) {
      # try 1
      png(file)
      print(make_plot1())

      # try 2
      #plotly_IMAGE(make_plot1(), format = "png", out_file = file)

      # try 3
      #orca(make_plot1(), file)

      #try 4
      #export(make_plot1(), file = file)

      dev.off()
      })
  }

shinyApp(ui, server)

Some things I've tried are commented out in that code.
Try 1 is based on how I would normally handle plot objects in a shiny app
Try 2 is based on this question and this post
Try 3 is based on some plotly documentation
Try 4 is based on this question
All of these attempts either download a blank .png (try 1) or simply fail to download anything (tries 2-4). I suspect I'm not quite using the download Handler correctly. Anybody have suggestions for getting this working?
EDIT: For this case I want .png files, but there are some good answers on this thread for downloading interactive .html files.

A: Do you need to accomplish this with a download button for some reason? If not, plotly has its own button in the modebar that downloads to a PNG.

Dashboard taken from https://plot.ly/r/dashboard/.
From the plotly support forum (https://community.plot.ly/t/remove-options-from-the-hover-toolbar/130/3), you can use config() to remove the other components.
make_plot1 <- function() {
  p1 = ggplot(cars, aes(x = speed, y = dist)) + geom_point()
  p1 = ggplotly(p1) %>%
    config(
      modeBarButtonsToRemove = list(
        "zoom2d",
        "pan2d",
        "zoomIn2d",
        "zoomOut2d",
        "autoScale2d",
        "resetScale2d",
        "hoverClosestCartesian",
        "hoverCompareCartesian",
        "sendDataToCloud",
        "toggleHover",
        "resetViews",
        "toggleSpikelines",
        "resetViewMapbox"
      ),
      displaylogo = FALSE
    )
  return(p1)
}

You can also move the modebar so that it doesn't cover the plot, using CSS.
.modebar {
    top: -30px !important;
}

A: Another way would be to use htmlwidgets to save the file as an interactive html, in case that is preferable to a png.
To turn this html into a static graphic, a further workaround - if you for some reason do not want to use plotly's printing function at all - would be to save a png with webshot (which requires phantomjs). See code below.
library("shiny")
library("ggplot2")
library("data.table")
library("plotly")
library("htmlwidgets")
library("webshot")

shinyApp(

  ui = fluidPage(

    mainPanel(plotlyOutput("plot1"),
              downloadButton('download1', 'Download Graph'))
  ),

  server = function(input, output) {

    inputPlot1 <- reactive({
      p1 = ggplot(cars, aes(x = speed, y = dist)) + geom_point()
      ggplotly(p1)
    })

    output$plot1 <- renderPlotly({
      print(inputPlot1())
    })

    output$download1 <- downloadHandler(
      filename = function() {'plot1.html'},
      content = function(file) {

      htmlwidgets::saveWidget(as_widget(inputPlot1()), file)

        # Alternative using webshot with phantomjs
        # saveWidget(as_widget(inputPlot1()), "temp.html", selfcontained = FALSE)
        # webshot(url = "temp.html", file)

      }
    )

  }

) # closes shinyApp

A: Following your comment to Wil's answer, you can remove the undesired buttons in the modebar as follows:
library(plotly)

x <- c(1:15)
y <- c(1:15)
xy <- as.data.frame(cbind(x,y))
example <- ggplot(data = xy,aes(x = x,y = y)) + geom_line()

ggplotly(example) %>%
  config(displaylogo = FALSE,
         collaborate = FALSE,
         modeBarButtonsToRemove = list(
           'sendDataToCloud',
           'autoScale2d',
           'resetScale2d',
           'hoverClosestCartesian',
           'hoverCompareCartesian',
           'zoom2d',
           'pan2d',
           'select2d',
           'lasso2d',
           'zoomIn2d',
           'zoomOut2d',
           'toggleSpikelines'
         )
  )

References:

*

*https://stackoverflow.com/a/39985051/1100107

*http://www.somesolvedproblems.com/2018/10/how-to-customize-plotlys-modebar.html

*?plotly::config

A: If you wish to download your ggplotly graphs with interactive feature, try this.


text:
Q: Pypandoc not accepting yml input I am able to compile an invoice with the following command:
pandoc details.yml -o output.pdf --template=invoice.tex --latex-engine=xelatex

But when I write the same thing in Python, I get an error complaning about the input format:
>>> pypandoc.convert_file('details.yml', 'pdf', outputfile='pyout.pdf', extra_args=['--latex-engine=xelatex', '--template=invoice.tex'])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python3.6/site-packages/pypandoc/__init__.py", line 140, in convert_file
    outputfile=outputfile, filters=filters)
  File "/usr/local/lib/python3.6/site-packages/pypandoc/__init__.py", line 262, in _convert_input
    format, to = _validate_formats(format, to, outputfile)
  File "/usr/local/lib/python3.6/site-packages/pypandoc/__init__.py", line 223, in _validate_formats
    _get_base_format(format), ', '.join(from_formats)))
RuntimeError: Invalid input format! Got "yml" but expected one of
these: commonmark, docbook, docx, epub, haddock, html, json, latex, markdown, markdown_github, markdown_mmd, markdown_phpextra, markdown_strict, mediawiki, native, odt, opml, org, rst, t2t, textile, twiki

What am I doing wrong here? Why is yml not accepted?

A: Figured it out by reading the source.
So it turns out that this is due to a design decision made by the pypandoc developers. The program infers the type of the input from the file extension, so the only way to pass a yaml file is to rename it with a .md-extension.
https://github.com/bebraw/pypandoc/blob/ffe82646d2ab6cc4e732960a1e1af6bfcb760bb1/pypandoc/init.py#L202


text:
Q: Import form web address, and save it for next time use I can get some information by
data=Import["http://xxxx/xxx/xxxx", "XMLObject"];

Then I can get some informatin by Case function, just like th following:
Cases[data, XMLElement[
"a", {___, "href" -> s_}, {___,
 XMLElement["span", {___}, {___}], ___,
 XMLElement["span", {___}, {___}], ___}] :> {s}, {0, Infinity}];

After that, I save "data" in a .txt file, by
Export["data.txt",data]

But I want to reanalysis those data, so I import the data.txt, (I think it convenient for use),
data = Import["data.txt"]

but it don't work when I use Case function again. I don't know why, I hope someone can help me, thanks.


text:
Q: Read input device in C I'm creating a 2-D platformer game in C that will run in the terminal. I need a way to register "KEY_DOWN" and "KEY_RELEASE" events. As far as I know getchar() reads from stdin and thus can not be used for registering "KEY_RELEASE" events. Neither can it be used for registering if multiple keys are being pressed down at the same time.
Is there a Mac OSX 10.10.5 C library that I can use to solve this problem? Maybe a library which reads input directly from the keyboard instead of the terminal?

A: None of the potential answers are likely to be simple:

*

*if you are running an application in the terminal, and lacking (as OSX does) a set of system calls for reading the keyboard state directly, it won't work.

*the available sources describe non-terminal applications (mostly using Cocoa, the OSX GUI, and mostly using ObjectiveC).

Here are a few:

*

*How can I detect that the Shift key has been pressed?

*Showing how to listen to all keypresses in OS X through the Cocoa API using Python and PyObjC

*Listening for Global Keypresses in OSX

*Mouse button and keypress counter for Mac OS X

*OSX: Detect system-wide keyDown events?
For reference (Cocoa Event Handling Guide):

*

*Handling Key Events

*Monitoring Events


text:
Q: Download file CakePHP 3 I try to download uploaded files which are saved in the folder 'files' in the webroot. Here is my download function in the controller:
   public function download($id=null) { $this->response->file(WWW_ROOT . DS .'files'. $id ,array('download'=> true,'id'=> 'file name.pdf',
        'name'=> 'file name'));

And in the view I have the following:
   <td>  <?= $this->Html->link('Download', ['controller' => 'Articles', 'action' => 'download',$id]) ?></td>

First of all this results in an error under the download button (undefined variable id) and then I get the (more global) error: The requested file C:\xampp\htdocs\articles\src\C:\xampp\htdocs\articles\webroot\files was not found or not readable. I cant really understand why the part C:\xampp\htdocs\articles is repeated twice and how to fix those problems and download uploaded files (not only the specified file in the function $this->response->file but any file found by its id). Any help would be greatly appreciated!

A: I don't think file() has id option also WWW_ROOT doen't need DS after it.
public function download($id=null) {
    $filePath = WWW_ROOT .'files'. DS . $id;
    $this->response->file($filePath ,
        array('download'=> true, 'name'=> 'file name'));
}

Path are repeated because your file path was wrong and file() is prepending APP to the path you are providing.

If the path is not an absolute path that resolves to a file, APP will be prepended to the path.

source

A: public function file_download()
{
    $file_path = WWW_ROOT.'uploads'.DS.'file_name.doc';
    $this->response->file($file_path, array(
        'download' => true,
        'name' => 'file_name.ppt',
    ));
    return $this->response;
}


text:
Q: Hide root category in the prestashop products URL I have this website:
https://implementos.com.pe/root/seguridad-carga/cadena-amarre-de-carga-38-609-mt-kinedyne
And I want to hide from the URL the /root/ (When I activate Friendly URL) part of the category, How can I do that?
I need this result:
https://implementos.com.pe/seguridad-carga/cadena-amarre-de-carga-38-609-mt-kinedyne
[UPDATE]
I have only this module for SEO URL

And is configure like that:

A: The "trouble" is your configuration, just change the: Route to products from
{categories:/}{rewrite}
to
{category:/}{rewrite}


text:
Q: Grails introduce an extra column in predefined table I just started Grails programming, and I was trying to access the table which was predefined and accessed by other application, Table contains only 3 columns id, filename, msgcount. I successfully connect and access the table through grails. Until this everything is going fine, but when I run the main application (previously, which was accessing the table) I faced an error, which was about table attribute mismatch, so I went through the table design and found that there was an extra column named 'version'. I am bit surprised by that extra column but after some diagnosis I realized that that column is added by grails application.
Is this addition of extra column is normal. Is there any solution so grails application doesn't change the tables's attribute (i.e. addition of extra column) which may bound us for using the same table for multiple application.

A: Yes, this is the default behavior of grails GORM. See this explanation: http://grails.org/doc/latest/guide/GORM.html#optimisticLockingAndVersioning
You can solve it in 2 ways:
a) Create a version field in your db table
OR
b) You can disable the version field from your domain class as follows:
class YourDomainClass {

   static mapping = {
       version false
   }

   ...

}


text:
Q: How to pass params as a function and call it after button is clicked I create my custom delete with function and parameters like this
function boxAlert(params){
   $('body').append(
     '
' +
        '
' +params.message+ '
' +
        '<button onclick="' +params.action()+ '"> YES </button>' +
     '
'
   );
}

then I use it like this
<button onclick="_delete()"> Delete Data </button>

It's work but, the alert is called before YES button is clicked, I want alert is called after YES button is clicked, how to solve it? thank you so much

A: I would rewrite it like this:

function boxAlert(params) {
  $('body').append(
    $('
').append(
      $('
').text(params.message),
      $('<button>YES</button>').click(params.action)
    )
  );
}
function _delete() {
  boxAlert({
    message: 'Lorem ipsum dolor?',
    action: function () { // call this after button is clicked
      alert();
    }
  });
}

<button onclick="_delete()"> Delete Data </button>

Use the .click function to specify the handler for the button element.  Also, while we're at it, use the .text function to specify the text for the message (which will properly escape it.)

A: The problem is that you use params.actions(). Note the parentheses, you are calling the function.
Solution:
<button onclick="setTimeout(' +params.action.toString()+ ',0)">

setTimeout is required in this solution in order to execute the function.
Hope this help!

A: <button onclick="' +params.action()+ '"> YES </button>

Will call the action and append a string to the click handler.
function boxAlert(params){
   let div = $('
' +
        '
' +params.message+ '
' +
   '
').append($('<button> YES </button>').click(params.action));
   $('body').append(div);
}


text:
Q: How to create dynamic squares using flexbox? I am having a few difficulties setting up the dynamic portion of the sketch project i am doing. The idea that i want to implement next is that the amount of squares (divs) changes inside the predetermined container and the boxes change size to always fill out the container. What happens is if the number of boxes is over 256 they overspill on the bottom and if it's not enough they just don't fill the extra space of the container.
link to codepen - https://codepen.io/kcolrehs/pen/eYKZXoa
css
  *,
  *:before,
  *:after {
    box-sizing: border-box;
    font-family: Impact, Haettenschweiler, 'Arial Narrow Bold', sans-serif;
  }

  .container {
    display: flex;
    flex-wrap: wrap;
    width: 250px;
    height: 250px;
  }

  .grid {
    border: 0.1px solid black;
    width: 15.63px;
    height: 15.63px;
  }

js
for (let i = 0; i < 256; i++) {
    const grid = document.createElement('div');
    grid.classList.add('grid');
    container.appendChild(grid);
}

question is : how do i style the boxes that they would automaticly change sizes based on the ammount of them inside the perent container?
for ex:

*

*User imputs 64x64 and the grid changes to match the user imput.  user

*Imputs 4x4 the grid changes to match the user imput.

*The container itself has the same size.

I've tried using all sorts of flex grow and shrink properties, but it didin't really do anything apart from deforming the squeres.
I've tried not using predetermant height and width of the squere divs , using margint top and maching width but it didin't work as well.
By now i am thinking of just switching to grid layout and re-working my java to generate column and horizontal squeres and making a grid like that , but before i am doing that i was thinking maybe theres a solution im not thinkign of here.

A: Thank you @Rory McCrossan for puting me on the right direction:
slider.addEventListener('change', function () {
    let boxes = document.querySelectorAll('.grid');
    boxes.forEach(box => {
        box.remove();//removes old grid
    });
    createGrid() //makes new grid afte reset
})

function createGrid() {
    for (let i = 0; i < (slider.value * slider.value); i++) {
        const grid = document.createElement('div');
        let a = slider.value;
        const boxSize = 250 / a; // creates the dynamic squeres
        grid.classList.add('grid');
        grid.style.width = boxSize + 'px';
        grid.style.height = boxSize + 'px';
        container.appendChild(grid);
    }
}

I'll post this in case sameone someday will have similar issues


text:
Q: Add loading icon in the textbox for jQuery Autocomplete I have the following autocomplete code, which is working well.
I just want to add a class to show loading image during the AJAX call and remove the loading image after the AJAX call is complete.
I know I can use addClass and removeClass of jQuery and do it. The problem is I'm not able to understand at which line I should add addClass and at which line I should add removeClass.
Can you help?
   (function( $ ) {
        $(function() {
             // Custom autocomplete instance.
            $.widget( "app.autocomplete", $.ui.autocomplete, {

                // Which class get's applied to matched text in the menu items.
                options: {
                    highlightClass: "ui-state-highlight"
                },

                _renderItem: function( ul, item ) {

   // Replace the matched text with a custom span. This
                // span uses the class found in the "highlightClass" option.
                var re = new RegExp( "(" + this.term + ")", "gi" ),
                    cls = this.options.highlightClass,
                    template = "$1",
                    label = item.label.replace( re, template ),
                    $li = $( "
" ).appendTo( ul );

                // Create and return the custom menu item content.
                $( "" ).attr( "href", "#" )
                           .html( label )
                           .appendTo( $li );

                return $li;

            }

        });
        var autocompleteTextbox = '
'
                                    +''
                                    +'
'
                                        +'<form role="search" method="get" action="<?php echo esc_url( home_url( '+"/"+' ) ); ?>">'
                                            +'<input type="text" name="s" class="form01 autocomplete-search-input" id="autocomplete-search-input" placeholder="Type something" autocomplete="off">'
                                            +''
                                        +'</form>'
                                    +'
'
                                +'
';

        var appendElement = function(){
            $('.st-navbar-collapse').append(autocompleteTextbox);
            $(this).unbind('click');
            $(".st-search .st-btn01 .search-icon").addClass('text-visibility');
        };
        $(".two-brokers").parent('a').on('click',appendElement);

        var removeElement = function(){
            $(this).parents('.autocomplete-search').remove();
            $(".two-brokers").parent('a').bind('click',appendElement);
            $(".st-search .st-btn01 .search-icon").removeClass('text-visibility');
        };
        $("body").on("click",".st-btn02.autocomplete-search-icon",removeElement);

        var searchRequest,timeoutRequest;
        $("body").on("keyup",".autocomplete-search-input",function(){
            clearTimeout(timeoutRequest);
            var _this = $(this);
            timeoutRequest = setTimeout(function(){
                // create an jq-ui autocomplete on your selected element
                _this.autocomplete({
                    minChars: 2,
                    highlightClass: "bold-text",
                    // use a function for its source, which will return ajax response
                    source: function(request, response){
                        try { searchRequest.abort(); } catch(e){}
                        // well use postautocomplete_search.ajax_url which we enqueued with WP
                        $.post(postautocomplete_search, {
                            action: 'get_test_pages',            // our action is called search
                            term: request.term           // and we get the term form jq-ui
                        }, function(data) {
                            if(!data.length){
                                var result = [{
                                    label: 'No matches found',
                                    value: response.term
                                }];
                                response(result);
                            }else{
                               response(data);
                            }
                        }, 'json');
                    },
                    select: function( evt, ui ) {
                        evt.preventDefault();
                        window.location = ui.item.link;
                    }
                });
            },100);
        });
    });
})( jQuery );

A: You just need to add a class .ui-autocomplete-loading with a background-image as specified here.
It auto detects the class and, adds and removes the loading image when the request finishes.
.ui-autocomplete-loading
{
    background: white url("HERE_GOES_LOADING_IMAGE_URL") right center no-repeat;
}

A: you can set div as hidden on your template and then when you need do hide  and show

and the css for that
.loader {
    border: 16px solid #f3f3f3; /* Light grey */
    border-top: 16px solid #3498db; /* Blue */
    border-radius: 50%;
    width: 120px;
    height: 120px;
    animation: spin 2s linear infinite;
}

@keyframes spin {
    0% { transform: rotate(0deg); }
    100% { transform: rotate(360deg); }
}

so bassicly when you try to do ajax you should show it and when you return resule hide it.
full example

A: I copied only the relevant part of your code and added were I would put the addClass() / removeClass().
That is an ADD on input keyup... And a REMOVE on .post() callback.
$("body").on("keyup",".autocomplete-search-input",function(){

  // ADD on keyup
  $("#loaderImgId").addClass("spin");

  clearTimeout(timeoutRequest);
  var _this = $(this);
  timeoutRequest = setTimeout(function(){
    // create an jq-ui autocomplete on your selected element
    _this.autocomplete({
      minChars: 2,
      highlightClass: "bold-text",
      // use a function for its source, which will return ajax response
      source: function(request, response){
        try { searchRequest.abort(); } catch(e){}
        // well use postautocomplete_search.ajax_url which we enqueued with WP
        $.post(postautocomplete_search, {
          action: 'get_test_pages',            // our action is called search
          term: request.term           // and we get the term form jq-ui
        }, function(data) {

          // REMOVE when Ajax result is in!
          $("#loaderImgId").removeClass("spin");

          if(!data.length){
            var result = [{
              label: 'No matches found',
              value: response.term
            }];
            response(result);
          }else{
           response(data);
          }
        }, 'json');
      },
      select: function( evt, ui ) {
          evt.preventDefault();
          window.location = ui.item.link;
      }
    });
  },100);
});


text:
Q: Unable to mock a method with generic parameters I have a function with the following definition in a class, say Stack -
public <K, T> T nameOfFunction(final String string1, final K usebByFunction, final Class<T> returnType)

I have used the following Mockito call -
Mockito.when(instanceOfStack.nameOfFunction((String) any(), - , - ).thenThrow(CallFailedException.class))

I am able to mock the String parameter using (String) any(), but unable to mock the other two - K and Class. I need to mock this call to throw a CallFailedException.

A: Mockito.any() is not applicable for the type Class in your case. Should be fine if you specify Mockito.any(Class.class) in your condition.
public class TestClass
{
    public class MyClass
    {
        public <K, T> T test(String s, K obj, final Class<T> clazz)
        {
            return null;
        }
    }

    @Test
    public void test()
    {
        MyClass myClass = Mockito.mock(MyClass.class);

        Mockito.when(myClass.test(Mockito.anyString(), Mockito.any(), Mockito.any(Class.class))).thenThrow(new IllegalArgumentException());

        myClass.test(null, null, null);
    }
}


text:
Q: Uploading and Playing large videos. HttpRuntime tag settings Combination. Asp.net4.0 , C# net page to upload a large file and a generic handler to play these large wmv video files of size which can be upto 150 MB's. I have the file content stored in varbinary type in SQL Server 2005.
I have set following settings in httpRuntime in web.config
<httpRuntime executionTimeout="110"
                 maxRequestLength="2097151"
                 requestLengthDiskThreshold="2097150"
                 shutdownTimeout="600"
                 delayNotificationTimeout="400"/>

The problem is that sometimes my files doesnt play. It get uploaded properly but when playing the request seems to get timeout. I was able to play files upto 100 MB's. It works 9 out of 10 times on local and production but why does it fails sometimes. The same file get played in one instance but on other instance it doesnt. Can anybody suggest where the problem may be. I think there must be some combination of httpRuntime attributes which i am missing. Please suggest. Its a production issue which keeps popping up.

A: why don't you use IHttpHandler? try this Uploading FIle Using IHttpHandler Might be there will be better solutions to use IHttpHandler if you will search for it.


text:
Q: Browse database tabels in Flutter with Stetho or other program Im trying to migrate from Android to Flutter programming. I want to know if there is any program that could give me access to the database tabels in Flutter?
For Android I used a program called Stetho for browsing my database. I just installed it by adding a dependency to it in build.gradle;
 dependencies {
     ....
     implementation 'com.facebook.stetho:stetho:1.5.0'
     implementation 'com.facebook.stetho:stetho-okhttp3:1.5.0'
     .... }

then importing it to my main class;
 @Override protected void onCreate(Bundle savedInstanceState) {
     ...
     Stetho.initializeWithDefaults(this);
     new OkHttpClient.Builder().addNetworkInterceptor(new StethoInterceptor()).build();

Can I achieve this in Flutter also?


text:
Q: C# get/set value of html input field Is it possible to get the value of the html input field (expiration) in C# after the user clicks outside of the field? And set the value from database to the html input field on page load or on refresh.
Here is my code:
<ext:Panel runat="server" Border="false">
     <Content>
            <label for="expiration"> Unknown date 2 </label>
            <input id="expiration" type="text" placeholder="DD(uu)/MM(uu)/YY(uu)" class="masked" title="title" runat="server"
                                    pattern="^(?:(?:31(\/|-|\.)(?:0?[13578]|1[02]))\1|(?:(?:29|30)(\/|-|\.)(?:0?[1,3-9]|1[0-2])\2))(?:(?:1[6-9]|[2-9]\d)?\d{2})$|^(?:29(\/|-|\.)0?2\3(?:(?:(?:1[6-9]|[2-9]\d)?(?:0[48]|[2468][048]|[13579][26])|(?:(?:16|[2468][048]|[3579][26])00))))$|^(?:0?[1-9]|1\d|2[0-8])(\/|-|\.)(?:(?:0?[1-9])|(?:1[0-2]))\4(?:(?:1[6-9]|[2-9]\d)?\d{2})$|(uu\/([1-9]|0[1-9]|1[0-9]|2[0-9]|3[0-1])\/[0-9]{1,4})|(uu\/uu\/[0-9]{1,4})|(uu\/uu\/uu)"
                                    data-valid-example="01/05/18">
     </Content>
</ext:Panel>

A: It should normally be done with Request.Form["elementName"].
In this case, Request.Form["expiration"] to access its value, change your input to use name instead of id   <input name="expiration" ... /> for it to work


text:
Q: Printing pdfs including AcroJS in C# I searched houres about, how I can print a pdf silently from C# including AcroJs.
I know there are solutions for it, like starting AdobeReader as Process by CommandLine and Print the document. (http://www.codeproject.com/Tips/598424/How-to-Silently-Print-PDFs-using-Adobe-Reader-and)
But this solutions always open the Reader. Even if you can hide the window,depending on the speed of your computer, you can see the adobe reader window a few seconds. I need a workaround which doesn't open the reader but process the AcroJS forms in pdf jut like the normal reader.
Do you konw any alternatives oder libs, that I can use?
How do I print PDFs silently with procesing AcroJS and wthout open the Adobe Reader process in c#?
Thanks :)

A: Your application need to be built using the Adobe Reader OCX or some PDF library. Then, the application needs to be configured to use a default printer. It can then be issued commands to print documents without showing a window.


text:
Q: PHP - Fetch correct XML values if elements have similar tags per record PHP - Fetch correct XML values if elements have similar tags per record
I'm fetching the below xml file:
XML file:
<?xml version='1.0' encoding='UTF-8'?>
<abc:ABCData xmlns:abc="http://www.abc-example.com" xmlns:xyz="http:/www.xyz-example.com">
<abc:ABCRecords>
 <abc:ABCRecord>
 <abc:ABC>5EXZX4LPK</abc:ABC>
  <abc:Entity>
    <abc:Name>I Bornheim</abc:Name>
    <abc:Periods>
      <abc:Period>
        <abc:Start>2017-01-01</abc:Start>
        <abc:End>2017-12-31</abc:End>
        <abc:Type>ACCOUNTING</abc:Type>
      </abc:Period>
      <abc:Period>
        <abc:Start>2007-09-01</abc:Start>
        <abc:Type>RELATIONSHIP</abc:Type>
      </abc:Period>
    </abc:Periods>
  </abc:Entity>
</abc:ABCRecord>
<abc:ABCRecord>
  <abc:ABC>5967007LI</abc:ABC>
  <abc:Entity>
    <abc:Name>SUN BANK</abc:Name>
    <abc:Periods>
      <abc:Period>
        <abc:Start>2018-01-01</abc:Start>
        <abc:End>2018-12-31</abc:End>
        <abc:Type>BALANCED</abc:Type>
      </abc:Period>
      <abc:Period>
        <abc:Start>2008-09-01</abc:Start>
        <abc:Type>PARENT</abc:Type>
      </abc:Period>
    </abc:Periods>
  </abc:Entity>
</abc:ABCRecord>
</abc:ABCRecords>
</abc:ABCData>

... with this script I output the values as csv:
PHP file:
<?php

$reader = new XMLReader();
$reader->open('php://stdin');

$output = fopen('php://stdout', 'w');
fputcsv($output, ['id', 'name']);

$xmlns = [
  'abc' => 'http://www.abc-example.com'
];

$dom   = new DOMDocument;
$xpath = new DOMXpath($dom);
foreach ($xmlns as $prefix => $namespaceURI) {
  $xpath->registerNamespace($prefix, $namespaceURI);
}

while (
  $reader->read() &&
  (
    $reader->localName !== 'ABCRecord' ||
    $reader->namespaceURI !== $xmlns['abc']
  )
) {
  continue;
}

while ($reader->localName === 'ABCRecord') {
  if ($reader->namespaceURI === 'http://www.abc-example.com') {
    $node = $reader->expand($dom);
    fputcsv(
      $output,
      [
        $xpath->evaluate('string(abc:ABC)', $node),
        $xpath->evaluate('string(abc:Entity/abc:Name)', $node)
      ]
    );
  }

  $reader->next('ABCRecord');
}

... like this:
Output:
5EXZX4LPK,"I Bornheim"
5967007LI,"SUN BANK"

Yet ... how do I fetch the correct 'period' values if each period record has the same tag definition?
Desired Output:
5EXZX4LPK,"I Bornheim",2017-01-01,2017-12-31,"ACCOUNTING",2007-09-01,"RELATIONSHIP"
5967007LI,"SUN BANK",2018-01-01,2018-12-31,"BALANCED",2008-09-01,"PARENT"

A: You can simply use XPath's index notation; think of the <abc:Period> elements as being in an array. Remember that XPath indices are one-based, not zero-based.
...
    fputcsv(
      $output,
      [
        $xpath->evaluate('string(abc:ABC)', $node),
        $xpath->evaluate('string(abc:Entity/abc:Name)', $node),
        $xpath->evaluate('string(abc:Entity/abc:Periods/abc:Period[1]/abc:Start)', $node),
        $xpath->evaluate('string(abc:Entity/abc:Periods/abc:Period[1]/abc:End)', $node),
        $xpath->evaluate('string(abc:Entity/abc:Periods/abc:Period[1]/abc:Type)', $node),
        $xpath->evaluate('string(abc:Entity/abc:Periods/abc:Period[2]/abc:Start)', $node),
        $xpath->evaluate('string(abc:Entity/abc:Periods/abc:Period[2]/abc:Type)', $node),
      ]
    );
...

Output:
id,name
5EXZX4LPK,"I Bornheim",2017-01-01,2017-12-31,ACCOUNTING,2007-09-01,RELATIONSHIP
5967007LI,"SUN BANK",2018-01-01,2018-12-31,BALANCED,2008-09-01,PARENT

A: You could use the type to group periods and fetch the first of the grouped results:
$xpath->evaluate(
    'string(
        abc:Entity/abc:Periods/abc:Period[
            abc:Type = "ACCOUNTING" or abc:Type="BALANCED"
        ][1]/abc:Type
    )',
    $node
),

Or you check if here is an abc:End child element:
$xpath->evaluate(
    'string(
        abc:Entity/abc:Periods/abc:Period[
            count(abc:End) = 0
        ][1]/abc:Type
    )',
    $node
),


text:
Q: How to change the attr and id of a button after clicking? using jquery? I am trying to have a button change its onclick and id attributes on the fly. But for some ready, I'm only able to change these attributes the first time.
http://jsfiddle.net/WJTD5/1/
$("#btn1").click(function () {
    window.alert("im changing id to btn2 and ho ho ho");
    $("#btn1").val("ho ho ho");
    $("#btn1").attr("id", "btn2");
});

$("#btn2").click(function () {
    window.alert("im changing id to btn1 and hey hey");
    $("#btn2").val("hey hey");
    $("#btn2").attr("id", "btn1");
});

Here is the example. I see that the id has changed, but the wrong onclick function is been called.
What I want to accomplish is the following:

*

*user enter some stuff on the form, then click search --> should return some data

*if there is data, then the button should change its id and onclick

*if not, remain the same

A: You are attaching the event before the id has changed to btn2, so $("#btn2") is an empty collection. Bind the click handler in the first callback, like so:
$("#btn1").click(function () {
    window.alert("im changing id to btn2 and ho ho ho");
    $("#btn1").val("ho ho ho");
    $("#btn1").attr("id", "btn2");

    $("#btn2").unbind("click").click(function () {
        window.alert("im changing id to btn1 and hey hey");
        $("#btn2").val("hey hey");
        $("#btn2").attr("id", "btn1");
    });
});

Here is a demonstration: http://jsfiddle.net/73zA2/
Alternatively, you can delegate event handling to an ancestor of the element:
$("#btn1").parent().on("click","#btn1", function () {
    window.alert("im changing id to btn2 and ho ho ho");
    $("#btn1").val("ho ho ho");
    $("#btn1").attr("id", "btn2");
})
.on("click","#btn2",function () {
    window.alert("im changing id to btn1 and hey hey");
    $("#btn2").val("hey hey");
    $("#btn2").attr("id", "btn1");
});

Here is a demonstration of that approach: http://jsfiddle.net/2YKFG/

A: I would recommend you use a delegate on a higher element to bind the click to, i.e.:
$("#buttonParent").on('click', '#btn1', function () {
    window.alert("im changing id to btn2 and ho ho ho");
    $("#btn1").val("ho ho ho");
    $("#btn1").attr("id", "btn2");
});

$("#buttonParent").on('click', '#btn2', function () {
    window.alert("im changing id to btn1 and hey hey");
    $("#btn2").val("hey hey");
    $("#btn2").attr("id", "btn1");
});

Here is the solution in the jsFiddle: http://jsfiddle.net/WJTD5/4/

A: Is there a reason you are changing the ID of the element? I would not recommend it and instead opt for using classes. Here is an example:
$("#btn1").click(function () {
    if ($(this).hasClass("state1")){
       window.alert("im changing id to btn2 and ho ho ho");
       $(this).val("ho ho ho");
       $(this).toggleClass("state1 state2");
    } else {
        window.alert("im changing id to btn1 and hey hey");
       $(this).val("hey hey");
       $(this).toggleClass("state1 state2");
    }
});

http://jsfiddle.net/WJTD5/2/

A: For me, I had to use something like what is posted below. Using the separate .val() and .attr() sections would NOT run in my code. This was the solution for me.
var clickSelectFav = true;

var one = function () {
    $("#heart").on('click', '#select_fav', function () {
        alert("changing id to delete_favorite");
        $("#select_fav").attr({id: 'del_fav', src: 'heart.png'});
    });
}

var two = function () {
    $("#heart").on('click', '#del_fav', function () {
        alert("changing id to select_favorite ");
        $("#del_fav").attr({id: 'select_fav', src: 'emptyheart.png'});
    });
}

function call(){
    if(clickSelectFav) one();
    else two();
    clickSelectFav = !clickSelectFav;
}

Hope this can help someone out.


text:
Q: How do i create this graph on latex? So…i made this graph using paint(!)…and it looks horrible. I have used tikz to create similar graphs but this one seems to be more difficult.

A: Here is one approach. Most parts are straightforward TikZ syntax. The somewhat unique parts of this drawing are the multipart nodes and the smooth curves, which I'll explain a bit more in this answer.
For the multipart nodes, I defined a style mysplit that's applied to each node we want to split. This avoids repeating yourself and ensures consistency in your drawing. The first node text is placed in the one subpart of the node, and following \nodepart{<part>} following text is placed in the <part> subpart of the node. Then later on we can refer to anchors of each specific subpart (the last two \draw commands).
Some people find the .. controls .. interface for creating Bézier curves too verbose for some curves (myself included). Here, I use to paths instead. Each part of the to path takes in and out parameters: the incoming and outgoing angle of the curve. These angles can be varied to produce different curves. The looseness parameter (default 1.0) is also adjustable.
Here's the full code:
\documentclass[tikz]{standalone}
\usetikzlibrary{shapes.multipart}
\tikzset{mysplit/.style={%
  draw,
  anchor=text,
  rectangle split,
  rectangle split horizontal,
  rectangle split parts=2,
}}

\begin{document}
\begin{tikzpicture}[align=left]
  \draw[looseness=0.7] (0.5,2.8) coordinate (OutMoney)
    to[out=-45,in=180] (3,1.5) coordinate (AtMoney)
    to[out=0,in=210] coordinate[pos=0.75] (InMoney) (6,2.8);
  \draw[dashed] (OutMoney) |- (3,0) -| (InMoney);
  \draw (AtMoney) -- (3,0) node[midway,fill=white] {At the money};
  \draw[thick] (0,3) node[below left] {Implied\\volatility}
    |- (6,0) node[below] {Strike};
  \node[mysplit] (Out) at (-1.5,-2) {Out of the\\money\\put
                                      \nodepart{two}
                                     In the\\money\\call};
  \node[mysplit] (In)  at ( 4.5,-2) {In the\\money\\put
                                      \nodepart{two}
                                     Out of the\\money\\call};
  \draw (Out.one north) to[out=90,in=210] (1.25,1.5);
  \draw  (In.one north) to[out=90,in=-30] (4.25,1.25);
\end{tikzpicture}
\end{document}

And the output:


text:
Q: use part of Entity Framework (4+) to convert data types? Is there any accessible code in the Entity Framework (version 4+) that I can use to convert .NET data types to SQL Server data types?
Taking that a step farther, is there some way to pass it a .NET type and get a full table definition in some kind of walkable tree?
Update 1: It seems that ModelConfiguration inside DbModelBuilder (v6) has what I want. However, that property is not exposed and the class is internal.


text:
Q: How to make music flow between activities. (Android) I made a music class that will play a song.
I have made onResume and onStop methods in activities so that the song will play.
However, when i switch between activities the the music stops and starts, therefore it is very chopping. How can I make it so that the music flows between the activities, and does not stop and start?

A: Implement a Service that plays your music in the background. See http://developer.android.com/guide/topics/fundamentals/services.html.
Here's an example that plays an audio file in the background using the mentioned Service. http://marakana.com/forums/android/examples/60.html.


text:
Q: How can I remove a gem from my Rails 3 project without getting this really strange Bundle error? The error is:
You have modified your Gemfile in development but did not check
the resulting snapshot (Gemfile.lock) into version control
WHAT VERSION CONTROL? Why/how does Bundle know anything about version control?  I just removed a line from my Gemfile. Am I not supposed to do that?

A: Do rm -rf .bundle && bundle install from your project root.


text:
Q: request for member 'insert' in 'x', which is of non-class type I have a map variable called x which is defined as :
    std::map <std::string, std::string, std::less<std::string>,
    MyAlloc<std::pair <std::string, std::string> > >
    x (std::less<std::string> (), MyAlloc <std::pair <std::string, std::string> > ());

where MyAlloc is my custom STL Allocator defined by me. When I try to insert a pair into the map, like :
    x.insert(std::pair<std::string,std::string>("key","value"));

I'm getting the following error :
    error: request for member 'insert' in 'x', which is of non-class type
   'std::map<std::basic_string<char>, std::basic_string<char>,
    std::less<std::basic_string<char> >, MyAlloc<std::pair<std::basic_string<char>,
    std::basic_string<char> > > >(std::less<std::basic_string<char> > (*)(),
    MyAlloc<std::pair<std::basic_string<char>, std::basic_string<char> > > (*)())'

I don't get this error if I'm using the default constructor of the Allocator,  like :
    std::map <std::string, std::string, std::less<std::string>,MyAlloc <std::pair <std::string, std::string> > > x;

I'm not sure whether the intialisation with the default constructor is correct.. ?
Thanks in advance .. :)

A: The keyword to look for here is "most vexing parse". The definition of x is parsed as a function declaration. Wikipedia has an example which mentions the exact same error message.

A: You've defined a function x, not an object.
The default ctor would use the same comparison and allocator, so use that.


text:
Q: Как нарисовать что-нибудь поверх картинки с камеры? Получил картинку с камеры как объясняется в уроке  и хочу нарисовать поверх какой-нибудь стандартный примитив (линию, круг...).
Не порекомендуют ли гуру как это сделать?
Попытка вставить функцию ниже не удалась.
@Override
protected void onDraw(Canvas canvas) {
...
   canvas.drawCircle(500, 500, 300, mCirclePaint);
}


text:
Q: Search Bar Not Displaying Search Results The search bar in my app isn't working. Ive narrowed down the problem to the method cellforRowAt. It's not able to show the search result when words are typed in. The cellforRowAt contains the information of the filtered articles in the indexpath. How do I resolve this  ?
Project Link: https://github.com/lexypaul13/Covid-News.git
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int { //determines what data source should be used when user types

        if isFiltering{

            return filteredArticles?.count ?? 0

    }

        return articles?.count ?? 0

    }

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

        let cell = tableView.dequeueReusableCell(withIdentifier: "cell1", for: indexPath) as! NewsTableViewCell

        let news: Articles

        filteredArticles = articles

        if isFiltering{

            news = filteredArticles![indexPath.row]

        }

        else{

            news = articles![indexPath.row]

        }

        cell.authorName.text = filteredArticles?[indexPath.row].author

        cell.headLine.text = filteredArticles?[indexPath.row].title

        cell.newsImage.downloadImage(from:(self.filteredArticles?[indexPath.item].urlImage ?? "nill"))

        cell.timePublication.text = filteredArticles?[indexPath.row].publishedAt

        if let dateString = filteredArticles?[indexPath.row].publishedAt,

        let date = indDateFormatter.date(from: dateString){

                   let formattedString = outDateFormtter.string(from: date)

                   cell.timePublication.text = formattedString

               } else {

                   cell.timePublication.text = "----------"

               }

               return cell

           }

    func updateSearchResults(for searchController: UISearchController) {

        let searchBar = searchController.searchBar

        filterContentForSearchText(searchBar.text!, articles!)

    }

    func filterContentForSearchText(_ searchText:String ,_ category: [Articles]){

        filteredArticles =  articles?.filter({ (article:Articles) -> Bool in

            return article.description.lowercased().contains(searchText.lowercased())

        })

        table_view.reloadData()

    }

A: The problem in your code is the line return article.description.lowercased().contains(searchText.lowercased())
In this line the article.description gives you the description of the whole object and is a method of NSObjectProtocol.
So for this scenario you need to know on which item you need to search to get the filtered result. I looked at the code and got to know that the Articles contains title as a parameter. You can use this for filtering your search
So the code should change toreturn (article.title?.lowercased().contains(searchText.lowercased()) ?? false).


text:
Q: How to find the last ul in every li using jquery? I have a list

        Lidingö

                Direktåtkomst Förrådslänga

                        7 kvm (1199 kr/mån)

                Hissplan

                        0,5 kvm (349 kr/mån)

Do you know how can I find the last ul of .cat-item-444 and cat-item-314 then select 7 kvm (1199 kr/mån) and 0,5 kvm (349 kr/mån) in one jquery code? The selected  tag should have .css('border', '1px solid red');

A: To achieve this you can use the :last-child selector to find the last li within each sub-level ul, like this:

$('.cat-item > ul li ul li:last-child').addClass('foo');
.foo {
  border: 1px solid red;
}

    Lidingö

        Direktåtkomst Förrådslänga

            7 kvm (1199 kr/mån)

        Hissplan

            0,5 kvm (349 kr/mån)

If you only want to get the li in the second level, and there are multiple lower levels then you'd need to add additional child selectors, something like .cat-item > ul > li > ul > li:last-child, but the above will work given the provided HTML.
Also note the use of addClass() over css(). This is preferred as you don't really want to put any styling rules directly in JS; they belong in CSS.

A: what about a dynamic version :)

$(".cat-item li:not(:has('ul')) a").addClass('foo');
.foo {
  border: 1px solid red;
}

    Lidingö

        Direktåtkomst Förrådslänga

            7 kvm (1199 kr/mån)

        Hissplan

            0,5 kvm (349 kr/mån)

A: Try this :

$('.children li.cat-item').each(function() {
  console.log($(this).find('ul:last-child li a').text());

});

        Lidingö

                Direktåtkomst Förrådslänga

                        7 kvm (1199 kr/mån)

                Hissplan

                        0,5 kvm (349 kr/mån)

A: Use .last():

$('.cat-item-444 ul li').last().css('border','1px solid red');
$('.cat-item-314 ul li').last().css('border','1px solid red');
debugger

        Lidingö

                Direktåtkomst Förrådslänga

                        7 kvm (1199 kr/mån)

                Hissplan

                        0,5 kvm (349 kr/mån)


text:
Q: Axioms of seperation I am studying topological spaces, and I have seen that there are $3$ main axioms of separation: $\mathrm{T1}$,  Hausdorff and normal.
Now, between Hausdorff and normal there is a case where:
 given any closed set $F\in T$ and any point $x \in T$,  there is open set $O$ containing $F$ and a neighborhood $U$ containing $x$,  such that $U \cap O = \varnothing $.
 This axiom of seperation is not the Hausdorff (stronger than Hausdorff) and not normal (weaker than normal).
My question is: is this indeed a different axiom?  Or can it be related via some theorem to one of the existing axioms?

A: Such a space is called (unimaginatively) regular. It is neither weaker nor stronger than Hausdorff. However, a regular $T_0$ space is automatically Hausdorff. A counterexample: a space with more than one point equipped with the trivial (indiscrete) topology is regular, but it's not Hausdorff.


text:
Q: How do I filter AWS Cloud Watch Logs on a hash on the main page? How can I go directly to the log 7cf2c033bfec48e8a74c40b08cdxx15f from the main Cloud Watch logs page filter? This is the one that filters out log groups.
Here is the message
Failed to create resource. See the details in CloudWatch Log Stream: 2019/08/22/[$LATEST]7cf2c033bfec48e8a74c40b08cdxx15f

Now I want to use the hash to find the log group and the log stream

A: You can do it with Logs Insights.

*

*On CloudWatch Console, navigate to Insights on the left panel (just under logs).

*Click the Select log group(s) on the top and select all of them.

*Select the correct time range for the log stream. You can see it in the log stream name, 2019/08/22/[$LATEST]...

*Use this query: fields @log, @logStream, @message | filter @logStream like "7cf2c033bfec48e8a74c40b08cdxx15f"
Description of fields:

*

*@log will give you the log group

*@logStream will give you the stream name and it should be a clickable link to the actual stream.

*@message will give you the log line.


text:
Q: Fire Trigger if deleted.Column <> inserted.Column This is similar to Compare deleted and inserted table in SQL Server 2008 but the results were not what I was looking for.
I do want the trigger to fire if a specific column changes, however the program we have does a delete of all information and an reinsert of all new information every time it is saved. there is no simple update.
I want to write to an audit table, but ONLY if that specific column has changed once a save has occurred.
ALTER TRIGGER [dbo].[deleted]
ON [dbo].[DispTech]
FOR DELETE, INSERT
AS
    SET NOCOUNT ON;

    IF (SELECT serviceman FROM deleted) <> (SELECT ServiceMan FROM inserted)
    BEGIN
        INSERT INTO misc.dbo.DeletedTest ("Status", dispatch, serviceman)
            SELECT
                'Deleted', d.Dispatch, d.ServiceMan
            FROM
                deleted d

       INSERT INTO misc.dbo.DeletedTest ("Status", dispatch, serviceman)
           SELECT
               'Inserted', i.Dispatch, i.ServiceMan
           FROM
               inserted i
END

This does NOT work as it results back NULL for everything. I know I could sort it all out in the audit table if I dump everything in there each time, but I really want a cleaner set of data and want to use it for other processing.


text:
Q: re.finditer isn't finding substrings I currently have a string and a substring that's extracted from that string. I'm trying to find the start and end positions of the substring within the original string, and have found useful answers on this community that advise to use Python's regular expression library.
I've tried something like:
>>> string = "'Co - carcinogenic effect of retinyl acetate on forestomach carcinogenesis of male F344 rats induced \
... with butylated hydroxyanisole . The potential modifying effect of retinyl acetate ( RA ) on butylated \
... hydroxyanisole ( BHA ) - induced rat forestomach tumorigenesis was examined . Male F344 rats , 5 weeks of age , \
... were maintained on diet containing 1 % or 2 % BHA by weight and simultaneously on drinking water supplemented \
... with RA at various concentrations ( w / v ) for 52 weeks . In groups given 2 % BHA , although marked hyperplastic \
... changes of the forestomach epithelium were observed in all animals , co - administration of 0 . 25 % RA \
... significantly ( P less than 0 . 05 ) increased the incidence of forestomach tumors ( squamous cell papilloma and \
... carcinoma ) to 60 % ( 9 / 15 , 2 rats with carcinoma ) from 15 % ( 3 / 20 , one rat with carcinoma ) in the group \
... given RA - free water . In rats given 1 % BHA , RA co - administered at a dose of 0 . 05 , 0 . 1 , 0 . 2 or 0 . 25 \
... % showed a dose - dependent enhancing effect on the development of the BHA - induced epithelial hyperplasia . \
... Tumors , all papillomas , were induced in 3 rats ( 17 % ) with 0 . 25 % RA and in one rat ( 10 % ) with 0 . 05 % \
... RA co - administration . RA alone did not induce hyperplastic changes in the forestomach . These findings \
... indicate that RA acted as a co - carcinogen in the BHA forestomach carcinogenesis of the rat .'"
...
>>> substring = "on butylated hydroxyanisole ( BHA ) - induced rat forestomach tumorigenesis was examined . Male \
... F344 rats , 5 weeks of age , were maintained on diet containing 1 % or 2 % BHA by weight and simultaneously on \
... drinking water supplemented with RA at various concentrations ( w / v ) for 52 weeks . In groups given 2 % BHA \
... , although marked hyperplastic changes of the forestomach epithelium were observed in all animals , co - \
... administration of 0 . 25 % RA significantly ( P less than 0 . 05 ) increased the incidence of forestomach \
... tumors ( squamous cell papilloma and carcinoma ) to 60 % ( 9 / 15 , 2 rats with carcinoma ) from 15 % ( 3 / 20 \
... , one rat with carcinoma ) in the group given RA - free water . In rats given 1 % BHA , RA co - administered at \
... a dose of 0 . 05 , 0 . 1 , 0 . 2 or 0 . 25 % showed a dose - dependent enhancing effect on the development of \
... the BHA"
...
>>> import re
>>> printx([(m.start(0), m.end(0)) for m in re.finditer(substring, string)]
[]
>>> print(string.index(substring))
189

As you can see, the substring exists within string, but the use of re.finditer is returning an empty list (i.e., None). Does anybody know why this behavior occurs, and how I can fix it?
Thanks.


text:
Q: Prestashop 1.7 multiple ajax action functions in controller I have a javascript file and i have two ajax calls in it on different buttons. I have a controller, Auction.php, in which i have the functions for both actions ( showPopup and askBidControl ), but for the second function, the ajax returns 404 not found. It doesn't even enter the initContent function. Here is a sample of the code:
 class askbidAuctionModuleFrontController extends ProductControllerCore {

    public function initContent(){
        $this->ajax = true;
        parent::initContent();
    }

    public function displayAjaxShowPopup(){
        $type = Tools::getValue('type');
        switch($type){
            case 'bid':

                break;
            case 'ask':

                break;
            default:
                return false;
        }
        $product = $this->getTemplateVarProduct();
        ob_end_clean();
        header('Content-Type: application/json');

        $tpl = _PS_MODULE_DIR_.'askbid/views/templates/front/productPopUp.tpl';
        $this->context->smarty->assign('product', $product);
        $this->context->smarty->assign('type', $type);
        $html = $this->context->smarty->fetch($tpl);
        $this->ajaxDie(Tools::jsonEncode([
            'askbid_popup' => $html,
            'product' => $product,
        ]));
    }

    public function displayAjaxAskBidControl(){
        $type = Tools::getValue('type');
        $price = Tools::getValue('price');
        ob_end_clean();
        header('Content-Type: application/json');
        die('saracie');
//        $this->ajaxDie(Tools::jsonEncode(['trafalet']));
    }

}

The JS:
$(document).ready(function(){
    $('.askBidButton').on('click', function () {
        let buttons_container = $("#askbid_buttons");
        let data = {
            'action': 'showPopup',
            'id_product': buttons_container.data('id-product'),
            'id_product_attribute': buttons_container.data('id-product-attribute'),
            'type': $(this).val()
        };
        let url = buttons_container.data('popup-url');
        $.post(url, data, null, 'json').then(function (resp) {
            $('body').append(resp.askbid_popup);
            let productModal = $(`#bidask-modal-${resp.product.id}-${resp.product.id_product_attribute}`);
            productModal.modal('show');
            productConfig(productModal);
            productModal.on('hidden.bs.modal', function () {
                productModal.remove();
            });
        }).fail((resp) => {
            prestashop.emit('handleError', {eventType: 'clickQuickView', resp: resp});
        });
        return false;
    });
    $('body').delegate('#continue_place_askbid', 'click', function(e){
       let type = $(this).val();
       let price = $(this).parent().find('#askbid_price_input').val();
       let data = {
           'action':'askBidControl',
           'type': type,
           'price': price
       };
       let url = $(this).closest('.quickview').data('popup-url');
       console.log(url);
       console.log('trafalet');
       $.ajax({
           url: url,
           data: data,
           success: function(resp){
               console.log('trafaleteeeee');
           },
           error: function(err){
               console.log(err);
           }
       });
       return false;
    });

productPopUp.tpl is in views/templates/front/
I don't know exactly how to make the second ajax call work. It just gives 404 error.
UPDATE: It seems it doesn't even go through initContent function of Auction.php on the second ajax request ( askBidController ) and it has 2 calls, one for the url i have in ajax, that returns 302 found, and another call to index.php?controller=404.

A: The ajax methods of the PrestaShop controllers require a precise syntax (to be called with the action param):
displayAjax + myCustomAction
in your case:
public function displayAjaxAskBidControl(){}

should works ;)
NOTICE:
the module controllers should ever extend the ModuleFrontController class and not other controllers.
In your case in the first ajax call you give the id_product as a param, so the parent controller do the initContent method, in the second call the productController doesn't find the id_product so it redirects


text:
Q: Does a child have to be both born and raised in Great Britain to be admitted to Hogwarts? I am a little confused about Hogwart's admission criteria.
Does a child have to be both born and raised in GB to be admitted to Hogwarts?
Would a child born outside of GB, whose family moved to England just before their 11th Birthday have their name in the book of Admittance?
What about a child born in GB and raised in another country?
Or a child who wasn't born in GB but spend a few years of their life there?
What if they "first exhibits signs of magic" (3rd paragraph in Pottermore) while on vacation abroad?

A:  Although it's been never directly addressed, it is quite plausible
Firstly, the only Wizarding schools that we know of are:

Hogwarts School of Witchcraft and Wizardry (Scotland)
Beauxbatons Academy of Magic (France)
Castelobruxo (Central Brazil)
Durmstrang Institute (Northern Europe)
Ilvermorny (Eastern North America)
Mahoutokoro School of Magic (Japan)
Uagadou School of Magic (Uganda)
Koldovstoretz (Russia)
source: here

So, there are many countries and regions that don't have their own Wizarding schools. It is highly plausible that wizarding kids could have been accepted at Hogwarts because, well, wizards have been known to live in other regions where there are no Wizarding schools.
About the fees structures, no one pays to go to Hogwarts; the only fees are those for textbooks and other necessary materials. In fact there is even a funding for those who cannot afford to buy those necessities.
Moreover, Draco Malfoy bragged about how he wished his father would send him to Durmstrang where there was no admittance for muggle-borns. So, it is the parents who decide where the kid should go.
So answering the first part of your question:
 It is not necessary to be born in the U.K to be accepted at Hogwarts. One could be born in America and if the parent/guardian submit application at Hogwarts (and it is accepted), they can.
NOTE: Hogwarts has also been known to have permanent exchange students as mentioned in the answer here. So internationals admitted in Hogwarts (in a different way though) - Possible.

Speaking about What if they "first exhibits signs of magic" while on vacation abroad?
From the movie Harry Potter and the Sorcerer's Stone, it is mentioned by Hagrid that Harry's name was added to the Hogwarts' list since the day he was born.

HAGRID: A great Muggle like you is going to stop him?
HARRY: Muggle?
HAGRID: (to Harry) Non-magic folk. (to Vernon) This boy's had his name down since he were born. He's going to the finest school of witchcraft and wizardry.

So, your school would send you an Owl accepting your admission at Hogwarts no matter where you are (if of course you have been enrolled by your parents before coming of age).

A: Likely not - Leta's father was French.
While most students attending Hogwarts are born and raised in Britain, Leta Lestrange attended Hogwarts, and it seems likely that she had been born in France, and spent the first few years of her life there. Her father, Corvus Lestrange Sr., was French.

"SCENE 100
EXT. PARK—1896—DAY
We see a beautiful woman, LAURENA, dressed in an exquisite gown, walking through a park with her husband, MUSTAFA—clearly in love. A YOUNG YUSUF by their side.
KAMA (V.O.)
My mother, Laurena, was equally high-bred—a noted beauty. They were deeply in love. They knew a man of great influence, from a famous French pureblood family. He desired her.
Watching from a distance, an intense wizard, CORVUS LESTRANGE SR., studies her beauty." - Fantastic Beasts: The Crimes of Grindelwald (The Original Screenplay)

While it is not stated clearly where Leta was born, since her father was French and her mother was forced to obey with the Imperius Curse, it seems likely she would have been born in France, where he was from and most likely living at the time.

"SCENE 101
INT. KAMA MANSION—1896—NIGHT
LAURENA'S gown changes to a nightdress. She is walking slowly downstairs, a supernatural wind blowing.
KAMA (V.O.)
Lestrange used the Imperius Curse to seduce and abduct her . . .
The twelve-year-old KAMA runs after his mother, tugs at her hand, and tries to pull her back upstairs. She throws him off. The front door flies open. LESTRANGE SR. stands at the foot of the garden path. LAURENA walks toward him. KAMA chases after her. LESTRANGE SR. points his wand at KAMA and sends him sprawling.
LAURENA lies on the bed as IRMA carries a newborn swaddled in a blanket to LESTRANGE SR." - Fantastic Beasts: The Crimes of Grindelwald (The Original Screenplay)

If this is true, while it may be unusual for a child not both born and raised in Britain to attend Hogwarts, this would prove is is indeed possible for a child not born in Britain to attend.


text:
Q: VueJs: Focus on Input using v-el Directive inside v-repeat Directive I display a list by using the v-repeat directive.
http://jsfiddle.net/ftc9ev7p/1/
Please notice the dynamically created argument of the v-el directive, which is made of
v-el="inputField{{task.id}}"

or alternatively
v-el="{{'inputField' + task.id }}"

Still it doesn't get recognized, since I get:
Uncaught TypeError: Cannot read property 'focus' of undefined

I want to click the edit button and have the according input field focused on.
A similar syntax works, when I dynamically add a css class. Just uncomment the line with the .focus() and click "edit".

  new Vue({
    el: '#tasks',

    data: {
      "tasks": [{
        "id": 25,
        "body": "Slack Noooo Yes",
        "completed": true,
        "created_at": "2015-08-05 17:00:26",
        "updated_at": "2015-08-05 17:00:26"
      }, {
        "id": 27,
        "body": "And",
        "completed": false,
        "created_at": "2015-08-05 17:22:14",
        "updated_at": "2015-08-05 17:22:14"
      }, {
        "id": 28,
        "body": "Happiness",
        "completed": false,
        "created_at": "2015-08-05 17:22:16",
        "updated_at": "2015-08-05 17:22:16"
      }, {
        "id": 29,
        "body": "Love",
        "completed": true,
        "created_at": "2015-08-06 07:45:02",
        "updated_at": "2015-08-06 07:45:02"
      }],

      newTask: ''
    },

    methods: {
      editTask: function(task) {

        var inputField = 'inputField' + task.id;
        alert(inputField);

        var self = this;
        self.$$.inputField.focus();

        document.querySelector(".task" + task.id).className += " edit";
      }
    }
  });

      Task
      Edit
      Options

      {{ task.body }}

        <input type="text" class="editInputField" v-el="inputField{{ task.id }}" value="{{ task.body }}" v-on="keyup:editTask(task) | key 'enter'">

        <button class="btn btn-xs btn-primary" v-on="click: editTask(task)">Edit</button>

Here is the jsfiddle:
http://jsfiddle.net/ftc9ev7p/1/

A: You don't really have to number the elements by v-el since you can get a child ViewModel created by v-repeat. The official guide is on http://vuejs.org/guide/events.html#Invoke_Handler_with_Expression.
You can pass this to editTask in v-on and then you can get the child ViewModel by the first argument:

  <input type="text" v-el="inputField" class="editInputField" value="{{ task.body }}">

editTask: function (task) {
    task.$$.inputField.focus();
    task.$$.label.className += " edit";
}

Also you can get the targetVM by using event.targetVM in the function without the need of passing this to your function.

  <input type="text" v-el="inputField" class="editInputField" value="{{ task.body }}">

editTask: function () {
    event.targetVM.$$.inputField.focus();
    event.targetVM.$$.label.className += " edit";
}

JS Fiddle: http://jsfiddle.net/n1ef18uq/1/


text:
Q: Similar effect to gravity horizontally? I've been pondering this today. Say you have a moving vehicle, with enough space to move around in (say, an empty moving truck). How fast would it have to be going for you to jump and go flying across it, like falling?
I thought I'd start with an effect similar to gravity, so using F=ma & F=.5mv^2 and equating them you get 2a = v^2. But subbing in for a and resolving for v gives ~4.4ms^-2 or just under 10mph. This seems a little on the small side, so I guess my questions are:
How fast would you actually need to be going to get a similar effect?
And what did I do wrong?
Cheers.

A: You will not "fly" inside the vehicle unless it is accelerated (and even then you will simply be pushed to the back unless the vehicle acclerates very quickly and by a huge amount). This is actually the (Gallilean) principle of relativity: a state of rest is indistinguishable from a state of constant velocity motion by the observer who is moving/ stationary. There is no absolute motion.
In regards to your question, the vehicle would have to accelerate at about 9.807 m/s^2 for you to experience a "fake gravity" effect (directed opposite the motion of the car) equivalent to that experienced towards the center of the Earth. This is the principle of equivalence that was used by Einstein to formulate GR. But if the acceleration is 0, you will stay where you are inside the vehicle, as your body is also moving at the same velocity as the vehicle. You will "feel" that you are at rest. The only way you can "fly" inside is if the vehicle is undergoing acceleration (which is quite absolute), which your body will resist (inertia) and you will be pushed behind. As to where you went wrong, I have no idea where v came from in your equation. The force equals to the rate of change of momentum, that is
$$F=\frac{dmv}{dt}=m\frac {dv}{dt}=ma$$
(I've used the classical assumption that mass stays constant for simplicity)
As you can clearly see, the magnitude of the velocity in itself has no impact on the force.


text:
Q: Who does Bottle & Cappy cheer up? So I ran a mission and rescued Bottle & Cappy. They now show up randomly, and I've seen some people's happiness rise, one in particular went from 10% to 75%.
Now one of my quest runners (basically my Avatar in the game, so I keep a close eye on him). He recently died, and on revival, his happiness has dropped to 10%. Now, since he's one of my primary quest runner, he doesn't get assigned to a room.
So will Bottle & Cappy cheer him up while he's wandering around the vault?

A: I stopped playing this game, but a number of forums and Nukapedia seem to agree that they provide a vault-wide happiness boost upon appearing that wears off once they leave.
Nukapedia:

They provide a temporary 20% happiness increase to every dweller in the vault, regardless of which room Bottle and Cappy are in. After they leave, dweller happiness is returned to their previous level.


text:
Q: Why is PASOE WebHandler escaping slashes in the JSON request content? I'm using Progress OpenEdge 11.6.1 on Windows Server 2012. I'm converting some APIs that used the REST Adapter to now use a PASOE WebHandler. The same JSON request content is giving different results between the two. In the request I pass a Progress-formatted date, such as
"FieldValue": "11/30/2016"

The REST adapter API gets that exact value for the date and processes it successfully. However the WebHandler API gets
11\/30\/2016

The slashes appear to be escaped with backslashes, which causes an invalid date error. How can I avoid this? Do I have to write a function to strip the backslashes or is there a setting I can change to prevent the escaping?

A: I was using the GetJsonText() method to read the input values from the JSON request content, which apparently returns the raw text with escaped characters. I changed it to the GetCharacter() method and the escaped characters were removed.


text:
Q: Alarm does not work when phone is in deeply asleep
I have an Alarm App that works perfectly
except when the phone is deeply asleep.
When truly asleep my alarm activity shows up after the user wakes up the phone. I want the phone to wake up the user...
The app starts my AlarmAcivity directly from a BroadcastReceiver. (Not from a Service.)

One clue:
Log D DeepSleepService:  AlarmManager go out of deepsleep
...

PowerManagerService: putReleasedWakeLock
PowerManagerService: *mAcquiredLocks contents****
PowerManagerService: LockList entry : flags=0x10000006 tag=com.solidllc.foo.WakeLock
PowerManagerService: LockList entry : flags=0x1 tag=RILJ
PowerManagerService: LockList entry : flags=0x1 tag=network-location
PowerManagerService: LockList entry : flags=0xa tag=KEEP_SCREEN_ON_FLAG
PowerManagerService: putReleasedWakeLock --> remove partial wakelocks into list, size i
...

//
//My manifest:
android.permission.INTERNET
android.permission.WAKE_LOCK
android.permission.DEVICE_POWER
android.permission.DISABLE_KEYGUARD

The Alarm Clock that comes with Android has the above plus: "Modify global system settings" and "Retrieve Running apps".
Anyone know what can be done?
Thanks much.
Here is the code that sets the alarm:
void armAlarm(int hour, int minute) {

    Calendar alarmtime = new GregorianCalendar();

    alarmtime.set(Calendar.HOUR_OF_DAY, hour);
    alarmtime.set(Calendar.MINUTE, minute);
    alarmtime.set(Calendar.SECOND, 0);

    Intent intent = new Intent(RatActivity.this, AlarmReceiver.class);
    PendingIntent pi = PendingIntent.getBroadcast(RatActivity.this, 0,
            intent, 0);

    AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
    am.cancel(pi);
    am.setRepeating(AlarmManager.RTC_WAKEUP, alarmtime.getTimeInMillis(),
            AlarmManager.INTERVAL_DAY, pi);
}

A: I figured out what was wrong with my code: In was accessing a database in the  BroadcastReceiver. This is a bad/wrong (as the documentation states).  The fact that it only shows up after a long sleep just makes the bug harder to find.


text:
Q: WSo2 Siddhi: How to count the number of events that fulfill a condition I'm working on a use case to detect login bruteforce attacks based on some incoming events. To do so I have to use wso2 + siddhi (not optional).
The structure of the Code I've build is:

*

*Create a partition for each attacked target

*Create windows of 5 seconds

*For each event belonging to the previous window, select all the entries whose Category is "attempt.login"

*insert them into a new table.

Once I have each entry in the new table, I would like to know how many events have been stored in the table, in order to be able to detect brute force or not (If the number of events is greater than 20, for example, that means a bruteforce attacks is taking place).
partition with (Target_IP4 of I_Events)
begin
    from I_Events[Category == 'Attempt.Login']#window.time(5 sec)
    select meta_EventTime, correlation__id, Source_IP4, Source_Proto, Source_Hostname, Target_IP4, Target_Proto, Target_Hostnmae, Category, count() as attempts
    insert into #login_attempts;

from #login_attempts[attempts > 20]#window.time(5 sec)
    select ...
    insert into alert;

end;

As it can be seen in above chuck of code, I've tried to use the count() function but it doesn't work, it just increases the value by 1 each time a new element is added, for example, the firs element added will have attemps = 1, the second one attemps = 2, etc.
If the above idea can not can not be made... at least anyone knows how to select all the elements of a string if a given condition is fullfilled?. For example if one element of the stream has an attribute set to true, then select all the elements from this stream.

A: You can use the below Siddhi query to fulfill your requirement.
partition with (Target_IP4 of I_Events)
begin
from I_Events[Category == 'Attempt.Login']#window.time(5 sec)
select meta_EventTime, correlation__id, Source_IP4, Source_Proto, Source_Hostname, Target_IP4, Target_Proto, Target_Hostnmae, Category, count() as attempts
having attempts > 20
insert into alert;
end;

Here first 20 events which comes under same target ip within 5 mins will not generate any alert. After that each and every event which exceeds that limit within 20 mins will generate an alert. One downside of this implementation is that if you are having large number of distinct target_ips it will lead to large number of partition creations which will lead to server going OOM. Solution for that is to use group by.
Tishan


text:
Q: VC++ ReadFile Unexpectedly Blocks While Reading a Closed Anonymous Pipe I am trying to create a child process running any exe command and redirect all its stdio and stderr to my parent process through an anonymous pipe. But when my parent process tries to do a ReadFile() on the READ end of the anonymous pipe after the child has terminated, it just blocks instead of returning an error.
Here is the code:
#include "windows.h"
//==================================================
void createChildPipes(PHANDLE phRead, PHANDLE phWrite){
  SECURITY_ATTRIBUTES sa={sizeof(SECURITY_ATTRIBUTES) ,NULL,TRUE};
  if ( !CreatePipe(phRead, phWrite, &sa, 2048) ) { //...  }
}
//==================================================
void setupStartupInfo(LPSTARTUPINFO lpsi, HANDLE hStdOutput, HANDLE hStdError) {
  lpsi->cb = sizeof(STARTUPINFO);
  lpsi->lpReserved=NULL;
  lpsi->lpDesktop=NULL;
  lpsi->lpTitle=NULL;
  lpsi->dwX=0;
  lpsi->dwY=0;
  lpsi->dwXSize=200;
  lpsi->dwYSize=500;
  lpsi->dwFlags=STARTF_USESTDHANDLES;
  lpsi->cbReserved2=0;
  lpsi->lpReserved2=NULL;
  lpsi->hStdInput=GetStdHandle(STD_INPUT_HANDLE);
  lpsi->hStdError= hStdError;
  lpsi->hStdOutput=hStdOutput;
}
//==================================================
void createChildProcess(PHANDLE phOutRead, PHANDLE phOutWrite, PHANDLE phErrRead, PHANDLE phErrWrite) {
  TCHAR name[]=_T("cl.exe");
  createChildPipes(phOutRead, phOutWrite);
  STARTUPINFO si;
  setupStartupInfo(&si, *phOutWrite, *phOutWrite);
  PROCESS_INFORMATION pi;
  if (!CreateProcess(NULL, name, NULL,  NULL,   true, 0,   NULL,  NULL,  &si,  &pi)) { //...}
}
//==================================================
void _tmain(int argc, _TCHAR* argv[]){
  HANDLE hOutRead, hOutWrite, hErrRead, hErrWrite;
  createChildProcess(&hOutRead, &hOutWrite, &hErrRead, &hErrWrite) ;
  char buf[10];

  BOOL readState;
  for (;;) {
    DWORD dwBytesRead;
    memset(buf, '\0', sizeof(buf));
    readState=ReadFile(hOutRead, buf, sizeof(buf)-2 , &dwBytesRead, NULL);
    printf("%s", buf);
    if (!readState)
      break;
  }

}

This is what my code is doing.  My _tmain() creates a child process (I am using the VC++ cl.exe command as a test) and redirects its stdio and stderr to the write HANDLE of an anonymous pipe.  My parent process reads from the read HANDLE of the same pipe.
These are printed by my _tmain() showing that the pipe can communicate across the parent-child processes. These are what we expect to see if we type cl.exe in the command line without any arguments.  Note the peculiar behaviour of cl.exe that the first 2 lines are from the stderr of cl.exe and the last line is from the stdout.
Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 16.00.30319.01 for 80x86
Copyright (C) Microsoft Corporation.  All rights reserved.

usage: cl [ option... ] filename... [ /link linkoption... ]

Now about the problem, the line:
readState=ReadFile(hOutRead, buf, sizeof(buf)-2 , &dwBytesRead, NULL);

in _tmain() blocks after the child cl.exe process terminated.  But, I am expecting the ReadFile() call to return with an ERROR_BROKEN_PIPE error status and exit the parent loop instead of blocking the ReadFile() call.
Why the ReadFile() blocks when reading an anonymous pipe?

A: You forgot to close the pipe handles in the parent process, so the pipe is not completely closed yet.


text:
Q: firefox ignores background-size css Trying to scale an image down using the background-size CSS rule but seems to be ignored with Firefox 3.5
CSS
.privatejoker {
    background: aqua url("../styles/images/home-privatejoker.png") no-repeat 0 0;
    background-size: 365px 341px;
    height:341px;
    margin: 0 auto;
    display:block;
    margin-top: -6px;
    }

A: background-size was added to Firefox 3.6, however the -moz vendor prefix was required.
Since version 4, it is no longer required. If you want to support Firefox 3.6 too, include the vendor prefix in addition to the normal property.
Joseph provides a good link for further reading at MDN.

A: background-size will only work in FF4 + see https://developer.mozilla.org/en/CSS/background-size for earlier FF version workarounds.

A: Try providing the sizes in the percentage format
background-size:100% 70%;
100% is the width
70% is the height


text:
Q: ConEmu: possible to change the up arrow behavior? The ↑ arrow cycles through the command history, for example, I get these suggestions:
cd project
git init
git commit
cd ..

Is it possible to adjust the behavior of the up arrow in ConEmu so that it behaves like in zsh which filters the suggestions based on my current prompt? For example, if I wrote "git" to the console, up arrow would only cycle through these two:
git init
git commit

A: You can do that by installing clink: http://mridgers.github.io/clink/ and enabling it in the settings (see docs: https://conemu.github.io/en/TabCompletion.html)